2025年12月4日 星期四

自動初始化 Git 倉庫一個空 README.md 當作起點的腳本

自動初始化 Git 倉庫一個空 README.md 當作起點的腳本

這不是必要的,只是我通常習慣第一點用空 README.md 來當作起始,寫個腳本之後要複製比較容易

# 自動初始化Git倉庫腳本
function Initialize-GitRepository {
    [CmdletBinding()]
    [Alias("igr")]
    param(
        [Parameter(Position = 0)]
        [string]$Path = ".",

        [Parameter()]
        [string]$ReadmeFileName = "README.md",

        [Parameter()]
        [string]$CommitMessage = "Init"
    )

    # 啟用嚴格模式
    Set-StrictMode -Version Latest
    $ErrorActionPreference = 'Stop'

    # 切換到指定目錄
    $originalLocation = Get-Location
    Set-Location $Path

    # Git 包裝函式 - 自動檢查錯誤並拋出例外
    function git {
        & (Get-Command git.exe -CommandType Application) @args
        if ($LASTEXITCODE -ne 0) {
            Write-Error "Git command failed: git $($args -join ' ') (exit code: $LASTEXITCODE)"
        }
    }

    try {
        # ==================== 預檢查階段 ====================
        # 檢查 README 檔案是否已存在
        if (Test-Path $ReadmeFileName) {
            Write-Error "Error: $ReadmeFileName file already exists!"
        }
        # 檢查 Git 倉庫是否已存在
        if (Test-Path ".git") {
            Write-Error "Error: Git repository already exists!"
        }
        # 檢查 Git 命令是否可用
        try {
            git --version | Out-Null
        } catch {
            Write-Error "Error: Git is not installed or not in PATH!"
        }

        # ==================== 執行階段 ====================
        # 創建 README 檔案
        New-Item -Name $ReadmeFileName -ItemType File | Out-Null
        # 初始化Git倉庫
        git init
        # 添加檔案並提交
        git add $ReadmeFileName
        # 提交
        git commit -m $CommitMessage

    } catch {
        throw
    } finally {
        Set-Location $originalLocation
    }
}





沒有留言:

張貼留言