Last active
January 8, 2019 12:46
-
-
Save artragis/7da25205db5ea218ce0738b21a3c708b to your computer and use it in GitHub Desktop.
Détecteur de mauvaix titre pour big tuto
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from argparse import ArgumentParser | |
def warn_title(title, parents): | |
nb_of_sharp = title.count('#') | |
bias = min(len(parents), 3) | |
final_number = max(nb_of_sharp - len(parents) - bias, 1) | |
print('AVERTISSEMENT', title[min(len(parents) - 1, 3):], 'devrait être', '#' * (final_number), title.replace('#', '')) | |
def error_title(title, parents): | |
nb_of_sharp = title.count('#') | |
bias = min(len(parents), 3) | |
final_number = max(nb_of_sharp - len(parents) - bias, 1) | |
print('ERREUR ', title[3:], 'devrait être', '#' * (final_number), title.replace('#', '')) | |
def is_title(line): | |
return line.startswith('#') and line.replace('#', '').startswith(' ') | |
def get_title_level(line): | |
return line.index(' ') | |
def main(): | |
parser = ArgumentParser() | |
parser.add_argument('file', help='Chemin vers le fichier md') | |
parser.add_argument('-w', '--warn', action='store_true', dest='warn', default=False, help='Affiche les avertissements en plus des erreurs') | |
args = parser.parse_args() | |
with open(args.file) as f: | |
in_code = False | |
code_char = None | |
title_stack = [' '] | |
for line in f: | |
if line.startswith('```') or line.startswith('~~~'): | |
if code_char and line[:3] == code_char: | |
in_code = False | |
code_char = None | |
else: | |
in_code = True | |
code_char = code_char or line[:3] | |
if in_code: | |
continue | |
if is_title(line): | |
current_title_level = get_title_level(line.strip()) | |
if current_title_level > get_title_level(title_stack[-1]): | |
if current_title_level > 6: | |
print('/'.join(title_stack).replace('#', '')) | |
error_title(line, title_stack[1:]) | |
elif args.warn and current_title_level - get_title_level(title_stack[-1]) > 1: | |
print('/'.join(title_stack).replace('#', '')) | |
warn_title(line, title_stack[1:]) | |
title_stack.append(line) | |
else: | |
title_stack.append(line.strip()) | |
else: | |
while current_title_level <= get_title_level(title_stack[-1]): | |
title_stack = title_stack[:-1] | |
title_stack.append(line.strip()) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment