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

时间:2013-01-19 22:23:47

标签: 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.
//

我想将钩子更改为:

/*

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.

*/

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

3 个答案:

答案 0 :(得分:2)

使用smudge/clean filters(完整章节,最谨慎地链接“关键字扩展”)?

答案 1 :(得分:0)

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

我做了以下工作,应该满足您的需求,给予一些调整和测试:D。

新的源标头在perl脚本的__DATA__部分中定义。

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

已经有一段时间了,因为我已经完成了一些严肃的perl,但它可以在我的测试用例上运行,它会创建备份,尽管我建议你先备份你的文件。

我希望它在某种程度上有所帮助。

使用示例:

$ perl add_header *.h *.m 

脚本:

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}
 */

答案 2 :(得分:0)

我曾经做过类似的事情,但从带注释的标签中获取版本号,这是我们在发布版本最终确定时创建的。构建过程会;

  • 使用指定的标签
  • 查看代码
  • 从标记生成版本号(格式为“foo_version_1_2” - > 1.2),并将其写入文件。这是一个模板可以将其拉入以在应用程序中显示
  • 执行构建
  • 打包

您可以轻松地运行脚本,以便在构建期间随时随地填充版本号。我记得看过涂抹/清洁过滤器,但它似乎是一种狡猾的方法。

如果您尝试填充文件特定的数字,上面的内容就不那么有用了,但是之后我会质疑它的值,因为你没有在git中对单个文件进行版本化。你为什么要这样做?