Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add code format check #91

Closed
wants to merge 7 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ jobs:
- python: "3.7"
env: PLONE_VERSION=5.2
install:
- bin/pip install black || true
- bin/buildout -N -t 3
- make build-frontend
script:
Expand Down
29 changes: 28 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ build-backend:
virtualenv --clear --python=python3 .
bin/pip install --upgrade pip
bin/pip install -r requirements.txt
bin/pip install black || true
bin/buildout

build-frontend:
Expand All @@ -52,7 +53,33 @@ start-frontend:
(cd src/collective/taxonomy/javascripts && yarn start)

.PHONY: Test
test: code-analysis test-backend test-frontend ## Test
test: code-format-check code-analysis test-backend test-frontend ## Test

.PHONY: Code Format Check
code-format-check: code-format-check-backend code-format-check-frontend ## Code Format Check

code-format-check-backend:
@echo "$(GREEN)==> Run Python code format check$(RESET)"
if [ "$$(command -v bin/black)" ]; then \
bin/black --check src/; \
fi

code-format-check-frontend:
@echo "$(GREEN)==> Run Javascript code format check$(RESET)"
(cd src/collective/taxonomy/javascripts && yarn prettier)

.PHONY: Code Format
code-format: code-format-backend code-format-frontend ## Code Format

code-format-backend:
@echo "$(GREEN)==> Run Python code format$(RESET)"
if [ "$$(command -v bin/black)" ]; then \
bin/black src/; \
fi

code-format-frontend:
@echo "$(GREEN)==> Run Javascript code format$(RESET)"
(cd src/collective/taxonomy/javascripts && yarn prettier:fix)

code-analysis:
@echo "$(green)==> Run static code analysis$(reset)"
Expand Down
3 changes: 2 additions & 1 deletion src/collective/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
try:
__import__('pkg_resources').declare_namespace(__name__)
__import__("pkg_resources").declare_namespace(__name__)
except ImportError:
from pkgutil import extend_path

__path__ = extend_path(__path__, __name__)
2 changes: 1 addition & 1 deletion src/collective/taxonomy/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@

PATH_SEPARATOR = u"\u241F"
LEGACY_PATH_SEPARATOR = u"/"
PRETTY_PATH_SEPARATOR = u' » '
PRETTY_PATH_SEPARATOR = u" » "
NODE = u"#NODE"
132 changes: 80 additions & 52 deletions src/collective/taxonomy/behavior.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,12 @@
import pkg_resources

try:
pkg_resources.get_distribution('plone.app.multilingual')
pkg_resources.get_distribution("plone.app.multilingual")
except pkg_resources.DistributionNotFound:
HAS_PAM = False
else:
from plone.app.multilingual.dx.interfaces import ILanguageIndependentField

HAS_PAM = True

logger = logging.getLogger("collective.taxonomy")
Expand All @@ -46,11 +47,20 @@ class TaxonomyBehavior(Persistent):
is_single_select = False
field_prefix = "taxonomy_"

def __init__(self, name, title, description, field_title,
field_description, is_required=False,
is_single_select=False, write_permission='',
field_prefix="taxonomy_",
default_language='en', taxonomy_fieldset='categorization'):
def __init__(
self,
name,
title,
description,
field_title,
field_description,
is_required=False,
is_single_select=False,
write_permission="",
field_prefix="taxonomy_",
default_language="en",
taxonomy_fieldset="categorization",
):
self.name = name
self.title = _(title)
self.description = _(description)
Expand All @@ -66,75 +76,98 @@ def __init__(self, name, title, description, field_title,

def deactivateSearchable(self):
registry = getUtility(IRegistry)
prefix = 'plone.app.querystring.field.' + self.field_name
for suffix in ('title', 'enabled', 'group',
'operations', 'vocabulary', 'sortable', 'description'):
record_name = prefix + '.' + suffix
prefix = "plone.app.querystring.field." + self.field_name
for suffix in (
"title",
"enabled",
"group",
"operations",
"vocabulary",
"sortable",
"description",
):
record_name = prefix + "." + suffix
if record_name in registry.records:
del registry.records[record_name]

def removeIndex(self):
context = getSite()
sm = context.getSiteManager()
sm.unregisterAdapter(
factory=None, required=(IDexterityContent, IZCatalog),
provided=IIndexer, name=self.field_name)
catalog = getToolByName(context, 'portal_catalog')
factory=None,
required=(IDexterityContent, IZCatalog),
provided=IIndexer,
name=self.field_name,
)
catalog = getToolByName(context, "portal_catalog")
try:
catalog.delIndex(self.field_name)
except CatalogError:
logging.info(
"Could not delete index {0} .. something is not right.".format(
self.field_name))
self.field_name
)
)

def activateSearchable(self):
registry = getUtility(IRegistry)
prefix = 'plone.app.querystring.field.' + self.field_name
prefix = "plone.app.querystring.field." + self.field_name

def add(name, value):
registry.records[prefix + '.' + name] = value

add('title', Record(field.TextLine(), safe_unicode(self.field_title)))
add('enabled', Record(field.Bool(), True))
add('group', Record(field.TextLine(), safe_unicode('Taxonomy')))
add('operations', Record(field.List(value_type=field.TextLine()),
[u'plone.app.querystring.operation.selection.is']))
add('vocabulary', Record(field.TextLine(), safe_unicode(self.vocabulary_name))) # noqa: E501
add('sortable', Record(field.Bool(), False))
add('description', Record(field.Text(), safe_unicode('')))
registry.records[prefix + "." + name] = value

add("title", Record(field.TextLine(), safe_unicode(self.field_title)))
add("enabled", Record(field.Bool(), True))
add("group", Record(field.TextLine(), safe_unicode("Taxonomy")))
add(
"operations",
Record(
field.List(value_type=field.TextLine()),
[u"plone.app.querystring.operation.selection.is"],
),
)
add(
"vocabulary", Record(field.TextLine(), safe_unicode(self.vocabulary_name))
) # noqa: E501
add("sortable", Record(field.Bool(), False))
add("description", Record(field.Text(), safe_unicode("")))

def addIndex(self):
context = getSite()
sm = context.getSiteManager()
sm.registerAdapter(
TaxonomyIndexer(self.field_name, self.vocabulary_name),
(IDexterityContent, IZCatalog),
IIndexer, name=self.field_name)
IIndexer,
name=self.field_name,
)

catalog = getToolByName(context, 'portal_catalog')
catalog = getToolByName(context, "portal_catalog")
idx_object = KeywordIndex(str(self.field_name))
try:
catalog.addIndex(self.field_name, idx_object)
except CatalogError:
logging.info(
"Index {0} already exists, we hope it is proper configured".format( # noqa: E501
self.field_name))
self.field_name
)
)

def unregisterInterface(self):
if hasattr(generated, self.short_name):
delattr(generated, self.short_name)

@property
def short_name(self):
return str(self.name.split('.')[-1])
return str(self.name.split(".")[-1])

@property
def field_name(self):
return (self.field_prefix or "") + self.short_name

@property
def vocabulary_name(self):
return 'collective.taxonomy.' + self.short_name
return "collective.taxonomy." + self.short_name

@property
def interface(self):
Expand All @@ -145,14 +178,14 @@ def marker(self):
return getattr(generated, self.short_name)

def generateInterface(self):
logger.debug('generating interface for %s' % self.short_name)
logger.debug("generating interface for %s" % self.short_name)

if hasattr(self, 'is_single_select') and self.is_single_select:
if hasattr(self, "is_single_select") and self.is_single_select:
select_field = schema.Choice(
title=_(safe_unicode(self.field_title)),
description=_(safe_unicode(self.field_description)),
required=self.is_required,
vocabulary=self.vocabulary_name
vocabulary=self.vocabulary_name,
)
else:
select_field = schema.List(
Expand All @@ -161,43 +194,38 @@ def generateInterface(self):
required=self.is_required,
min_length=self.is_required and 1 or 0,
value_type=schema.Choice(
vocabulary=self.vocabulary_name,
required=self.is_required
)
vocabulary=self.vocabulary_name, required=self.is_required
),
)

schemaclass = SchemaClass(
self.short_name, (Schema, ),
__module__='collective.taxonomy.generated',
attrs={
str(self.field_name): select_field
}
self.short_name,
(Schema,),
__module__="collective.taxonomy.generated",
attrs={str(self.field_name): select_field},
)

if self.write_permission:
schemaclass.setTaggedValue(
WRITE_PERMISSIONS_KEY,
{self.field_name:
self.write_permission}
WRITE_PERMISSIONS_KEY, {self.field_name: self.write_permission}
)

try:
taxonomy_fieldset = self.taxonomy_fieldset
except AttributeError:
# Backwards compatible:
taxonomy_fieldset = 'categorization'
if taxonomy_fieldset != 'default':
taxonomy_fieldset = "categorization"
if taxonomy_fieldset != "default":
schemaclass.setTaggedValue(
FIELDSETS_KEY,
[Fieldset(taxonomy_fieldset,
fields=[self.field_name])]
FIELDSETS_KEY, [Fieldset(taxonomy_fieldset, fields=[self.field_name])]
)

if hasattr(self, 'is_single_select') and not self.is_single_select:
if hasattr(self, "is_single_select") and not self.is_single_select:
schemaclass.setTaggedValue(
WIDGETS_KEY,
{self.field_name:
'collective.taxonomy.widget.TaxonomySelectFieldWidget'}
{
self.field_name: "collective.taxonomy.widget.TaxonomySelectFieldWidget"
},
)

alsoProvides(schemaclass, IFormFieldProvider)
Expand Down
37 changes: 21 additions & 16 deletions src/collective/taxonomy/browser.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@


class TaxonomyView(BrowserView):

def taxonomiesForContext(self, short_names=[]):
results = []

Expand All @@ -21,41 +20,47 @@ def taxonomiesForContext(self, short_names=[]):
if short_names and short_name not in short_names:
continue

if getattr(self.context, 'taxonomy_' + short_name, None):
for taxon in getattr(self.context, 'taxonomy_' + short_name):
results.append(self.translate(
taxon,
domain='collective.taxonomy.' + short_name
))
if getattr(self.context, "taxonomy_" + short_name, None):
for taxon in getattr(self.context, "taxonomy_" + short_name):
results.append(
self.translate(
taxon, domain="collective.taxonomy." + short_name
)
)

return results

def translate(self, msgid, domain='', target_language=None):
def translate(self, msgid, domain="", target_language=None):
""" Eq to context.translate(msgid, domain) """
sm = getSiteManager()
utility = sm.queryUtility(ITaxonomy, name=domain)
return utility.translate(msgid, context=self.context, target_language=target_language) # noqa: E501
return utility.translate(
msgid, context=self.context, target_language=target_language
) # noqa: E501


class VocabularyTuplesView(BrowserView):

def __init__(self, context, request, vocabulary):
super(VocabularyTuplesView, self).__init__(context, request)
self.vocabulary = vocabulary

def __call__(self, target_language=None):
return ((term.token, translate(term.title,
context=self.request,
target_language=target_language))
for term in self.vocabulary)
return (
(
term.token,
translate(
term.title, context=self.request, target_language=target_language
),
)
for term in self.vocabulary
)


@implementer_only(ITraversable)
class TaxonomyTraverser(BrowserView):

def traverse(self, name, remaining):
sm = getSiteManager()
domain = 'collective.taxonomy.' + name
domain = "collective.taxonomy." + name
factory = sm.queryUtility(IVocabularyFactory, name=domain)

if factory is not None:
Expand Down