|
2 | 2 |
|
3 | 3 | def clean(u, fn, fc): |
4 | 4 | nums, numItems = [], [] |
| 5 | + # pre-populate arrays |
5 | 6 | for _ in range(fc): |
6 | 7 | nums.append({}) |
7 | 8 | numItems.append(0) |
8 | 9 |
|
| 10 | + # extract line numbers, filenames |
9 | 11 | 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 |
18 | 18 | numItems[ind] += 1 |
19 | 19 |
|
| 20 | + # for each file |
20 | 21 | for i in range(fc): |
| 22 | + # sort by line number |
21 | 23 | nums[i] = sorted(nums[i].items()) |
22 | | - index = 0 |
23 | | - file = fn[i] |
| 24 | + index, file = 0, fn[i] |
24 | 25 | with open(file) as f: |
25 | 26 | new = file[:-4] + '-clean.css' |
26 | 27 | print(f'Wrote {new}') |
27 | 28 |
|
| 29 | + # open new file to write |
28 | 30 | with open(new, 'w') as newF: |
29 | 31 | soloFlag, mediaFlag, multiFlag, newline = False, False, False, False |
30 | 32 | for num, line in enumerate(f, 1): |
| 33 | + # if haven't yet removed all items |
31 | 34 | if index < numItems[i]: |
| 35 | + # if line has an unused rule |
32 | 36 | if num == nums[i][index][0]: |
33 | 37 | x = solo(line) |
34 | 38 | soloFlag = x |
35 | 39 | multiFlag = not(x) |
| 40 | + # if multiple rules |
36 | 41 | if multiFlag: |
37 | 42 | l = line.split() |
38 | 43 | ll = len(l) |
39 | 44 | for word in l: |
| 45 | + # remove unused rules |
40 | 46 | if comma(word) == nums[i][index][1] or word == nums[i][index][1]: |
41 | 47 | l.remove(word) |
42 | 48 | ll = len(l) |
| 49 | + # adjust commas based on presence of opening brace |
43 | 50 | if l[ll - 1] == '{': |
44 | 51 | l[ll - 2] = comma(l[ll - 2]) |
45 | 52 | else: |
46 | 53 | l[ll - 1] = comma(l[ll - 1]) |
47 | 54 | line = ' '.join(l) + '\n' |
48 | 55 | index += 1 |
49 | 56 | multiFlag = False |
| 57 | + # if media query opening |
50 | 58 | if line[:6] == '@media': |
51 | 59 | mediaFlag = True |
| 60 | + # if one rule |
52 | 61 | if soloFlag: |
53 | 62 | for c in line: |
| 63 | + # ignore until rule closes |
54 | 64 | if c == '}': |
55 | 65 | soloFlag = False |
56 | 66 | index += 1 |
57 | 67 | elif not soloFlag: |
| 68 | + # add newlines, but never more than 1 |
58 | 69 | if not newline or line != '\n': |
59 | 70 | newF.write(line) |
60 | 71 | newline = True if line == '\n' else False |
| 72 | + # bandage, add closing brace to media query |
61 | 73 | if mediaFlag: |
62 | 74 | newF.write('}') |
63 | 75 | newF.close() |
0 commit comments