-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser.py
executable file
·412 lines (325 loc) · 16.8 KB
/
parser.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
#!/usr/bin/env python3
'''
OCDcommenter: A program to ensure code aesthetic.
Copyright (C) 2017 Gonzalo Ruiz aka RGON.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
'''
############################################################
# #
# IMPORTS #
# #
############################################################
# Division required to perform ceil() and floor() with precision, and not just clip/round the values, which might lead to uneven line lengths.
from __future__ import print_function, division # Only needed for Python 2
import os, sys # argv
import math # ceil() and floor()
import shutil # copy(i, o): preserve the backup file's mode and ownership.
# This will replace the two following blocks in the next version.
#from __init__ import *
############################################################
# #
# Program options. Feel free to modify them. #
# #
############################################################
commentStartColumn = 80 # Ideally a multiple of 4.
castleSize = 60
slcommentchar = "//" # The character that denotes a single line comment.
slcharByLang = {
"python": "#",
"javascript": "//",
"c": "//",
"cpp": "//",
"c++": "//",
"objective-c": "//",
"c#": "//"
}
langByExtension = {
"py": "python",
"js": "javascript",
"c": "c",
"cpp": "cpp",
"m": "objective-c",
"c#": "cs"
}
disableKeywords = ""
castlekeyWords = ""
wallphrase = ""
fortphrase = ""
paddedCastles = True
reduceCastleSizeWithIndentation = True
minimumCastleSize = 40
commentStartColumn -= 1 # Columns start at 1, the program starts at 0.
############################################################
# #
# Internal utilities. #
# #
############################################################
# Ready for parsing non-pythonic languages.
def getIndentation(string): # AKA Get indentation.
firstActualChar = 0
for character in range(1, len(string)):
if(string[:character].strip() != ""): # If all the following chars are spaces/padding, that's the last char.
firstActualChar = character
break
return string[:firstActualChar-1]
# Ready for parsing non-pythonic languages.
def stripRight(string):
lastActualChar = 0
for character in range(0, len(string)):
if(string[character:].strip() == ""): # If all the following chars are spaces/padding, that's the last char.
lastActualChar = character
break
return string[:lastActualChar]
def guessLang(fname):
fname = fname.split(".")
fname = fname[len(fname) -1]
print("File extension: '{}'".format(fname))
lang = None
if(fname in langByExtension):
lang = langByExtension[fname]
while(lang not in slcharByLang):
lang = input("Language unknown. Choose one of the following:").lower()
print(slcharByLang.keys())
print("Processing for language '{}'".format(lang))
updateSLchar(slcharByLang[lang])
def updateSLchar(_slcommentchar):
global slcommentchar
global disableKeywords, castlekeyWords, wallphrase, fortphrase
slcommentchar = _slcommentchar
disableKeywords = [slcommentchar + " OCD Disabled", slcommentchar + " OCD Enabled"]
castlekeyWords = [slcommentchar + " ocdcastle", slcommentchar + " !ocdcastle"]
wallphrase = slcommentchar + " ocdwall"
fortphrase = slcommentchar + " ocdfort "
############################################################
# #
# Internal functions. #
# #
############################################################
# Ready for parsing non-pythonic languages.
def analyzeCommentLine(line, startPos):
# If the text inside the line (without taking into account the comment itself) isn't longer than the column where the comment should start.
lineWithoutComment = line[:startPos]
lineWithoutComment = stripRight(lineWithoutComment)
comment = line[startPos:]
idealStart = commentStartColumn
if(len(lineWithoutComment) > commentStartColumn):
idealStart = len(lineWithoutComment) + 4
padding = idealStart - len(lineWithoutComment)
return lineWithoutComment + (" "*padding) + comment
# Ready for parsing non-pythonic languages.
def getModdedLine(line):
commentCharsFound = 0
for character in range(0, len(line)):
if(character+len(slcommentchar) > len(line)): # End of the line. Cannot seek past it.
continue
if (line[character:character+len(slcommentchar)] == slcommentchar): # When a # is found.
if(not (line[character-len(slcommentchar)] == "\\" and line[character-len(slcommentchar)-1] != "\\")): # If it isn't escaped.
if((commentCharsFound % 2) == 0): # If it isn't inside quotes.
if(character < len(line)-1): # Also, if it isn't the last character, and there's a comment.
line = analyzeCommentLine(line, character)
break # Comment found. Stop searching this line's chars.
# endif
# endif
# endif
elif(line[character] == "'" or line[character] == '"'):
if(not (line[character-1] == "\\" and line[character-2] != "\\")): # If it isn't escaped.
commentCharsFound += 1
# endfor
return line
# Ready for parsing non-pythonic languages.
def castleBuilder(line):
global castleSize
strippedLine = line.strip()
indentation = getIndentation(line)
actualCastleSize = castleSize
if (reduceCastleSizeWithIndentation):
actualCastleSize = castleSize - len(indentation)
if(actualCastleSize < minimumCastleSize):
actualCastleSize = minimumCastleSize
if(strippedLine == castlekeyWords[0] or strippedLine == castlekeyWords[1]):
if(paddedCastles):
line = line.replace(
castlekeyWords[0],
slcommentchar*int(actualCastleSize/len(slcommentchar)) + "\n" + indentation + slcommentchar + " "*int(actualCastleSize - len(slcommentchar)*2) + slcommentchar).replace(
castlekeyWords[1],
slcommentchar + " "*int(actualCastleSize - len(slcommentchar)*2) + slcommentchar + "\n" + indentation + slcommentchar*int(actualCastleSize/len(slcommentchar)))
else:
line = line.replace(
castlekeyWords[0],
slcommentchar*int(actualCastleSize/len(slcommentchar))).replace(
castlekeyWords[1],
slcommentchar*int(actualCastleSize/len(slcommentchar)))
return line
else:
# Remove any SLChar characters that might be left over in the start/end.
line = line.strip()
if(line[0:len(slcommentchar)] == slcommentchar):
line = line[len(slcommentchar):]
if(line[len(line)-len(slcommentchar):len(line)] == slcommentchar):
line = line[:len(line)-len(slcommentchar)]
line = line.strip()
spacesToAdd = actualCastleSize - len(line) - (len(slcommentchar)*2) # mind the slcommentchars
if(spacesToAdd <= 0):
spacesToAdd = 2
spacesToAdd /= 2
# Int required in python2.
line = indentation + slcommentchar + " "*int(math.ceil(spacesToAdd)) + line + " "*int(math.floor(spacesToAdd)) + slcommentchar + "\n"
return line
# Ready for parsing non-pythonic languages.
def wallBuilder(line):
indentation = getIndentation(line)
strippedLine = line.strip()
actualCastleSize = castleSize
if (reduceCastleSizeWithIndentation):
actualCastleSize = castleSize - len(indentation)
if(actualCastleSize < minimumCastleSize):
actualCastleSize = minimumCastleSize
line = indentation + strippedLine.replace(wallphrase, slcommentchar*int(actualCastleSize/len(slcommentchar))) + "\n"
return line
def fortBuilder(line):
strippedLine = line.strip()[len(fortphrase):]
indentation = getIndentation(line)
strippedLine = " " + strippedLine + " "
actualCastleSize = castleSize
if (reduceCastleSizeWithIndentation):
actualCastleSize = castleSize - len(indentation)
charactersToAdd = actualCastleSize - len(strippedLine)
if(charactersToAdd <= 8):
charactersToAdd = 8
charactersToAdd /= 2
charactersToAdd /= len(slcommentchar)
line = indentation + slcommentchar*int(math.ceil(charactersToAdd)) + strippedLine + slcommentchar*int(math.floor(charactersToAdd)) + "\n"
return line
############################################################
# #
# Main program functionality. #
# #
############################################################
# Ready for parsing non-pythonic languages.
def ocdFile(_infile, _outfile):
_outfile = open(_outfile, 'w')
'''
try:
_outfile = open(_outfile, 'w')
except:
pass
'''
with open(_infile) as f:
print("Processing file.")
tempdisabled = False
buildcastle = False
for line in f.readlines():
line = line.replace("\t", " "*4) # Tab to spaces.
strippedLine = line.strip() # Remove indentation.
analyzeThisLine = True
if(not len(strippedLine)): # The line is empty. Avoid errors.
analyzeThisLine = False
else:
if(strippedLine[0:len(slcommentchar)] == slcommentchar): # If it isn't the first character in the line, aka the line isnt't a comment.
analyzeThisLine = False
if(not tempdisabled):
if(strippedLine == castlekeyWords[0]):
buildcastle = True
if(buildcastle):
line = castleBuilder(line) # Redefined
if(strippedLine == castlekeyWords[1]):
buildcastle = False
if(strippedLine == wallphrase):
line = wallBuilder(line) # Redefined
elif(strippedLine[:len(fortphrase)] == fortphrase):
line = fortBuilder(line)
if(strippedLine == disableKeywords[0]):
tempdisabled = True
elif(strippedLine == disableKeywords[1]):
tempdisabled = False
if(tempdisabled == True):
analyzeThisLine = False # Forcefully disabled.
if(analyzeThisLine):
line = getModdedLine(line)
print((line), file=_outfile, end="")
print("Done.")
# Ready for parsing non-pythonic languages.
def checkSyntax(_file): # Before letting castleBuilder break a file, check if there are any syntax errors and prevent that.
with open(_file) as f:
print("Checking file syntax.")
buildingcastle = False
lastOcurrence = None
for i, line in enumerate(f.readlines()):
strippedLine = line.strip() # Remove indentation.
line = strippedLine + getIndentation(line).replace("\t", " ") # Tab to spaces.
if(len(strippedLine)): # The line is empty. Avoid errors.
if(strippedLine[0:len(slcommentchar)] == slcommentchar): # If it isn't the first character in the line, aka the line isnt't a comment.
if(strippedLine == castlekeyWords[0]):
if(buildingcastle):
print("ERROR @ line {}: File contains an unclosed castle tag.".format(i+1))
print("Line content: {}".format(line.strip()))
print("Last ocdcastle tag found @ line {}".format(lastOcurrence))
print("\nQuitting right now.")
quit()
else:
buildingcastle = True
lastOcurrence = i
elif(strippedLine == castlekeyWords[1]):
if(buildingcastle):
buildingcastle = False
lastOcurrence = i
else:
print("ERROR @ line {}: File contains a closing castle tag, but no new castle has been started.".format(i+1))
print("Line content: {}".format(line.strip()))
print("Last ocdcastle tag found @ line {}".format(lastOcurrence))
print("\nQuitting right now.")
quit()
elif(strippedLine[ len(slcommentchar) : (len(slcommentchar)+len(wallphrase)) ] == wallphrase):
if(len(strippedLine[ len(wallphrase): ].strip()) > 0):
print("ERROR @ line {}: There's some content after an ocdwall tag. This text will removed. NOT CONTINUING.".format(i+1))
print("Line content: {}".format(line.strip()))
print("\nQuitting right now.")
quit()
else:
pass
if(buildingcastle):
print("ERROR: File contains an unclosed castle tag.")
print("Last ocdcastle tag found @ line {}".format(lastOcurrence))
print("\nQuitting right now.")
quit()
print("File contains no improperly placed tags.")
# Not checking for "OCD-Disabling" tags, as they're harmless.
'''
if(strippedLine == disableKeywords[0]):
tempdisabled = True
elif(strippedLine == disableKeywords[1]):
tempdisabled = False
'''
# Ready for parsing non-pythonic languages.
def processFile(fname):
guessLang(fname)
checkSyntax(fname)
backupFileName = os.path.join( os.path.dirname(fname), "." + os.path.basename(fname) + ".bak")
print("Backing up original file.")
shutil.copy(fname, backupFileName)
ocdFile(backupFileName, fname) # Read the backed up file, edit the actual file. This maintains the file's permissions.
############################################################
# Ready for parsing non-pythonic languages.
if(__name__ == "__main__"):
arguments = sys.argv
########################################################
# #
# Precarious UI. #
# #
########################################################
print()
if(len(arguments) == 2):
fname = arguments[1]
else:
fname = input("Drop your file here -> ").strip().replace("'", "").replace('"', "")
processFile(fname)
print()