Skip to content

Commit

Permalink
Update to new ruff
Browse files Browse the repository at this point in the history
by jelmer review by jelmer
  • Loading branch information
jelmer authored and The Breezy Bot committed Feb 18, 2024
2 parents 9ab5991 + 6e216fa commit 9976853
Show file tree
Hide file tree
Showing 17 changed files with 45 additions and 69 deletions.
2 changes: 2 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ all: extensions
extensions:
@echo "building extension modules."
$(PYTHON) setup.py build_ext -i $(PYTHON_BUILDFLAGS)
$(PYTHON) setup.py build_rust -i $(PYTHON_BUILDFLAGS)

check:: docs check-nodocs

Expand Down Expand Up @@ -238,6 +239,7 @@ exe:
@echo *** Make brz.exe
$(PYTHON) tools/win32/ostools.py remove breezy/*.pyd
$(PYTHON) setup.py build_ext -i -f $(PYTHON_BUILDFLAGS)
$(PYTHON) setup.py build_rust -i -f $(PYTHON_BUILDFLAGS)
$(PYTHON) setup.py py2exe > py2exe.log
$(PYTHON) tools/win32/ostools.py copytodir tools/win32/start_brz.bat win32_brz.exe
$(PYTHON) tools/win32/ostools.py copytodir tools/win32/breezy.url win32_brz.exe
Expand Down
2 changes: 1 addition & 1 deletion breezy/bzr/inventory.py
Original file line number Diff line number Diff line change
Expand Up @@ -765,7 +765,7 @@ def deserialise(klass, chk_store, lines, expected_revision_id):
revision_id = info[b"revision_id"]
root_id = info[b"root_id"]
search_key_name = info.get(b"search_key_name", b"plain")
parent_id_basename_to_file_id = info.get(b"parent_id_basename_to_file_id", None)
parent_id_basename_to_file_id = info.get(b"parent_id_basename_to_file_id")
if not parent_id_basename_to_file_id.startswith(b"sha1:"):
raise ValueError(
"parent_id_basename_to_file_id should be a sha1"
Expand Down
5 changes: 4 additions & 1 deletion breezy/bzr/remote.py
Original file line number Diff line number Diff line change
Expand Up @@ -2823,7 +2823,10 @@ def _copy_repository_tarball(self, to_bzrdir, revision_id=None):
with tarfile.open(
"repository", fileobj=tar_file, mode="r|bz2"
) as tar, osutils.TemporaryDirectory() as tmpdir:
tar.extractall(tmpdir)
members = tar.getmembers()
if any(m.name.startswith("/") or ".." in m.name for m in members):
raise AssertionError("Tarball contains absolute paths")
tar.extractall(tmpdir, members=members) # noqa: S202
tmp_bzrdir = _mod_bzrdir.BzrDir.open(tmpdir)
tmp_repo = tmp_bzrdir.open_repository()
tmp_repo.copy_content_into(destination, revision_id)
Expand Down
4 changes: 1 addition & 3 deletions breezy/bzr/tests/test_knit.py
Original file line number Diff line number Diff line change
Expand Up @@ -290,9 +290,7 @@ class MockReadvFailingTransport(MockTransport):
"""

def readv(self, relpath, offsets):
count = 0
for result in MockTransport.readv(self, relpath, offsets):
count += 1
for count, result in enumerate(MockTransport.readv(self, relpath, offsets), 1):
# we use 2 because the first offset is the pack header, the second
# is the first actual content requset
if count > 2:
Expand Down
4 changes: 1 addition & 3 deletions breezy/bzr/tests/test_weave.py
Original file line number Diff line number Diff line change
Expand Up @@ -660,11 +660,9 @@ def test_multi_line_merge(self):

k = Weave()
parents = set()
i = 0
for t in texts:
for i, t in enumerate(texts):
k.add_lines(b"text%d" % i, list(parents), t)
parents.add(b"text%d" % i)
i += 1

self.log("k._weave=" + pformat(k._weave))

Expand Down
5 changes: 2 additions & 3 deletions breezy/bzr/vf_repository.py
Original file line number Diff line number Diff line change
Expand Up @@ -465,7 +465,7 @@ def record_iter_changes(self, tree, basis_revision_id, iter_changes):
carried_over = False
if len(heads) == 1:
# Could be a carry-over situation:
parent_entry_revs = parent_entries.get(file_id, None)
parent_entry_revs = parent_entries.get(file_id)
if parent_entry_revs:
parent_entry = parent_entry_revs.get(heads[0], None)
else:
Expand Down Expand Up @@ -1508,10 +1508,9 @@ def _find_file_keys_to_fetch(self, revision_ids, pb):
file_ids = self.fileids_altered_by_revision_ids(revision_ids, inv_w)
count = 0
num_file_ids = len(file_ids)
for file_id, altered_versions in file_ids.items():
for count, (file_id, altered_versions) in enumerate(file_ids.items()):
if pb is not None:
pb.update(gettext("Fetch texts"), count, num_file_ids)
count += 1
yield ("file", file_id, altered_versions)

def _find_non_file_keys_to_fetch(self, revision_ids):
Expand Down
10 changes: 2 additions & 8 deletions breezy/bzr/weave.py
Original file line number Diff line number Diff line change
Expand Up @@ -651,9 +651,7 @@ def _walk_internal(self, version_ids=None):
istack = []
dset = set()

lineno = 0 # line of weave, 0-based

for l in self._weave:
for lineno, l in enumerate(self._weave):
if l.__class__ == tuple:
c, v = l
if c == b"{":
Expand All @@ -668,7 +666,6 @@ def _walk_internal(self, version_ids=None):
raise WeaveFormatError(f"unexpected instruction {v!r}")
else:
yield lineno, istack[-1], frozenset(dset), l
lineno += 1

if istack:
raise WeaveFormatError(
Expand Down Expand Up @@ -740,8 +737,6 @@ def _extract(self, versions):
iset = set()
dset = set()

lineno = 0 # line of weave, 0-based

isactive = None

result = []
Expand Down Expand Up @@ -770,7 +765,7 @@ def _extract(self, versions):
# 'in' test could dominate, so I'm leaving this change in place - when
# its fast enough to consider profiling big datasets we can review.

for l in self._weave:
for lineno, l in enumerate(self._weave):
if l.__class__ == tuple:
c, v = l
isactive = None
Expand All @@ -792,7 +787,6 @@ def _extract(self, versions):
isactive = (not dset) and istack and (istack[-1] in included)
if isactive:
result.append((istack[-1], lineno, l))
lineno += 1
if istack:
raise WeaveFormatError(
"unclosed insertion blocks " "at end of weave: %s" % istack
Expand Down
10 changes: 4 additions & 6 deletions breezy/plugins/stats/cmds.py
Original file line number Diff line number Diff line change
Expand Up @@ -291,10 +291,10 @@ def run(self, location="."):
with a_branch.lock_read():
graph = a_branch.repository.get_graph()
revno = 0
cur_parents = 0
sorted_graph = tsort.merge_sort(graph.iter_ancestry([last_rev]), last_rev)
for _num, _node_name, depth, _isend in reversed(sorted_graph):
cur_parents += 1
for cur_parents, (_num, _node_name, depth, _isend) in enumerate(
reversed(sorted_graph), 1
):
if depth == 0:
revno += 1
self.outf.write("%4d, %4d\n" % (revno, cur_parents))
Expand All @@ -304,15 +304,13 @@ def gather_class_stats(repository, revs):
ret = {}
total = 0
with ui.ui_factory.nested_progress_bar() as pb, repository.lock_read():
i = 0
for delta in repository.get_revision_deltas(revs):
for i, delta in enumerate(repository.get_revision_deltas(revs)):
pb.update("classifying commits", i, len(revs))
for c in classify_delta(delta):
if c not in ret:
ret[c] = 0
ret[c] += 1
total += 1
i += 1
return ret, total


Expand Down
4 changes: 1 addition & 3 deletions breezy/plugins/weave_fmt/bzrdir.py
Original file line number Diff line number Diff line change
Expand Up @@ -357,11 +357,9 @@ def _write_all_weaves(self):
transaction = WriteTransaction()

try:
i = 0
for file_id, file_weave in self.text_weaves.items():
for i, (file_id, file_weave) in enumerate(self.text_weaves.items()):
self.pb.update(gettext("writing weave"), i, len(self.text_weaves))
weaves._put_weave(file_id, file_weave, transaction)
i += 1
self.pb.update(gettext("inventory"), 0, 1)
controlweaves._put_weave(b"inventory", self.inv_weave, transaction)
self.pb.update(gettext("inventory"), 1, 1)
Expand Down
8 changes: 2 additions & 6 deletions breezy/tests/test_http.py
Original file line number Diff line number Diff line change
Expand Up @@ -963,8 +963,7 @@ def get_multiple_ranges(self, file, file_size, ranges):
self.end_headers()

# Send the multipart body
cur = 0
for start, end in ranges:
for cur, (start, end) in enumerate(ranges):
self.wfile.write(boundary_line)
self.send_header("Content-type", "application/octet-stream")
self.send_header(
Expand All @@ -976,7 +975,6 @@ def get_multiple_ranges(self, file, file_size, ranges):
self.close_connection = 1
return
self.send_range_content(file, start, end - start + 1)
cur += 1
# Final boundary
self.wfile.write(boundary_line)

Expand Down Expand Up @@ -1038,8 +1036,7 @@ def get_multiple_ranges(self, file, file_size, ranges):
self.end_headers()

# Send the multipart body
cur = 0
for start, end in ranges:
for cur, (start, end) in enumerate(ranges):
if cur + self._truncated_ranges >= len(ranges):
# Abruptly ends the response and close the connection
self.close_connection = 1
Expand All @@ -1051,7 +1048,6 @@ def get_multiple_ranges(self, file, file_size, ranges):
)
self.end_headers()
self.send_range_content(file, start, end - start + 1)
cur += 1
# Final boundary
self.wfile.write(boundary_line)

Expand Down
4 changes: 1 addition & 3 deletions breezy/transport/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -552,14 +552,12 @@ def _iterate_over(self, multi, func, pb, msg, expand=True):
"""
total = self._get_total(multi)
result = []
count = 0
for entry in multi:
for count, entry in enumerate(multi):
self._update_pb(pb, msg, count, total)
if expand:
result.append(func(*entry))
else:
result.append(func(entry))
count += 1
return tuple(result)

def abspath(self, relpath):
Expand Down
4 changes: 1 addition & 3 deletions breezy/ui/text.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,13 +72,12 @@ def _build_alternatives(self, msg, choices, default):
Setup final prompt and the lists of choices and associated
shortcuts.
"""
index = 0
help_list = []
self.alternatives = {}
choices = choices.split("\n")
if default is not None and default not in range(0, len(choices)):
raise ValueError("invalid default index")
for c in choices:
for index, c in enumerate(choices):
name = c.replace("&", "").lower()
choice = (name, index)
if name in self.alternatives:
Expand All @@ -103,7 +102,6 @@ def _build_alternatives(self, msg, choices, default):
self.alternatives[""] = choice
self.alternatives["\r"] = choice
help_list.append(help)
index += 1

self.prompt = f"{msg} ({', '.join(help_list)}): "

Expand Down
30 changes: 14 additions & 16 deletions crates/bazaar-py/src/inventory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -252,23 +252,21 @@ impl InventoryEntry {
// * there was a bug in revision updates with executable bit support
let mut candidate =
candidate.extract::<PyRefMut<InventoryEntry>>(py)?;
match (&mut candidate.0, &mut entry.0) {
(
Entry::File {
executable: candidate_executable,
..
},
Entry::File {
executable: entry_executable,
..
},
) => {
if candidate_executable != entry_executable {
*entry_executable = false;
*candidate_executable = false;
}
if let (
Entry::File {
executable: candidate_executable,
..
},
Entry::File {
executable: entry_executable,
..
},
) = (&mut candidate.0, &mut entry.0)
{
if candidate_executable != entry_executable {
*entry_executable = false;
*candidate_executable = false;
}
_ => {}
}
} else {
// add this revision as a candidate.
Expand Down
9 changes: 3 additions & 6 deletions crates/graph-py/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -301,13 +301,10 @@ impl MergeSorter {
};

// The null: revision doesn't exist in the graph, so don't attempt to remove it
match branch_tip {
Some(ref mut tip_obj) => {
if branch_tip_is_null(py, tip_obj.clone_ref(py)) {
branch_tip = None;
}
if let Some(ref mut tip_obj) = branch_tip {
if branch_tip_is_null(py, tip_obj.clone_ref(py)) {
branch_tip = None;
}
None => (),
}

let sorter = breezy_graph::tsort::MergeSorter::<PyNode>::new(
Expand Down
2 changes: 1 addition & 1 deletion crates/transport-py/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use breezy_transport::lock::{FileLock, Lock as LockTrait, LockError};
use breezy_transport::{Error, ReadStream, Transport as TransportTrait, UrlFragment, WriteStream};
use breezy_transport::{Error, ReadStream, Transport as _, UrlFragment, WriteStream};
use log::debug;
use pyo3::exceptions::{PyRuntimeError, PyValueError};
use pyo3::import_exception;
Expand Down
1 change: 0 additions & 1 deletion crates/transport-py/src/sftp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ use pyo3::prelude::*;
use pyo3::types::{PyBytes, PyType};

use std::collections::VecDeque;
use std::io::{Read, Seek};
use std::sync::Arc;

create_exception!(breezy._transport_rs, SFTPError, PyException);
Expand Down
10 changes: 5 additions & 5 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,9 @@ version = {attr = "breezy.__version__"}
ignore_missing_imports = true

[tool.ruff]
extend-exclude = ["lib", "bin"]

[tool.ruff.lint]
select = [
"ANN", # annotations
"D", # pydocstyle
Expand Down Expand Up @@ -173,15 +176,12 @@ ignore = [
]
# These are actually fine, but they make mypy more strict and then it fails.
unfixable = ["ANN204"]
extend-exclude = ["lib", "bin"]

[tool.ruff.isort]

[tool.ruff.extend-per-file-ignores]
[tool.ruff.lint.extend-per-file-ignores]
"breezy/plugins/po_merge/tests/test_po_merge.py" = ["RUF001"]


[tool.ruff.pydocstyle]
[tool.ruff.lint.pydocstyle]
convention = "google"

[tool.setuptools-gettext]
Expand Down

0 comments on commit 9976853

Please sign in to comment.