Skip to content

Commit

Permalink
仅当文件有修改时才更新copyright year信息
Browse files Browse the repository at this point in the history
  • Loading branch information
BernardXiong authored and mysterywolf committed Jun 6, 2023
1 parent 77b7265 commit 767762c
Showing 1 changed file with 41 additions and 8 deletions.
49 changes: 41 additions & 8 deletions formatting.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
# 2021-06-07 iysheng Add support with format single file and parse command line parameters
# 2021-08-24 陈迎春 解决格式化脚本需要和被格式化文件放在同一个磁盘的问题
# 2021-08-29 Meco Man 优化文件后缀名的判断
# 2023-04-24 BernardXiong 仅当文件有修改时才更新copyright year信息

# 本文件会自动对指定路径下的所有文件包括子文件夹的文件(.c/.h/.cpp/.hpp)进行扫描
# 1)将源文件编码统一为UTF-8
Expand All @@ -31,6 +32,7 @@
import re
import chardet
import datetime
import filecmp

# 用空格代替TAB键
# 这里并不是简单的将TAB替换成4个空格
Expand Down Expand Up @@ -80,6 +82,35 @@ def change_realthread_copyright_year(line):
line = line.replace(line[end-4:end], str_year)# 将20xx替换为今年
return line

def format_copyright_year(filename):
try:
file = open(filename, 'r', encoding = 'utf-8')

temp_file = os.path.join(os.path.dirname(filename), "temp")
file_temp = open(temp_file, 'w', encoding='utf-8')

line_num = 0
for line in file:
line_num = line_num + 1
if line_num < 20: #文件前20行对版权头注释进行扫描,找到截至年份并修改至今年
line = change_rtthread_copyright_year(line)
line = change_realthread_copyright_year(line)

file_temp.write(line)
file_temp.close()
file.close()
os.remove(filename)
os.rename(temp_file, filename)

except UnicodeDecodeError:
print("解码失败,该文件处理失败" + filename)
file_temp.close()
file.close()
except UnicodeEncodeError:
print("编码失败,该文件处理失败" + filename)
file_temp.close()
file.close()

# 对单个文件进行格式整理
def format_codes(filename):
try:
Expand All @@ -88,21 +119,23 @@ def format_codes(filename):
temp_file = filepath + "temp"
file = open(filename, 'r', encoding='utf-8')
file_temp = open(temp_file, 'w', encoding='utf-8')
line_num = 0

for line in file:
line = tab2spaces(line)
line = formattail(line)

line_num = line_num + 1
if line_num < 20: #文件前20行对版权头注释进行扫描,找到截至年份并修改至今年
line = change_rtthread_copyright_year(line)
line = change_realthread_copyright_year(line)

file_temp.write(line)
file_temp.close()
file.close()
os.remove(filename)
os.rename(temp_file, filename)

if filecmp.cmp(filename, temp_file):
os.remove(temp_file) # same file, no modification
else:
os.remove(filename)
os.rename(temp_file, filename)

format_copyright_year(filename) # re-format for copyright year information

except UnicodeDecodeError:
print("解码失败,该文件处理失败" + filename)
file_temp.close()
Expand Down

0 comments on commit 767762c

Please sign in to comment.