用于创建git changelog

时间:2018-11-26 09:30:20

标签: git powershell

我正在创建一个简单的Powershell脚本,用于从git中获取提交并从中创建更改日志,但是遇到了麻烦。现在,提交被压缩为适合一行,但是我无法在其后添加“换行符”,因此可以使用MarkDown在列表中显示它们。

这是我到目前为止(已更新)的内容:

# Getting project location
$location = Get-Location
Write-Host $location

# Getting version number from project
$currentVersion = (Select-String -Path .\package.json -Pattern '"version": "(.*)"').Matches.Groups[1].Value
Write-Host $currentVersion

#Adding header to log file if there are any commits marked with current version number
$commits = git log --grep="ver($currentVersion)"
if (![string]::IsNullOrEmpty($commits)) {
    Add-Content "$location\log.md" "### All changes for version $currentVersion ###`n"

    # Fetching commits based on version number and tags
    $fixed = git log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit --grep="ver($currentVersion) --grep="(fixed)"
    if (![string]::IsNullOrEmpty($fixed)) {
        Add-Content "$location\log.md" "## Fixed ##`n"
        Add-Content "$location\log.md" "$fixed`n`n"
    }

    $removed = git log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit --grep="ver($currentVersion) --grep="(breaking)"
    if (![string]::IsNullOrEmpty($removed)) {
        Add-Content "$location\log.md" "## Removed ##`n"
        Add-Content "$location\log.md" "$removed`n`n"
    }

    $added = git log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit --grep="ver($currentVersion) --grep="(added)"
    if (![string]::IsNullOrEmpty($added)) {
        Add-Content "$location\log.md" "## Added ##`n"
        Add-Content "$location\log.md" "$added`n`n"
    }   
}

#Asking user for new version number
$newVersion = Read-Host "Choose new version number - current version is $currentVersion"

#Running npm-version to update project version number
npm version $newVersion

1 个答案:

答案 0 :(得分:1)

首先$commits是一个对象数组,因此建议如下调整第一个if语句:

if ($commits -ne $null -and $commits.count -gt 0) {

以下if语句也是如此。现在解决您的问题。您正在错误地对待git log命令的输出...正如已经指出的那样,它返回一个对象数组。与其将整个数组添加到文件中,不如下面那样遍历数组。

$fixed = git log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit --grep="ver($currentVersion) --grep="(fixed)"
if ($fixed -ne $null -and $fixed.count -gt 0) {
    Add-Content "$location\log.md" "## Fixed ##`n"
    foreach ($f in $fixed)
    {
        Add-Content "$location\log.md" "$f`n`n"
    }
}