Skip to content

Commit 657c91a

Browse files
committed
MNT: Run PTH flake test in prep for supporting pathlib (config)
1 parent 35bba8d commit 657c91a

4 files changed

Lines changed: 66 additions & 138 deletions

File tree

‎.ruff.toml‎

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -203,10 +203,7 @@ lint.unfixable = [
203203
# When a general exclusion is being fixed, but it affects many subpackages, it
204204
# is better to fix for subpackages individually. The general exclusion should be
205205
# copied to these subpackage sections and fixed there.
206-
"astropy/config/*" = [
207-
"PTH", # all flake8-use-pathlib
208-
"PTH206", # Replace `.split(os.sep)` with `Path.parts`
209-
]
206+
"astropy/config/*" = []
210207
"astropy/constants/*" = [
211208
"N817", # camelcase-imported-as-acronym
212209
"RET505", # superfluous-else-return

‎astropy/config/configuration.py‎

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
import pkgutil
1717
import warnings
1818
from contextlib import contextmanager, nullcontext
19-
from os import path
19+
from pathlib import Path
2020
from textwrap import TextWrapper
2121
from warnings import warn
2222

@@ -608,10 +608,14 @@ def get_config(packageormod=None, reload=False, rootname=None):
608608
try:
609609
# This feature is intended only for use by the unit tests
610610
if _override_config_file is not None:
611-
cfgfn = _override_config_file
611+
cfgfn = Path(_override_config_file)
612612
else:
613-
cfgfn = path.join(get_config_dir(rootname=rootname), pkgname + ".cfg")
614-
cobj = configobj.ConfigObj(cfgfn, interpolation=False)
613+
cfgfn = (
614+
Path(get_config_dir(rootname=rootname))
615+
.joinpath(pkgname)
616+
.with_suffix(".cfg")
617+
)
618+
cobj = configobj.ConfigObj(str(cfgfn), interpolation=False)
615619
except OSError:
616620
# This can happen when HOME is not set
617621
cobj = configobj.ConfigObj(interpolation=False)
@@ -784,7 +788,7 @@ def create_config_file(pkg, rootname="astropy", overwrite=False):
784788
# local import to prevent using the logger before it is configured
785789
from astropy.logger import log
786790

787-
cfgfn = get_config_filename(pkg, rootname=rootname)
791+
cfgfn = Path(get_config_filename(pkg, rootname=rootname))
788792

789793
# generate the default config template
790794
template_content = io.StringIO()
@@ -795,7 +799,7 @@ def create_config_file(pkg, rootname="astropy", overwrite=False):
795799
doupdate = True
796800

797801
# if the file already exists, check that it has not been modified
798-
if cfgfn is not None and path.exists(cfgfn):
802+
if cfgfn is not None and cfgfn.is_file():
799803
with open(cfgfn, encoding="latin-1") as fd:
800804
content = fd.read()
801805

‎astropy/config/paths.py‎

Lines changed: 47 additions & 120 deletions
Original file line numberDiff line numberDiff line change
@@ -7,76 +7,12 @@
77
import shutil
88
import sys
99
from functools import wraps
10+
from pathlib import Path
1011

1112
__all__ = ["get_config_dir", "get_cache_dir", "set_temp_config", "set_temp_cache"]
1213

1314

14-
def _find_home():
15-
"""Locates and return the home directory (or best approximation) on this
16-
system.
17-
18-
Raises
19-
------
20-
OSError
21-
If the home directory cannot be located - usually means you are running
22-
Astropy on some obscure platform that doesn't have standard home
23-
directories.
24-
"""
25-
try:
26-
homedir = os.path.expanduser("~")
27-
except Exception:
28-
# Linux, Unix, AIX, OS X
29-
if os.name == "posix":
30-
if "HOME" in os.environ:
31-
homedir = os.environ["HOME"]
32-
else:
33-
raise OSError(
34-
"Could not find unix home directory to search for "
35-
"astropy config dir"
36-
)
37-
elif os.name == "nt": # This is for all modern Windows (NT or after)
38-
if "MSYSTEM" in os.environ and os.environ.get("HOME"):
39-
# Likely using an msys shell; use whatever it is using for its
40-
# $HOME directory
41-
homedir = os.environ["HOME"]
42-
# See if there's a local home
43-
elif "HOMEDRIVE" in os.environ and "HOMEPATH" in os.environ:
44-
homedir = os.path.join(os.environ["HOMEDRIVE"], os.environ["HOMEPATH"])
45-
# Maybe a user profile?
46-
elif "USERPROFILE" in os.environ:
47-
homedir = os.path.join(os.environ["USERPROFILE"])
48-
else:
49-
try:
50-
import winreg as wreg
51-
52-
shell_folders = r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders"
53-
key = wreg.OpenKey(wreg.HKEY_CURRENT_USER, shell_folders)
54-
55-
homedir = wreg.QueryValueEx(key, "Personal")[0]
56-
key.Close()
57-
except Exception:
58-
# As a final possible resort, see if HOME is present
59-
if "HOME" in os.environ:
60-
homedir = os.environ["HOME"]
61-
else:
62-
raise OSError(
63-
"Could not find windows home directory to "
64-
"search for astropy config dir"
65-
)
66-
else:
67-
# for other platforms, try HOME, although it probably isn't there
68-
if "HOME" in os.environ:
69-
homedir = os.environ["HOME"]
70-
else:
71-
raise OSError(
72-
"Could not find a home directory to search for "
73-
"astropy config dir - are you on an unsupported "
74-
"platform?"
75-
)
76-
return homedir
77-
78-
79-
def get_config_dir(rootname="astropy"):
15+
def get_config_dir(rootname: str = "astropy") -> str:
8016
"""
8117
Determines the package configuration directory name and creates the
8218
directory if it doesn't exist.
@@ -105,25 +41,25 @@ def get_config_dir(rootname="astropy"):
10541
# If using set_temp_config, that overrides all
10642
if set_temp_config._temp_path is not None:
10743
xch = set_temp_config._temp_path
108-
config_path = os.path.join(xch, rootname)
109-
if not os.path.exists(config_path):
110-
os.mkdir(config_path)
111-
return os.path.abspath(config_path)
44+
config_path = xch / rootname
45+
config_path.mkdir(exist_ok=True)
46+
return str(config_path.resolve())
11247

11348
# first look for XDG_CONFIG_HOME
114-
xch = os.environ.get("XDG_CONFIG_HOME")
49+
if (
50+
(xdg_config_home := os.getenv("XDG_CONFIG_HOME")) is not None
51+
and (xch := Path(xdg_config_home)).exists()
52+
and not (xchpth := xch / rootname).is_symlink()
53+
):
54+
if xchpth.exists():
55+
return str(xchpth.resolve())
56+
else:
57+
linkto = xchpth
11558

116-
if xch is not None and os.path.exists(xch):
117-
xchpth = os.path.join(xch, rootname)
118-
if not os.path.islink(xchpth):
119-
if os.path.exists(xchpth):
120-
return os.path.abspath(xchpth)
121-
else:
122-
linkto = xchpth
123-
return os.path.abspath(_find_or_create_root_dir("config", linkto, rootname))
59+
return str(_find_or_create_root_dir("config", linkto, rootname))
12460

12561

126-
def get_cache_dir(rootname="astropy"):
62+
def get_cache_dir(rootname: str = "astropy") -> str:
12763
"""
12864
Determines the Astropy cache directory name and creates the directory if it
12965
doesn't exist.
@@ -152,23 +88,23 @@ def get_cache_dir(rootname="astropy"):
15288
# If using set_temp_cache, that overrides all
15389
if set_temp_cache._temp_path is not None:
15490
xch = set_temp_cache._temp_path
155-
cache_path = os.path.join(xch, rootname)
156-
if not os.path.exists(cache_path):
157-
os.mkdir(cache_path)
158-
return os.path.abspath(cache_path)
91+
cache_path = xch / rootname
92+
if not cache_path.is_file():
93+
cache_path.mkdir(exist_ok=True)
94+
return str(cache_path.resolve())
15995

16096
# first look for XDG_CACHE_HOME
161-
xch = os.environ.get("XDG_CACHE_HOME")
162-
163-
if xch is not None and os.path.exists(xch):
164-
xchpth = os.path.join(xch, rootname)
165-
if not os.path.islink(xchpth):
166-
if os.path.exists(xchpth):
167-
return os.path.abspath(xchpth)
168-
else:
169-
linkto = xchpth
97+
if (
98+
(xdg_config_home := os.getenv("XDG_CONFIG_HOME")) is not None
99+
and (xch := Path(xdg_config_home)).exists()
100+
and not (xchpth := xch / rootname).is_symlink()
101+
):
102+
if xchpth.exists():
103+
return str(xchpth.resolve())
104+
else:
105+
linkto = xchpth
170106

171-
return os.path.abspath(_find_or_create_root_dir("cache", linkto, rootname))
107+
return str(_find_or_create_root_dir("cache", linkto, rootname))
172108

173109

174110
class _SetTempPath:
@@ -177,7 +113,7 @@ class _SetTempPath:
177113

178114
def __init__(self, path=None, delete=False):
179115
if path is not None:
180-
path = os.path.abspath(path)
116+
path = Path(path).resolve()
181117

182118
self._path = path
183119
self._delete = delete
@@ -287,39 +223,30 @@ class set_temp_cache(_SetTempPath):
287223
_default_path_getter = staticmethod(get_cache_dir)
288224

289225

290-
def _find_or_create_root_dir(dirnm, linkto, pkgname="astropy"):
291-
innerdir = os.path.join(_find_home(), f".{pkgname}")
292-
maindir = os.path.join(_find_home(), f".{pkgname}", dirnm)
226+
def _find_or_create_root_dir(
227+
dirnm: str,
228+
linkto: Path | None,
229+
pkgname: str = "astropy",
230+
) -> Path:
231+
innerdir = Path.home() / f".{pkgname}"
232+
maindir = innerdir / dirnm
293233

294-
if not os.path.exists(maindir):
234+
if maindir.is_file():
235+
raise OSError(
236+
f"Intended {pkgname} {dirnm} directory {maindir} is actually a file."
237+
)
238+
if not maindir.is_dir():
295239
# first create .astropy dir if needed
296-
if not os.path.exists(innerdir):
297-
try:
298-
os.mkdir(innerdir)
299-
except OSError:
300-
if not os.path.isdir(innerdir):
301-
raise
302-
elif not os.path.isdir(innerdir):
240+
if innerdir.is_file():
303241
raise OSError(
304242
f"Intended {pkgname} {dirnm} directory {maindir} is actually a file."
305243
)
306-
307-
try:
308-
os.mkdir(maindir)
309-
except OSError:
310-
if not os.path.isdir(maindir):
311-
raise
312-
244+
maindir.mkdir(parents=True, exist_ok=True)
313245
if (
314246
not sys.platform.startswith("win")
315247
and linkto is not None
316-
and not os.path.exists(linkto)
248+
and not linkto.exists()
317249
):
318250
os.symlink(maindir, linkto)
319251

320-
elif not os.path.isdir(maindir):
321-
raise OSError(
322-
f"Intended {pkgname} {dirnm} directory {maindir} is actually a file."
323-
)
324-
325-
return os.path.abspath(maindir)
252+
return maindir.resolve()

‎astropy/samp/lockfile_helpers.py‎

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,10 @@
1010
import warnings
1111
import xmlrpc.client as xmlrpc
1212
from contextlib import suppress
13+
from pathlib import Path
1314
from urllib.parse import urlparse
1415

1516
from astropy import log
16-
from astropy.config.paths import _find_home
1717
from astropy.utils.data import get_readable_fileobj
1818

1919
from .errors import SAMPHubError, SAMPWarning
@@ -76,9 +76,9 @@ def create_lock_file(lockfilename=None, mode=None, hub_id=None, hub_params=None)
7676
log.debug("Running mode: " + mode)
7777

7878
if mode == "single":
79-
lockfilename = os.path.join(_find_home(), ".samp")
79+
lockfilename = os.path.join(Path.home(), ".samp")
8080
else:
81-
lockfiledir = os.path.join(_find_home(), ".samp-1")
81+
lockfiledir = os.path.join(Path.home(), ".samp-1")
8282

8383
# If missing create .samp-1 directory
8484
try:
@@ -127,7 +127,7 @@ def get_main_running_hub():
127127
else:
128128
raise SAMPHubError("SAMP Hub profile not supported.")
129129
else:
130-
lockfilename = os.path.join(_find_home(), ".samp")
130+
lockfilename = os.path.join(Path.home(), ".samp")
131131

132132
return hubs[lockfilename]
133133

@@ -160,7 +160,7 @@ def get_running_hubs():
160160
if os.environ["SAMP_HUB"].startswith("std-lockurl:"):
161161
lockfilename = os.environ["SAMP_HUB"][len("std-lockurl:") :]
162162
else:
163-
lockfilename = os.path.join(_find_home(), ".samp")
163+
lockfilename = os.path.join(Path.home(), ".samp")
164164

165165
hub_is_running, lockfiledict = check_running_hub(lockfilename)
166166

@@ -171,7 +171,7 @@ def get_running_hubs():
171171

172172
lockfiledir = ""
173173

174-
lockfiledir = os.path.join(_find_home(), ".samp-1")
174+
lockfiledir = os.path.join(Path.home(), ".samp-1")
175175

176176
if os.path.isdir(lockfiledir):
177177
for filename in os.listdir(lockfiledir):
@@ -231,7 +231,7 @@ def remove_garbage_lock_files():
231231

232232
# HUB SINGLE INSTANCE MODE
233233

234-
lockfilename = os.path.join(_find_home(), ".samp")
234+
lockfilename = os.path.join(Path.home(), ".samp")
235235

236236
hub_is_running, lockfiledict = check_running_hub(lockfilename)
237237

@@ -243,7 +243,7 @@ def remove_garbage_lock_files():
243243

244244
# HUB MULTIPLE INSTANCE MODE
245245

246-
lockfiledir = os.path.join(_find_home(), ".samp-1")
246+
lockfiledir = os.path.join(Path.home(), ".samp-1")
247247

248248
if os.path.isdir(lockfiledir):
249249
for filename in os.listdir(lockfiledir):

0 commit comments

Comments
 (0)