Created
November 21, 2012 00:22
-
-
Save mikeclagg/4122228 to your computer and use it in GitHub Desktop.
Read a css file that contains @import directives, follows those to build a list of files to concatenate for web optimization
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def getCssFiles(baseCssFile, css_files): | |
import os, re | |
""" | |
Checks for css files that are just @import containers, | |
traverses the files and builds a list in the order they | |
appear in the files. This prepares a list to use for | |
bundling n webassets | |
""" | |
with open(baseCssFile, 'r') as f: | |
# Check to see if baseCssFile contains an @import statement at the top | |
isImport = (f.readline()[:7] == '@import') | |
f.seek(0) # move the file read cursor back to the beginning | |
if isImport: | |
for line in f.readlines(): | |
# regexp for the stuff in the quotes | |
reg = re.search('\"(.*)\"',line) | |
if reg: | |
cssFile = reg.group(0).replace('"','') | |
# determine absolute path for Bundle() arg | |
absCssFile = os.path.split(os.path.abspath(baseCssFile))[0] + '/' + cssFile | |
# Yes, read the first line of every file to determine if it is | |
with open(absCssFile,'r') as cf: | |
# Check to see if each file contains an @import statement at the top | |
eachIsImport = (cf.readline()[:7] == '@import') | |
if not eachIsImport: | |
# Append files to object passed in | |
css_files.append(absCssFile) | |
else: | |
# *Recursion: for a definition see *Recursion | |
getCssFiles(absCssFile,css_files) | |
cf.closed | |
f.closed | |
return css_files | |
# run the function, my file has 15 import statements, | |
# one being an import to another file with import statements | |
# The reason to do this is because CSS loading order is | |
# important, and needs to be preserved | |
baseCssFile = '../public/web/assets/css/base.css' | |
cssFiles = getCssFiles(baseCssFile,[]) | |
for cssFile in cssFiles: | |
print cssFile |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
../public/web/assets/css/base.css Looks like this:
/assets/css/base.css is a shared file between the apps and the main site and looks like this:
Having many smaller files for development reduces merge conflicts with a medium sized dev team, but this is not ideal for production.
I will be releasing the entire build script this is part of soon