Permalink
Browse files

more aggressive flake8-based cleanup

Mostly style, but a few dropped unused vars
and imports.
  • Loading branch information...
BigBlueHat committed Dec 16, 2013
1 parent d82ed94 commit 84c41ed229a2758a7a008968cc3312153113cc89
@@ -86,7 +86,7 @@ def run(self):
except (StopIteration, KeyboardInterrupt):
self.observer.stop()
return 0
- except Exception, e:
+ except Exception:
log.info("unhandled exception in main loop:\n%s" %
traceback.format_exc())
return -1
View
@@ -19,7 +19,7 @@
except ImportError:
desktopcouch = None
-from restkit import Resource, ClientResponse, ResourceError, request
+from restkit import Resource, ClientResponse, ResourceError
from restkit import util
from restkit import oauth2 as oauth
from restkit.filters import OAuthFilter
@@ -115,7 +115,8 @@ def request(self, method, path=None, payload=None, headers=None,
except ResourceError, e:
msg = getattr(e, 'msg', '')
if e.response and msg:
- if e.response.headers.get('content-type') == 'application/json':
+ if e.response.headers.get('content-type') == \
+ 'application/json':
try:
msg = json.loads(str(msg))
except ValueError:
@@ -150,7 +151,7 @@ def couchdb_version(server_uri):
try:
resp = res.get()
- except Exception, e:
+ except Exception:
return UNKNOWN_VERSION
version = resp.json_body["version"]
@@ -280,7 +281,8 @@ def save_doc(self, doc, encode=False, force_update=False, **params):
by CouchDB server when you save.
@param force_update: boolean, if there is conlict, try to update
with latest revision
- @param encode: Encode attachments if needed (depends on couchdb version)
+ @param encode: Encode attachments if needed (depends on couchdb
+ version)
@return: new doc with updated revision an id
"""
@@ -353,14 +355,15 @@ def save_docs(self, docs, all_or_nothing=False, use_uuids=True):
@param docs: list of docs
@param use_uuids: add _id in doc who don't have it already set.
- @param all_or_nothing: In the case of a power failure, when the database
- restarts either all the changes will have been saved or none of them.
- However, it does not do conflict checking, so the documents will
+ @param all_or_nothing: In the case of a power failure, when the
+ database restarts either all the changes will have been saved or none
+ of them. However, it does not do conflict checking, so the documents
+ will.
@return doc lists updated with new revision or raise BulkSaveError
- exception. You can access to doc created and docs in error as properties
- of this exception.
+ exception. You can access to doc created and docs in error as
+ properties of this exception.
"""
def is_id(doc):
@@ -475,7 +478,9 @@ def view(self, view_name, **params):
if "keys" in params:
keys = params.pop("keys")
- return self.res.post(path, json.dumps({"keys": keys}, **params)).json_body
+ return self.res.post(path,
+ json.dumps({"keys":
+ keys}, **params)).json_body
return self.res.get(path, **params).json_body
View
@@ -404,50 +404,51 @@ def get_switch_str(opt):
table = {
"init":
- (init,
- [],
- "[COUCHAPPDIR]"),
+ (init,
+ [],
+ "[COUCHAPPDIR]"),
"push":
- (push,
- pushopts + [('', 'docid', '', "set docid")],
- "[OPTION]... [COUCHAPPDIR] DEST"),
+ (push,
+ pushopts + [('', 'docid', '', "set docid")],
+ "[OPTION]... [COUCHAPPDIR] DEST"),
"clone":
- (clone,
- [('r', 'rev', '', "clone specific revision")],
- "[OPTION]...[-r REV] SOURCE [COUCHAPPDIR]"),
+ (clone,
+ [('r', 'rev', '', "clone specific revision")],
+ "[OPTION]...[-r REV] SOURCE [COUCHAPPDIR]"),
"pushapps":
- (pushapps,
- pushopts,
- "[OPTION]... SOURCE DEST"),
+ (pushapps,
+ pushopts,
+ "[OPTION]... SOURCE DEST"),
"pushdocs":
- (pushdocs,
- pushopts,
- "[OPTION]... SOURCE DEST"),
+ (pushdocs,
+ pushopts,
+ "[OPTION]... SOURCE DEST"),
"startapp":
- (startapp,
- [],
- "[COUCHAPPDIR] NAME"),
+ (startapp,
+ [],
+ "[COUCHAPPDIR] NAME"),
"generate":
- (generate,
- [('', 'template', '', "template name")],
- "[OPTION]... [app|view,list,show,filter,function,vendor] [COUCHAPPDIR] NAME"),
+ (generate,
+ [('', 'template', '', "template name")],
+ "[OPTION]... [app|view,list,show,filter,function,vendor] [COUCHAPPDIR] "
+ + "NAME"),
"vendor":
- (vendor,
- [("f", 'force', False, "force install or update")],
- "[OPTION]...[-f] install|update [COUCHAPPDIR] SOURCE"),
+ (vendor,
+ [("f", 'force', False, "force install or update")],
+ "[OPTION]...[-f] install|update [COUCHAPPDIR] SOURCE"),
"browse":
- (browse,
- [],
- "[COUCHAPPDIR] DEST"),
+ (browse,
+ [],
+ "[COUCHAPPDIR] DEST"),
"autopush":
- (autopush,
- [('', 'no-atomic', False, "send attachments one by one"),
- ('', 'update-delay', DEFAULT_UPDATE_DELAY, "time between each update")],
- "[OPTION]... [COUCHAPPDIR] DEST"),
+ (autopush,
+ [('', 'no-atomic', False, "send attachments one by one"),
+ ('', 'update-delay', DEFAULT_UPDATE_DELAY, "time between each update")],
+ "[OPTION]... [COUCHAPPDIR] DEST"),
"help":
- (usage, [], ""),
+ (usage, [], ""),
"version":
- (version, [], "")
+ (version, [], "")
}
withcmd = ['generate', 'vendor']
View
@@ -162,14 +162,13 @@ def parseopts(args, options, state):
opts, args = getopt.getopt(args, shortlist, namelist)
for opt, val in opts:
name = argmap[opt]
- t = type(defmap[name])
- if t is type(1):
+ if isinstance(defmap[name], int):
state[name] = int(val)
- elif t is type(''):
+ elif isinstance(defmap[name], basestring):
state[name] = val
- elif t is type([]):
+ elif isinstance(defmap[name], list):
state[name].append(val)
- elif t is type(None) or t is type(False):
+ elif defmap[name] is None or isinstance(defmap[name], bool):
state[name] = True
return args
View
@@ -42,15 +42,16 @@ def start_app(path):
with open(fid, 'wb') as f:
f.write('_design/%s' % os.path.split(path)[1])
- doc = localdoc.document(path, create=True)
+ localdoc.document(path, create=True)
logger.info("%s created." % path)
def generate_app(path, template=None, create=False):
""" Generates a CouchApp in app_dir
:attr verbose: boolean, default False
- :return: boolean, dict. { 'ok': True } if ok, { 'ok': False, 'error': message }
+ :return: boolean, dict. { 'ok': True } if ok,
+ { 'ok': False, 'error': message }
if something was wrong.
"""
@@ -94,7 +95,7 @@ def generate_app(path, template=None, create=False):
f.write('_design/%s' % os.path.split(appdir)[1])
if create:
- doc = localdoc.document(path, create=True)
+ localdoc.document(path, create=True)
logger.info("%s generated." % path)
@@ -3,14 +3,11 @@
# This file is part of couchapp released under the Apache 2 license.
# See the NOTICE for more information.
-from optparse import OptionParser
import os
import re
import sys
sys.path.append(os.path.dirname(__file__))
-from couchapp.util import relpath
-
__all__ = ['CSSParser']
re_selector = re.compile("/\./")
View
@@ -152,8 +152,9 @@ def browse_url(self, url):
ctx = local_files.DEFAULT_CONTEXT
bookmark_file = os.path.join(ctx.db_dir, "couchdb.html")
try:
- username, password = re.findall("<!-- !!([^!]+)!!([^!]+)!! -->",
- open(bookmark_file).read())[-1]
+ username, password = \
+ re.findall("<!-- !!([^!]+)!!([^!]+)!! -->",
+ open(bookmark_file).read())[-1]
except ValueError:
raise IOError("Bookmark file is corrupt." +
"Username/password are missing.")
@@ -168,8 +169,8 @@ def attachment_stub(self, name, filepath):
with open(filepath, "rb") as f:
re_sp = re.compile('\s')
att = {"data": re_sp.sub('', base64.b64encode(f.read())),
- "content_type": ';'.join(filter(None,
- mimetypes.guess_type(name)))}
+ "content_type":
+ ';'.join(filter(None, mimetypes.guess_type(name)))}
return att
@@ -246,8 +247,8 @@ def doc(self, db=None, with_attachments=True, force=False):
objects)
if 'validate_doc_update' in self._doc:
- tmp_dict = dict(validate_doc_update=self._doc[
- "validate_doc_update"])
+ tmp_dict = {'validate_doc_update':
+ self._doc["validate_doc_update"]}
package_shows(self._doc, tmp_dict, self.docdir, objects)
self._doc.update(tmp_dict)
@@ -351,18 +352,18 @@ def dir_to_fields(self, current_dir='', depth=0, manifest=[]):
else:
try:
content = util.read(current_path).strip()
- except UnicodeDecodeError, e:
+ except UnicodeDecodeError:
logger.warning("%s isn't encoded in utf8" %
current_path)
content = util.read(current_path, utf8=False)
try:
content.encode('utf-8')
- except UnicodeError, e:
+ except UnicodeError:
logger.warning("plan B didn't work, %s is a binary"
% current_path)
logger.warning("use plan C: encode to base64")
- content = "base64-encoded;%s" % base64.b64encode(
- content)
+ content = "base64-encoded;%s" % \
+ base64.b64encode(content)
# remove extension
name, ext = os.path.splitext(name)
View
@@ -110,8 +110,8 @@ def rjson(mo):
include_to = included
for i, field in enumerate(fields):
if not field in library:
- logger.warning("process json macro: unknown json source: %s"
- % mo.group(2))
+ logger.warning("process json macro: unknown json "
+ + "source: %s" % mo.group(2))
break
library = library[field]
if i+1 < count:
@@ -132,7 +132,7 @@ def rjson2(mo):
return f_string
for k, v in included.iteritems():
- varstrings.append("var %s = %s;" % (k,
- util.json.dumps(v).encode('utf-8')))
+ varstrings.append("var %s = %s;" %
+ (k, util.json.dumps(v).encode('utf-8')))
return re_json.sub(rjson2, f_string)
View
@@ -15,7 +15,7 @@
import string
import sys
-from couchapp.errors import ScriptError, AppError
+from couchapp.errors import ScriptError
try:
import json
@@ -73,7 +73,8 @@ def import_module(name, package=None):
"""
if name.startswith('.'):
if not package:
- raise TypeError("relative imports require the 'package' argument")
+ raise TypeError("relative imports require the 'package' "
+ + "argument")
level = 0
for character in name:
if character != '.':
@@ -168,8 +169,8 @@ def relpath(path, start=os.path.curdir):
unc_path, rest = splitunc(path)
unc_start, rest = splitunc(start)
if bool(unc_path) ^ bool(unc_start):
- raise ValueError("Cannot mix UNC and non-UNC paths (%s and %s)"
- % (path, start))
+ raise ValueError("Cannot mix UNC and non-UNC paths (%s "
+ + "and %s)" % (path, start))
else:
raise ValueError("path is on drive %s, start on drive %s"
% (path_list[0], start_list[0]))
@@ -347,7 +348,7 @@ def read(fname, utf8=True, force_read=False):
try:
with codecs.open(fname, 'rb', "utf-8") as f:
return f.read()
- except UnicodeError, e:
+ except UnicodeError:
if force_read:
return read(fname, utf8=False)
raise
@@ -470,8 +471,8 @@ def hook_uri(uri, cfg):
script_uri = uri
return ShellScript(script_uri)
-re_comment = re.compile(r'//.*?$|/\*.*?\*/|\'(?:\\.|[^\\\'])*\'|"(?:\\.|[^\\"])*"',
- re.DOTALL | re.MULTILINE)
+regex_comment = r'//.*?$|/\*.*?\*/|\'(?:\\.|[^\\\'])*\'|"(?:\\.|[^\\"])*"'
+re_comment = re.compile(regex_comment, re.DOTALL | re.MULTILINE)
def remove_comments(t):
View
@@ -144,8 +144,8 @@ def update(self, appdir, name=None, *args, **opts):
meta = util.read_json(metaf)
uri = meta.get("fetch_uri", "")
if not uri:
- raise VendorError("Can't update vendor `%s`: fetch_uri undefined."
- % name)
+ raise VendorError("Can't update vendor `%s`: fetch_uri "
+ + "undefined." % name)
new_vendors, temppath = self.fetch_vendor(uri, *args, **opts)
for vname, vpath, vmeta in new_vendors:
if name != vname:
@@ -169,8 +169,8 @@ def update(self, appdir, name=None, *args, **opts):
meta = util.read_json(metaf)
uri = meta.get("fetch_uri", "")
if not uri:
- logger.warning("Can't update vendor `%s`: fetch_uri undefined."
- % vendor)
+ logger.warning("Can't update vendor `%s`: fetch_uri "
+ + "undefined." % vendor)
continue
else:
new_vendors, temppath = self.fetch_vendor(uri, *args,

0 comments on commit 84c41ed

Please sign in to comment.