go项目添加版权声明

Go addlicense添加版权声明

快速使用

1.项目添加LICENSE文件

1
2
3
4
5
6
7
8
go install github.com/nishanths/license/v5@latest

license -list # 查看支持的代码协议

license -n 'lxy911(李星云) <lxyaa911@gmail.com>' -o LICENSE mit
# 在项目根目录下执行
ls LICENSE
LICENSE

2.给源文件添加版本声明

版权头信息保存的文件名,通常命名为:boilerplate。

新建boilerplate.txt文件

1
2
3
4
Copyright 2025 lxy911(李星云) <lxyaa911@gmail.com>. All rights reserved.
Use of this source code is governed by a [MIT/Apache/BSD] style license
that can be found in the LICENSE file.
Project repository: https://github.com/zhian9/projectname
  1. 安装 addlicense 工具。

    1
    go install github.com/marmotedu/addlicense@latest
  2. 运行 addlicense 工具添加版权头信息。

    运行命令如下:

    1
    2
    3
    4
    addlicense -v -f ./boilerplate.txt --skip-dirs=third_party,vendor,_output .

    #验证是否生成
    cat main.go

1.使用 addlicense 工具自动化

安装 addlicense

1
2
3
4
5
# 安装 addlicense 工具
go install github.com/google/addlicense@latest

# 或者使用 go get
go get -u github.com/google/addlicense

基本使用

1
2
3
4
5
6
7
8
9
10
11
# 为单个文件添加版权声明
addlicense -c "Your Company Name" main.go

# 为整个目录添加版权声明
addlicense -c "Your Company Name" .

# 指定年份
addlicense -c "Your Company Name" -y 2024 .

# 使用自定义许可证模板
addlicense -c "Your Company Name" -l mit .

在项目中批量添加

1
2
3
4
5
6
7
8
# 为所有 .go 文件添加版权声明
addlicense -c "Your Company Name" -y 2024 **/*.go

# 排除某些目录
addlicense -c "Your Company Name" -ignore "**/vendor/**" .

# 检查哪些文件缺少版权声明
addlicense -check -c "Your Company Name" .

2. 创建自定义脚本

Bash 脚本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#!/bin/bash
# add_copyright.sh

COPYRIGHT_HOLDER="Your Company Name"
YEAR=$(date +%Y)

# 版权声明模板
read -r -d '' COPYRIGHT_TEMPLATE << EOM
/*
* Copyright (c) $YEAR $COPYRIGHT_HOLDER. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
EOM

# 为所有 .go 文件添加版权声明
find . -name "*.go" -type f | while read file; do
# 检查是否已经有版权声明
if ! head -n 5 "$file" | grep -q "Copyright"; then
# 添加构建约束检查
if head -n 1 "$file" | grep -q "^//go:build"; then
# 如果有构建约束,在第二行插入版权声明
tmpfile=$(mktemp)
head -n 1 "$file" > "$tmpfile"
echo "$COPYRIGHT_TEMPLATE" >> "$tmpfile"
tail -n +2 "$file" >> "$tmpfile"
mv "$tmpfile" "$file"
else
# 普通文件,直接在最前面添加
tmpfile=$(mktemp)
echo "$COPYRIGHT_TEMPLATE" > "$tmpfile"
cat "$file" >> "$tmpfile"
mv "$tmpfile" "$file"
fi
echo "Added copyright to $file"
fi
done

Go 脚本实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// tools/copyright/add_copyright.go
package main

import (
"bufio"
"fmt"
"os"
"path/filepath"
"strings"
"time"
)

const copyrightTemplate = `/*
* Copyright (c) %d %s. All rights reserved.
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file.
*/
`

func main() {
copyrightHolder := "Your Company Name"
year := time.Now().Year()

copyrightHeader := fmt.Sprintf(copyrightTemplate, year, copyrightHolder)

err := filepath.Walk(".", func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}

// 只处理 .go 文件
if !info.IsDir() && strings.HasSuffix(path, ".go") {
// 跳过 vendor 目录
if strings.Contains(path, "vendor/") {
return nil
}

if err := addCopyrightToFile(path, copyrightHeader); err != nil {
fmt.Printf("Error processing %s: %v\n", path, err)
}
}

return nil
})

if err != nil {
fmt.Printf("Error walking directory: %v\n", err)
os.Exit(1)
}
}

func addCopyrightToFile(filename, copyrightHeader string) error {
content, err := os.ReadFile(filename)
if err != nil {
return err
}

fileContent := string(content)

// 检查是否已经有版权声明
if strings.Contains(fileContent, "Copyright") {
fmt.Printf("Skipping %s (already has copyright)\n", filename)
return nil
}

var newContent strings.Builder

// 处理构建约束
lines := strings.Split(fileContent, "\n")
if len(lines) > 0 && strings.HasPrefix(lines[0], "//go:build") {
newContent.WriteString(lines[0] + "\n")
newContent.WriteString(copyrightHeader + "\n")
newContent.WriteString(strings.Join(lines[1:], "\n"))
} else {
newContent.WriteString(copyrightHeader + "\n\n")
newContent.WriteString(fileContent)
}

return os.WriteFile(filename, []byte(newContent.String()), 0644)
}

4. 使用 Makefile 集成

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# Makefile
COPYRIGHT_HOLDER = "Your Company Name"

.PHONY: copyright
copyright:
@echo "Adding copyright notices..."
@addlicense -c $(COPYRIGHT_HOLDER) -y 2024 .

.PHONY: copyright-check
copyright-check:
@echo "Checking copyright notices..."
@addlicense -check -c $(COPYRIGHT_HOLDER) .

.PHONY: copyright-fix
copyright-fix:
@echo "Fixing copyright notices..."
@go run tools/copyright/add_copyright.go

.PHONY: build
build: copyright-check
@go build -o bin/app ./cmd/app

.PHONY: test
test: copyright-check
@go test ./...

5. 在 CI/CD 中集成版权检查

GitHub Actions 示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# .github/workflows/copyright-check.yml
name: Copyright Check

on:
push:
branches: [ main, develop ]
pull_request:
branches: [ main ]

jobs:
copyright-check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3

- name: Set up Go
uses: actions/setup-go@v4
with:
go-version: '1.19'

- name: Install addlicense
run: go install github.com/google/addlicense@latest

- name: Check copyright headers
run: |
addlicense -check -c "Your Company Name" .

6. 不同许可证的版权声明模板

MIT 许可证

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/*
Copyright (c) 2024 Your Company Name.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

Apache 2.0 许可证

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/*
Copyright 2024 Your Company Name.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

BSD 3-Clause 许可证

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/*
Copyright (c) 2024, Your Company Name
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

7. 项目结构示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
myproject/
├── cmd/
│ └── app/
│ └── main.go
├── internal/
│ ├── handler/
│ │ └── user.go
│ └── service/
│ └── user.go
├── pkg/
│ └── utils/
│ └── string.go
├── tools/
│ └── copyright/
│ └── add_copyright.go
├── Makefile
├── LICENSE
└── go.mod

8. 最佳实践

  1. 一致性:在整个项目中保持版权声明格式一致
  2. 自动化:使用工具自动添加和检查版权声明
  3. CI 集成:在 CI 流水线中加入版权检查
  4. 许可证文件:在项目根目录包含完整的 LICENSE 文件
  5. 年份更新:定期更新版权年份
  6. 排除第三方代码:不要为 vendor 目录中的第三方代码添加版权声明

通过以上方法,你可以有效地为 Go 项目添加和管理版权声明,确保代码的合法性和专业性。

[up主专用,视频内嵌代码贴在这]