Skip to content

Commit 35d3758

Browse files
committed
minify and organize
1 parent f857b53 commit 35d3758

17 files changed

+193
-222
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
.vscode
22
.pytest_cache
33
test.py
4+
__pycache__

README.md

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,17 @@
1-
# Css Hashfy Converter
1+
# Css Hashfy Minify Converter
22

33
This is a python script to hashfy css classes.
44
It was inspired on Google's approach to minimize classes names to faster load web pages.
55

66
## What it does
77

88
- [x] Make a hash out of css and id classes
9+
- [x] Make a random hash each run
10+
- [x] Minify your css
911
- [x] Auto apply for all the html files
1012
- [x] Create `-hashed` file with the output
11-
- [x] Auto change the css file to `-hashed` in the html link tag
12-
- [x] Multiple files on multiple folders
13+
- [x] Auto change the css file names to `-hashed` in the html link tag
14+
- [x] Multiple files on multiple folders (top-down)
1315

1416
## Usage
1517

@@ -19,10 +21,14 @@ It will search all files with the extensions marked on the configuration file.
1921

2022
It will give the output with `foo-hashed.html` and `foo-hashed.css`.
2123

24+
2225
### Configure
2326

2427
Change in the [configuration file](/config.json) the directories to be ignored, hash length and overwrite files.
2528

26-
## To Change?
29+
**Mind that: if `overwrite` is `false` the hash will not be equal to the old files, therefore not in sync.**
30+
31+
## What to come
2732

28-
- [ ] Separation of classes and ids in prefix
33+
- [ ] Obfuscate everything?
34+
- [ ] How about js too?

config.json

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,15 +6,17 @@
66
"filesIgnore": [
77
"-hashed"
88
],
9-
"dirsIgnore":[
9+
"dirsIgnore": [
1010
".",
1111
"packages",
1212
"src",
1313
"dist"
1414
],
1515
"extCopy": "-hashed",
16-
"patternCSS": "[\\.\\#]-?[_a-zA-Z]+[_a-zA-Z0-9-]*\\s*\\{",
16+
"patternCSS": "[\\.\\#]-?([_a-zA-Z]+[_a-zA-Z0-9-]*)\\s*\\{",
1717
"patternHTML": "class[\t]*=[\t]*\"[^\"]+",
1818
"hashLength": 6,
19-
"overwriteFiles": false
19+
"overwriteFiles": false,
20+
"minimize": true,
21+
"output": true
2022
}

convert.py

Lines changed: 17 additions & 127 deletions
Original file line numberDiff line numberDiff line change
@@ -1,145 +1,35 @@
11
import os
2-
import json
3-
import re
4-
from os import listdir
5-
from os.path import isfile, join
2+
from functions import *
63

4+
config, _PATH = loadconfig()
75

8-
def read(file):
9-
with open(file, 'r') as f:
10-
lines = f.readlines()
11-
f.close()
12-
return lines
13-
14-
15-
def write(root, new_name, lines):
16-
with open(os.path.join(root, new_name), 'w') as exf:
17-
exf.writelines(lines)
18-
exf.close()
19-
20-
21-
def getVars(file, config):
22-
# Get the extension and use as a flag e.g.: HTML, CSS...
23-
pattern_file = file.split('.')[1].upper()
24-
25-
lines = read(file)
26-
27-
# Use the right regex to find the classes on the file
28-
substring = re.findall(config['pattern' + pattern_file], str(lines))
29-
30-
name, ext = file.split('.')
31-
new_name = name + config['extCopy'] + '.' + ext
32-
33-
return new_name, substring
6+
search_files = lookfiles()
347

358

369
def main():
37-
# Load config.json
38-
with open("config.json") as json_data_file:
39-
config = json.load(json_data_file)
40-
_PATH = os.getcwd() + '/'
41-
42-
search_files = []
43-
# Look for files
44-
for root, subdirectories, files in os.walk(_PATH):
45-
# Comprehension to break outter loop
46-
if any([dirsIgnore for dirsIgnore in config['dirsIgnore'] if dirsIgnore in root]):
47-
continue
10+
search_files = lookfiles()
4811

49-
# And all its files
50-
for index, file in enumerate(files):
51-
for filesSearch in config['filesSearch']:
52-
for filesIgnore in config['filesIgnore']:
53-
if(filesSearch in file and filesIgnore not in file):
54-
search_files.append((root, file))
12+
if(config['output']):
5513

56-
#print(f'files: {search_files}\n')
14+
#print(f'files: {search_files}\n')
5715

58-
print('CSS Hashfy found files:', end='\n\n')
59-
for root, file in search_files:
60-
print(os.path.join(root, file))
61-
print()
16+
print('CSS Hashfy found files:', end='\n\n')
17+
for root, file in search_files:
18+
print(os.path.join(root, file))
19+
print()
6220

63-
print('Starting hashing...', end='\n\n')
21+
print('Starting hashing...', end='\n\n')
6422

6523
# Initializing alg vars
66-
count = 0
67-
classes_dict = {}
68-
69-
# Get all the files with the '.css' extension
70-
css_files = [(root, file)
71-
for root, file in search_files if file.endswith('.css')]
72-
73-
# Copy the files of the search
74-
for root, file in css_files:
75-
lines = read(os.path.join(root, file))
76-
77-
new_name, substring = getVars(os.path.join(root, file), config)
78-
79-
# If the file doesn't exist, create a new one
80-
if(config['overwriteFiles'] or not isfile(join(root, new_name))):
81-
substring = [s.translate({ord('.'): None, ord(
82-
'{'): None, ord('#'): None}).strip() for s in substring]
83-
84-
# Create the dictionary with the classe's hashes of the CSS
85-
classes_dict.update(
86-
{s: str(abs(hash(s)) % (10 ** config['hashLength'])) for s in substring})
87-
88-
# CSS WRITE
89-
90-
# Copy the hashes to the copied lines of the file
91-
for index, l in enumerate(lines):
92-
for k, v in classes_dict.items():
93-
if k in l:
94-
l = l.replace(k, 'c'+v)
95-
lines[index] = l
96-
97-
write(root, new_name, lines)
98-
count += 1
99-
print(f"{10*'*'} \t {new_name.split('/')[-1]} \t {10*'*'}")
100-
101-
# If it exists, pass
102-
else:
103-
print(f'!! file already existed: {new_name}')
104-
105-
# Overwrite HTML classes
106-
html_files = [(root, file)
107-
for root, file in search_files if file.endswith('.html')]
108-
109-
# Copy the files of the search
110-
for root, file in html_files:
111-
lines = read(os.path.join(root, file))
112-
113-
new_name, substring = getVars(os.path.join(root, file), config)
114-
115-
# HTML WRITE
116-
117-
# HTML overwrite link tags
118-
if(config['overwriteFiles'] or not isfile(join(root, new_name))):
119-
for index, l in enumerate(lines):
120-
for root, file in css_files:
121-
if file in l and 'link' in l:
122-
l = l.replace(
123-
file, f"{file.split('.')[0]}{config['extCopy']}.css")
124-
lines[index] = l
125-
126-
# Overwrite html lines with the hashed css classes
127-
for index, l in enumerate(lines):
128-
for k, v in classes_dict.items():
129-
if k in l:
130-
l = l.replace(k, 'c'+v)
131-
lines[index] = l
24+
classes_dict, css_files, css_count = csshash(search_files)
13225

133-
write(root, new_name, lines)
134-
count += 1
135-
print(f"{10*'*'} \t {new_name.split('/')[-1]} \t {10*'*'}")
26+
html_count = htmlhash(search_files, classes_dict, css_files)
13627

137-
# If it exists, pass
138-
else:
139-
print(f'!! file already existed: {new_name}')
28+
if(config['output']):
14029

141-
print()
142-
print(f'finished! {str(int(count/len(search_files))*100)}% done.')
30+
print()
31+
print(
32+
f'finished! {str(int((html_count + css_count)/len(search_files))*100)}% done.')
14333

14434

14535
main()

css/newstyle-hashed.css

Lines changed: 0 additions & 4 deletions
This file was deleted.

examples/css/newstyle-hashed.css

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
.c472338{color:black;background-color:aqua;}
File renamed without changes.

examples/htmls/another-hashed.html

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><metahttp-equiv="X-UA-Compatible"content="IE=edge"><metaname="viewport"content="width=device-width,initial-scale=1.0"><linkhref="/style-hashed.css"rel="stylesheet"><linkhref="/css/newstyle-hashed.css"rel="stylesheet"><linkrel="stylesheet"href="https://use.fontawesome.com/releases/v5.13.0/css/all.css"integrity="sha384-Bfad6CLCknfcloXFOyFnlgtENryhrpZCe29RTifKEixXQZ38WheV+i/6YWSzkz3V"crossorigin="anonymous"/><title>Document</title></head><body><divclass="c472338c892938c472338"><p>AnotherTestofhtml</p></div></body></html>
File renamed without changes.

examples/index-hashed.html

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><metahttp-equiv="X-UA-Compatible"content="IE=edge"><metaname="viewport"content="width=device-width,initial-scale=1.0"><linkhref="/style-hashed.css"rel="stylesheet"><linkrel="stylesheet"href="https://use.fontawesome.com/releases/v5.13.0/css/all.css"integrity="sha384-Bfad6CLCknfcloXFOyFnlgtENryhrpZCe29RTifKEixXQZ38WheV+i/6YWSzkz3V"crossorigin="anonymous"/><title>Document</title></head><body><divclass="c892938c328534"><pclass="c65182">Thisisatextofahtml</p></div><divclass="c892938"><divclass="c65182"><spanclass="c209394">testofanotherkind</span></div></div><divid="c627821"><!--Itdoesn'tchangethecndfiles--><ulclass="fa-ul"><li><iclass="fa-lifafa-check-square"></i>Listicons</li><li><iclass="fa-lifafa-check-square"></i>canbeused</li><li><iclass="fa-lifafa-spinnerfa-spin"></i>asbullets</li><li><iclass="fa-lifafa-square"></i>inlists</li></ul></div></body></html>

0 commit comments

Comments
 (0)