Skip to content

Commit 6cbddc0

Browse files
committed
black
1 parent b4d5b9d commit 6cbddc0

File tree

1 file changed

+92
-77
lines changed
  • src/collective/documentgenerator

1 file changed

+92
-77
lines changed

src/collective/documentgenerator/utils.py

Lines changed: 92 additions & 77 deletions
Original file line numberDiff line numberDiff line change
@@ -33,16 +33,12 @@
3333
import tempfile
3434

3535

36-
logger = logging.getLogger('collective.documentgenerator')
36+
logger = logging.getLogger("collective.documentgenerator")
3737

3838

39-
def translate(msgid, domain='collective.documentgenerator'):
39+
def translate(msgid, domain="collective.documentgenerator"):
4040
portal = api.portal.get()
41-
translation = i18n.translate(
42-
msgid,
43-
domain=domain,
44-
context=portal.REQUEST
45-
)
41+
translation = i18n.translate(msgid, domain=domain, context=portal.REQUEST)
4642
return translation
4743

4844

@@ -51,98 +47,109 @@ def compute_md5(data):
5147
return md5
5248

5349

54-
def update_templates(templates, profile='', force=False):
50+
def update_templates(templates, profile="", force=False):
5551
"""
56-
function to manage templates update.
57-
# see http://trac.imio.be/trac/ticket/9383 for full implementation
58-
:param list templates: list of tuples containing ('plone-template-path', 'os-template-path')
59-
:param str profile: profile path stored on template (or various identification)
60-
:param bool force: force overrides of templates
52+
function to manage templates update.
53+
# see http://trac.imio.be/trac/ticket/9383 for full implementation
54+
:param list templates: list of tuples containing ('plone-template-path', 'os-template-path')
55+
:param str profile: profile path stored on template (or various identification)
56+
:param bool force: force overrides of templates
6157
"""
6258
# Don't use profile now !
6359
portal = api.portal.getSite()
6460
ret = []
6561
for (ppath, ospath) in templates:
66-
ppath = ppath.strip('/ ')
62+
ppath = ppath.strip("/ ")
6763
obj = portal.unrestrictedTraverse(ppath, default=None)
6864
if not obj:
6965
logger.warn("The plone template '%s' was not found" % ppath)
70-
ret.append((ppath, ospath, 'plone path error'))
66+
ret.append((ppath, ospath, "plone path error"))
7167
continue
7268
if not obj.odt_file:
7369
logger.warn("The plone template '%s' doesn't have odt file" % ppath)
74-
ret.append((ppath, ospath, 'no odt file'))
70+
ret.append((ppath, ospath, "no odt file"))
7571
continue
7672
if not os.path.exists(ospath):
7773
logger.warn("The template file '%s' doesn't exist" % ospath)
78-
ret.append((ppath, ospath, 'os path error'))
74+
ret.append((ppath, ospath, "os path error"))
7975
continue
80-
with open(ospath, 'rb') as f:
76+
with open(ospath, "rb") as f:
8177
data = f.read()
8278
new_md5 = compute_md5(data)
8379
if obj.initial_md5 == new_md5:
84-
ret.append((ppath, ospath, 'unchanged'))
80+
ret.append((ppath, ospath, "unchanged"))
8581
continue
8682
elif obj.has_been_modified() and not force:
87-
ret.append((ppath, ospath, 'kept'))
83+
ret.append((ppath, ospath, "kept"))
8884
continue
8985
obj.initial_md5 = new_md5
9086
obj.style_modification_md5 = new_md5
9187
obj.odt_file.data = data
92-
modified(obj, Attributes(Interface, 'odt_file'))
93-
ret.append((ppath, ospath, 'replaced'))
88+
modified(obj, Attributes(Interface, "odt_file"))
89+
ret.append((ppath, ospath, "replaced"))
9490
return ret
9591

9692

9793
def update_dict_with_validation(original_dict, update_dict, error_message=_("Dict update collision on key")):
9894
for key in update_dict:
9995
if key in original_dict:
100-
raise Invalid(_("${error_message} for key = '${key}'",
101-
mapping={'error_message': error_message, 'key': key}))
96+
raise Invalid(
97+
_("${error_message} for key = '${key}'", mapping={"error_message": error_message, "key": key})
98+
)
10299

103100
original_dict[key] = update_dict[key]
104101

105102

106-
def ulocalized_time(date, long_format=None, time_only=None, custom_format=None,
107-
domain='plonelocales', target_language=None, context=None,
108-
request=None, month_lc=True, day_lc=True):
103+
def ulocalized_time(
104+
date,
105+
long_format=None,
106+
time_only=None,
107+
custom_format=None,
108+
domain="plonelocales",
109+
target_language=None,
110+
context=None,
111+
request=None,
112+
month_lc=True,
113+
day_lc=True,
114+
):
109115
"""
110-
Return for a datetime the string value with week and mont translated.
111-
Take into account %a, %A, %b, %B
116+
Return for a datetime the string value with week and mont translated.
117+
Take into account %a, %A, %b, %B
112118
"""
113119
if not custom_format:
114120
# use toLocalizedTime
115-
plone = getMultiAdapter((context, request), name=u'plone')
121+
plone = getMultiAdapter((context, request), name=u"plone")
116122
formatted_date = plone.toLocalizedTime(date, long_format, time_only)
117123
else:
118124
from Products.CMFPlone.i18nl10n import monthname_msgid
119125
from Products.CMFPlone.i18nl10n import monthname_msgid_abbr
120126
from Products.CMFPlone.i18nl10n import weekdayname_msgid
121127
from Products.CMFPlone.i18nl10n import weekdayname_msgid_abbr
128+
122129
if request is None:
123130
portal = api.portal.get()
124131
request = portal.REQUEST
125132
# first replace parts to translate
126-
custom_format = custom_format.replace('%%', '_p_c_')
133+
custom_format = custom_format.replace("%%", "_p_c_")
127134

128135
conf = {
129-
'a': {'fct': weekdayname_msgid_abbr, 'fmt': '%w', 'low': day_lc},
130-
'A': {'fct': weekdayname_msgid, 'fmt': '%w', 'low': day_lc},
131-
'b': {'fct': monthname_msgid_abbr, 'fmt': '%m', 'low': month_lc},
132-
'B': {'fct': monthname_msgid, 'fmt': '%m', 'low': month_lc},
136+
"a": {"fct": weekdayname_msgid_abbr, "fmt": "%w", "low": day_lc},
137+
"A": {"fct": weekdayname_msgid, "fmt": "%w", "low": day_lc},
138+
"b": {"fct": monthname_msgid_abbr, "fmt": "%m", "low": month_lc},
139+
"B": {"fct": monthname_msgid, "fmt": "%m", "low": month_lc},
133140
}
134-
matches = re.findall(r'%([aAbB])', custom_format)
141+
matches = re.findall(r"%([aAbB])", custom_format)
135142
for match in sorted(set(matches)):
136143
# function( int(date.strftime(format) )
137-
msgid = conf[match]['fct'](int(date.strftime(conf[match]['fmt'])))
144+
msgid = conf[match]["fct"](int(date.strftime(conf[match]["fmt"])))
138145
repl = i18n.translate(msgid, domain, context=request, target_language=target_language)
139-
if conf[match]['low']:
146+
if conf[match]["low"]:
140147
repl = repl.lower()
141-
custom_format = re.sub('%{}'.format(match), repl, custom_format)
148+
custom_format = re.sub("%{}".format(match), repl, custom_format)
142149

143150
# then format date
144-
custom_format = custom_format.replace('_p_c_', '%%')
145-
formatted_date = date.strftime(custom_format.encode('utf8'))
151+
custom_format = custom_format.replace("_p_c_", "%%")
152+
formatted_date = date.strftime(custom_format.encode("utf8"))
146153
return safe_unicode(formatted_date)
147154

148155

@@ -155,15 +162,15 @@ def remove_tmp_file(filename):
155162

156163

157164
def update_oo_config():
158-
""" Update config following buildout var """
159-
key_template = 'collective.documentgenerator.browser.controlpanel.IDocumentGeneratorControlPanelSchema.{}'
160-
var = {'oo_server': 'OO_SERVER', 'oo_port_list': 'OO_PORT', 'uno_path': 'PYTHON_UNO'}
165+
"""Update config following buildout var"""
166+
key_template = "collective.documentgenerator.browser.controlpanel.IDocumentGeneratorControlPanelSchema.{}"
167+
var = {"oo_server": "OO_SERVER", "oo_port_list": "OO_PORT", "uno_path": "PYTHON_UNO"}
161168
for key in var.keys():
162169
full_key = key_template.format(key)
163170
configured_oo_option = api.portal.get_registry_record(full_key)
164-
env_value = os.getenv(var.get(key, 'NO_ONE'), None)
171+
env_value = os.getenv(var.get(key, "NO_ONE"), None)
165172
if env_value:
166-
new_oo_option = type(configured_oo_option)(os.getenv(var.get(key, 'NO_ONE'), ''))
173+
new_oo_option = type(configured_oo_option)(os.getenv(var.get(key, "NO_ONE"), ""))
167174
if new_oo_option and new_oo_option != configured_oo_option:
168175
api.portal.set_registry_record(full_key, new_oo_option)
169176
logger.info("LibreOffice configuration updated for " + getSite().getId())
@@ -178,56 +185,52 @@ def update_oo_config_after_bigbang(event):
178185

179186

180187
def get_site_root_relative_path(obj):
181-
return "/" + '/'.join(
182-
getToolByName(obj, 'portal_url').getRelativeContentPath(obj)
183-
)
188+
return "/" + "/".join(getToolByName(obj, "portal_url").getRelativeContentPath(obj))
184189

185190

186-
def temporary_file_name(suffix=''):
187-
tmp_dir = os.getenv('CUSTOM_TMP', None)
191+
def temporary_file_name(suffix=""):
192+
tmp_dir = os.getenv("CUSTOM_TMP", None)
188193
if tmp_dir and not os.path.exists(tmp_dir):
189194
os.mkdir(tmp_dir)
190195
return tempfile.mktemp(suffix=suffix, dir=tmp_dir)
191196

192197

193-
def create_temporary_file(initial_file=None, base_name=''):
198+
def create_temporary_file(initial_file=None, base_name=""):
194199
tmp_filename = temporary_file_name(suffix=base_name)
195200
# create the file in any case
196-
with open(tmp_filename, 'w+') as tmp_file:
201+
with open(tmp_filename, "w+") as tmp_file:
197202
if initial_file:
198203
tmp_file.write(initial_file.data)
199204
return tmp_file
200205

201206

202207
def clean_notes(pod_template):
203-
""" Use appy.pod Cleaner to clean notes (comments). """
208+
"""Use appy.pod Cleaner to clean notes (comments)."""
204209
cleaned = 0
205210
odt_file = pod_template.odt_file
206211
if odt_file:
207212
# write file to /tmp to be able to use appy.pod Cleaner
208-
tmp_file = create_temporary_file(odt_file, '-to-clean.odt')
213+
tmp_file = create_temporary_file(odt_file, "-to-clean.odt")
209214
cleaner = Cleaner(path=tmp_file.name, verbose=1)
210215
cleaned = cleaner.run()
211216
if cleaned:
212217
manually_modified = pod_template.has_been_modified()
213-
with open(tmp_file.name, 'rb') as res_file:
218+
with open(tmp_file.name, "rb") as res_file:
214219
# update template
215220
result = NamedBlobFile(
216-
data=res_file.read(),
217-
contentType=odt_file.contentType,
218-
filename=pod_template.odt_file.filename)
221+
data=res_file.read(), contentType=odt_file.contentType, filename=pod_template.odt_file.filename
222+
)
219223
pod_template.odt_file = result
220224
if not manually_modified:
221225
pod_template.style_modification_md5 = pod_template.current_md5
222-
extras = 'pod_template={0} cleaned_parts={1}'.format(
223-
repr(pod_template), cleaned)
224-
fplog('clean_notes', extras=extras)
226+
extras = "pod_template={0} cleaned_parts={1}".format(repr(pod_template), cleaned)
227+
fplog("clean_notes", extras=extras)
225228
remove_tmp_file(tmp_file.name)
226229

227230
return bool(cleaned)
228231

229232

230-
def convert_odt(afile, fmt='pdf', gen_context=None, delete_temp_files=True, **kwargs):
233+
def convert_odt(afile, fmt="pdf", gen_context=None, delete_temp_files=True, **kwargs):
231234
"""
232235
Convert an odt file to another format using appy.pod.
233236
@@ -238,7 +241,7 @@ def convert_odt(afile, fmt='pdf', gen_context=None, delete_temp_files=True, **kw
238241
:param kwargs: other parameters passed to Renderer, i.e pdfOptions='ExportNotes=True;SelectPdfVersion=1'
239242
:return: converted file content
240243
"""
241-
temp_file = create_temporary_file(afile, '.odt')
244+
temp_file = create_temporary_file(afile, ".odt")
242245
converted_filename = temporary_file_name(suffix=".{extension}".format(extension=fmt))
243246
if not gen_context:
244247
gen_context = {}
@@ -265,7 +268,7 @@ def convert_odt(afile, fmt='pdf', gen_context=None, delete_temp_files=True, **kw
265268
type="error",
266269
)
267270
raise Invalid(u"Conversion failed, no converted file '{}'".format(safe_unicode(converted_filename)))
268-
with open(converted_filename, 'rb') as f:
271+
with open(converted_filename, "rb") as f:
269272
converted_file = f.read()
270273
finally:
271274
if delete_temp_files:
@@ -287,28 +290,34 @@ def convert_file(afile, fmt="pdf", renderer=False, gen_context=None, delete_temp
287290
:param delete_temp_files:
288291
"""
289292
if renderer:
290-
if not afile.filename.endswith('.odt'):
293+
if not afile.filename.endswith(".odt"):
291294
message = _(u"Conversion with renderer only works from odt files.")
292295
raise Invalid(message)
293296
return convert_odt(afile, fmt=fmt, gen_context=gen_context, delete_temp_files=delete_temp_files)
294297
from appy.pod import converter
298+
295299
converter_path = converter.__file__.endswith(".pyc") and converter.__file__[:-1] or converter.__file__
296-
file_ext = afile.filename.split('.')[-1].lower()
300+
file_ext = afile.filename.split(".")[-1].lower()
297301
temp_file = create_temporary_file(afile, base_name=".{}".format(file_ext))
298302
converted_filename = temp_file.name.replace(".{}".format(file_ext), ".{}".format(fmt))
299303
converted_file = ""
300304
try:
301305
ports = get_oo_port_list()
302306
port = ports[0] if ports else DEFAULT_OO_PORT
303307
command = "{python_uno_path} {converter_path} {temp_file} {fmt} -p {port} -e {server}".format(
304-
python_uno_path=get_uno_path(), converter_path=converter_path, temp_file=temp_file.name, fmt=fmt,
305-
port=port, server=get_oo_server())
308+
python_uno_path=get_uno_path(),
309+
converter_path=converter_path,
310+
temp_file=temp_file.name,
311+
fmt=fmt,
312+
port=port,
313+
server=get_oo_server(),
314+
)
306315
out, err, code = runCommand(command)
307316
# This command has no output on success
308317
if code != 0 or err or not os.path.exists(converted_filename):
309318
message = _(u"Conversion failed, no converted file '{}'".format(safe_unicode(converted_filename)))
310319
raise Invalid(message)
311-
with open(converted_filename, 'rb') as f:
320+
with open(converted_filename, "rb") as f:
312321
converted_file = f.read()
313322
except Exception as e:
314323
api.portal.show_message(message=str(e), request=getSite().REQUEST, type="error")
@@ -320,8 +329,17 @@ def convert_file(afile, fmt="pdf", renderer=False, gen_context=None, delete_temp
320329
return converted_file
321330

322331

323-
def convert_and_save_file(afile, container, portal_type, output_name, fmt='pdf', from_uid=None, attributes=None,
324-
renderer=False, gen_context=None):
332+
def convert_and_save_file(
333+
afile,
334+
container,
335+
portal_type,
336+
output_name,
337+
fmt="pdf",
338+
from_uid=None,
339+
attributes=None,
340+
renderer=False,
341+
gen_context=None,
342+
):
325343
"""
326344
Convert a file to another libreoffice readable format using appy.pod and save it in a NamedBlobFile.
327345
@@ -341,11 +359,8 @@ def convert_and_save_file(afile, container, portal_type, output_name, fmt='pdf',
341359
attributes = {}
342360
attributes["conv_from_uid"] = from_uid
343361
new_file = createContentInContainer(
344-
container,
345-
portal_type,
346-
title=safe_unicode(output_name),
347-
file=file_object,
348-
**attributes)
362+
container, portal_type, title=safe_unicode(output_name), file=file_object, **attributes
363+
)
349364
if from_uid:
350365
annot = IAnnotations(new_file)
351366
annot["documentgenerator"] = {"conv_from_uid": from_uid}

0 commit comments

Comments
 (0)