用于向源文件添加许可证标头的工具?
时间:2020-03-06 14:54:20 来源:igfitidea点击:
我正在寻找一种工具,该工具将向大量源文件添加许可证标头,其中一些源文件已经具有标头。是否有工具可以插入标头(如果尚不存在)?
编辑:我故意不标记此问题的答案,因为答案基本上都是针对特定环境且主观的
解决方案
Python解决方案,根据需要进行修改
特征:
- 处理UTF标头(对于大多数IDE都很重要)
- 通过给定的掩码递归地更新目标目录中的所有文件(为语言(.c,.java,.. etc)的文件掩码修改.endswith参数
- 能够覆盖先前的版权文本(为此提供旧的版权参数)
- 可以选择省略excludeirir数组中给出的目录
--
# updates the copyright information for all .cs files # usage: call recursive_traversal, with the following parameters # parent directory, old copyright text content, new copyright text content import os excludedir = ["..\Lib"] def update_source(filename, oldcopyright, copyright): utfstr = chr(0xef)+chr(0xbb)+chr(0xbf) fdata = file(filename,"r+").read() isUTF = False if (fdata.startswith(utfstr)): isUTF = True fdata = fdata[3:] if (oldcopyright != None): if (fdata.startswith(oldcopyright)): fdata = fdata[len(oldcopyright):] if not (fdata.startswith(copyright)): print "updating "+filename fdata = copyright + fdata if (isUTF): file(filename,"w").write(utfstr+fdata) else: file(filename,"w").write(fdata) def recursive_traversal(dir, oldcopyright, copyright): global excludedir fns = os.listdir(dir) print "listing "+dir for fn in fns: fullfn = os.path.join(dir,fn) if (fullfn in excludedir): continue if (os.path.isdir(fullfn)): recursive_traversal(fullfn, oldcopyright, copyright) else: if (fullfn.endswith(".cs")): update_source(fullfn, oldcopyright, copyright) oldcright = file("oldcr.txt","r+").read() cright = file("copyrightText.txt","r+").read() recursive_traversal("..", oldcright, cright) exit()
#!/bin/bash for i in *.cc # or whatever other pattern... do if ! grep -q Copyright $i then cat copyright.txt $i >$i.new && mv $i.new $i fi done
这是一个Bash脚本,如果我们在文件license.txt中具有许可证标头,便可以完成此操作:
文件addlicense.sh:
#!/bin/bash for x in $*; do head -$LICENSELEN $x | diff license.txt - || ( ( cat license.txt; echo; cat $x) > /tmp/file; mv /tmp/file $x ) done
现在在源目录中运行此命令:
export LICENSELEN=`wc -l license.txt | cut -f1 -d ' '` find . -type f \(-name \*.cpp -o -name \*.h \) -print0 | xargs -0 ./addlicense.sh
对于Java,请http://code.google.com/p/maven-license-plugin/
亲切的问候
这是我在Apache列表中找到的一个。它是用Ruby编写的,似乎很容易阅读。我们甚至应该可以从rake调用它,以获得额外的特殊乐趣。 :)
如果我们仍然需要一个,我已经写了一个小工具,名为SrcHead。我们可以在http://www.solvasoft.nl/downloads.html上找到它