1
+ from cfbs .pretty import pretty_file
1
2
import markdown_it
2
3
import os
3
4
import argparse
@@ -63,7 +64,7 @@ def extract(path, i, language, first_line, last_line):
63
64
with open (path , "r" ) as f :
64
65
content = f .read ()
65
66
66
- code_snippet = "\n " .join (content .split ("\n " )[first_line + 1 : last_line - 1 ])
67
+ code_snippet = "\n " .join (content .split ("\n " )[first_line + 1 : last_line - 1 ])
67
68
68
69
with open (f"{ path } .snippet-{ i } .{ language } " , "w" ) as f :
69
70
f .write (code_snippet )
@@ -81,8 +82,30 @@ def replace():
81
82
pass
82
83
83
84
84
- def autoformat ():
85
- pass
85
+ def autoformat (path , i , language , first_line , last_line ):
86
+
87
+ match language :
88
+ case "json" :
89
+ file_name = f"{ path } .snippet-{ i } .{ language } "
90
+
91
+ try :
92
+ pretty_file (file_name )
93
+ with open (file_name , "r" ) as f :
94
+ pretty_content = f .read ()
95
+ except :
96
+ print (
97
+ f"[error] Couldn't find the file '{ file_name } '. Run --extract to extract the inline code."
98
+ )
99
+ return
100
+
101
+ with open (path , "r" ) as f :
102
+ origin_content = f .read ()
103
+
104
+ lines = origin_content .split ("\n " )
105
+ lines [first_line + 1 : last_line - 1 ] = pretty_content .split ("\n " )
106
+
107
+ with open (path , "w" ) as f :
108
+ f .write ("\n " .join (lines ))
86
109
87
110
88
111
def parse_args ():
@@ -171,7 +194,13 @@ def parse_args():
171
194
check_syntax ()
172
195
173
196
if args .autoformat and "noautoformat" not in code_block ["flags" ]:
174
- autoformat ()
197
+ autoformat (
198
+ path ,
199
+ i + 1 ,
200
+ supported_languages [code_block ["language" ]],
201
+ code_block ["first_line" ],
202
+ code_block ["last_line" ],
203
+ )
175
204
176
205
if args .replace and "noreplace" not in code_block ["flags" ]:
177
206
replace ()
0 commit comments