Commit 16aa08fb authored by Alexandru Băluț's avatar Alexandru Băluț
Browse files

Update pre-commit plugins

Make fixes suggested by pylint
parent 52035efc
Pipeline #314667 failed with stages
in 38 minutes and 45 seconds
---
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks.git
rev: v3.4.0
rev: v4.0.1
hooks:
- id: check-yaml
# Hooks able to fix small things.
......@@ -13,14 +13,14 @@ repos:
- id: check-docstring-first
- id: debug-statements
- repo: https://github.com/asottile/reorder_python_imports.git
rev: v2.4.0
rev: v2.6.0
hooks:
- id: reorder-python-imports
args:
- --py3-plus
- --unclassifiable-application-module=tests
- repo: https://github.com/pycqa/pydocstyle
rev: 5.1.1
rev: 6.1.1
hooks:
- id: pydocstyle
args:
......@@ -28,7 +28,7 @@ repos:
- --ignore=D1,D203,D213,D401,D406,D407,D413
exclude: '.*pitivi/utils/extract.py$|.*pitivi/autoaligner.py$'
- repo: https://gitlab.com/PyCQA/flake8
rev: 3.8.4
rev: 3.9.2
hooks:
- id: flake8
args:
......@@ -41,7 +41,7 @@ repos:
pitivi/autoaligner.py|
)$
- repo: https://github.com/pre-commit/mirrors-mypy
rev: 'v0.800'
rev: 'v0.910'
hooks:
- id: mypy
files: '^pitivi/(clipproperties.py|timeline/timeline.py)$'
......@@ -62,14 +62,14 @@ repos:
bin/pitivi.in
)$
- repo: https://github.com/adrienverge/yamllint.git
rev: v1.26.0
rev: v1.26.3
hooks:
- id: yamllint
args:
- -d
- "{extends: default, rules: {line-length: disable}}"
- repo: https://gitlab.com/devopshq/gitlab-ci-linter
rev: v1.0.1
rev: v1.0.3
hooks:
- id: gitlab-ci-linter
args:
......
......@@ -86,7 +86,7 @@ def remove_comments(string):
def load_manifest(manifest_path):
with open(manifest_path, "r") as mr:
with open(manifest_path, "r", encoding="UTF-8") as mr:
contents = mr.read()
contents = remove_comments(contents)
manifest = json.loads(contents)
......@@ -145,7 +145,7 @@ def expand_manifest(manifest_path, outfile, basedir, gst_version, branchname):
module["sources"][0]["url"] = repo
module["sources"][0]["branch"] = branch
with open(outfile, "w") as of:
with open(outfile, "w", encoding="UTF-8") as of:
print(json.dumps(template, indent=4), file=of)
......@@ -306,11 +306,11 @@ class FlatpakRepos(FlatpakObject):
self.packages = FlatpakPackages(self)
def add(self, name, flatpakrepo_url, override=True):
flatpakrepo = tempfile.NamedTemporaryFile(mode="w")
try:
urlretrieve(flatpakrepo_url, flatpakrepo.name)
repo = configparser.ConfigParser()
repo.read(flatpakrepo.name)
with tempfile.NamedTemporaryFile(mode="w") as flatpakrepo:
urlretrieve(flatpakrepo_url, flatpakrepo.name)
repo = configparser.ConfigParser()
repo.read(flatpakrepo.name)
url = repo["Flatpak Repo"]["Url"]
except URLError:
url = None
......@@ -445,18 +445,16 @@ class PitiviFlatpak:
self.build_name = self.name
if os.path.exists(os.path.join(self.topdir, ".git")):
devnull = open(os.devnull)
try:
branch = subprocess.check_output(
"git rev-parse --abbrev-ref HEAD".split(" "),
stderr=devnull,
cwd=self.topdir).decode("utf-8").strip("\n")
self.build_name = self.name + "." + branch
self.build_name = self.build_name.replace(os.path.sep, "_")
except subprocess.CalledProcessError:
pass
finally:
devnull.close()
with open(os.devnull, encoding="UTF-8") as devnull:
try:
branch = subprocess.check_output(
"git rev-parse --abbrev-ref HEAD".split(" "),
stderr=devnull,
cwd=self.topdir).decode("utf-8").strip("\n")
self.build_name = self.name + "." + branch
self.build_name = self.build_name.replace(os.path.sep, "_")
except subprocess.CalledProcessError:
pass
self.coredumpgdb = None
self.coredumpctl_matches = ""
......@@ -617,7 +615,7 @@ class PitiviFlatpak:
command = ["coredumpctl", "dump"] + shlex.split(self.coredumpctl_matches)
subprocess.check_call(command, stdout=coredump, stderr=stderr)
with open(stderr.name, 'r') as stderrf:
with open(stderr.name, "r", encoding="UTF-8") as stderrf:
stderr = stderrf.read()
executable, = re.findall(".*Executable: (.*)", stderr)
if not executable.startswith("/newroot"):
......
......@@ -254,14 +254,14 @@ class Pitivi(Gtk.Application, Loggable):
scenario_path = os.path.join(cache_dir, scenario_name + ".scenario")
scenario_path = path_from_uri(quote_uri(scenario_path))
self._scenario_file = open(scenario_path, "w")
# pylint: disable=consider-using-with
self._scenario_file = open(scenario_path, "w", encoding="UTF-8")
if project_path and not project_path.endswith(".scenario"):
# It's an xges file probably.
with open(project_path) as project:
with open(project_path, encoding="UTF-8") as project:
content = project.read().replace("\n", "")
self.write_action("load-project",
serialized_content=content)
self.write_action("load-project", serialized_content=content)
def _new_project_loaded_cb(self, unused_project_manager, project):
uri = project.get_uri()
......
......@@ -108,6 +108,8 @@ class TitleProperties(Gtk.Expander, Loggable):
self.x_absolute_spin = builder.get_object("x-absolute")
self.y_absolute_spin = builder.get_object("y-absolute")
# TODO: Remove when we upgrade pylint https://github.com/PyCQA/pylint/issues/4962
# pylint: disable=superfluous-parens
for value_id, text in (("absolute", _("Absolute")),
("top", _("Top")),
("center", _("Center")),
......@@ -300,7 +302,7 @@ class TitleProperties(Gtk.Expander, Loggable):
assert res, pspec.name
if pspec.name == "text":
text = html.unescape(value)
if self.textbuffer.props.text == text or "":
if self.textbuffer.props.text == text:
return
self.textbuffer.props.text = text
elif pspec.name in ["x-absolute", "y-absolute"]:
......
......@@ -877,10 +877,7 @@ class EffectProperties(Gtk.Expander, Loggable):
def _move_effect(self, clip, source_index, drop_index):
# Handle edge cases
if drop_index < 0:
drop_index = 0
if drop_index > len(clip.get_top_effects()) - 1:
drop_index = len(clip.get_top_effects()) - 1
drop_index = min(max(0, drop_index), len(clip.get_top_effects()) - 1)
if source_index == drop_index:
# Noop.
return
......
......@@ -364,8 +364,8 @@ class PreferencesDialog(Loggable):
self.__update_proxy_size_revert_button()
def __update_proxy_size_revert_button(self):
default = all([self.settings.is_default(setting)
for setting in ("default_scaled_proxy_width", "default_scaled_proxy_height")])
default = all(self.settings.is_default(setting)
for setting in ("default_scaled_proxy_width", "default_scaled_proxy_height"))
self.scaled_proxy_size_revert_button.set_sensitive(not default)
def __update_scaled_proxies_infobar(self):
......
......@@ -72,14 +72,14 @@ class EditorState(Loggable):
self.log("Editor state saving.")
if self.conf_file_path:
with open(self.conf_file_path, "w") as file:
with open(self.conf_file_path, "w", encoding="UTF-8") as file:
json.dump(self._editor_state, file)
def load_editor_state(self):
"""Load an editor state file into the current editor state."""
self.log("Loading state from file: %s", self.conf_file_path)
try:
with open(self.conf_file_path, "r") as file:
with open(self.conf_file_path, "r", encoding="UTF-8") as file:
try:
self._editor_state = json.load(file)
except (json.decoder.JSONDecodeError, ValueError) as e:
......
......@@ -425,8 +425,8 @@ class AssetThumbnail(GObject.Object, Loggable):
cls.icons_by_name[icon_name] = (small_icon, large_icon)
return cls.icons_by_name[icon_name]
@classmethod
def __get_icon(cls, icon_name, size):
@staticmethod
def __get_icon(icon_name, size):
icon_theme = Gtk.IconTheme.get_default()
try:
icon = icon_theme.load_icon(icon_name, size, Gtk.IconLookupFlags.FORCE_SIZE)
......@@ -817,7 +817,7 @@ class MediaLibraryWidget(Gtk.Box, Loggable):
matches = not tags.difference(self.store[i].tags)
if matches:
row_text = self.store[i].infotext.lower()
matches = all([escaped_word in row_text for escaped_word in escaped_words])
matches = all(escaped_word in row_text for escaped_word in escaped_words)
row_widget.set_visible(bool(matches))
def _update_search_suggestions(self, prefix: str, entered_tags: Set[str]):
......@@ -1415,6 +1415,7 @@ class MediaLibraryWidget(Gtk.Box, Loggable):
return
path = os.path.abspath(path_from_uri(assets[0].get_id()))
# pylint: disable=consider-using-with
subprocess.Popen([sys.argv[0], path])
def __create_menu_model(self):
......
......@@ -182,7 +182,7 @@ class PresetManager(GObject.Object, Loggable):
for uri in files:
filepath = os.path.join(presets_dir, uri)
if filepath.endswith("json"):
with open(filepath) as section:
with open(filepath, encoding="UTF-8") as section:
parser = json.loads(section.read())
name = parser["name"]
if parser.get("removed"):
......@@ -212,7 +212,7 @@ class PresetManager(GObject.Object, Loggable):
except KeyError:
file_path = self._build_file_path(preset_name)
self.presets[preset_name]["filepath"] = file_path
with open(file_path, "w") as fout:
with open(file_path, "w", encoding="UTF-8") as fout:
values = self.presets[preset_name]
raw = self._serialize_preset(values)
raw["name"] = preset_name
......@@ -371,7 +371,7 @@ class PresetManager(GObject.Object, Loggable):
def _mark_removed(self, name):
data = json.dumps({"name": name, "removed": True}, indent=4)
filepath = self._create_user_preset_path(name)
with open(filepath, "w") as fout:
with open(filepath, "w", encoding="UTF-8") as fout:
fout.write(data)
def prepend_preset(self, name, values):
......
......@@ -282,8 +282,8 @@ class PresetsManager(GObject.Object, Loggable):
# Check the GStreamer elements are available.
profiles = [profile] + profile.get_profiles()
if not all([self.project.get_element_factory_name(p)
for p in profiles]):
if not all(self.project.get_element_factory_name(p)
for p in profiles):
self.warning("unusable preset: %s", name)
continue
......
......@@ -247,7 +247,7 @@ class GlobalSettings(GObject.Object, Loggable):
else:
self._config.remove_option(section, key)
try:
with open(self.conf_file_path, 'w') as file:
with open(self.conf_file_path, "w", encoding="UTF-8") as file:
self._config.write(file)
except (IOError, OSError) as e:
self.error("Failed to write to %s: %s", self.conf_file_path, e)
......
......@@ -56,18 +56,19 @@ class ShortcutsManager(GObject.Object):
if not os.path.isfile(self.config_path):
return
for line in open(self.config_path, "r"):
action_name, accelerators = line.split(":", 1)
accelerators = accelerators.strip("\n").split(",")
self.app.set_accels_for_action(action_name, accelerators)
yield action_name
with open(self.config_path, "r", encoding="UTF-8") as conf_file:
for line in conf_file:
action_name, accelerators = line.split(":", 1)
accelerators = accelerators.strip("\n").split(",")
self.app.set_accels_for_action(action_name, accelerators)
yield action_name
def save(self):
"""Saves the accelerators for each action to the config file.
Only the actions added using `add` with a title are considered.
"""
with open(self.config_path, "w") as conf_file:
with open(self.config_path, "w", encoding="UTF-8") as conf_file:
for unused_group_id, actions in self.group_actions.items():
for action, unused_title, unused_action_object in actions:
accels = ",".join(self.app.get_accels_for_action(action))
......@@ -136,7 +137,7 @@ class ShortcutsManager(GObject.Object):
str: The name of the conflicting action using the accelerator, or None.
"""
group_name = action.split(".")[0]
for group in {group_name, "app", "win"}:
for group in (group_name, "app", "win"):
for neighbor_action, unused_title, unused_action_object in self.group_actions[group]:
if neighbor_action == action:
continue
......
......@@ -268,7 +268,7 @@ class LayerControls(Gtk.EventBox, Loggable):
self.__update_audio_button()
def __check_tracks_active(self, tracks):
return all([self.ges_layer.get_active_for_track(t) for t in tracks])
return all(self.ges_layer.get_active_for_track(t) for t in tracks)
def update(self, media_types):
self.props.height_request = self.ges_layer.ui.props.height_request
......
......@@ -148,9 +148,9 @@ class MarkersBox(Gtk.EventBox, Zoomable, Loggable):
if start >= end:
return None
markers_positions = list([ges_marker.props.position
for ges_marker in self.markers_container.get_markers()
if start <= ges_marker.props.position < end])
markers_positions = list(ges_marker.props.position
for ges_marker in self.markers_container.get_markers()
if start <= ges_marker.props.position < end)
if not markers_positions:
return None
......
......@@ -1442,8 +1442,8 @@ class TitlePreviewer(Gtk.Layout, Previewer, Zoomable, Loggable):
context.set_source(grad)
context.fill()
def set_selected(self, select):
self._selected = select
def set_selected(self, selected):
self._selected = selected
def release(self):
# Nothing to release
......
......@@ -226,8 +226,7 @@ class ScaleRuler(Gtk.DrawingArea, Loggable):
position = max(0, position)
if seeking:
timeline_duration = self.ges_timeline.props.duration
if position > timeline_duration:
position = timeline_duration
position = min(position, timeline_duration)
human_time = beautify_length(position)
cur_frame = self.ges_timeline.get_frame_at(position) + 1
self.set_tooltip_text(human_time + "\n" + _("Frame #%d") % cur_frame)
......
......@@ -644,7 +644,8 @@ def init(env_var_name, enable_color_output=True, enable_crack_output=True):
if filename_env_var_name in os.environ:
# install a log handler that uses the value of the environment var
_outfile = open(os.environ[filename_env_var_name], "w+")
# pylint: disable=consider-using-with
_outfile = open(os.environ[filename_env_var_name], "w+", encoding="UTF-8")
else:
_outfile = sys.stderr
......
......@@ -109,7 +109,8 @@ def is_valid_file(path):
try:
# The path doesn't exist, so open(path, "w") is safe to use.
open(path, "w").close()
# pylint: disable=consider-using-with
open(path, "w", encoding="UTF-8").close()
os.unlink(path)
return True
except IOError:
......@@ -132,6 +133,7 @@ def is_writable(path):
return os.access(os.path.dirname(path), os.W_OK)
except UnicodeDecodeError:
unicode_error_dialog()
return False
def uri_is_valid(uri):
......@@ -269,6 +271,7 @@ def show_user_manual(page=None):
# not have a portal to access system wild apps)
page_uri = get_page_uri(APPMANUALURL_OFFLINE, page)
try:
# pylint: disable=consider-using-with
subprocess.Popen(["yelp", page_uri])
except FileNotFoundError as e:
log.warning("utils", "Failed loading %s: %s", page_uri, e)
......@@ -547,7 +550,7 @@ def is_pathname_valid(pathname: str) -> bool:
return False
# If a "TypeError" exception was raised, it almost certainly has the
# error message "embedded NUL character" indicating an invalid pathname.
except TypeError as exc:
except TypeError:
return False
# If no exception was raised, all path components and hence this
# pathname itself are valid. (Praise be to the curmudgeonly python.)
......
......@@ -335,9 +335,9 @@ class TimeWidget(TextWidget, DynamicWidget):
nanosecs = frame_no / float(self._framerate) * Gst.SECOND
return int(nanosecs)
def set_widget_value(self, timeNanos, send_signal=True):
self.default = timeNanos
timecode = time_to_string(timeNanos)
def set_widget_value(self, time_nanos, send_signal=True):
self.default = time_nanos
timecode = time_to_string(time_nanos)
if timecode.startswith("0:"):
timecode = timecode[2:]
TextWidget.set_widget_value(self, timecode, send_signal=send_signal)
......@@ -1108,9 +1108,9 @@ class GstElementSettingsWidget(Gtk.Box, Loggable):
return widget
def get_widget_of_prop(self, prop_name):
for prop in self.properties:
for prop, value in self.properties.items():
if prop.name == prop_name:
return self.properties[prop]
return value
return None
......
......@@ -56,9 +56,9 @@ class Guideline(Enum):
cr.move_to(width, 0)
cr.line_to(0, height)
three_by_three = (_("3 by 3"), __three_by_three_draw_func)
vertical_horizontal_center = (_("Vertical/Horizontal"), __vertical_horizontal_center_draw_func)
diagonals = (_("Diagonals"), __diagonals_draw_func)
THREE_BY_THREE = (_("3 by 3"), __three_by_three_draw_func)
VERTICAL_HORIZONTAL_CENTER = (_("Vertical/Horizontal"), __vertical_horizontal_center_draw_func)
DIAGONALS = (_("Diagonals"), __diagonals_draw_func)
def __init__(self, label, func):
self.label = label
......@@ -76,12 +76,12 @@ class GuidelinesPopover(Gtk.Popover):
def __init__(self):
Gtk.Popover.__init__(self)
self.switches = dict()
self.switches = {}
self.overlay = GuidelinesOverlay()
self._create_ui()
self._last_guidelines = {Guideline.three_by_three}
self._last_guidelines = {Guideline.THREE_BY_THREE}
def _create_ui(self):
grid = Gtk.Grid()
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment