Skip to content

Commit

Permalink
ENH: support pathlib.Path everywhere
Browse files Browse the repository at this point in the history
  • Loading branch information
neutrinoceros committed Oct 28, 2024
1 parent 3aeec21 commit 1d31559
Show file tree
Hide file tree
Showing 7 changed files with 82 additions and 76 deletions.
5 changes: 2 additions & 3 deletions docs/source/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,11 @@
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
import os
import sys
from codecs import open
from importlib.metadata import version as md_version
from pathlib import Path

sys.path.insert(0, os.path.abspath("../.."))
sys.path.insert(0, str(Path().resolve().parents[1]))


# -- Project information -----------------------------------------------------
Expand Down
3 changes: 2 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ ignore = [
"E226",
"F401",
"F403",
"PTH123", # builtin-open
]
select = [
"E",
Expand All @@ -105,11 +106,11 @@ select = [
"C4", # flake8-comprehensions
"B", # flake8-bugbear
"YTT", # flake8-2020
"PTH", # flake8-use-pathlib
"I", # isort
"UP", # pyupgrade
"NPY", # numpy specific rules
]

[tool.ruff.lint.isort]
combine-as-imports = true
known-first-party = ["cmasher"]
Expand Down
14 changes: 7 additions & 7 deletions src/cmasher/app_usage.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,9 @@

# %% IMPORTS
# Built-in imports
import os
import re
from os import path
from pathlib import Path
from textwrap import dedent, indent

# Import packages
Expand All @@ -21,7 +22,7 @@

# %% FUNCTION DEFINITIONS
# Define function that generates a Tableau properties file with colormaps
def update_tableau_pref_file(dirname: str = ".") -> None:
def update_tableau_pref_file(dirname: str | os.PathLike[str] = ".") -> None:
"""
Update an existing Tableau 'Preferences.tps' file to include colormaps from
*CMasher*.
Expand All @@ -30,7 +31,7 @@ def update_tableau_pref_file(dirname: str = ".") -> None:
Optional
--------
dirname : str. Default: '.'
dirname : str or os.PathLike[str] Default: '.'
The relative or absolute path to the directory where the Tableau
preferences file should be updated.
If `dirname` contains an existing file called 'Preferences.tps', it
Expand Down Expand Up @@ -89,10 +90,10 @@ def update_tableau_pref_file(dirname: str = ".") -> None:
entries_dict[cmap.name] = entry_str

# Obtain absolute path to preferences file in provided dirname
filename = path.abspath(path.join(dirname, "Preferences.tps"))
filename = Path(dirname).joinpath("Preferences.tps").resolve()

# Check if this file already exists
if path.exists(filename):
if filename.exists():
# If so, read in the file contents
with open(filename) as f:
text = f.read()
Expand Down Expand Up @@ -184,5 +185,4 @@ def update_tableau_pref_file(dirname: str = ".") -> None:
).format(entries_str)[1:]

# Create this file
with open(filename, "w") as f:
f.write(pref_file)
filename.write_text(pref_file)
5 changes: 3 additions & 2 deletions src/cmasher/cli_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import re
import sys
from importlib import import_module
from pathlib import Path
from textwrap import dedent

# Package imports
Expand Down Expand Up @@ -220,7 +221,7 @@ def cli_app_usage_tableau():
cmr.app_usage.update_tableau_pref_file(dirname=ARGS.dir)

# Print on commandline that properties file was created/updated
print(f"Created/Updated Tableau preferences file in {os.path.abspath(ARGS.dir)!r}.")
print(f"Created/Updated Tableau preferences file in {ARGS.dir.resolve()!r}.")


# This function handles the 'lang_usage r' subcommand
Expand Down Expand Up @@ -619,7 +620,7 @@ def main():
help="Path to directory where the module must be saved.",
action="store",
default=cmr.create_cmap_mod.__kwdefaults__["save_dir"],
type=str,
type=Path,
)

# Set defaults for mk_cmod_parser
Expand Down
41 changes: 19 additions & 22 deletions src/cmasher/colormaps/prep_cmap_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import sys
from itertools import zip_longest
from os import path
from pathlib import Path
from textwrap import dedent

import matplotlib.pyplot as plt
Expand All @@ -26,15 +27,13 @@
)

# %% GLOBALS
docs_dir = path.abspath(path.join(path.dirname(__file__), "../../docs/source/user"))
docs_dir = Path(__file__).parents[2].joinpath("docs", "source", "user").resolve()


# %% FUNCTION DEFINITIONS
def create_cmap_app_overview():
# Load sequential image data
image_seq = np.loadtxt(
path.join(path.dirname(__file__), "app_data.txt.gz"), dtype=int
)
image_seq = np.loadtxt(Path(__file__).parent / "app_data.txt.gz", dtype=int)

# Obtain resolution ratio
image_ratio = image_seq.shape[0] / image_seq.shape[1]
Expand Down Expand Up @@ -162,8 +161,8 @@ def create_cmap_app_overview():
)

# Obtain figure path
fig_path_100 = path.join(docs_dir, "images", "cmr_cmaps_app_100.png")
fig_path_250 = path.join(docs_dir, "../_static", "cmr_cmaps_app_250.png")
fig_path_100 = docs_dir / "images" / "cmr_cmaps_app_100.png"
fig_path_250 = docs_dir.parent / "_static" / "cmr_cmaps_app_250.png"

# Save the figure
plt.savefig(fig_path_100, dpi=100)
Expand All @@ -176,17 +175,17 @@ def create_cmap_app_overview():
# %% MAIN SCRIPT
if __name__ == "__main__":
# Obtain path to .jscm-file
jscm_path = path.abspath(sys.argv[1])
jscm_path = Path(sys.argv[1]).resolve()

# If this path does not exist, try again with added 'PROJECTS'
if not path.exists(jscm_path):
jscm_path = path.abspath(path.join("PROJECTS", sys.argv[1]))
if not jscm_path.exists():
jscm_path = Path("PROJECTS", sys.argv[1])

# Get colormap name
name = path.splitext(path.basename(jscm_path))[0]
name = jscm_path.stem

# Make a directory for the colormap files
os.mkdir(name)
Path(name).mkdir()

# Move the .jscm-file to it
shutil.move(jscm_path, name)
Expand Down Expand Up @@ -248,18 +247,18 @@ def create_cmap_app_overview():
# Make new colormap overview
create_cmap_overview(savefig="cmap_overview.png", sort="lightness")
create_cmap_overview(
savefig=path.join(docs_dir, "images", "cmap_overview.png"), sort="lightness"
savefig=docs_dir / "images" / "cmap_overview.png", sort="lightness"
)
create_cmap_overview(
savefig=path.join(docs_dir, "images", "cmap_overview_perceptual.png"),
savefig=docs_dir / "images" / "cmap_overview_perceptual.png",
sort="perceptual",
show_info=True,
)
create_cmap_overview(
plt.colormaps(),
plot_profile=True,
sort="lightness",
savefig=path.join(docs_dir, "images", "mpl_cmaps.png"),
savefig=docs_dir / "images" / "mpl_cmaps.png",
)
create_cmap_app_overview()

Expand Down Expand Up @@ -296,7 +295,7 @@ def create_cmap_app_overview():
cmaps,
sort="perceptual",
use_types=(cmtype == "diverging"),
savefig=path.join(docs_dir, "images", f"{cmtype[:3]}_cmaps.png"),
savefig=docs_dir / "images" / f"{cmtype[:3]}_cmaps.png",
title=f"{cmtype.capitalize()} Colormaps",
show_info=True,
)
Expand All @@ -306,25 +305,24 @@ def create_cmap_app_overview():
cmaps,
use_types=False,
title="Sequential MPL Colormaps",
savefig=path.join(docs_dir, "images", "seq_mpl_cmaps.png"),
savefig=docs_dir / "images" / "seq_mpl_cmaps.png",
)

# Update Tableau preferences file
update_tableau_pref_file(path.join(docs_dir, "../_static"))
update_tableau_pref_file(docs_dir.parent / "_static")

# Create docs entry for this colormap if possible
try:
# Create docs entry
with open(path.join(docs_dir, cmtype, f"{name}.rst"), "x") as f:
with docs_dir.joinpath(cmtype, f"{name}.rst").open("x") as f:
f.write(docs_entry[1:])
# If this file already exists, then skip
except FileExistsError:
pass
# If the file did not exist yet, add it to the corresponding overview
else:
# Read the corresponding docs overview page
with open(path.join(docs_dir, f"{cmtype}.rst")) as f:
docs_overview = f.read()
docs_overview = docs_dir.joinpath(f"{cmtype}.rst").read_text()

# Set the string used to start the toctree with
toctree_header = ".. toctree::\n :caption: Individual colormaps\n\n"
Expand All @@ -348,8 +346,7 @@ def create_cmap_app_overview():
docs_overview = "".join([desc, toctree_header, toctree])

# Save this as the new docs_overview
with open(path.join(docs_dir, f"{cmtype}.rst"), "w") as f:
f.write(docs_overview)
docs_dir.joinpath(f"{cmtype}.rst").write_text(docs_overview)

# Create viscm output figure
viscm.gui.main(
Expand Down
Loading

0 comments on commit 1d31559

Please sign in to comment.