Skip to content

Commit 728fb0e

Browse files
committed
Ruff formatting
1 parent fde1eb9 commit 728fb0e

17 files changed

Lines changed: 73 additions & 202 deletions

File tree

.dockerignore

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,6 @@ benchmark/
1919
.gitignore
2020
.git
2121
.gitattributes
22-
.flake8
2322
.readthedocs.yaml
2423
CHANGELOG.md
2524
CONTRIBUTING.md

.github/workflows/main.yml

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -22,16 +22,13 @@ jobs:
2222
python-version: ${{ matrix.python-version }}
2323

2424
- name: Install dependencies
25-
run: pip install --no-cache-dir -U pip black flake8 bandit
25+
run: pip install --no-cache-dir -U pip ruff
2626

27-
- name: Lint with flake8
28-
run: flake8 pyproxy tests benchmark
27+
- name: Lint and security check with Ruff
28+
run: ruff check pyproxy tests benchmark
2929

30-
- name: Check with black
31-
run: black --check pyproxy tests benchmark
32-
33-
- name: Check with bandit
34-
run: bandit -r pyproxy tests benchmark
30+
- name: Check code formatting with Ruff
31+
run: ruff format --check pyproxy tests benchmark
3532

3633
unittest:
3734
needs: code-scan

.pre-commit-config.yaml

Lines changed: 0 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,7 @@
11
repos:
2-
- repo: https://github.com/psf/black
3-
rev: 25.9.0
4-
hooks:
5-
- id: black
6-
language_version: python3.13
7-
82
- repo: https://github.com/charliermarsh/ruff-pre-commit
93
rev: v0.14.0
104
hooks:
115
- id: ruff-check
126
args: [--fix]
137
- id: ruff-format
14-
15-
- repo: https://github.com/PyCQA/bandit
16-
rev: 1.8.6
17-
hooks:
18-
- id: bandit
19-
args: ["-r", "pyproxy", "tests", "benchmark"]
20-
exclude: "setup.py"

CONTRIBUTING.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,9 @@ Whether you're fixing bugs, writing tests, or improving documentation, all contr
1919
## ✅ Development Guidelines
2020

2121
- Follow [PEP8](https://peps.python.org/pep-0008/) coding style.
22-
- We use **flake8** to ensure code quality:
22+
- We use **Ruff** to ensure code quality:
2323
```bash
24-
flake8 pyproxy tests benchmark
24+
ruff check
2525
```
2626
- Tests are written using **unittest**. To run all tests:
2727
```bash

benchmark/utils/html.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -47,12 +47,12 @@ def generate_combined_table(all_results: dict) -> str:
4747
table_html += f"""
4848
<tr>
4949
<td>{url}</td>
50-
<td>{stats['avg_without_proxy']:.5f}</td>
51-
<td>{stats['min_without_proxy']:.5f}</td>
52-
<td>{stats['max_without_proxy']:.5f}</td>
53-
<td>{stats['avg_with_proxy']:.5f}</td>
54-
<td>{stats['min_with_proxy']:.5f}</td>
55-
<td>{stats['max_with_proxy']:.5f}</td>
50+
<td>{stats["avg_without_proxy"]:.5f}</td>
51+
<td>{stats["min_without_proxy"]:.5f}</td>
52+
<td>{stats["max_without_proxy"]:.5f}</td>
53+
<td>{stats["avg_with_proxy"]:.5f}</td>
54+
<td>{stats["min_with_proxy"]:.5f}</td>
55+
<td>{stats["max_with_proxy"]:.5f}</td>
5656
</tr>
5757
"""
5858

pyproject.toml

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ classifiers = [
1717
"Programming Language :: Python :: 3.10",
1818
"Programming Language :: Python :: 3.11",
1919
"Programming Language :: Python :: 3.12",
20+
"Programming Language :: Python :: 3.13",
2021
"Topic :: Internet",
2122
"Topic :: Software Development :: Libraries",
2223
"Topic :: Software Development :: Libraries :: Python Modules",
@@ -44,10 +45,11 @@ exclude = [
4445
"build",
4546
"dist",
4647
"venv",
48+
"setup.py",
4749
]
4850

4951
[tool.ruff.lint]
50-
select = ["E", "F", "W"]
52+
select = ["E", "F", "W", "S"]
5153

5254
[tool.ruff.format]
5355
quote-style = "double"

pyproxy/handlers/http.py

Lines changed: 8 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -62,9 +62,7 @@ def _get_modified_headers(self, url, request_text):
6262
new_headers = self.custom_header_result_queue.get(timeout=5)
6363
headers.update(new_headers)
6464
except Exception:
65-
self.console_logger.warning(
66-
"Timeout while getting custom headers for %s", url
67-
)
65+
self.console_logger.warning("Timeout while getting custom headers for %s", url)
6866
return headers
6967

7068
def _rebuild_http_request(self, request_line, headers, body=""):
@@ -86,9 +84,7 @@ def _apply_shortcut(self, url: str) -> str | None:
8684
try:
8785
return self.shortcuts_result_queue.get(timeout=5)
8886
except Exception:
89-
self.console_logger.warning(
90-
"Timeout while getting shortcut for %s", url
91-
)
87+
self.console_logger.warning("Timeout while getting shortcut for %s", url)
9288
return None
9389

9490
def _is_blocked(self, url: str) -> bool:
@@ -150,10 +146,7 @@ def handle_http_request(self, client_socket, request):
150146
shortcut_url = self._apply_shortcut(url)
151147
if shortcut_url:
152148
response = (
153-
f"HTTP/1.1 302 Found\r\n"
154-
f"Location: {shortcut_url}\r\n"
155-
f"Content-Length: 0\r\n"
156-
"\r\n"
149+
f"HTTP/1.1 302 Found\r\nLocation: {shortcut_url}\r\nContent-Length: 0\r\n\r\n"
157150
)
158151

159152
client_socket.sendall(response.encode())
@@ -170,16 +163,10 @@ def handle_http_request(self, client_socket, request):
170163
request_lines = request_text.split("\r\n")
171164
headers = self._get_modified_headers(url, request_text)
172165
request_line = request_lines[0]
173-
body = (
174-
request_text.split("\r\n\r\n", 1)[1]
175-
if "\r\n\r\n" in request_text
176-
else ""
177-
)
166+
body = request_text.split("\r\n\r\n", 1)[1] if "\r\n\r\n" in request_text else ""
178167
modified_request = self._rebuild_http_request(request_line, headers, body)
179168

180-
self.forward_request_to_server(
181-
client_socket, modified_request, url, first_line
182-
)
169+
self.forward_request_to_server(client_socket, modified_request, url, first_line)
183170

184171
else:
185172
self.forward_request_to_server(client_socket, request, url, first_line)
@@ -199,9 +186,7 @@ def forward_request_to_server(self, client_socket, request, url, first_line):
199186
else:
200187
parsed_url = urlparse(url)
201188
server_host = parsed_url.hostname
202-
server_port = parsed_url.port or (
203-
443 if parsed_url.scheme == "https" else 80
204-
)
189+
server_port = parsed_url.port or (443 if parsed_url.scheme == "https" else 80)
205190

206191
try:
207192
ip_address = socket.gethostbyname(server_host)
@@ -233,17 +218,13 @@ def forward_request_to_server(self, client_socket, request, url, first_line):
233218
response = server_socket.recv(4096)
234219
if response:
235220
client_socket.send(response)
236-
self.active_connections[thread_id]["bytes_received"] += len(
237-
response
238-
)
221+
self.active_connections[thread_id]["bytes_received"] += len(response)
239222
else:
240223
break
241224
except socket.timeout:
242225
break
243226
except (socket.timeout, socket.gaierror, ConnectionRefusedError, OSError) as e:
244-
self.console_logger.error(
245-
"Error connecting to the server %s : %s", server_host, e
246-
)
227+
self.console_logger.error("Error connecting to the server %s : %s", server_host, e)
247228
response = (
248229
f"HTTP/1.1 502 Bad Gateway\r\n"
249230
f"Content-Length: {len('Bad Gateway')} \r\n"

pyproxy/handlers/https.py

Lines changed: 6 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -271,12 +271,8 @@ def handle_https_connection(self, client_socket, first_line):
271271

272272
tls_version = ssl_client_socket.version() or "unknown"
273273

274-
server_socket = self._establish_server_connection(
275-
server_host, server_port
276-
)
277-
ssl_server_socket = self._wrap_server_socket_with_ssl(
278-
server_socket, server_host
279-
)
274+
server_socket = self._establish_server_connection(server_host, server_port)
275+
ssl_server_socket = self._wrap_server_socket_with_ssl(server_socket, server_host)
280276

281277
first_request, full_url, is_blocked = self._process_first_ssl_request(
282278
ssl_client_socket, server_host, first_line
@@ -324,9 +320,7 @@ def handle_https_connection(self, client_socket, first_line):
324320

325321
else:
326322
try:
327-
server_socket = self._establish_server_connection(
328-
server_host, server_port
329-
)
323+
server_socket = self._establish_server_connection(server_host, server_port)
330324
client_socket.sendall(b"HTTP/1.1 200 Connection Established\r\n\r\n")
331325

332326
client_ip = client_socket.getpeername()[0]
@@ -355,9 +349,7 @@ def handle_https_connection(self, client_socket, first_line):
355349
ConnectionRefusedError,
356350
OSError,
357351
) as e:
358-
self.console_logger.error(
359-
"Error connecting to the server %s: %s", server_host, e
360-
)
352+
self.console_logger.error("Error connecting to the server %s: %s", server_host, e)
361353
response = (
362354
f"HTTP/1.1 502 Bad Gateway\r\n"
363355
f"Content-Length: {len('Bad Gateway')} \r\n"
@@ -401,19 +393,15 @@ def transfer_data_between_sockets(self, client_socket, server_socket):
401393
client_socket.close()
402394
server_socket.close()
403395
bytes_sent = self.active_connections[thread_id]["bytes_sent"]
404-
bytes_received = self.active_connections[thread_id][
405-
"bytes_received"
406-
]
396+
bytes_received = self.active_connections[thread_id]["bytes_received"]
407397
self.active_connections.pop(threading.get_ident(), None)
408398
return bytes_sent, bytes_received
409399
if sock is client_socket:
410400
server_socket.sendall(data)
411401
self.active_connections[thread_id]["bytes_sent"] += len(data)
412402
else:
413403
client_socket.sendall(data)
414-
self.active_connections[thread_id]["bytes_received"] += len(
415-
data
416-
)
404+
self.active_connections[thread_id]["bytes_received"] += len(data)
417405
except (socket.error, OSError):
418406
client_socket.close()
419407
server_socket.close()

pyproxy/modules/filter.py

Lines changed: 6 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,7 @@
1818
import requests
1919

2020

21-
def load_blacklist(
22-
blocked_sites_path: str, blocked_url_path: str, filter_mode: str
23-
) -> set:
21+
def load_blacklist(blocked_sites_path: str, blocked_url_path: str, filter_mode: str) -> set:
2422
"""
2523
Loads blocked FQDNs or URLs from a file or URL into a set for fast lookup.
2624
@@ -50,9 +48,7 @@ def load_from_http(url: str) -> set:
5048
for line in response.text.splitlines():
5149
data.add(line.strip())
5250
except requests.exceptions.RequestException as e:
53-
raise requests.exceptions.RequestException(
54-
f"Failed to load data from {url}: {e}"
55-
)
51+
raise requests.exceptions.RequestException(f"Failed to load data from {url}: {e}")
5652
return data
5753

5854
if filter_mode == "local":
@@ -88,12 +84,8 @@ def filter_process(
8884
manager = multiprocessing.Manager()
8985
blocked_data = manager.dict(
9086
{
91-
"sites": load_blacklist(blocked_sites_path, blocked_url_path, filter_mode)[
92-
0
93-
],
94-
"urls": load_blacklist(blocked_sites_path, blocked_url_path, filter_mode)[
95-
1
96-
],
87+
"sites": load_blacklist(blocked_sites_path, blocked_url_path, filter_mode)[0],
88+
"urls": load_blacklist(blocked_sites_path, blocked_url_path, filter_mode)[1],
9789
}
9890
)
9991

@@ -136,13 +128,10 @@ def file_monitor() -> None:
136128
full_url = server_host
137129

138130
if "*" in blocked_data["sites"] or any(
139-
server_host.startswith(blocked_host)
140-
for blocked_host in blocked_data["sites"]
131+
server_host.startswith(blocked_host) for blocked_host in blocked_data["sites"]
141132
):
142133
result_queue.put((server_host, "Blocked"))
143-
elif any(
144-
full_url.startswith(blocked_url) for blocked_url in blocked_data["urls"]
145-
):
134+
elif any(full_url.startswith(blocked_url) for blocked_url in blocked_data["urls"]):
146135
result_queue.put((full_url, "Blocked"))
147136
else:
148137
result_queue.put((server_host, "Allowed"))

pyproxy/monitoring/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,4 +35,4 @@ def start_flask_server(proxy_server, flask_port, flask_pass, debug) -> None:
3535
log.setLevel(logging.ERROR)
3636

3737
register_routes(app, auth, proxy_server, ProxyMonitor)
38-
app.run(host="0.0.0.0", port=flask_port) # nosec
38+
app.run(host="0.0.0.0", port=flask_port) # noqa: S104

0 commit comments

Comments
 (0)