使用git hook添加许可证和应用程序版本以在源文件顶部发表评论

Bry*_*eux 7 git hook

我正在尝试为git创建一个预提交钩子,它编辑我每个.h和.m文件顶部的注释.我想更改x-code添加的标题注释,以包含应用版本和许可证信息.更改为新版本时,这将非常有用.

这是我在x-code中创建文件时自动插入的文本:

//
//  myFile.h
//  myApp 
//
//  Created by Developer on 11/13/12.
//  Copyright (c) 2012 myCompany LLC. All rights reserved.
//
Run Code Online (Sandbox Code Playgroud)

我想钩子把它改成这个:

/*

myFile.h
myApp
Version: 1.0

myApp 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 2 of the License, or (at your option) any later version.

myApp 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 myApp.
If not, see <http://www.gnu.org/licenses/>

Copyright 2012 myCompany. All rights reserved.


This notice may not be removed from this file.

*/
Run Code Online (Sandbox Code Playgroud)

我以为我会有一个文本文件,其中包含我想要更改的标题文本.或检测应用程序版本号何时更改.当使用新版本号和git更新此文件时,我执行git commit,然后它将使用新版本更新所有其他文件,并更改任何新文件以获得正确的标题文本.这似乎可能有用.

sot*_*pme 0

我在使用相当于 perl inplace-edit '-i' 之前做过类似的事情,但使用 perl 脚本而不是仅仅在命令行上,因为数据更大。

经过一些调整和测试,我已经完成了以下工作,应该可以满足您的需求:D。

新的源头在__DATA__perl 脚本的 部分中定义。

这里有一个说明如何通过环境变量传递 VERSION 和 COPY_YEAR 。

我已经有一段时间没有做过一些认真的 Perl 了,但它适用于我的测试用例,它会创建备份,尽管我建议您先备份文件。

我希望它能以某种方式有所帮助。

用法示例:

$ perl add_header *.h *.m 
Run Code Online (Sandbox Code Playgroud)

脚本:

use strict;
my $extension = '.orig';
local $/ = undef; # slurp
my $oldargv = undef;

my $replacement = <DATA>;
$replacement =~ s/{VERSION}/$ENV{VERSION} or '1.0.alpha'/e;
$replacement =~ s/{COPY_YEAR}/$ENV{COPY_YEAR} or '2013'/e;

LINE: while (<>) {
    if ( $ARGV ne $oldargv) {
        my $backup = undef;
        if ($extension !~ /\*/) {
            $backup = $ARGV . $extension;
        }
        else {
             ($backup = $extension) =~ s/\*/$ARGV/;
        }
        rename($ARGV, $backup);
        open(ARGVOUT, ">$ARGV");
        select(ARGVOUT);
        my $oldargv = $ARGV;
    }
    s!^//.*Copy.*?//$!$replacement!sm; # THE BUSINESS END.
}
continue {
    print;
}
select(STDOUT);
__DATA__
/**
 *  My New Header...
 *  Version info {VERSION} ]}
 *  made {COPY_YEAR}
 */
Run Code Online (Sandbox Code Playgroud)