Skip to content

Commit

Permalink
Cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
gforcada committed Feb 5, 2016
1 parent fb71aee commit cb1bf28
Show file tree
Hide file tree
Showing 33 changed files with 619 additions and 550 deletions.
2 changes: 2 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ Fixes:
Issue https://github.com/plone/Products.CMFPlone/issues/1332
[staeff, fredvd]

- Cleanup code according to our style guide.
[gforcada]


2.4.9 (2015-11-25)
Expand Down
8 changes: 2 additions & 6 deletions plone/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,2 @@
# See http://peak.telecommunity.com/DevCenter/setuptools#namespace-packages
try:
__import__('pkg_resources').declare_namespace(__name__)
except ImportError:
from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)
# -*- coding: utf-8 -*-
__import__('pkg_resources').declare_namespace(__name__)
8 changes: 2 additions & 6 deletions plone/app/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,2 @@
# See http://peak.telecommunity.com/DevCenter/setuptools#namespace-packages
try:
__import__('pkg_resources').declare_namespace(__name__)
except ImportError:
from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)
# -*- coding: utf-8 -*-
__import__('pkg_resources').declare_namespace(__name__)
5 changes: 3 additions & 2 deletions plone/app/discussion/browser/captcha.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@
from z3c.form.field import Fields
from zope import interface
from zope.annotation import factory
from zope.component import adapts, queryUtility
from zope.component import adapts
from zope.component import queryUtility
from zope.interface import Interface
from zope.publisher.interfaces.browser import IDefaultBrowserLayer

Expand Down Expand Up @@ -51,7 +52,7 @@ def __init__(self, context, request, form):
def update(self):
if self.captcha != 'disabled' and self.isAnon:
# Add a captcha field if captcha is enabled in the registry
self.add(ICaptcha, prefix="")
self.add(ICaptcha, prefix='')
if self.captcha == 'captcha':
from plone.formwidget.captcha import CaptchaFieldWidget
self.form.fields['captcha'].widgetFactory = CaptchaFieldWidget
Expand Down
37 changes: 19 additions & 18 deletions plone/app/discussion/browser/comment.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
# -*- coding: utf-8 -*-
from AccessControl import getSecurityManager
from Acquisition import aq_inner
from Acquisition import aq_parent
from zope.component import getUtility
from Products.CMFCore.utils import getToolByName
from Products.Five.browser import BrowserView
from Products.statusmessages.interfaces import IStatusMessage
from comments import CommentForm
from plone.app.discussion import _
from plone.registry.interfaces import IRegistry
from plone.z3cform.layout import wrap_form
from Products.CMFCore.utils import getToolByName
from Products.Five.browser import BrowserView
from Products.statusmessages.interfaces import IStatusMessage
from z3c.form import button
from zope.component import getMultiAdapter
from zope.component import getUtility


class View(BrowserView):
Expand All @@ -21,9 +22,9 @@ class View(BrowserView):
has been posted.
Redirect from the comment object URL
"/path/to/object/++conversation++default/123456789" to the content object
'/path/to/object/++conversation++default/123456789' to the content object
where the comment has been posted appended by an HTML anchor that points to
the comment "/path/to/object#comment-123456789".
the comment '/path/to/object#comment-123456789'.
Context is the comment object. The parent of the comment object is the
conversation. The parent of the conversation is the content object where
Expand All @@ -46,15 +47,15 @@ def __call__(self):
will redirect right to the binary object, bypassing comments.
"""
if obj.portal_type in view_action_types:
url = "%s/view" % url
url = '{0}/view'.format(url)

self.request.response.redirect('%s#%s' % (url, context.id))
self.request.response.redirect('{0}#{1}'.format(url, context.id))


class EditCommentForm(CommentForm):
"""Form to edit an existing comment."""
ignoreContext = True
id = "edit-comment-form"
id = 'edit-comment-form'
label = _(u'edit_comment_form_title', default=u'Edit comment')

def updateWidgets(self):
Expand All @@ -71,8 +72,8 @@ def _redirect(self, target=''):
target = portal_state.portal_url()
self.request.response.redirect(target)

@button.buttonAndHandler(_(u"edit_comment_form_button",
default=u"Edit comment"), name='comment')
@button.buttonAndHandler(_(u'edit_comment_form_button',
default=u'Edit comment'), name='comment')
def handleComment(self, action):

# Validate form
Expand All @@ -93,19 +94,19 @@ def handleComment(self, action):

# Redirect to comment
IStatusMessage(self.request).add(_(u'comment_edit_notification',
default="Comment was edited"),
default='Comment was edited'),
type='info')
return self._redirect(
target=self.action.replace("@@edit-comment", "@@view"))
target=self.action.replace('@@edit-comment', '@@view'))

@button.buttonAndHandler(_(u'cancel_form_button',
default=u'Cancel'), name='cancel')
def handle_cancel(self, action):
IStatusMessage(self.request).add(
_(u'comment_edit_cancel_notification',
default=u'Edit comment cancelled'),
type='info')
return self._redirect(target=self.context.absolute_url())
IStatusMessage(self.request).add(
_(u'comment_edit_cancel_notification',
default=u'Edit comment cancelled'),
type='info')
return self._redirect(target=self.context.absolute_url())

EditComment = wrap_form(EditCommentForm)

Expand Down
102 changes: 54 additions & 48 deletions plone/app/discussion/browser/comments.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,8 @@
from AccessControl import getSecurityManager
from AccessControl import Unauthorized
from Acquisition import aq_inner
from DateTime import DateTime
from Products.CMFCore.utils import getToolByName
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile
from Products.statusmessages.interfaces import IStatusMessage
from datetime import datetime
from DateTime import DateTime
from plone.app.discussion import _
from plone.app.discussion.browser.validator import CaptchaValidator
from plone.app.discussion.interfaces import ICaptcha
Expand All @@ -19,6 +16,9 @@
from plone.z3cform import z2
from plone.z3cform.fieldsets import extensible
from plone.z3cform.interfaces import IWrappedForm
from Products.CMFCore.utils import getToolByName
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile
from Products.statusmessages.interfaces import IStatusMessage
from urllib import quote as url_quote
from z3c.form import button
from z3c.form import field
Expand All @@ -34,32 +34,36 @@


COMMENT_DESCRIPTION_PLAIN_TEXT = _(
u"comment_description_plain_text",
default=u"You can add a comment by filling out the form below. " +
u"Plain text formatting.")
u'comment_description_plain_text',
default=u'You can add a comment by filling out the form below. '
u'Plain text formatting.'
)

COMMENT_DESCRIPTION_MARKDOWN = _(
u"comment_description_markdown",
default=u"You can add a comment by filling out the form below. " +
u"Plain text formatting. You can use the Markdown syntax for " +
u"links and images.")
u'comment_description_markdown',
default=u'You can add a comment by filling out the form below. '
u'Plain text formatting. You can use the Markdown syntax for '
u'links and images.'
)

COMMENT_DESCRIPTION_INTELLIGENT_TEXT = _(
u"comment_description_intelligent_text",
default=u"You can add a comment by filling out the form below. " +
u"Plain text formatting. Web and email addresses are " +
u"transformed into clickable links.")
u'comment_description_intelligent_text',
default=u'You can add a comment by filling out the form below. '
u'Plain text formatting. Web and email addresses are '
u'transformed into clickable links.'
)

COMMENT_DESCRIPTION_MODERATION_ENABLED = _(
u"comment_description_moderation_enabled",
default=u"Comments are moderated.")
u'comment_description_moderation_enabled',
default=u'Comments are moderated.'
)


class CommentForm(extensible.ExtensibleForm, form.Form):

ignoreContext = True # don't use context to get widget data
id = None
label = _(u"Add a comment")
label = _(u'Add a comment')
fields = field.Fields(IComment).omit('portal_type',
'__parent__',
'__name__',
Expand All @@ -81,13 +85,13 @@ def updateWidgets(self):

# Widgets
self.widgets['in_reply_to'].mode = interfaces.HIDDEN_MODE
self.widgets['text'].addClass("autoresize")
self.widgets['user_notification'].label = _(u"")
self.widgets['text'].addClass('autoresize')
self.widgets['user_notification'].label = _(u'')

# Rename the id of the text widgets because there can be css-id
# clashes with the text field of documents when using and overlay
# with TinyMCE.
self.widgets['text'].id = "form-widgets-comment-text"
self.widgets['text'].id = 'form-widgets-comment-text'

# Anonymous / Logged-in
mtool = getToolByName(self.context, 'portal_membership')
Expand All @@ -99,7 +103,7 @@ def updateWidgets(self):
if anon:
if settings.anonymous_email_enabled:
# according to IDiscussionSettings.anonymous_email_enabled:
# "If selected, anonymous user will have to give their email."
# 'If selected, anonymous user will have to give their email.'
self.widgets['author_email'].field.required = True
self.widgets['author_email'].required = True
else:
Expand All @@ -121,11 +125,11 @@ def updateWidgets(self):

def updateActions(self):
super(CommentForm, self).updateActions()
self.actions['cancel'].addClass("standalone")
self.actions['cancel'].addClass("hide")
self.actions['comment'].addClass("context")
self.actions['cancel'].addClass('standalone')
self.actions['cancel'].addClass('hide')
self.actions['comment'].addClass('context')

@button.buttonAndHandler(_(u"add_comment_button", default=u"Comment"),
@button.buttonAndHandler(_(u'add_comment_button', default=u'Comment'),
name='comment')
def handleComment(self, action):
context = aq_inner(self.context)
Expand All @@ -134,8 +138,9 @@ def handleComment(self, action):
if not self.__parent__.restrictedTraverse(
'@@conversation_view'
).enabled():
raise Unauthorized("Discussion is not enabled for this content "
"object.")
raise Unauthorized(
'Discussion is not enabled for this content object.'
)

# Validation form
data, errors = self.extractData()
Expand All @@ -151,7 +156,7 @@ def handleComment(self, action):
anon = portal_membership.isAnonymousUser()
if captcha_enabled and anonymous_comments and anon:
if 'captcha' not in data:
data['captcha'] = u""
data['captcha'] = u''
captcha = CaptchaValidator(self.context,
self.request,
None,
Expand All @@ -160,7 +165,7 @@ def handleComment(self, action):
captcha.validate(data['captcha'])

# some attributes are not always set
author_name = u""
author_name = u''

# Create comment
comment = createObject('plone.Comment')
Expand Down Expand Up @@ -207,14 +212,14 @@ def handleComment(self, action):
if email and isinstance(email, str):
email = unicode(email, 'utf-8')
comment.changeOwnership(user, recursive=False)
comment.manage_setLocalRoles(memberid, ["Owner"])
comment.manage_setLocalRoles(memberid, ['Owner'])
comment.creator = memberid
comment.author_username = memberid
comment.author_name = fullname

# XXX: according to IComment interface author_email must not be
# set for logged in users, cite:
# "for anonymous comments only, set to None for logged in comments"
# 'for anonymous comments only, set to None for logged in comments'
comment.author_email = email
# /XXX

Expand All @@ -223,8 +228,8 @@ def handleComment(self, action):

else: # pragma: no cover
raise Unauthorized(
u"Anonymous user tries to post a comment, but anonymous "
u"commenting is disabled. Or user does not have the "
u'Anonymous user tries to post a comment, but anonymous '
u'commenting is disabled. Or user does not have the '
u"'reply to item' permission."
)

Expand Down Expand Up @@ -255,14 +260,14 @@ def handleComment(self, action):
if comment_review_state == 'pending' and not can_review:
# Show info message when comment moderation is enabled
IStatusMessage(self.context.REQUEST).addStatusMessage(
_("Your comment awaits moderator approval."),
type="info")
_('Your comment awaits moderator approval.'),
type='info')
self.request.response.redirect(self.action)
else:
# Redirect to comment (inside a content object page)
self.request.response.redirect(self.action + '#' + str(comment_id))

@button.buttonAndHandler(_(u"Cancel"))
@button.buttonAndHandler(_(u'Cancel'))
def handleCancel(self, action):
# This method should never be called, it's only there to show
# a cancel button that is handled by a jQuery method.
Expand All @@ -278,9 +283,9 @@ def update(self):
super(CommentsViewlet, self).update()
discussion_allowed = self.is_discussion_allowed()
anonymous_allowed_or_can_reply = (
self.is_anonymous()
and self.anonymous_discussion_allowed()
or self.can_reply()
self.is_anonymous() and
self.anonymous_discussion_allowed() or
self.can_reply()
)
if discussion_allowed and anonymous_allowed_or_can_reply:
z2.switch_on(self, request_layer=IFormLayer)
Expand Down Expand Up @@ -356,26 +361,26 @@ def comment_transform_message(self):
settings = registry.forInterface(IDiscussionSettings, check=False)

# text transform setting
if settings.text_transform == "text/x-web-intelligent":
if settings.text_transform == 'text/x-web-intelligent':
message = translate(Message(COMMENT_DESCRIPTION_INTELLIGENT_TEXT),
context=self.request)
elif settings.text_transform == "text/x-web-markdown":
elif settings.text_transform == 'text/x-web-markdown':
message = translate(Message(COMMENT_DESCRIPTION_MARKDOWN),
context=self.request)
else:
message = translate(Message(COMMENT_DESCRIPTION_PLAIN_TEXT),
context=self.request)

# comment workflow
wftool = getToolByName(context, "portal_workflow", None)
wftool = getToolByName(context, 'portal_workflow', None)
workflow_chain = wftool.getChainForPortalType('Discussion Item')
if workflow_chain:
comment_workflow = workflow_chain[0]
comment_workflow = wftool[comment_workflow]
# check if the current workflow implements a pending state. If this
# is true comments are moderated
if 'pending' in comment_workflow.states:
message = message + " " + \
message = message + ' ' + \
translate(Message(COMMENT_DESCRIPTION_MODERATION_ENABLED),
context=self.request)

Expand Down Expand Up @@ -445,7 +450,7 @@ def get_commenter_home_url(self, username=None):
if username is None:
return None
else:
return "%s/author/%s" % (self.context.portal_url(), username)
return '{0}/author/{1}'.format(self.context.portal_url(), username)

def get_commenter_portrait(self, username=None):

Expand Down Expand Up @@ -491,9 +496,10 @@ def is_anonymous(self):
return portal_membership.isAnonymousUser()

def login_action(self):
return '%s/login_form?came_from=%s' % \
(self.navigation_root_url,
url_quote(self.request.get('URL', '')),)
return '{0}/login_form?came_from={1}'.format(
self.navigation_root_url,
url_quote(self.request.get('URL', '')),
)

def format_time(self, time):
# We have to transform Python datetime into Zope DateTime
Expand Down
Loading

1 comment on commit cb1bf28

@jenkins-plone-org
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@gforcada Jenkins CI reporting about code analysis
See the full report here: http://jenkins.plone.org/job/package-plone.app.discussion/26//violations

plone/app/discussion/contentrules.py:20:5: E731 do not assign a lambda expression, use a def
plone/app/discussion/browser/comments.py:132:1: C901 'CommentForm.handleComment' is too complex (17)
plone/app/discussion/browser/conversation.py:29:1: C901 'ConversationView._enabled_for_archetypes' is too complex (14)
plone/app/discussion/browser/conversation.py:135:12: P002 found "hasattr", consider replacing it
plone/app/discussion/browser/migration.py:34:1: C901 'View.__call__' is too complex (32)

Follow these instructions to reproduce it locally.

Please sign in to comment.