Cuando trabajas en un proyecto, necesitas analizar la cantidad de líneas de envío efectivas del código en git, es decir: la cantidad de líneas agregadas, líneas en blanco, líneas de comentarios. No encontré código de análisis que admita varios idiomas en Internet, así que escribí un fragmento de código y lo compartí.
El código recibe dos parámetros. El nombre del archivo cambiado por la ruta del archivo, el contenido cambiado del archivo (se puede ver a través de git diff {commit_id})
Características de este código:
- Juzgue el idioma contenido en el archivo por el sufijo filepath
- Obtenga el código enviado, la cantidad de adiciones y eliminaciones de comentarios y líneas en blanco en él
- Admite tipos de archivos, py, sh, java, rb, vue, html, js, xml, sql, css, etc.
- Si necesita admitir más análisis de código de idioma, simplemente agregue la clave correspondiente a los luanges, single representa un comentario de una sola línea y multi representa un comentario de varias líneas.
def get_commit_diff_comment_rows(filepath,diff):
endfix = filepath.split("/")[-1].split('.')[-1]
diff_rows = diff.split("\n")
if len(diff_rows) < 3:
return {}
luanges={
'py':{
'single':'#',
'multi_start':["'''",'"""'],
'multi_end':["'''",'"""']
},
'java':{
'single':'//',
'multi_start':["/*"],
'multi_end':["*/"],
},
'js':{
'single':'//',
'multi_start':["/*"],
'multi_end':["*/"],
},
'vue':{
'single':'//',
'multi_start':["<!--",'/*'],
'multi_end':["-->","*/"],
},
'html':{
'single':'//',
'multi_start':["<!--",'/*'],
'multi_end':["-->","*/"],
},
'jsx':{
'multi_start':["/*","{/*"],
'multi_end':["*/","*/}"],
},
'less':{
'single':'//',
'multi_start':["/*"],
'multi_end':["*/"],
},
'rb':{
'single':'#',
'multi_start':["=begin"],
'multi_end':["=end"],
},
'yml':{
'single':'#',
},
'xml':{
'multi_start':["<!--"],
'multi_end':["-->"],
},
'sql':{
'single':'--',
'multi_start':["/*"],
'multi_end':["*/"],
},
'sh':{
'single':'#',
},
'css':{
'multi_start':["/*"],
'multi_end':["*/"],
},
}
luange = luanges.get(endfix)
if not luange:
return {}
single_start = luange.get("single")
multi_start = luange.get("multi_start")
multi_end = luange.get("multi_end")
comment_add = 0
comment_del = 0
empty_add = 0
empty_del = 0
block_comment_flag=False #块注释默认为空
for row in diff_rows:
if row.startswith("---") or row.startswith("+++") or row.startswith("@@"):
continue
if row.startswith("+"):
node_type = '+'
elif row.startswith("-"):
node_type = '-'
else:
continue
row = row[1:].strip()
if row == '':
if node_type == '+':
empty_add += 1
elif node_type == '-':
empty_del += 1
else:
add_number = 0
if single_start:
if row.startswith(single_start):
add_number = 1
if multi_start:
for i in multi_start:
if row.startswith(i):
add_number = 1
block_comment_flag=True
if multi_end:
for i in multi_end:
if row.endswith(i):
add_number = 1
block_comment_flag=False
if block_comment_flag:
add_number = 1
if node_type == '+':
comment_add += add_number
elif node_type == '-':
comment_del += add_number
return {"comment_add":comment_add,
"comment_del":comment_del,
"empty_add":empty_add,
"empty_del":empty_del
}