Skip to content

Commit 43a9263

Browse files
committed
ruff: Fix SIM115 Use context handler for opening files.
Signed-off-by: Anders Kaseorg <[email protected]>
1 parent 5199c14 commit 43a9263

File tree

5 files changed

+30
-26
lines changed

5 files changed

+30
-26
lines changed

zulip/integrations/codebase/zulip_codebase_mirror

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import os
1313
import sys
1414
import time
1515
from datetime import datetime, timedelta
16+
from pathlib import Path
1617

1718
import pytz
1819
import requests
@@ -301,7 +302,7 @@ def run_mirror() -> None:
301302
time.sleep(sleep_interval)
302303

303304
except KeyboardInterrupt:
304-
open(config.RESUME_FILE, "w").write(since.strftime("%s"))
305+
Path(config.RESUME_FILE).write_text(since.strftime("%s"))
305306
logging.info("Shutting down Codebase mirror")
306307

307308

@@ -310,13 +311,15 @@ def check_permissions() -> None:
310311
# check that the log file can be written
311312
if config.LOG_FILE:
312313
try:
313-
open(config.LOG_FILE, "w")
314+
with open(config.LOG_FILE, "w"):
315+
pass
314316
except OSError as e:
315317
sys.stderr.write("Could not open up log for writing:")
316318
sys.stderr.write(str(e))
317319
# check that the resume file can be written (this creates if it doesn't exist)
318320
try:
319-
open(config.RESUME_FILE, "a+")
321+
with open(config.RESUME_FILE, "a+"):
322+
pass
320323
except OSError as e:
321324
sys.stderr.write(f"Could not open up the file {config.RESUME_FILE} for reading and writing")
322325
sys.stderr.write(str(e))

zulip/integrations/log2zulip/log2zulip

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import subprocess
1111
import sys
1212
import tempfile
1313
import traceback
14+
from pathlib import Path
1415
from typing import List
1516

1617
# Use the Zulip virtualenv if available
@@ -73,8 +74,8 @@ def process_logs() -> None:
7374
data_file_path = os.path.join(temp_dir, "log2zulip.state")
7475
mkdir_p(os.path.dirname(data_file_path))
7576
if not os.path.exists(data_file_path):
76-
open(data_file_path, "w").write("{}")
77-
last_data = json.loads(open(data_file_path).read())
77+
Path(data_file_path).write_text("{}")
78+
last_data = json.loads(Path(data_file_path).read_text())
7879
new_data = {}
7980
for log_file in log_files:
8081
file_data = last_data.get(log_file, {})
@@ -97,7 +98,7 @@ def process_logs() -> None:
9798
process_lines(new_lines, log_file)
9899
file_data["last"] += len(new_lines)
99100
new_data[log_file] = file_data
100-
open(data_file_path, "w").write(json.dumps(new_data))
101+
Path(data_file_path).write_text(json.dumps(new_data))
101102

102103

103104
if __name__ == "__main__":
@@ -115,10 +116,10 @@ if __name__ == "__main__":
115116

116117
# TODO: Convert this locking code to use a standard context manager.
117118
try:
118-
open(lock_path, "w").write("1")
119+
Path(lock_path).write_text("1")
119120
zulip_client = zulip.init_from_options(args)
120121
try:
121-
log_files = json.loads(open(args.control_path).read())
122+
log_files = json.loads(Path(args.control_path).read_text())
122123
except (json.JSONDecodeError, OSError):
123124
print(f"Could not load control data from {args.control_path}")
124125
traceback.print_exc()

zulip/integrations/zephyr/process_ccache

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
#!/usr/bin/env python3
22
import base64
3-
import os
43
import subprocess
54
import sys
5+
from pathlib import Path
66

77
short_user = sys.argv[1]
88
api_key = sys.argv[2]
@@ -14,25 +14,25 @@ with open(f"/home/zulip/ccache/{program_name}", "wb") as f:
1414
f.write(base64.b64decode(ccache_data_encoded))
1515

1616
# Setup API key
17-
api_key_path = f"/home/zulip/api-keys/{program_name}"
18-
open(api_key_path, "w").write(api_key + "\n")
17+
api_key_path = Path(f"/home/zulip/api-keys/{program_name}")
18+
api_key_path.write_text(api_key + "\n")
1919

2020
# Setup supervisord configuration
21-
supervisor_path = f"/etc/supervisor/conf.d/zmirror/{program_name}.conf"
22-
template = os.path.join(os.path.dirname(__file__), "zmirror_private.conf.template")
23-
template_data = open(template).read()
21+
supervisor_path = Path(f"/etc/supervisor/conf.d/zmirror/{program_name}.conf")
22+
template_path = Path(__file__).parent / "zmirror_private.conf.template"
23+
template_data = template_path.read_text()
2424
session_path = f"/home/zulip/zephyr_sessions/{program_name}"
2525

2626
# Preserve mail zephyrs forwarding setting across rewriting the config file
2727

2828
try:
29-
if "--forward-mail-zephyrs" in open(supervisor_path).read():
29+
if "--forward-mail-zephyrs" in supervisor_path.read_text():
3030
template_data = template_data.replace(
3131
"--use-sessions", "--use-sessions --forward-mail-zephyrs"
3232
)
3333
except Exception:
3434
pass
35-
open(supervisor_path, "w").write(template_data.replace("USERNAME", short_user))
35+
supervisor_path.write_text(template_data.replace("USERNAME", short_user))
3636

3737
# Delete your session
3838
subprocess.check_call(["rm", "-f", session_path])

zulip/integrations/zephyr/zephyr_mirror_backend.py

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
import textwrap
1515
import time
1616
from ctypes import POINTER, byref, c_char, c_int, c_ushort
17+
from pathlib import Path
1718
from queue import Queue
1819
from threading import Thread
1920
from types import FrameType
@@ -247,9 +248,7 @@ def zephyr_bulk_subscribe(subs: List[Tuple[str, str, str]]) -> None:
247248

248249
def update_subscriptions() -> None:
249250
try:
250-
f = open(options.stream_file_path)
251-
public_streams: List[str] = json.loads(f.read())
252-
f.close()
251+
public_streams: List[str] = json.loads(Path(options.stream_file_path).read_text())
253252
except Exception:
254253
logger.exception("Error reading public streams:")
255254
return
@@ -380,11 +379,11 @@ def parse_zephyr_body(zephyr_data: str, notice_format: str) -> Tuple[str, str]:
380379

381380
def parse_crypt_table(zephyr_class: str, instance: str) -> Optional[str]:
382381
try:
383-
crypt_table = open(os.path.join(os.environ["HOME"], ".crypt-table"))
382+
crypt_table = (Path(os.environ["HOME"]) / ".crypt-table").read_text()
384383
except OSError:
385384
return None
386385

387-
for line in crypt_table.readlines():
386+
for line in crypt_table.splitlines():
388387
if line.strip() == "":
389388
# Ignore blank lines
390389
continue
@@ -1090,13 +1089,13 @@ def valid_stream_name(name: str) -> bool:
10901089

10911090
def parse_zephyr_subs(verbose: bool = False) -> Set[Tuple[str, str, str]]:
10921091
zephyr_subscriptions: Set[Tuple[str, str, str]] = set()
1093-
subs_file = os.path.join(os.environ["HOME"], ".zephyr.subs")
1094-
if not os.path.exists(subs_file):
1092+
subs_path = Path(os.environ["HOME"]) / ".zephyr.subs"
1093+
if not subs_path.exists():
10951094
if verbose:
10961095
logger.error("Couldn't find ~/.zephyr.subs!")
10971096
return zephyr_subscriptions
10981097

1099-
for raw_line in open(subs_file).readlines():
1098+
for raw_line in subs_path.read_text().splitlines():
11001099
line = raw_line.strip()
11011100
if len(line) == 0:
11021101
continue
@@ -1271,7 +1270,7 @@ def die_gracefully(signal: int, frame: Optional[FrameType]) -> None:
12711270
),
12721271
)
12731272
sys.exit(1)
1274-
api_key = open(options.api_key_file).read().strip()
1273+
api_key = Path(options.api_key_file).read_text().strip()
12751274
# Store the API key in the environment so that our children
12761275
# don't need to read it in
12771276
os.environ["HUMBUG_API_KEY"] = api_key

zulip_bots/zulip_bots/lib.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import sys
88
import time
99
from contextlib import contextmanager
10+
from pathlib import Path
1011
from typing import IO, Any, Dict, Iterator, List, Optional, Set
1112

1213
from typing_extensions import Protocol
@@ -415,7 +416,7 @@ def is_private_message_but_not_group_pm(
415416

416417

417418
def display_config_file_errors(error_msg: str, config_file: str) -> None:
418-
file_contents = open(config_file).read()
419+
file_contents = Path(config_file).read_text()
419420
print(f"\nERROR: {config_file} seems to be broken:\n\n{file_contents}")
420421
print(f"\nMore details here:\n\n{error_msg}\n")
421422

0 commit comments

Comments
 (0)