Skip to content

Commit 7ef4b41

Browse files
Jack AdamJack Adam
authored andcommitted
finally commented my code lol
1 parent 213ed7e commit 7ef4b41

File tree

5 files changed

+59
-17
lines changed

5 files changed

+59
-17
lines changed

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,5 +32,5 @@ Wrote file2-clean.css
3232
TODO:
3333

3434
0. thoroughly edgecase re-writing stage
35-
1. fix comments disappearing in media queries?
36-
2. comment your code, dummy
35+
1. something is wrong with cleaning multiple files
36+
2. fix comments disappearing in media queries?

cleaner.py

Lines changed: 22 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,62 +2,74 @@
22

33
def clean(u, fn, fc):
44
nums, numItems = [], []
5+
# pre-populate arrays
56
for _ in range(fc):
67
nums.append({})
78
numItems.append(0)
89

10+
# extract line numbers, filenames
911
for key, value in u.items():
10-
x, y = key.split(), value.split()[2:]
11-
rule = x[0]
12-
ind = fn.index(x[2])
13-
for i in range(len(y)):
14-
if y[i][-1:] == ',':
15-
nums[ind][int(y[i][:-1])] = rule
16-
else:
17-
nums[ind][int(y[i])] = rule
12+
k, v = key.split(), value.split()[2:]
13+
rule = k[0]
14+
ind = fn.index(k[2])
15+
# for each line number
16+
for i in range(len(v)):
17+
nums[ind][int(comma(v[i]))] = rule
1818
numItems[ind] += 1
1919

20+
# for each file
2021
for i in range(fc):
22+
# sort by line number
2123
nums[i] = sorted(nums[i].items())
22-
index = 0
23-
file = fn[i]
24+
index, file = 0, fn[i]
2425
with open(file) as f:
2526
new = file[:-4] + '-clean.css'
2627
print(f'Wrote {new}')
2728

29+
# open new file to write
2830
with open(new, 'w') as newF:
2931
soloFlag, mediaFlag, multiFlag, newline = False, False, False, False
3032
for num, line in enumerate(f, 1):
33+
# if haven't yet removed all items
3134
if index < numItems[i]:
35+
# if line has an unused rule
3236
if num == nums[i][index][0]:
3337
x = solo(line)
3438
soloFlag = x
3539
multiFlag = not(x)
40+
# if multiple rules
3641
if multiFlag:
3742
l = line.split()
3843
ll = len(l)
3944
for word in l:
45+
# remove unused rules
4046
if comma(word) == nums[i][index][1] or word == nums[i][index][1]:
4147
l.remove(word)
4248
ll = len(l)
49+
# adjust commas based on presence of opening brace
4350
if l[ll - 1] == '{':
4451
l[ll - 2] = comma(l[ll - 2])
4552
else:
4653
l[ll - 1] = comma(l[ll - 1])
4754
line = ' '.join(l) + '\n'
4855
index += 1
4956
multiFlag = False
57+
# if media query opening
5058
if line[:6] == '@media':
5159
mediaFlag = True
60+
# if one rule
5261
if soloFlag:
5362
for c in line:
63+
# ignore until rule closes
5464
if c == '}':
5565
soloFlag = False
5666
index += 1
5767
elif not soloFlag:
68+
# add newlines, but never more than 1
5869
if not newline or line != '\n':
5970
newF.write(line)
6071
newline = True if line == '\n' else False
72+
# bandage, add closing brace to media query
6173
if mediaFlag:
6274
newF.write('}')
6375
newF.close()

helper.py

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,22 @@
11
from os import path
22
from re import match
33

4+
# obtain filepath/name to .css and .html files
45
def intro(hc):
56
filepath, ext = '', '',
67
end = -5 if hc == 'html' else -4
78

89
count = input('Do you have more than 1 .' + hc + ' file? (yes/no): ')
910

11+
# find all files in directory
1012
if count.lower() in ('yes', 'y'):
1113
filepath = input('Path to directory (blank if PWD): ')
1214
ext = '*.' + hc
1315
if filepath != '':
1416
if not path.isdir(filepath):
1517
exit('Invalid path')
1618

19+
# find 1 file
1720
elif count.lower() in ('no', 'n'):
1821
filepath = input('Path to .' + hc + ' file: ')
1922
if filepath[end:] != '.' + hc:
@@ -23,11 +26,9 @@ def intro(hc):
2326
else:
2427
exit('Invalid response')
2528

26-
if filepath[-1:] == '/' or filepath == '':
27-
return filepath + '*.' + hc
28-
else:
29-
return filepath
29+
return filepath + '*.' + hc if filepath[-1:] == '/' or filepath == '' else filepath
3030

31+
# remove duplicates from dictionary
3132
def remove_dups(d):
3233
r, l = {}, 0
3334
for k, v in d.items():
@@ -36,27 +37,34 @@ def remove_dups(d):
3637
l += 1
3738
return (r, l)
3839

40+
# determine if line has one or multiple rules
3941
def solo(line):
4042
pattern = '(\.|\#)-?[_a-zA-Z]+[_a-zA-Z0-9-]*'
4143
flag, found, count = False, '', 0
4244
for c in line:
45+
# found a rule
4346
if c == '.' or c == '#':
4447
flag = True
48+
# nevermind, start over
4549
if c == ';':
4650
flag = False
4751
found = ''
52+
# reached the end of a rule
4853
if c == '{' or c == ',':
4954
if len(found) > 0:
5055
if match(pattern, found):
5156
count += 1
5257
if flag:
5358
found += c
59+
# single rule
5460
if count == 0 or count == 1:
5561
if match(pattern, found):
5662
count += 1
5763
return True
64+
# multiple rules
5865
elif count > 1:
5966
return False
6067

68+
# removes comma if last character of string
6169
def comma(w):
6270
return w[:-1] if w[-1:] == ',' else w

main.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,17 +3,20 @@
33
from sys import exit
44

55
def main():
6+
# parse the files
67
c = parse_css()
78
h = parse_html()
89
unused, fileNames, css, fileCount = {}, [], [], 0
910

11+
# identify unused classes
1012
for cla, num in c[0][0].items():
1113
x = cla.split()
1214
if ':' not in x[0]:
1315
css.append(x[0])
1416
if x[0] not in h[0][0]:
1517
unused[cla] = num
1618

19+
# identify unused IDs
1720
for ID, num in c[1][0].items():
1821
y = ID.split()
1922
if ':' not in y[0]:
@@ -23,6 +26,7 @@ def main():
2326

2427
print(f'\nIdentified {c[0][1]} unique classes and {c[1][1]} unique IDs.\n')
2528

29+
# identify undefined classes and IDs
2630
for d in h:
2731
for dd in d:
2832
for rule, num in dd.items():
@@ -33,6 +37,7 @@ def main():
3337

3438
final = dict(unused)
3539

40+
# identify pseudoclasses
3641
for rule, num in unused.items():
3742
z = rule.split()
3843
if z[2] not in fileNames:

parser.py

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,34 +4,44 @@
44
from re import match
55

66
def parse_css():
7+
# obtain filename/path
78
filepath = intro('css')
89
classes, ids, found, flag = {}, {}, '', False
910

11+
# read each file
1012
for file in glob(filepath):
1113
with open(file) as f:
1214
print(f'Read {file}')
1315

1416
for num, line in enumerate(f, 1):
1517
for c in line:
18+
# found a rule
1619
if c == '.' or c == '#':
1720
flag = True
21+
# nevermind
1822
if c == ';':
1923
flag = False
2024
found = ''
25+
# rule is ending
2126
if c == '{' or c == ',':
2227
if len(found) > 0:
2328
found = found.strip()
29+
# check for invalid chars
2430
if match('(\.|\#)-?[_a-zA-Z]+[_a-zA-Z0-9-]*', found):
2531
found += ' : ' + file
32+
# if brace on own line, rule is on line before
2633
if line == '{\n':
2734
num -= 1
2835
sNum = str(num)
36+
# found a class
2937
if found[0] == '.':
3038
if found in classes:
39+
# avoid multiple occurrences on same line
3140
if sNum not in classes[found]:
3241
classes[found] += ', ' + sNum
3342
else:
3443
classes[found] = ', line ' + sNum
44+
# found an ID
3545
elif found[0] == '#':
3646
if found in ids:
3747
if sNum not in ids[found]:
@@ -49,27 +59,34 @@ def parse_css():
4959
return (remove_dups(classes), remove_dups(ids))
5060

5161
def parse_html():
62+
# obtain filename/path
5263
filepath = intro('html')
5364
cl, id, fc = [], [], 0
5465

66+
# read each file
5567
for file in glob(filepath):
5668
with open(file) as f:
5769
print(f'Read {file}')
70+
# append a dict for each file
5871
cl.append({})
5972
id.append({})
6073

6174
for num, line in enumerate(f, 1):
75+
# split line into words
6276
words = line.split()
6377
for piece in words:
6478
found, start = '', None
79+
# found an ID
6580
if piece[:2] == 'id':
6681
start, found = 4, '#'
82+
# found a class
6783
elif piece[:5] == 'class':
6884
start, found = 7, '.'
69-
if start != None:
85+
if start:
7086
for char in piece[start:]:
7187
if char != "'" and char != '"':
7288
found += char
89+
# at end of rule name
7390
else:
7491
if start == 4:
7592
id[fc][found] = file

0 commit comments

Comments
 (0)