Skip to content

Instantly share code, notes, and snippets.

@qnub
Created April 2, 2012 16:20
Show Gist options
  • Save qnub/2284744 to your computer and use it in GitHub Desktop.
Save qnub/2284744 to your computer and use it in GitHub Desktop.
Fabric local commenter and uncommenter
# -*- coding: utf-8 -*-
"""
Easy change settings with uncomment right string ang comment wrong.
Iterate over files in ``env.settings_files``, comment lines with
wrong marker and uncomment with right marker.
Usage
=====
>>> fab update_settings:mode=test
With this command all strings in ``/project_root/settings.py`` and
``/project_root/module/settings.py`` files with trailing '#-D' and
'#-P' sequences will be commented and with '#-T' will be
uncommented.
"""
from os import path
from fabric.api import env, local
env.settings_files = (
path.join('projcet_root', 'settings.py'),
path.join('projcet_root', 'module', 'settings.py'),
)
env.settings_versions = {
'develop': '#-D',
'test': '#-T',
'production': '#-P',
}
def _commenter(c_type, filename, regex, use_sudo=False, char='#', backup='.bak'):
"""
Work with comments in local files.
"""
if use_sudo:
sudoer = 'sudo '
else:
sudoer = ''
if regex.startswith('^'):
regex = regex[1:]
if regex.endswith('$'):
regex = regex[:-1]
if c_type == 'comment':
replacement = '%s ' % char
char = '[^%s ]' % char
regex = '(%s.+%s.*)' % (char, regex)
else:
replacement = ''
regex = r'%s ?(.+%s.*)' % (char, regex)
local(r"{sudo}sed -i{backup} -r -e 's/^([[:space:]]*){regex}$/"
r"\1{replacement}\2/g' {filename}".format(**{
'sudo': sudoer,
'backup': backup,
# 'char': char,
'replacement': replacement,
'regex': regex,
'filename': filename,
}))
def lcomment(*args, **kwargs):
"""
Comment local files.
"""
_commenter('comment', *args, **kwargs)
def luncomment(*args, **kwargs):
"""
Uncomment local files.
"""
_commenter('uncomment', *args, **kwargs)
def update_settings(mode):
"""
Change files.
"""
for filename in env.settings_files:
for version in env.settings_versions:
if mode == version:
luncomment(filename, versions[version])
elif:
lcomment(filename, versions[version])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment