13
13
14
14
15
15
class InvalidSyntax (Exception ):
16
- """ Raise when the syntax of processed object is invalid. """
16
+ """Raise when the syntax of processed object is invalid."""
17
+
17
18
pass
18
19
19
20
20
21
class DocstringUnavailable (Exception ):
21
- """ Raise when trying to process object to which there is no docstring. """
22
+ """Raise when trying to process object to which there is no docstring."""
23
+
22
24
pass
23
25
24
26
25
27
class Templater :
26
- """ Class used to template the docstrings
28
+ """Class used to template the docstrings
27
29
28
30
Attributes:
29
31
indent: used indentation
@@ -33,36 +35,54 @@ class Templater:
33
35
34
36
"""
35
37
36
- def __init__ (self , location , indent , style = ' google' ):
38
+ def __init__ (self , location , indent , style = " google" ):
37
39
self .style = style
38
40
self .indent = indent
39
41
self .location = location
40
42
41
43
def _docstring_helper (self , obj_indent , docstring ):
42
44
lines = []
43
- for line in docstring .split (' \n ' ):
44
- if re .match ('.' , line ):
45
+ for line in docstring .split (" \n " ):
46
+ if re .match ("." , line ):
45
47
line = concat_ (obj_indent , self .indent , line )
46
48
lines .append (line )
47
49
48
- return '\n ' .join (lines )
49
-
50
- def get_method_docstring (self , method_indent , args , returns , yields , raises , print_hints = False ):
51
- with open (os .path .join (self .location , '..' , 'styles/{}-{}.txt' .format (self .style , 'method' )), 'r' ) as f :
50
+ return "\n " .join (lines )
51
+
52
+ def get_method_docstring (
53
+ self , method_indent , args , returns , yields , raises , print_hints = False
54
+ ):
55
+ with open (
56
+ os .path .join (
57
+ self .location , ".." , "styles/{}-{}.txt" .format (self .style , "method" )
58
+ ),
59
+ "r" ,
60
+ ) as f :
52
61
self .template = ibis .Template (f .read ())
53
- docstring = self .template .render (indent = self .indent , args = args , hints = print_hints ,
54
- raises = raises , returns = returns , yields = yields )
62
+ docstring = self .template .render (
63
+ indent = self .indent ,
64
+ args = args ,
65
+ hints = print_hints ,
66
+ raises = raises ,
67
+ returns = returns ,
68
+ yields = yields ,
69
+ )
55
70
return self ._docstring_helper (method_indent , docstring )
56
71
57
72
def get_class_docstring (self , class_indent , attr ):
58
- with open (os .path .join (self .location , '..' , 'styles/{}-{}.txt' .format (self .style , 'class' )), 'r' ) as f :
73
+ with open (
74
+ os .path .join (
75
+ self .location , ".." , "styles/{}-{}.txt" .format (self .style , "class" )
76
+ ),
77
+ "r" ,
78
+ ) as f :
59
79
self .template = ibis .Template (f .read ())
60
80
docstring = self .template .render (indent = self .indent , attr = attr )
61
81
return self ._docstring_helper (class_indent , docstring )
62
82
63
83
64
84
class ObjectWithDocstring (abc .ABC ):
65
- """ Represents an object (class, method) with the enviroment in which it is opened
85
+ """Represents an object (class, method) with the enviroment in which it is opened
66
86
67
87
Attributes:
68
88
env: enviroment class
@@ -78,7 +98,7 @@ def __init__(self, env, templater):
78
98
79
99
@abc .abstractmethod
80
100
def write_docstring (self , * args , ** kwargs ):
81
- """ Method to create a docstring for appropriate object
101
+ """Method to create a docstring for appropriate object
82
102
83
103
Writes the docstring to correct lines in `self.env` object.
84
104
"""
@@ -88,27 +108,27 @@ def _get_sig(self):
88
108
lines = []
89
109
lines_it = self .env .lines_following_cursor ()
90
110
sig_line , first_line = next (lines_it )
91
- indent = re .findall (r' ^(\s*)' , first_line )[0 ]
111
+ indent = re .findall (r" ^(\s*)" , first_line )[0 ]
92
112
93
113
lines .append (first_line )
94
114
95
- while not self ._is_valid ('' .join (lines )):
115
+ while not self ._is_valid ("" .join (lines )):
96
116
try :
97
117
sig_line , line = next (lines_it )
98
118
except StopIteration as e :
99
- raise InvalidSyntax (' Object does not have valid syntax' )
119
+ raise InvalidSyntax (" Object does not have valid syntax" )
100
120
lines .append (line )
101
121
return sig_line , indent
102
122
103
123
def _object_tree (self ):
104
- """ Get the source code of the object under cursor. """
124
+ """Get the source code of the object under cursor."""
105
125
lines = []
106
126
lines_it = self .env .lines_following_cursor ()
107
127
sig_line , first_line = next (lines_it )
108
128
109
129
lines .append (first_line )
110
130
111
- obj_indent = re .findall (r' ^(\s*)' , first_line )[0 ]
131
+ obj_indent = re .findall (r" ^(\s*)" , first_line )[0 ]
112
132
expected_indent = concat_ (obj_indent , self .env .python_indent )
113
133
114
134
valid_sig , _ = self ._is_valid (first_line )
@@ -119,69 +139,70 @@ def _object_tree(self):
119
139
except Exception as e :
120
140
break
121
141
122
- if valid_sig and not self ._is_correct_indent (lines [- 1 ], line , expected_indent ):
142
+ if valid_sig and not self ._is_correct_indent (
143
+ lines [- 1 ], line , expected_indent
144
+ ):
123
145
break
124
146
125
147
lines .append (line )
126
148
if not valid_sig :
127
- data = '' .join (lines )
149
+ data = "" .join (lines )
128
150
valid_sig , _ = self ._is_valid (data )
129
151
sig_line = last_row
130
152
131
153
# remove obj_indent from the beginning of all lines
132
- lines = [re .sub ('^' + obj_indent , '' , l ) for l in lines ]
154
+ lines = [re .sub ("^" + obj_indent , "" , l ) for l in lines ]
133
155
for i , l in enumerate (reversed (lines )):
134
- if l .strip () == '' :
156
+ if l .strip () == "" :
135
157
lines .pop ()
136
158
else :
137
159
break
138
160
if len (lines ) == 1 :
139
- lines .append (f' { self .env .python_indent } pass' )
161
+ lines .append (f" { self .env .python_indent } pass" )
140
162
141
- data = ' \n ' .join (lines )
163
+ data = " \n " .join (lines )
142
164
try :
143
165
tree = ast .parse (data )
144
166
except Exception as e :
145
- raise InvalidSyntax (' Object has invalid syntax.' )
167
+ raise InvalidSyntax (" Object has invalid syntax." )
146
168
147
169
return sig_line , obj_indent , tree
148
170
149
171
def _is_correct_indent (self , previous_line , line , expected_indent ):
150
- """ Check whether given line has either given indentation (or more)
151
- or does contain only nothing or whitespaces.
172
+ """Check whether given line has either given indentation (or more)
173
+ or does contain only nothing or whitespaces.
152
174
"""
153
175
# Disclaimer: I know this does not check for multiline comments and strings
154
176
# strings ''' <newline> ...<newline>..''' are a problem !!!
155
- if re .match ('^' + expected_indent , line ):
177
+ if re .match ("^" + expected_indent , line ):
156
178
return True
157
- elif re .match (' ^\s*#' , line ):
179
+ elif re .match (" ^\s*#" , line ):
158
180
return True
159
- elif re .match (' ^\s*[" \ ' ]{3}' , line ):
181
+ elif re .match (" ^\s*[\" ']{3}" , line ):
160
182
return True
161
- elif re .match (' .*\\ $' , previous_line ):
183
+ elif re .match (" .*\\ $" , previous_line ):
162
184
return True
163
- elif re .match (' ^\s*$' , line ):
185
+ elif re .match (" ^\s*$" , line ):
164
186
return True
165
187
166
188
return False
167
189
168
190
def _is_valid (self , lines ):
169
- func = concat_ (lines .lstrip (), ' \n pass' )
191
+ func = concat_ (lines .lstrip (), " \n pass" )
170
192
try :
171
193
tree = ast .parse (func )
172
194
return True , tree
173
195
except SyntaxError as e :
174
196
return False , None
175
197
176
198
def write_simple_docstring (self ):
177
- """ Writes the generated docstring in the enviroment """
199
+ """Writes the generated docstring in the enviroment"""
178
200
sig_line , indent = self ._get_sig ()
179
201
docstring = concat_ (indent , self .templater .indent , '""" """' )
180
202
self .env .append_after_line (sig_line , docstring )
181
203
182
204
183
205
class MethodController (ObjectWithDocstring ):
184
-
185
206
def __init__ (self , env , templater ):
186
207
super ().__init__ (env , templater )
187
208
@@ -197,12 +218,12 @@ def write_docstring(self, print_hints=False):
197
218
sig_line , method_indent , tree = self ._object_tree ()
198
219
args , returns , yields , raises = self ._process_tree (tree )
199
220
docstring = self .templater .get_method_docstring (
200
- method_indent , args , returns , yields , raises , print_hints )
221
+ method_indent , args , returns , yields , raises , print_hints
222
+ )
201
223
self .env .append_after_line (sig_line , docstring )
202
224
203
225
204
226
class ClassController (ObjectWithDocstring ):
205
-
206
227
def __init__ (self , env , templater ):
207
228
super ().__init__ (env , templater )
208
229
@@ -222,7 +243,7 @@ def write_docstring(self, *args, **kwargs):
222
243
223
244
224
245
class Docstring :
225
- """ Class used by user to generate docstrings"""
246
+ """Class used by user to generate docstrings"""
226
247
227
248
def __init__ (self ):
228
249
env = VimEnviroment ()
@@ -235,32 +256,30 @@ def __init__(self):
235
256
236
257
def _controller_factory (self , env , templater ):
237
258
line = env .current_line
238
- first_word = re .match (r' ^\s*(\w+).*' , line ).groups ()[0 ]
239
- if first_word == ' def' :
259
+ first_word = re .match (r" ^\s*(\w+).*" , line ).groups ()[0 ]
260
+ if first_word == " def" :
240
261
return MethodController (env , templater )
241
- elif first_word == ' class' :
262
+ elif first_word == " class" :
242
263
return ClassController (env , templater )
243
- elif first_word == ' async' :
244
- second_word_catch = re .match (r' ^\s*\w+\s+(\w+).*' , line )
264
+ elif first_word == " async" :
265
+ second_word_catch = re .match (r" ^\s*\w+\s+(\w+).*" , line )
245
266
if second_word_catch :
246
267
second_word = second_word_catch .groups ()[0 ]
247
- if second_word == ' def' :
268
+ if second_word == " def" :
248
269
return MethodController (env , templater )
249
270
250
- raise DocstringUnavailable (
251
- 'Docstring cannot be created for selected object' )
271
+ raise DocstringUnavailable ("Docstring cannot be created for selected object" )
252
272
253
273
def full_docstring (self , print_hints = False ):
254
- """ Writes docstring containing arguments, returns, raises, ... """
274
+ """Writes docstring containing arguments, returns, raises, ..."""
255
275
try :
256
276
self .obj_controller .write_docstring (print_hints = print_hints )
257
277
except Exception as e :
258
- print (concat_ (' Doctring ERROR: ' , e ))
278
+ print (concat_ (" Doctring ERROR: " , e ))
259
279
260
280
def oneline_docstring (self ):
261
- """ Writes only a one-line empty docstring """
281
+ """Writes only a one-line empty docstring"""
262
282
try :
263
283
self .obj_controller .write_simple_docstring ()
264
284
except Exception as e :
265
- print (concat_ ('Doctring ERROR: ' , e ))
266
-
285
+ print (concat_ ("Doctring ERROR: " , e ))
0 commit comments