From 6ffec123a92ffc903af7e60a776f222d6e01cee8 Mon Sep 17 00:00:00 2001 From: Georg Brandl Date: Sat, 21 Aug 2010 19:03:44 +0200 Subject: [PATCH] Small code style changes, remove unused imports. --- sphinx/builders/__init__.py | 1 + sphinx/util/__init__.py | 12 ++++------- sphinx/versioning.py | 21 ++++++++++--------- sphinx/websupport/__init__.py | 10 +++++---- sphinx/websupport/search/__init__.py | 20 +++++++++--------- sphinx/websupport/search/nullsearch.py | 3 ++- sphinx/websupport/search/whooshsearch.py | 4 ++-- sphinx/websupport/search/xapiansearch.py | 3 +-- sphinx/websupport/storage/db.py | 8 +++---- sphinx/websupport/storage/differ.py | 1 + .../websupport/storage/sqlalchemystorage.py | 14 ++++++++----- 11 files changed, 51 insertions(+), 46 deletions(-) diff --git a/sphinx/builders/__init__.py b/sphinx/builders/__init__.py index 328b26683..1938b3615 100644 --- a/sphinx/builders/__init__.py +++ b/sphinx/builders/__init__.py @@ -311,6 +311,7 @@ class Builder(object): """ Cleanup any resources. The default implementation does nothing. """ + pass BUILTIN_BUILDERS = { diff --git a/sphinx/util/__init__.py b/sphinx/util/__init__.py index a434f3a82..6a38351f7 100644 --- a/sphinx/util/__init__.py +++ b/sphinx/util/__init__.py @@ -299,6 +299,7 @@ def format_exception_cut_frames(x=1): res += traceback.format_exception_only(typ, val) return ''.join(res) + class PeekableIterator(object): """ An iterator which wraps any iterable and makes it possible to peek to see @@ -312,24 +313,19 @@ class PeekableIterator(object): return self def next(self): - """ - Returns the next item from the iterator. - """ + """Return the next item from the iterator.""" if self.remaining: return self.remaining.popleft() return self._iterator.next() def push(self, item): - """ - Pushes the `item` on the internal stack, it will be returned on the + """Push the `item` on the internal stack, it will be returned on the next :meth:`next` call. """ self.remaining.append(item) def peek(self): - """ - Returns the next item without changing the state of the iterator. - """ + """Return the next item without changing the state of the iterator.""" item = self.next() self.push(item) return item diff --git a/sphinx/versioning.py b/sphinx/versioning.py index 06acc63dc..430dc1423 100644 --- a/sphinx/versioning.py +++ b/sphinx/versioning.py @@ -18,15 +18,14 @@ try: except ImportError: from itertools import zip_longest -from sphinx.util import PeekableIterator # anything below that ratio is considered equal/changed VERSIONING_RATIO = 65 + def add_uids(doctree, condition): - """ - Adds a unique id to every node in the `doctree` which matches the condition - and yields it. + """Add a unique id to every node in the `doctree` which matches the + condition and yield the nodes. :param doctree: A :class:`docutils.nodes.document` instance. @@ -38,10 +37,10 @@ def add_uids(doctree, condition): node.uid = uuid4().hex yield node + def merge_doctrees(old, new, condition): - """ - Merges the `old` doctree with the `new` one while looking at nodes matching - the `condition`. + """Merge the `old` doctree with the `new` one while looking at nodes + matching the `condition`. Each node which replaces another one or has been added to the `new` doctree will be yielded. @@ -102,16 +101,18 @@ def merge_doctrees(old, new, condition): new_node.uid = uuid4().hex yield new_node + def get_ratio(old, new): - """ - Returns a "similiarity ratio" representing the similarity between the two - strings where 0 is equal and anything above less than equal. + """Return a "similiarity ratio" (in percent) representing the similarity + between the two strings where 0 is equal and anything above less than equal. """ if not all([old, new]): return VERSIONING_RATIO return levenshtein_distance(old, new) / (len(old) / 100.0) + def levenshtein_distance(a, b): + """Return the Levenshtein edit distance between two strings *a* and *b*.""" if a == b: return 0 if len(a) < len(b): diff --git a/sphinx/websupport/__init__.py b/sphinx/websupport/__init__.py index 152516728..f2d2ba451 100644 --- a/sphinx/websupport/__init__.py +++ b/sphinx/websupport/__init__.py @@ -13,17 +13,17 @@ import sys import cPickle as pickle import posixpath from os import path -from datetime import datetime from jinja2 import Environment, FileSystemLoader from sphinx.application import Sphinx from sphinx.util.osutil import ensuredir from sphinx.util.jsonimpl import dumps as dump_json -from sphinx.websupport.search import BaseSearch, search_adapters +from sphinx.websupport.search import BaseSearch, SEARCH_ADAPTERS from sphinx.websupport.storage import StorageBackend from sphinx.websupport.errors import * + class WebSupportApp(Sphinx): def __init__(self, *args, **kwargs): self.staticdir = kwargs.pop('staticdir', None) @@ -32,6 +32,7 @@ class WebSupportApp(Sphinx): self.storage = kwargs.pop('storage', None) Sphinx.__init__(self, *args, **kwargs) + class WebSupport(object): """The main API class for the web support package. All interactions with the web support package should occur through this class. @@ -82,7 +83,7 @@ class WebSupport(object): if isinstance(search, BaseSearch): self.search = search else: - mod, cls = search_adapters[search or 'null'] + mod, cls = SEARCH_ADAPTERS[search or 'null'] mod = 'sphinx.websupport.search.' + mod SearchClass = getattr(__import__(mod, None, None, [cls]), cls) search_path = path.join(self.datadir, 'search') @@ -390,7 +391,8 @@ class WebSupport(object): :param username: The username of the user making the request. :param moderator: Whether the user making the request is a moderator. """ - parts = [self.base_comment_opts] + # XXX parts is not used? + #parts = [self.base_comment_opts] rv = self.base_comment_opts.copy() if username: rv.update({ diff --git a/sphinx/websupport/search/__init__.py b/sphinx/websupport/search/__init__.py index cb66618b5..0cba0f77f 100644 --- a/sphinx/websupport/search/__init__.py +++ b/sphinx/websupport/search/__init__.py @@ -11,6 +11,7 @@ import re + class BaseSearch(object): def __init__(self, path): pass @@ -63,11 +64,10 @@ class BaseSearch(object): def query(self, q): """Called by the web support api to get search results. This method - compiles the regular expression to be used when - :meth:`extracting context `, then calls - :meth:`handle_query`. You won't want to override this unless you - don't want to use the included :meth:`extract_context` method. - Override :meth:`handle_query` instead. + compiles the regular expression to be used when :meth:`extracting + context `, then calls :meth:`handle_query`. You + won't want to override this unless you don't want to use the included + :meth:`extract_context` method. Override :meth:`handle_query` instead. :param q: the search query string. """ @@ -93,7 +93,7 @@ class BaseSearch(object): raise NotImplementedError() def extract_context(self, text, length=240): - """Extract the context for the search query from the documents + """Extract the context for the search query from the document's full `text`. :param text: the full text of the document to create the context for @@ -113,9 +113,9 @@ class BaseSearch(object): except TypeError: return context -# The build in search adapters. -search_adapters = { +# The built-in search adapters. +SEARCH_ADAPTERS = { 'xapian': ('xapiansearch', 'XapianSearch'), 'whoosh': ('whooshsearch', 'WhooshSearch'), - 'null': ('nullsearch', 'NullSearch') - } + 'null': ('nullsearch', 'NullSearch'), +} diff --git a/sphinx/websupport/search/nullsearch.py b/sphinx/websupport/search/nullsearch.py index 743983c48..fd6d4dcfa 100644 --- a/sphinx/websupport/search/nullsearch.py +++ b/sphinx/websupport/search/nullsearch.py @@ -10,7 +10,8 @@ """ from sphinx.websupport.search import BaseSearch -from sphinx.websupport.errors import * +from sphinx.websupport.errors import NullSearchException + class NullSearch(BaseSearch): """A search adapter that does nothing. Used when no search adapter diff --git a/sphinx/websupport/search/whooshsearch.py b/sphinx/websupport/search/whooshsearch.py index 0f4635314..d395dcd7f 100644 --- a/sphinx/websupport/search/whooshsearch.py +++ b/sphinx/websupport/search/whooshsearch.py @@ -10,13 +10,13 @@ """ from whoosh import index -from whoosh.fields import Schema, ID, TEXT, STORED +from whoosh.fields import Schema, ID, TEXT from whoosh.analysis import StemmingAnalyzer -from whoosh import highlight from sphinx.util.osutil import ensuredir from sphinx.websupport.search import BaseSearch + class WhooshSearch(BaseSearch): """The whoosh search adapter for sphinx web support.""" diff --git a/sphinx/websupport/search/xapiansearch.py b/sphinx/websupport/search/xapiansearch.py index 16c7e2b1b..b0475435a 100644 --- a/sphinx/websupport/search/xapiansearch.py +++ b/sphinx/websupport/search/xapiansearch.py @@ -9,13 +9,12 @@ :license: BSD, see LICENSE for details. """ -from os import path - import xapian from sphinx.util.osutil import ensuredir from sphinx.websupport.search import BaseSearch + class XapianSearch(BaseSearch): # Adapted from the GSOC 2009 webapp project. diff --git a/sphinx/websupport/storage/db.py b/sphinx/websupport/storage/db.py index be81a3334..bf7b83dfd 100644 --- a/sphinx/websupport/storage/db.py +++ b/sphinx/websupport/storage/db.py @@ -11,11 +11,9 @@ """ from datetime import datetime -from uuid import uuid4 -from sqlalchemy import Column, Integer, Text, String, Boolean, ForeignKey,\ - DateTime -from sqlalchemy.schema import UniqueConstraint +from sqlalchemy import Column, Integer, Text, String, Boolean, \ + ForeignKey, DateTime from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relation, sessionmaker, aliased @@ -98,6 +96,7 @@ class Node(Base): self.document = document self.source = source + class Comment(Base): """An individual Comment being stored.""" __tablename__ = db_prefix + 'comments' @@ -188,6 +187,7 @@ class Comment(Base): return '%s %s ago' % dt if dt[0] == 1 else '%s %ss ago' % dt + class CommentVote(Base): """A vote a user has made on a Comment.""" __tablename__ = db_prefix + 'commentvote' diff --git a/sphinx/websupport/storage/differ.py b/sphinx/websupport/storage/differ.py index 8d6c4a497..d52250718 100644 --- a/sphinx/websupport/storage/differ.py +++ b/sphinx/websupport/storage/differ.py @@ -13,6 +13,7 @@ import re from cgi import escape from difflib import Differ + class CombinedHtmlDiff(object): """Create an HTML representation of the differences between two pieces of text. diff --git a/sphinx/websupport/storage/sqlalchemystorage.py b/sphinx/websupport/storage/sqlalchemystorage.py index c775f3bb4..ba011c06d 100644 --- a/sphinx/websupport/storage/sqlalchemystorage.py +++ b/sphinx/websupport/storage/sqlalchemystorage.py @@ -14,16 +14,19 @@ from datetime import datetime from sqlalchemy.orm import aliased from sqlalchemy.sql import func -from sphinx.websupport.errors import * +from sphinx.websupport.errors import CommentNotAllowedError, \ + UserNotAuthorizedError from sphinx.websupport.storage import StorageBackend -from sphinx.websupport.storage.db import Base, Node, Comment, CommentVote,\ - Session +from sphinx.websupport.storage.db import Base, Node, Comment, \ + CommentVote, Session from sphinx.websupport.storage.differ import CombinedHtmlDiff + class SQLAlchemyStorage(StorageBackend): - """A :class:`~sphinx.websupport.storage.StorageBackend` using - SQLAlchemy. """ + A :class:`.StorageBackend` using SQLAlchemy. + """ + def __init__(self, engine): self.engine = engine Base.metadata.bind = engine @@ -147,6 +150,7 @@ class SQLAlchemyStorage(StorageBackend): def accept_comment(self, comment_id): session = Session() + # XXX assignment to "comment" needed? comment = session.query(Comment).filter( Comment.id == comment_id).update( {Comment.displayed: True})