문제

대량으로 일부 소스 파일에 라이센스 헤더를 추가하는 도구를 찾고 있습니다. 일부는 이미 헤더가 있습니다. 헤더가 아직 존재하지 않으면 헤더를 삽입 할 도구가 있습니까?

편집 : 나는 의도적 으로이 질문에 대한 답을 표시하지 않습니다. 답변은 기본적으로 모든 환경과 주관적이기 때문입니다.

도움이 되었습니까?

해결책

#!/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

다른 팁

파이썬 솔루션, 자신의 요구에 맞게 수정하십시오

특징:

  • UTF 헤더 처리 (대부분의 IDE에 중요)
  • 주어진 마스크를 전달하는 대상 디렉토리의 모든 파일을 재귀 적으로 업데이트합니다 (언어의 fillemask에 대한 .endswith 매개 변수 수정 (.c, .java, ..etc)
  • 이전 저작권 텍스트를 덮어 쓰는 기능 (이를 위해 이전 저작권 매개 변수 제공)
  • 선택적으로 제외 배열에 제공된 디렉토리를 생략합니다

-

# 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()

확인하십시오 저작권 헤더 루그 름. 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 인수를 사용하여 사용자 정의 라이센스 파일을 지원합니다.

다음은 파일 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  

편집 : Eclipse를 사용하는 경우 있습니다 플러그인

나는 Silver Dragon의 답변을 바탕으로 간단한 Python 스크립트를 썼습니다. 더 유연한 솔루션이 필요했기 때문에 이것을 생각해 냈습니다. 디렉토리의 모든 파일에 헤더 파일을 재귀 적으로 추가 할 수 있습니다. 선택적으로 파일 이름이 일치 해야하는 Regex를 추가 할 수 있으며 디렉토리 이름이 일치 해야하는 정규식 및 파일의 첫 번째 줄이 일치하지 않아야 할 정전선을 추가 할 수 있습니다. 이 마지막 인수를 사용하여 헤더가 이미 포함되어 있는지 확인할 수 있습니다.

이 스크립트는 Shebang (#!)으로 시작하면 파일의 첫 번째 줄을 자동으로 건너 뜁니다. 이것은 이것에 의존하는 다른 스크립트를 깨뜨리지 않습니다. 이 동작을 원하지 않으면 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()

확인 폴더에서 지정된 유형의 모든 파일을 검색하고 원하는 텍스트를 상단 (라이센스 텍스트)에 선출하고 결과를 다른 디렉토리에 복사하는 간단한 Windows 전용 UI 도구가 있습니다 (잠재적 인복 문제 방지). . 또한 무료입니다. 필수 .NET 4.0.

저는 실제로 저자이므로 자유롭게 수정 또는 새로운 기능을 요청하십시오. 배송 일정에 대한 약속은 없습니다. ;)

더 많은 정보: 라이센스 헤더 도구 ~에 Amazify.com

라이센스 어드먼트를 확인하십시오. 여러 코드 파일 (사용자 정의 파일)을 지원하고 기존 헤더를 올바르게 처리합니다. 이미 가장 일반적인 오픈 소스 라이센스를위한 템플릿과 함께 제공됩니다.

여기 하나가 있습니다 아파치 목록에서 찾았습니다. 루비로 작성되었으며 읽기에 충분히 쉬워 보입니다. 당신은 더 특별한 냉담함을 위해 레이크에서 그것을 부를 수 있어야합니다. :)

다음은 PHP 파일을 수정하기 위해 PHP로 롤 한 것이 있습니다. 또한 이전 텍스트를 먼저 대체 한 다음 오프닝 직후 새 텍스트를 추가 할 이전 라이센스 정보가 삭제되었습니다.

<?php
class Licenses
{
    protected $paths = array();
    protected $oldTxt = '/**
 * Old license to delete
 */';
    protected $newTxt = '/**
 * @license    http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
 */';

    function licensesForDir($path)
    {
        foreach(glob($path.'/*') as $eachPath)
        {
            if(is_dir($eachPath))
            {
                $this->licensesForDir($eachPath);
            }
            if(preg_match('#\.php#',$eachPath))
            {
                $this->paths[] = $eachPath;
            }
        }
    }

    function exec()
    {

        $this->licensesForDir('.');
        foreach($this->paths as $path)
        {
            $this->handleFile($path);
        }
    }

    function handleFile($path)
    {
        $source = file_get_contents($path);
        $source = str_replace($this->oldTxt, '', $source);
        $source = preg_replace('#\<\?php#',"<?php\n".$this->newTxt,$source,1);
        file_put_contents($path,$source);
        echo $path."\n";
    }
}

$licenses = new Licenses;
$licenses->exec();

아직도 필요한 경우 내가 쓴 작은 도구가 있습니다. Srchead. 당신은 그것을 찾을 수 있습니다 http://www.solvasoft.nl/downloads.html

SBT를 사용하는 경우 있습니다 https://github.com/banno/sbt-license-plugin

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top