94

いくつかのソース ファイルにライセンス ヘッダーを一括で追加するツールを探していますが、その一部には既にヘッダーが含まれています。ヘッダーがまだ存在しない場合、ヘッダーを挿入するツールはありますか?

編集:回答は基本的にすべて環境固有で主観的なものであるため、意図的にこの質問への回答をマークしていません

4

12 に答える 12

69
#!/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
于 2008-09-30T03:48:48.540 に答える
16

Python 2 ソリューション、必要に応じて変更

特徴:

  • UTF ヘッダーを処理します (ほとんどの IDE にとって重要)
  • 指定されたマスクを渡して、ターゲットディレクトリ内のすべてのファイルを再帰的に更新します (言語のファイルマスク (.c、.java、..etc) の .endswith パラメータを変更します)
  • 以前の著作権テキストを上書きする機能 (これを行うには、古い著作権パラメーターを提供します)
  • excludedirオプションで、配列で指定されたディレクトリを省略します
# 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()
于 2008-09-30T03:44:46.817 に答える
16

ファイル license.txt にライセンス ヘッダーがあると仮定して、このトリックを実行する Bash スクリプトを次に示します。

ファイル 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  
于 2008-09-30T03:56:06.773 に答える
16

著作権ヘッダーのRubyGemを確認してください。php、c、h、cpp、hpp、hh、rb、css、js、html で終わる拡張子を持つファイルをサポートします。また、ヘッダーを追加および削除することもできます。

sudo gem install copyright-header「 」と入力してインストールします

その後、次のようなことができます:

copyright-header --license GPL3 \
  --add-path lib/ \
  --copyright-holder 'Dude1 <dude1@host.com>' \
  --copyright-holder 'Dude2 <dude2@host.com>' \
  --copyright-software 'Super Duper' \
  --copyright-software-description "A program that makes life easier" \
  --copyright-year 2012 \
  --copyright-year 2012 \
  --word-wrap 80 --output-dir ./

--license-file 引数を使用して、カスタム ライセンス ファイルもサポートします。

于 2012-07-17T22:05:05.133 に答える
13

編集:Eclipseを使用している場合は、プラグインがあります

SilverDragonの返信に基づいて簡単なPythonスクリプトを作成しました。より柔軟なソリューションが必要だったので、これを思いつきました。これにより、ディレクトリ内のすべてのファイルに再帰的にヘッダーファイルを追加できます。オプションで、ファイル名が一致する必要がある正規表現、ディレクトリ名が一致する必要がある正規表現、およびファイルの最初の行が一致しない必要がある正規表現を追加できます。この最後の引数を使用して、ヘッダーがすでに含まれているかどうかを確認できます。

このスクリプトは、これがシバン(#!)で始まる場合、ファイルの最初の行を自動的にスキップします。これは、これに依存する他のスクリプトを壊さないためです。この動作を望まない場合は、writeheaderで3行をコメントアウトする必要があります。

ここにあります:

#!/usr/bin/python
"""
This script attempts to add a header to each file in the given directory 
The header will be put the line after a Shebang (#!) if present.
If a line starting with a regular expression 'skip' is present as first line or after the shebang it will ignore that file.
If filename is given only files matchign the filename regex will be considered for adding the license to,
by default this is '*'

usage: python addheader.py headerfile directory [filenameregex [dirregex [skip regex]]]

easy example: add header to all files in this directory:
python addheader.py licenseheader.txt . 

harder example adding someone as copyrightholder to all python files in a source directory,exept directories named 'includes' where he isn't added yet:
python addheader.py licenseheader.txt src/ ".*\.py" "^((?!includes).)*$" "#Copyright .* Jens Timmerman*" 
where licenseheader.txt contains '#Copyright 2012 Jens Timmerman'
"""
import os
import re
import sys

def writeheader(filename,header,skip=None):
    """
    write a header to filename, 
    skip files where first line after optional shebang matches the skip regex
    filename should be the name of the file to write to
    header should be a list of strings
    skip should be a regex
    """
    f = open(filename,"r")
    inpt =f.readlines()
    f.close()
    output = []

    #comment out the next 3 lines if you don't wish to preserve shebangs
    if len(inpt) > 0 and inpt[0].startswith("#!"): 
        output.append(inpt[0])
        inpt = inpt[1:]

    if skip and skip.match(inpt[0]): #skip matches, so skip this file
        return

    output.extend(header) #add the header
    for line in inpt:
        output.append(line)
    try:
        f = open(filename,'w')
        f.writelines(output)
        f.close()
        print "added header to %s" %filename
    except IOError,err:
        print "something went wrong trying to add header to %s: %s" % (filename,err)


def addheader(directory,header,skipreg,filenamereg,dirregex):
    """
    recursively adds a header to all files in a dir
    arguments: see module docstring
    """
    listing = os.listdir(directory)
    print "listing: %s " %listing
    #for each file/dir in this dir
    for i in listing:
        #get the full name, this way subsubdirs with the same name don't get ignored
        fullfn = os.path.join(directory,i) 
        if os.path.isdir(fullfn): #if dir, recursively go in
            if (dirregex.match(fullfn)):
                print "going into %s" % fullfn
                addheader(fullfn, header,skipreg,filenamereg,dirregex)
        else:
            if (filenamereg.match(fullfn)): #if file matches file regex, write the header
                writeheader(fullfn, header,skipreg)


def main(arguments=sys.argv):
    """
    main function: parses arguments and calls addheader
    """
    ##argument parsing
    if len(arguments) > 6 or len(arguments) < 3:
        sys.stderr.write("Usage: %s headerfile directory [filenameregex [dirregex [skip regex]]]\n" \
                         "Hint: '.*' is a catch all regex\nHint:'^((?!regexp).)*$' negates a regex\n"%sys.argv[0])
        sys.exit(1)

    skipreg = None
    fileregex = ".*"
    dirregex = ".*"
    if len(arguments) > 5:
        skipreg = re.compile(arguments[5])
    if len(arguments) > 3:
        fileregex =  arguments[3]
    if len(arguments) > 4:
        dirregex =  arguments[4]
    #compile regex    
    fileregex = re.compile(fileregex)
    dirregex = re.compile(dirregex)
    #read in the headerfile just once
    headerfile = open(arguments[1])
    header = headerfile.readlines()
    headerfile.close()
    addheader(arguments[2],header,skipreg,fileregex,dirregex)

#call the main method
main()
于 2012-03-12T17:11:03.963 に答える
12

Java の場合、Maven のライセンス プラグインを使用できます: http://code.google.com/p/maven-license-plugin/

于 2008-10-01T02:07:49.757 に答える
11

これは、フォルダ内の指定されたタイプのすべてのファイルを検索し、必要なテキスト(ライセンステキスト)を先頭に追加し、結果を別のディレクトリにコピーする(潜在的な上書きの問題を回避する)単純なWindows専用UIツールです。 。それも無料です。必要な.Net4.0。

私は実際に作者なので、修正や新機能をリクエストしてください...ただし、配信スケジュールについての約束はありません。;)

詳細:Amazify.comライセンスヘッダーツール

于 2011-10-29T19:39:51.477 に答える
5

license-adder を確認してください。複数のコード ファイル (カスタム ファイルも含む) をサポートし、既存のヘッダーを正しく処理します。最も一般的なオープン ソース ライセンスのテンプレートが既に付属しています。

于 2012-09-02T08:49:06.577 に答える
3

Apacheリストで見つけたものを次に示します。Rubyで書かれているので読みやすいです。特別な機能を追加するために、rake から呼び出すこともできるはずです。:)

于 2009-01-31T11:59:25.417 に答える
1

それでも必要な場合は、SrcHeadという名前の小さなツールがあります。あなたはそれをhttp://www.solvasoft.nl/downloads.htmlで見つけることができます

于 2009-03-20T20:03:27.463 に答える
1

sbt を使用している場合は、https://github.com/Banno/sbt-license-pluginがあります。

于 2013-05-28T21:58:25.480 に答える