LoginSignup
0
0

More than 3 years have passed since last update.

PowerShellでヘッダーにGitの情報から自動的に作成日時と変更日時を挿入してみた

Posted at

動機

大量の .h ファイルと .cpp ファイルに以下のようなヘッダーを挿入しなければいけない
image.png
140ファイル近くあるソースコードのヘッダーに手作業で日付を入れるのは無理だと考えた。

ヘッダーを入れるためには?

今回ヘッダーを全ソースファイルに挿入するために Visual Studio の拡張機能の License Header Manager を使用した。

以下のテンプレートファイルを作成した。あとで置き換えるためにプレイスホルダー ${created_date}${modified_date} を作成した。
(なお、${ydeagames} は後で名前に置き換える予定だ。)

3DShootingGame.licenseheader
extensions: designer.cs generated.cs
extensions: .cs .cpp .h
// Copyright (c) 2019-2020 ydeagames
// Released under the MIT license
// https://github.com/ydeagames/3DShootingGame/blob/master/LICENSE
//
// Author: ${ydeagames}
// Created: ${created_date}
// Modified: ${modified_date}

プロジェクトを右クリックして License Headers > Add License Headers to All Files を選ぶことですべてのファイルにヘッダーを挿入できる。
image.png

プレイスホルダーを日付に置き換えよう

今回置き換えるために比較的簡単な、PowerShell を採用した。

Gitでのファイルの作成日は

git log --diff-filter=A --follow --pretty="format:%ci" -1 -- $file.Path

最終変更日は

git log -1 --pretty="format:%ci" $file.Path

で取得できる。

ソリューションがあるフォルダに PowerShellのバッチファイルである .ps1 ファイルを作成した。

作成日時置き換え

ReplaceCreationDate.ps1
$sel = '\${' + 'created_date' + '}' # 置き換える対象

# 対象を含むファイルをループ
foreach ($file in Get-ChildItem . * -Recurse -Force | Select-String $sel -casesensitive)
{
    Write-Host "Processing " -ForegroundColor Red -NoNewline
    Write-Host $file.Path
    # Gitの作成日時を取得
    $gitCreated = git log --diff-filter=A --follow --pretty="format:%ci" -1 -- $file.Path
    Write-Host 'Created: ' + $gitCreated
    ((Get-Content -path $file.Path -Raw) -replace $sel,$gitCreated) | Set-Content -Path $file.Path
}

変更日時置き換え

ReplaceModifiedDate.ps1
$sel = '\${' + 'modified_date' + '}' # 置き換える対象

# 対象を含むファイルをループ
foreach ($file in Get-ChildItem . * -Recurse -Force | Select-String $sel -casesensitive)
{
    Write-Host "Processing " -ForegroundColor Red -NoNewline
    Write-Host $file.Path
    # Gitの変更日時を取得
    $gitModified = git log -1 --pretty="format:%ci" $file.Path
    Write-Host 'Modified: ' + $gitModified
    ((Get-Content -path $file.Path -Raw) -replace $sel,$gitModified) | Set-Content -Path $file.Path
}

プレイスホルダーを日付に置き換えることができた。めでたしめでたし。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0