Skip to content

Commit 53b42ea

Browse files
committed
[chore] util: handle ruff claims
Part of odoo/upgrade#5130 Signed-off-by: Christophe Simonis (chs) <[email protected]>
1 parent 03481a6 commit 53b42ea

17 files changed

+84
-84
lines changed

src/util/const.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,12 +12,12 @@
1212
ENVIRON = {
1313
"__renamed_fields": collections.defaultdict(dict),
1414
"__modules_auto_discovery_force_installs": set(),
15-
"__modules_auto_discovery_force_upgrades": dict(),
15+
"__modules_auto_discovery_force_upgrades": {},
1616
"__fix_fk_allowed_cascade": [],
1717
"__no_model_data_delete": {},
1818
}
1919

2020
NEARLYWARN = 25 # between info and warning; appear on runbot build page
2121
netsvc.LEVEL_COLOR_MAPPING[NEARLYWARN] = (netsvc.YELLOW, netsvc.DEFAULT)
2222

23-
BIG_TABLE_THRESHOLD = int(os.getenv("ODOO_UPG_BIG_TABLE_THRESHOLD", 40000))
23+
BIG_TABLE_THRESHOLD = int(os.getenv("ODOO_UPG_BIG_TABLE_THRESHOLD", "40000"))

src/util/convert_bootstrap.py

Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -253,9 +253,7 @@ def simple_css_selector_to_xpath(selector, prefix="//"):
253253
separator = prefix
254254
xpath_parts = []
255255
combinators = "+>,~ "
256-
for selector_part in re.split(rf"(\s*[{combinators}]\s*)", selector):
257-
selector_part = selector_part.strip()
258-
256+
for selector_part in map(str.strip, re.split(rf"(\s*[{combinators}]\s*)", selector)):
259257
if not selector_part:
260258
separator = "//"
261259
elif selector_part == ">":
@@ -310,8 +308,7 @@ def adapt_xpath_for_qweb(xpath):
310308
r"normalize-space(concat(@\1, ' ', @t-att-\1, ' ', @t-attf-\1))",
311309
xpath,
312310
)
313-
xpath = re.sub(r"\[@(?<!t-)([\w-]+)\]", r"[@\1 or @t-att-\1 or @t-attf-\1]", xpath)
314-
return xpath
311+
return re.sub(r"\[@(?<!t-)([\w-]+)\]", r"[@\1 or @t-att-\1 or @t-attf-\1]", xpath)
315312

316313

317314
class ElementOperation:
@@ -367,7 +364,6 @@ def __call__(self, element, converter):
367364
if parent is None:
368365
raise ValueError(f"Cannot remove root element {element}")
369366
parent.remove(element)
370-
return None
371367

372368

373369
class EditClasses(ElementOperation):
@@ -484,7 +480,6 @@ def __call__(self, element, converter):
484480
element.addprevious(child)
485481

486482
parent.remove(element)
487-
return None
488483

489484

490485
class RenameAttribute(ElementOperation):
@@ -711,7 +706,7 @@ class BS4to5ConvertCardDeck(ElementOperation):
711706
def __call__(self, element, converter):
712707
cards = element.xpath(converter.adapt_xpath("./*[hasclass('card')]"))
713708

714-
cols_class = f"row-cols-{len(cards) if 0 < len(cards) <= 6 else 'auto'}"
709+
cols_class = f"row-cols-{len(cards)}" if len(cards) in range(1, 7) else "row-cols-auto"
715710
edit_element_classes(element, add=["row", cols_class], remove="card-deck", is_qweb=converter.is_qweb)
716711

717712
for card in cards:
@@ -1008,7 +1003,7 @@ def convert(self, src_version, dst_version):
10081003
for operation in operations:
10091004
if element is None: # previous operations that returned None (i.e. deleted element)
10101005
raise ValueError("Matched xml element is not available anymore! Check operations.")
1011-
element = operation(element, self)
1006+
element = operation(element, self) # noqa: PLW2901
10121007
applied_operations_count += 1
10131008
return self.tree, applied_operations_count
10141009

src/util/data.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -206,5 +206,5 @@ def drop_workflow(cr, osv):
206206
FOREIGN KEY (instance_id) REFERENCES wkf_instance(id)
207207
ON DELETE CASCADE;
208208
""",
209-
dict(osv=osv),
209+
{"osv": osv},
210210
)

src/util/domains.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -279,12 +279,13 @@ def adapt_domains(cr, model, old, new, adapter=None, skip_inherit=(), force_adap
279279
[match_old],
280280
)
281281
for id_, model, domain in cr.fetchall():
282-
domain = _adapt_one_domain(
282+
new_domain = _adapt_one_domain(
283283
cr, target_model, old, new, model, domain, adapter=adapter, force_adapt=force_adapt
284284
)
285-
if domain:
285+
if new_domain:
286286
cr.execute(
287-
"UPDATE {df.table} SET {df.domain_column} = %s WHERE id = %s".format(df=df), [unicode(domain), id_]
287+
"UPDATE {df.table} SET {df.domain_column} = %s WHERE id = %s".format(df=df),
288+
[unicode(new_domain), id_],
288289
)
289290

290291
# adapt domain in dashboards.

src/util/fields.py

Lines changed: 15 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -98,15 +98,15 @@ def remove_field(cr, model, fieldname, cascade=False, drop_column=True, skip_inh
9898
def filter_value(key, value):
9999
if key == "orderedBy" and isinstance(value, dict):
100100
res = {k: (filter_value(None, v) if k == "name" else v) for k, v in value.items()}
101-
if "name" not in res or res["name"] is not None:
102-
# return if name didn't match fieldname
103-
return res
104-
elif not isinstance(value, basestring): # noqa: SIM114
101+
# return if name didn't match fieldname
102+
return res if "name" not in res or res["name"] is not None else None
103+
if not isinstance(value, basestring):
105104
# if not a string, ignore it
106105
return value
107-
elif value.split(":")[0] != fieldname:
106+
if value.split(":")[0] != fieldname:
108107
# only return if not matching fieldname
109108
return value
109+
return None # value filtered out
110110

111111
def clean_context(context):
112112
if not isinstance(context, dict):
@@ -119,7 +119,7 @@ def clean_context(context):
119119
changed |= context_part != context[key]
120120
context[key] = [e for e in context_part if e is not None]
121121

122-
for vt in {"pivot", "graph", "cohort"}:
122+
for vt in ["pivot", "graph", "cohort"]:
123123
key = "{}_measure".format(vt)
124124
if key in context:
125125
new_value = filter_value(key, context[key])
@@ -146,8 +146,8 @@ def clean_context(context):
146146
"SELECT id, name, context FROM ir_filters WHERE model_id = %s AND context ~ %s",
147147
[model, r"\y{}\y".format(fieldname)],
148148
)
149-
for id_, name, context in cr.fetchall():
150-
context = safe_eval(context or "{}", SelfPrintEvalContext(), nocopy=True)
149+
for id_, name, context_s in cr.fetchall():
150+
context = safe_eval(context_s or "{}", SelfPrintEvalContext(), nocopy=True)
151151
changed = clean_context(context)
152152
cr.execute("UPDATE ir_filters SET context = %s WHERE id = %s", [unicode(context), id_])
153153
if changed:
@@ -255,9 +255,9 @@ def adapter(leaf, is_or, negated):
255255
""",
256256
[model, r"\y%s\y" % (fieldname,)],
257257
)
258-
for alias_id, defaults in cr.fetchall():
258+
for alias_id, defaults_s in cr.fetchall():
259259
try:
260-
defaults = dict(safe_eval(defaults)) # XXX literal_eval should works.
260+
defaults = dict(safe_eval(defaults_s)) # XXX literal_eval should works.
261261
except Exception:
262262
continue
263263
defaults.pop(fieldname, None)
@@ -638,12 +638,12 @@ def convert_binary_field_to_attachment(cr, model, field, encoded=True, name_fiel
638638
for rid, data, name in iter_cur:
639639
# we can't save create the attachment with res_model & res_id as it will fail computing
640640
# `res_name` field for non-loaded models. Store it naked and change it via SQL after.
641-
data = bytes(data)
641+
data = bytes(data) # noqa: PLW2901
642642
if re.match(b"^\\d+ (bytes|[KMG]b)$", data, re.I):
643643
# badly saved data, no need to create an attachment.
644644
continue
645645
if not encoded:
646-
data = base64.b64encode(data)
646+
data = base64.b64encode(data) # noqa: PLW2901
647647
att = A.create({"name": name, "datas": data, "type": "binary"})
648648
cr.execute(
649649
"""
@@ -937,7 +937,7 @@ def adapt_dict(d):
937937
if d.get(key):
938938
d[key] = [adapt_value(key, e) for e in d[key]]
939939

940-
for vt in {"pivot", "graph", "cohort"}:
940+
for vt in ["pivot", "graph", "cohort"]:
941941
key = "{}_measure".format(vt)
942942
if key in d:
943943
d[key] = adapt_value(key, d[key])
@@ -990,8 +990,7 @@ def adapt_related(cr, model, old, new, skip_inherit=()):
990990
for id_, model, related in cr.fetchall():
991991
domain = _adapt_one_domain(cr, target_model, old, new, model, [(related, "=", "related")])
992992
if domain:
993-
related = domain[0][0]
994-
cr.execute("UPDATE ir_model_fields SET related = %s WHERE id = %s", [related, id_])
993+
cr.execute("UPDATE ir_model_fields SET related = %s WHERE id = %s", [domain[0][0], id_])
995994

996995
# TODO adapt paths in email templates?
997996

@@ -1059,7 +1058,7 @@ def update_server_actions_fields(cr, src_model, dst_model=None, fields_mapping=N
10591058

10601059
# update ir_act_server records to point to the right model if set
10611060
if dst_model is not None and src_model != dst_model and cr.rowcount > 0:
1062-
action_ids = tuple(set([row[0] for row in cr.fetchall()]))
1061+
action_ids = tuple({row[0] for row in cr.fetchall()}) # uniquify ids
10631062

10641063
cr.execute(
10651064
"""

src/util/helpers.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
"o2m_changes_parent",
2121
"o2m_changes_children",
2222
}
23-
| set(m.strip() for m in os.getenv("UPG_VALID_MODELS", "").split(";")) - {""}
23+
| {m.strip() for m in os.getenv("UPG_VALID_MODELS", "").split(";")} - {""}
2424
)
2525

2626
# python3 shims
@@ -184,10 +184,10 @@ def _dashboard_actions(cr, arch_match, *models):
184184
for dash_id, arch in cr.fetchall():
185185
try:
186186
if isinstance(arch, unicode):
187-
arch = arch.encode("utf-8")
187+
arch = arch.encode("utf-8") # noqa: PLW2901
188188
dash = lxml.etree.fromstring(arch)
189189
except lxml.etree.XMLSyntaxError:
190-
_logger.error("Cannot parse dashboard %s", dash_id)
190+
_logger.exception("Cannot parse dashboard %s", dash_id)
191191
continue
192192
for act in dash.xpath("//action"):
193193
if models:

src/util/indirect_references.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ def indirect_references(cr, bound_only=False):
7474
IR("marketing_participant", "model_name", "res_id", "model_id", set_unknown=True),
7575
IR("payment_transaction", None, "callback_res_id", "callback_model_id"),
7676
IR("project_project", "alias_model", None, set_unknown=True),
77-
# IR("pos_blackbox_be_log", "model_name", None), # ACTUALLY NOT. We need to keep records intact, even when renaming a model
77+
# IR("pos_blackbox_be_log", "model_name", None), # ACTUALLY NOT. We need to keep records intact, even when renaming a model # noqa: ERA001
7878
IR("quality_point", "worksheet_model_name", None),
7979
IR("rating_rating", "res_model", "res_id", "res_model_id"),
8080
IR("rating_rating", "parent_res_model", "parent_res_id", "parent_res_model_id"),
@@ -97,9 +97,9 @@ def indirect_references(cr, bound_only=False):
9797
# versions (i.e. rating_rating.res_model_id was added in saas~15).
9898
# we need to verify existance of columns before using them.
9999
if ir.res_model and not column_exists(cr, ir.table, ir.res_model):
100-
ir = ir._replace(res_model=None)
100+
ir = ir._replace(res_model=None) # noqa: PLW2901
101101
if ir.res_model_id and not column_exists(cr, ir.table, ir.res_model_id):
102-
ir = ir._replace(res_model_id=None)
102+
ir = ir._replace(res_model_id=None) # noqa: PLW2901
103103
if not ir.res_model and not ir.res_model_id:
104104
continue
105105

src/util/jinja_to_qweb.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,8 @@
55
import re
66

77
import babel
8-
import dateutil.relativedelta as relativedelta
98
import lxml
9+
from dateutil import relativedelta
1010
from jinja2.sandbox import SandboxedEnvironment
1111
from markupsafe import Markup
1212
from werkzeug import urls
@@ -164,8 +164,7 @@ def convert_jinja_to_qweb(string):
164164
result = lxml.etree.tostring(lxml.html.fragment_fromstring(result, create_parent="div"), encoding="unicode")
165165

166166
# Remove the parent div
167-
result = result[5:-6]
168-
return result
167+
return result[5:-6]
169168

170169

171170
def _get_set(matchobj):

src/util/logger.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ def __init__(self):
1515
super(CriticalHandler, self).__init__(logging.CRITICAL)
1616

1717
def emit(self, record):
18-
global _REGISTERED
18+
global _REGISTERED # noqa: PLW0603
1919
if _REGISTERED:
2020
return
2121

src/util/misc.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -144,7 +144,7 @@ def import_script(path, name=None):
144144
if full_path.exists():
145145
break
146146
else:
147-
raise ImportError(path)
147+
raise ImportError(path) # noqa: TRY301
148148
spec = importlib.util.spec_from_file_location(name, full_path)
149149
module = importlib.util.module_from_spec(spec)
150150
spec.loader.exec_module(module)
@@ -219,7 +219,8 @@ def log_progress(it, logger, qualifier="elements", size=None, estimate=True, log
219219
for i, e in enumerate(it, 1):
220220
yield e
221221
t2 = datetime.datetime.now()
222-
if (t2 - t1).total_seconds() > 60 or (log_hundred_percent and i == size and (t2 - t0).total_seconds() > 10):
222+
secs_last, secs_start = (t2 - t1).total_seconds(), (t2 - t0).total_seconds()
223+
if secs_last > 60 or (log_hundred_percent and i == size and secs_start > 10):
223224
t1 = datetime.datetime.now()
224225
tdiff = t2 - t0
225226
j = float(i)

0 commit comments

Comments
 (0)