Git Setup Tools (AetherOS)

From OODA WIKI
Revision as of 20:51, 5 September 2025 by AdminIsidore (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Git Setup Tools

Overview

The Git Setup Tools are a collection of scripts designed to streamline the initialization of Git repositories for new projects. Developed by LE Nova, these tools automate the creation of a Git repository with a `main` branch, standard `.gitignore`, `README.md`, and `LICENSE` files, and push the initial commit to a specified GitHub repository. The tools are particularly useful for quickly setting up new projects in a consistent manner, ensuring best practices for version control.

The tools consist of two scripts:

  • `setup_git.sh`: A shell script that performs the Git setup directly.
  • `setup_git.py`: A Python script that generates a customized `setup_git.sh` based on command-line arguments or a JSON configuration file.

These scripts were initially developed for the Avatara project and are intended for reuse across other projects, potentially as part of a larger project-building directory/repository.

Usage

setup_git.sh

The `setup_git.sh` script initializes a Git repository in the specified project directory, creates standard files, and pushes to a remote GitHub repository.

Prerequisites

  • Git installed and configured with credentials (SSH or HTTPS with a Personal Access Token).
  • The project directory must exist (e.g., `~/projects/<project_name>`).
  • Run within a Python virtual environment if applicable.

Execution

Save the script as `setup_git.sh`, make it executable, and run it with or without arguments:

chmod +x setup_git.sh
./setup_git.sh <project_name> <repo_url>

Or, run without arguments to be prompted:

./setup_git.sh

Example:

./setup_git.sh myproject https://github.com/IsidoreLands/myproject.git

Script Content

#!/bin/bash

# Check for command-line arguments, else prompt
if [ $# -lt 2 ]; then
    echo "Usage: $0 <project_name> <repo_url>"
    read -p "Enter project name: " project_name
    read -p "Enter GitHub repository URL (e.g., https://github.com/username/repo.git): " repo_url
else
    project_name="$1"
    repo_url="$2"
fi

# Navigate to project directory
if [ ! -d "$(pwd)/$project_name" ]; then
    echo "Directory $project_name does not exist. Please run in the correct directory."
    exit 1
fi
cd "$(pwd)/$project_name" || exit 1

# Initialize git repository
git init

# Set remote origin
git remote add origin "$repo_url"

# Create .gitignore
cat <<EOL > .gitignore
# Python virtual environment
venv/
__pycache__/
*.pyc

# Common IDE files
.idea/
.vscode/

# Output files
*.png
*.log

# Environment files
.env
EOL

# Create README.md
cat <<EOL > README.md
# $project_name

A new project initialized with a basic Git setup.

## Setup

1. Clone the repository:
   \`\`\`bash
   git clone $repo_url
   cd $project_name
   \`\`\`

2. Set up the Python virtual environment (if applicable):
   \`\`\`bash
   python3 -m venv venv
   source venv/bin/activate
   \`\`\`

## License
See [LICENSE](./LICENSE) for details.
EOL

# Create LICENSE
cat <<EOL > LICENSE
MIT License

Copyright (c) $(date +%Y) $(git config user.name)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
EOL

# Ensure main branch
git branch -M main

# Add and commit files
git add .gitignore README.md LICENSE
git commit -m "Initial commit with .gitignore, README, and LICENSE"

# Push to GitHub
git push -u origin main

setup_git.py

The `setup_git.py` script generates a customized `setup_git.sh` based on command-line arguments or a JSON configuration file, making it reusable for multiple projects.

Prerequisites

  • Python 3.x installed.
  • Run within a Python virtual environment if dependencies are needed.

Execution

Run with command-line arguments:

python3 setup_git.py --project-name myproject --repo-url https://github.com/IsidoreLands/myproject.git --license MIT

Or use a JSON config file (e.g., `config.json`):

{
    "project_name": "myproject",
    "repo_url": "https://github.com/IsidoreLands/myproject.git",
    "license": "MIT"
}

Then:

python3 setup_git.py --config config.json

This generates `setup_git.sh`, which you can then execute:

chmod +x setup_git.sh
./setup_git.sh

Script Content

import argparse
import json
import os
from datetime import datetime

def generate_setup_git(project_name, repo_url, license_type='MIT', output_path='setup_git.sh'):
    """Generate a setup_git.sh script for a given project."""
    user_name = os.popen('git config user.name').read().strip() or 'Your Name'
    year = datetime.now().year

    # License templates
    licenses = {
        'MIT': f"""MIT License

Copyright (c) {year} {user_name}

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.""",
        'GPL': f"""GNU General Public License v3.0

Copyright (c) {year} {user_name}

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>."""
    }

    license_content = licenses.get(license_type, licenses['MIT'])

    # Shell script content
    script_content = f"""#!/bin/bash

# Check for command-line arguments, else use defaults
project_name="{project_name}"
repo_url="{repo_url}"

# Navigate to project directory
if [ ! -d "$(pwd)/$project_name" ]; then
    echo "Directory $project_name does not exist. Please run in the correct directory."
    exit 1
fi
cd "$(pwd)/$project_name" || exit 1

# Initialize git repository
git init

# Set remote origin
git remote add origin "$repo_url"

# Create .gitignore
cat <<EOL > .gitignore
# Python virtual environment
venv/
__pycache__/
*.pyc

# Common IDE files
.idea/
.vscode/

# Output files
*.png
*.log

# Environment files
.env
EOL

# Create README.md
cat <<EOL > README.md
# $project_name

A new project initialized with a basic Git setup.

## Setup

1. Clone the repository:
   \`\`\`bash
   git clone $repo_url
   cd $project_name
   \`\`\`

2. Set up the Python virtual environment (if applicable):
   \`\`\`bash
   python3 -m venv venv
   source venv/bin/activate
   \`\`\`

## License
See [LICENSE](./LICENSE) for details.
EOL

# Create LICENSE
cat <<EOL > LICENSE
{license_content}
EOL

# Ensure main branch
git branch -M main

# Add and commit files
git add .gitignore README.md LICENSE
git commit -m "Initial commit with .gitignore, README, and LICENSE"

# Push to GitHub
git push -u origin main
"""

    # Write the script
    with open(output_path, 'w') as f:
        f.write(script_content)
    os.chmod(output_path, 0o755)  # Make executable
    print(f"Generated {output_path}")

def main():
    parser = argparse.ArgumentParser(description="Generate a setup_git.sh script for a new project.")
    parser.add_argument('--project-name', help="Name of the project")
    parser.add_argument('--repo-url', help="GitHub repository URL")
    parser.add_argument('--license', default='MIT', choices=['MIT', 'GPL'], help="License type (MIT or GPL)")
    parser.add_argument('--config', help="Path to JSON config file")
    args = parser.parse_args()

    if args.config:
        try:
            with open(args.config, 'r') as f:
                config = json.load(f)
            project_name = config.get('project_name')
            repo_url = config.get('repo_url')
            license_type = config.get('license', 'MIT')
        except Exception as e:
            print(f"Error reading config: {e}")
            return
    else:
        project_name = args.project_name
        repo_url = args.repo_url
        license_type = args.license

    if not project_name or not repo_url:
        print("Error: project_name and repo_url are required.")
        return

    generate_setup_git(project_name, repo_url, license_type)

if __name__ == "__main__":
    main()

Future Integration

These scripts are planned to be incorporated into a larger project-building directory/repository managed by another team. This will enable automated setup of entire project structures, including additional tools and configurations. The scripts are designed to be extensible, allowing for customization of the `.gitignore`, `README.md`, and `LICENSE` files as needed.

Credits

  • Developer: LE Nova
  • Developer: Isidore Lands
  • Initial Project: Avatara

See Also