Skip to content
This repository has been archived by the owner on Apr 16, 2019. It is now read-only.

Commit

Permalink
Python 2.x is long since deprecated.. let's use Python 3 for real thi…
Browse files Browse the repository at this point in the history
…s time.
  • Loading branch information
EnigmaCurry committed Mar 13, 2011
1 parent eb4211e commit fb99e2b
Show file tree
Hide file tree
Showing 14 changed files with 118 additions and 122 deletions.
4 changes: 2 additions & 2 deletions blogofile/argparse.py
Expand Up @@ -1687,7 +1687,7 @@ def parse_known_args(self, args=None, namespace=None):
if not hasattr(namespace, action.dest): if not hasattr(namespace, action.dest):
if action.default is not SUPPRESS: if action.default is not SUPPRESS:
default = action.default default = action.default
if isinstance(action.default, basestring): if isinstance(action.default, str):
default = self._get_value(action, default) default = self._get_value(action, default)
setattr(namespace, action.dest, default) setattr(namespace, action.dest, default)


Expand Down Expand Up @@ -2161,7 +2161,7 @@ def _get_values(self, action, arg_strings):
value = action.const value = action.const
else: else:
value = action.default value = action.default
if isinstance(value, basestring): if isinstance(value, str):
value = self._get_value(action, value) value = self._get_value(action, value)
self._check_value(action, value) self._check_value(action, value)


Expand Down
6 changes: 3 additions & 3 deletions blogofile/command_completion.py
@@ -1,7 +1,7 @@
import sys import sys
import shlex import shlex


import argparse from . import argparse


bash_bootstrap = """ bash_bootstrap = """
_blogofile_completion() { _blogofile_completion() {
Expand All @@ -18,7 +18,7 @@


def get_subparsers(parser): def get_subparsers(parser):
if parser._subparsers: if parser._subparsers:
subparsers = parser._subparsers._group_actions[0].choices.items() subparsers = list(parser._subparsers._group_actions[0].choices.items())
else: else:
subparsers = [] subparsers = []
return subparsers return subparsers
Expand All @@ -42,7 +42,7 @@ def print_completions(parser, command, current_word):
for name, sub_subparser in get_subparsers(subparser): for name, sub_subparser in get_subparsers(subparser):
if name.startswith(current_word): if name.startswith(current_word):
if name != current_word: if name != current_word:
print name + " " print(name + " ")
num_completions += 1 num_completions += 1
finally: finally:
#Turn back on the default exit on error behaviour of argparse: #Turn back on the default exit on error behaviour of argparse:
Expand Down
21 changes: 10 additions & 11 deletions blogofile/config.py
Expand Up @@ -10,14 +10,13 @@
import logging import logging
import sys import sys


import util from . import util
import writer
import blogofile_bf as bf import blogofile_bf as bf
import cache from . import cache
import controller from . import controller
import plugin from . import plugin
import site_init from . import site_init
import filter from . import filter


bf.config = sys.modules['blogofile.config'] bf.config = sys.modules['blogofile.config']


Expand Down Expand Up @@ -49,7 +48,7 @@ def recompile():
global site global site
site.compiled_file_ignore_patterns = [] site.compiled_file_ignore_patterns = []
for p in site.file_ignore_patterns: for p in site.file_ignore_patterns:
if isinstance(p, basestring): if isinstance(p, str):
site.compiled_file_ignore_patterns.append( site.compiled_file_ignore_patterns.append(
re.compile(p, re.IGNORECASE)) re.compile(p, re.IGNORECASE))
else: else:
Expand All @@ -69,12 +68,12 @@ def __load_config(path=None):
filter.preload_filters() filter.preload_filters()
controller.load_controllers(namespace=bf.config.controllers) controller.load_controllers(namespace=bf.config.controllers)
if path: if path:
execfile(path) exec(compile(open(path).read(), path, 'exec'))
#config is now in locals() but needs to be in globals() #config is now in locals() but needs to be in globals()
for k, v in locals().items(): for k, v in list(locals().items()):
globals()[k] = v globals()[k] = v
#Override any options (from unit tests) #Override any options (from unit tests)
for k, v in override_options.items(): for k, v in list(override_options.items()):
if "." in k: if "." in k:
parts = k.split(".") parts = k.split(".")
cache_object = ".".join(parts[:-1]) cache_object = ".".join(parts[:-1])
Expand Down
14 changes: 7 additions & 7 deletions blogofile/controller.py
Expand Up @@ -54,7 +54,7 @@
import operator import operator
import logging import logging


from cache import bf from .cache import bf
bf.controller = sys.modules['blogofile.controller'] bf.controller = sys.modules['blogofile.controller']


logger = logging.getLogger("blogofile.controller") logger = logging.getLogger("blogofile.controller")
Expand All @@ -79,7 +79,7 @@ def __find_controller_names(directory="_controllers"):
def init_controllers(namespace): def init_controllers(namespace):
"""Controllers have an optional init method that runs before the run """Controllers have an optional init method that runs before the run
method""" method"""
for controller in sorted(namespace.values(), for controller in sorted(list(namespace.values()),
key=operator.attrgetter("priority")): key=operator.attrgetter("priority")):
if "mod" in controller \ if "mod" in controller \
and type(controller.mod).__name__ == "module"\ and type(controller.mod).__name__ == "module"\
Expand Down Expand Up @@ -107,23 +107,23 @@ def load_controller(name, namespace, directory="_controllers", defaults={}, is_p
controller = __import__(name) controller = __import__(name)
controller.__initialized = False controller.__initialized = False
logger.debug("found controller: {0} - {1}".format(name,controller)) logger.debug("found controller: {0} - {1}".format(name,controller))
except (ImportError,),e: except (ImportError,) as e:
logger.error( logger.error(
"Cannot import controller : {0} ({1})".format(name, e)) "Cannot import controller : {0} ({1})".format(name, e))
raise raise
# Remember the actual imported module # Remember the actual imported module
namespace[name].mod = controller namespace[name].mod = controller
# Load the blogofile defaults for controllers: # Load the blogofile defaults for controllers:
for k, v in default_controller_config.items(): for k, v in list(default_controller_config.items()):
namespace[name][k] = v namespace[name][k] = v
# Load provided defaults: # Load provided defaults:
for k, v in defaults.items(): for k, v in list(defaults.items()):
namespace[name][k] = v namespace[name][k] = v
if not is_plugin: if not is_plugin:
# Load any of the controller defined defaults: # Load any of the controller defined defaults:
try: try:
controller_config = getattr(controller, "config") controller_config = getattr(controller, "config")
for k, v in controller_config.items(): for k, v in list(controller_config.items()):
if "." in k: if "." in k:
#This is a hierarchical setting #This is a hierarchical setting
tail = namespace[name] tail = namespace[name]
Expand Down Expand Up @@ -183,7 +183,7 @@ def defined_controllers(namespaces, only_enabled=True):
""" """
controllers = [] controllers = []
for namespace in namespaces: for namespace in namespaces:
for c in namespace.controllers.values(): for c in list(namespace.controllers.values()):
#Get only the ones that are enabled: #Get only the ones that are enabled:
if "enabled" not in c or c['enabled'] == False: if "enabled" not in c or c['enabled'] == False:
#The controller is disabled #The controller is disabled
Expand Down
19 changes: 9 additions & 10 deletions blogofile/filter.py
Expand Up @@ -4,13 +4,13 @@
import imp import imp
import uuid import uuid


import util from . import util


logger = logging.getLogger("blogofile.filter") logger = logging.getLogger("blogofile.filter")


from cache import bf from .cache import bf
from cache import HierarchicalCache from .cache import HierarchicalCache
import exception from . import exception


bf.filter = sys.modules['blogofile.filter'] bf.filter = sys.modules['blogofile.filter']


Expand All @@ -25,8 +25,7 @@ def run_chain(chain, content):
Works with either a string or a sequence of filters""" Works with either a string or a sequence of filters"""
if chain is None: if chain is None:
return content return content
if not hasattr(chain, '__iter__'): if isinstance(chain, str):
#Not a sequence, must be a string, parse it
chain = parse_chain(chain) chain = parse_chain(chain)
for fn in chain: for fn in chain:
f = get_filter(fn) f = get_filter(fn)
Expand Down Expand Up @@ -67,7 +66,7 @@ def init_filters(namespace=None):
built""" built"""
if namespace is None: if namespace is None:
namespace=bf.config.filters namespace=bf.config.filters
for name, filt in namespace.items(): for name, filt in list(namespace.items()):
if "mod" in filt \ if "mod" in filt \
and type(filt.mod).__name__ == "module"\ and type(filt.mod).__name__ == "module"\
and not filt.mod.__initialized: and not filt.mod.__initialized:
Expand All @@ -84,7 +83,7 @@ def get_filter(name, namespace=None):
#Return an already loaded filter: #Return an already loaded filter:
if namespace is None: if namespace is None:
namespace = bf.config.filters namespace = bf.config.filters
if namespace.has_key(name) and namespace[name].has_key("mod"): if name in namespace and "mod" in namespace[name]:
logger.debug("Retrieving already loaded filter: " + name) logger.debug("Retrieving already loaded filter: " + name)
return namespace[name]['mod'] return namespace[name]['mod']
else: else:
Expand Down Expand Up @@ -128,12 +127,12 @@ def load_filter(name, module_path, namespace=None):
except: except:
pass pass
#Load the default blogofile config for filters: #Load the default blogofile config for filters:
for k, v in default_filter_config.items(): for k, v in list(default_filter_config.items()):
namespace[name][k] = v namespace[name][k] = v
#Load any filter defined defaults: #Load any filter defined defaults:
try: try:
filter_config = getattr(mod, "config") filter_config = getattr(mod, "config")
for k, v in filter_config.items(): for k, v in list(filter_config.items()):
if "." in k: if "." in k:
#This is a hierarchical setting #This is a hierarchical setting
tail = namespace[name] tail = namespace[name]
Expand Down
57 changes: 29 additions & 28 deletions blogofile/main.py
Expand Up @@ -30,19 +30,20 @@
import sys import sys
import shlex import shlex
import time import time
import platform


import argparse from . import argparse


from cache import bf from .cache import bf
from writer import Writer from .writer import Writer
import server from . import server
import config from . import config
import site_init from . import site_init
import util from . import util
import plugin from . import plugin
import site_init from . import site_init
from exception import * from .exception import *
import command_completion from . import command_completion


locale.setlocale(locale.LC_ALL, '') locale.setlocale(locale.LC_ALL, '')


Expand All @@ -66,8 +67,9 @@ def setup_command_parser():
help="Be extra verbose") help="Be extra verbose")
global parser, subparsers global parser, subparsers
parser = argparse.ArgumentParser(parents=[parser_template]) parser = argparse.ArgumentParser(parents=[parser_template])
parser.version = "Blogofile {0} -- http://www.blogofile.com".format( parser.version = "Blogofile {0} -- http://www.Blogofile.com -- {1} {2}"\
__version__) .format( __version__,platform.python_implementation(),
platform.python_version())
subparsers = parser.add_subparsers() subparsers = parser.add_subparsers()


p_help = subparsers.add_parser("help", help="Show help for a command.", p_help = subparsers.add_parser("help", help="Show help for a command.",
Expand Down Expand Up @@ -146,15 +148,15 @@ def find_src_root(path=os.curdir):
path = parts[0] path = parts[0]


def do_completion(cmd): def do_completion(cmd):
if os.environ.has_key("BLOGOFILE_BASH_BOOTSTRAP"): if "BLOGOFILE_BASH_BOOTSTRAP" in os.environ:
print command_completion.bash_bootstrap print(command_completion.bash_bootstrap)
sys.exit(1) sys.exit(1)
if os.environ.has_key("BLOGOFILE_COMPLETION_MODE"): if "BLOGOFILE_COMPLETION_MODE" in os.environ:
#Complete the current Blogofile command rather than run it: #Complete the current Blogofile command rather than run it:
command_completion.complete(parser, cmd) command_completion.complete(parser, cmd)
sys.exit(1) sys.exit(1)


def main(cmd=None): def main(cmd=None):
do_debug() do_debug()
parser = setup_command_parser() parser = setup_command_parser()
do_completion(cmd) do_completion(cmd)
Expand All @@ -176,7 +178,7 @@ def main(cmd=None):
args.src_dir = os.path.abspath(os.curdir) args.src_dir = os.path.abspath(os.curdir)
#Not a valid src dir, the next block warns the user #Not a valid src dir, the next block warns the user
if not args.src_dir or not os.path.isdir(args.src_dir): if not args.src_dir or not os.path.isdir(args.src_dir):
print("source dir does not exist : %s" % args.src_dir) print(("source dir does not exist : %s" % args.src_dir))
sys.exit(1) sys.exit(1)
os.chdir(args.src_dir) os.chdir(args.src_dir)


Expand All @@ -189,7 +191,7 @@ def main(cmd=None):
def do_bash_complete(args): def do_bash_complete(args):
for subcommand in args.command: for subcommand in args.command:
parser = subparsers.choices[subcommand] parser = subparsers.choices[subcommand]
print parser print(parser)


def do_help(args): def do_help(args):
global parser global parser
Expand All @@ -214,11 +216,11 @@ def do_help(args):


# Print help for each subcommand requested. # Print help for each subcommand requested.
for subcommand in args.command: for subcommand in args.command:
print >>sys.stderr, "{0} - {1}".format( print("{0} - {1}".format(
subcommand, helptext[subcommand]) subcommand, helptext[subcommand]), file=sys.stderr)
parser = subparsers.choices[subcommand] parser = subparsers.choices[subcommand]
parser.print_help() parser.print_help()
print >>sys.stderr, "\n" print("\n", file=sys.stderr)
#Perform any extra help tasks: #Perform any extra help tasks:
if hasattr(parser, "extra_help"): if hasattr(parser, "extra_help"):
parser.extra_help() parser.extra_help()
Expand All @@ -229,8 +231,7 @@ def config_init(args):
# We already changed to the directory specified with --src-dir # We already changed to the directory specified with --src-dir
config.init("_config.py") config.init("_config.py")
except config.ConfigNotFoundException: except config.ConfigNotFoundException:
print >>sys.stderr, \ print("No configuration found in source dir: {0}".format(args.src_dir), file=sys.stderr)
"No configuration found in source dir: {0}".format(args.src_dir)
parser.exit(1, "Want to make a new site? Try `blogofile init`\n") parser.exit(1, "Want to make a new site? Try `blogofile init`\n")




Expand Down Expand Up @@ -283,16 +284,16 @@ def do_debug():


def do_info(args): def do_info(args):
"""Print some information about the Blogofile installation and the current site""" """Print some information about the Blogofile installation and the current site"""
print("This is Blogofile (version {0}) -- http://www.blogofile.com".\ print(("This is Blogofile (version {0}) -- http://www.blogofile.com".\
format(__version__)) format(__version__)))
print("") print("")
### Show _config.py paths ### Show _config.py paths
print("Default config file: {0}".format(config.default_config_path())) print(("Default config file: {0}".format(config.default_config_path())))
print("(Override these default settings in your own _config.py, don't edit " print("(Override these default settings in your own _config.py, don't edit "
"the file above.)") "the file above.)")
print("") print("")
if os.path.isfile("_config.py"): if os.path.isfile("_config.py"):
print("Found site _config.py: {0}".format(os.path.abspath("_config.py"))) print(("Found site _config.py: {0}".format(os.path.abspath("_config.py"))))
else: else:
print("The specified directory has no _config.py") print("The specified directory has no _config.py")


Expand Down

0 comments on commit fb99e2b

Please sign in to comment.