Skip to content

Instantly share code, notes, and snippets.

@felipsmartins
Created February 8, 2016 20:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save felipsmartins/9e66867820a0108801f1 to your computer and use it in GitHub Desktop.
Save felipsmartins/9e66867820a0108801f1 to your computer and use it in GitHub Desktop.
import os
import os.path as path
htmlroot = '/home/martins/Desktop/htmltest'
asset_replacements = {
'http://symfony.com/js/v5/all.js': '{}_static/all.js',
'http://symfony.com/css/compiled/v5/all.css': '{}_static/all.css'
}
def calculate_relative_path_to_root(path, start='html'):
levels = [level for level in path.split(start)[-1].split('/') if level]
level = ''
for l in levels[1:]: # levels[1:] skip one level
level += '../'
return level
def search_and_replace(filename):
calculated_relative_path = calculate_relative_path_to_root(filename,
path.basename(htmlroot))
with open(filename, 'r+') as f:
content = f.read() # Yeah! Whole file in the memory
for search, replacement in asset_replacements.iteritems():
if search in content:
replacewith = replacement.format(calculated_relative_path)
content = content.replace(search, replacewith)
f.seek(0)
f.truncate()
f.write(content)
os.chdir(htmlroot)
for parentpath, dirs, filenames in os.walk(htmlroot):
print "\n>>> {}".format(parentpath)
for filename in filenames:
if path.splitext(filename)[1] == '.html':
search_and_replace(path.join(parentpath, filename))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment