Skip to main content

批量修改版权的python脚本

必须是python3

# coding=utf-8
import os
import re
import linecache

golicense = "--- \n" \
"----- \n"

pylicense = "--- \n" \
"----- \n"

mdlicense = "--- \n" \
"title: %s \n" \
"----- \n"

# 跳过以下文件或目录
blacklist = ["youdaonote-pull"]
# 只处理以下类型的文件
whitelist = [ ".md"]

def get_lisence(suffix):
lisence = ""
if suffix == ".go":
lisence = golicense
if suffix == ".py":
lisence = pylicense
if suffix == ".md":
lisence = mdlicense
return lisence


def gen(filepath):
for allow in whitelist:
idx = len(filepath) - len(allow)

print(filepath)
if idx <= 0 or filepath[idx:] != allow:
continue
# 清除头部信息
with open(filepath, "r+", encoding='utf-8') as f:
old = f.read()
f.seek(0)
lines = old.splitlines(keepends=True)
linecnt = 0
for idx, line in enumerate(lines):
if "-----" in line:
linecnt = idx + 1
break
lines = lines[linecnt:]
f.seek(0)
f.truncate()
for line in lines:
f.write(line)

# 生成头部信息
with open(filepath, "r+", encoding='utf-8') as f:
old = f.read()
f.seek(0)
l = re.search("^package\s([a-zA-Z0-9_]*)\s*$", old, flags=re.M)
filename = (filepath.split('.')[-2]).split('\\')[-1].split('/')[-1] # 文件名
if l != None: # go files
packagename = l.group(1)
f.write("// Package " + packagename + " .\n")
hard = get_lisence(allow)
hard = hard %(filename)
f.write(hard)
f.write(old)
return

def dirlist(path):
filelist = os.listdir(path)
for filename in filelist:
skip = False
for ignore in blacklist:
idx = len(filename) - len(ignore)
if idx >= 0 and filename[idx:] == ignore:
skip = True
continue
if skip:
continue
filepath = os.path.join(path, filename)
if os.path.isdir(filepath):
dirlist(filepath)
else:
gen(filepath)

def start():
dirlist("./")

if __name__ == "__main__":
start()