pwsh 自動建立 README.md 並初始化 git 倉庫
運用場景是每次開心的 cursor 都要建立一次很煩,寫了腳本省一點時間
建議可以把它寫到 $PROFILE 中這樣開新的終端機就會自動讀入了
腳本在這這裡
# 自動初始化Git倉庫腳本
function Initialize-GitRepository {
[CmdletBinding()]
[Alias("igr")]
param(
[Parameter(Position = 0)]
[string]$Path = ".",
[Parameter()]
[string]$ReadmeFileName = "README.md",
[Parameter()]
[string]$CommitMessage = "Init"
)
# 啟用嚴格模式 (不會擴散到 func 外)
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
}
}
# 如果直接執行腳本,則調用函式
if ($MyInvocation.MyCommand.Name -and $MyInvocation.InvocationName -ne '.') {
Initialize-GitRepository @args
}
加入之後重新打開終端機直接使用 igr 就可以初始化庫了
沒有留言:
張貼留言