Skip to content

Commit

Permalink
add pep8-naming dev dependency (#880)
Browse files Browse the repository at this point in the history
* add pep8-naming dev dependency

* pep8 naming cli.py

* reformat

* ignore etree/ET pattern

* ignore plastex formatting

* more snake case fixes

* formatting
  • Loading branch information
StevenClontz authored Dec 18, 2024
1 parent 4ac3142 commit 074781d
Show file tree
Hide file tree
Showing 8 changed files with 86 additions and 60 deletions.
23 changes: 21 additions & 2 deletions poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

24 changes: 12 additions & 12 deletions pretext/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -255,9 +255,11 @@ def devscript(args: List[str]) -> None:
"""
Aliases the core pretext script.
"""
PY_CMD = sys.executable
subprocess.run(
[PY_CMD, str(resources.resource_base_path() / "core" / "pretext" / "pretext")]
[
sys.executable,
str(resources.resource_base_path() / "core" / "pretext" / "pretext"),
]
+ list(args)
)

Expand Down Expand Up @@ -790,8 +792,8 @@ def view(

if stop_server:
try:
projectHash = utils.hash_path(project.abspath())
current_server = server.active_server_for_path_hash(projectHash)
project_hash = utils.hash_path(project.abspath())
current_server = server.active_server_for_path_hash(project_hash)
log.info("\nStopping server.")
if current_server:
current_server.terminate()
Expand Down Expand Up @@ -848,22 +850,22 @@ def view(
if no_launch:
log.info(f"The {target_name} will be available at {url}")
else:
SECONDS = 2
log.info(f"Opening browser for {target_name} at {url} in {SECONDS} seconds")
time.sleep(SECONDS)
seconds = 2
log.info(f"Opening browser for {target_name} at {url} in {seconds} seconds")
time.sleep(seconds)
webbrowser.open(url)
return
# Start server if there isn't one running already:
projectHash = utils.hash_path(project.abspath())
current_server = server.active_server_for_path_hash(projectHash)
project_hash = utils.hash_path(project.abspath())
current_server = server.active_server_for_path_hash(project_hash)
if restart_server and current_server is not None:
log.info(
f"Terminating existing server {current_server.pid} on port {current_server.port}"
)
current_server.terminate()
current_server = None
# Double check that the current server really is active:
if current_server is not None and current_server.isActiveServer():
if current_server is not None and current_server.is_active_server():
url_base = utils.url_for_access(access=access, port=current_server.port)
url = url_base + url_path
log.info(f"Server is already available at {url_base}")
Expand Down Expand Up @@ -893,9 +895,7 @@ def callback(actual_port: int) -> None:
if no_launch:
log.info(f"The {target_name} will be available at {url}")
else:
# SECONDS = 2
log.info(f"Opening browser for {target_name} at {url}")
# time.sleep(SECONDS)
webbrowser.open(url)

log.info("starting server ...")
Expand Down
2 changes: 1 addition & 1 deletion pretext/codechat.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
# Third-party imports
# -------------------
# We assume a previous call to ``xsltproc`` has already verified that lxml is installed.
import lxml.etree as ET
import lxml.etree as ET # noqa: N812
import lxml.ElementInclude

# Local application imports
Expand Down
6 changes: 3 additions & 3 deletions pretext/plastex/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@
class Pretext(_Renderer):
"""Renderer for the PreTeXt XML format"""

fileExtension = ".ptx"
fileExtension = ".ptx" # noqa: N815

def processFileContent(self, document: str, s: str) -> str:
def processFileContent(self, document: str, s: str) -> str: # noqa: N802
s = _Renderer.processFileContent(self, document, s)

# Remove empty paragraphs
Expand All @@ -36,7 +36,7 @@ def convert(input_file: Path, output: Path) -> None:

input_file_dir = input_file.parent

def getLines(input_file: Path) -> str:
def getLines(input_file: Path) -> str: # noqa: N802
with open(input_file, "r") as f:
lines = str()
line = f.readline()
Expand Down
2 changes: 1 addition & 1 deletion pretext/project/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
import pickle
from pathlib import Path

from lxml import etree as ET
from lxml import etree as ET # noqa: N812

try:
import pelican # type: ignore
Expand Down
76 changes: 41 additions & 35 deletions pretext/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,27 +13,32 @@
# Get access to logger
log = logging.getLogger("ptxlogger")

# Limit for how many entries to allow in the server file
# before attempting to clean up non-running entries.
# Note: This is not a limit to the number of concurrent servers.
PURGE_LIMIT = 10


@dataclass
class RunningServerInfo:
"""A simple dataclass to hold the information in the running servers file."""

pathHash: str
path_hash: str
pid: int
port: int
binding: str

@staticmethod
def fromFileLine(line: str) -> RunningServerInfo:
(pathHash, pid, port, binding) = line.split()
def from_file_line(line: str) -> RunningServerInfo:
(path_hash, pid, port, binding) = line.split()
return RunningServerInfo(
pathHash=pathHash, pid=int(pid), port=int(port), binding=binding
path_hash=path_hash, pid=int(pid), port=int(port), binding=binding
)

def toFileLine(self) -> str:
return f"{self.pathHash} {self.pid} {self.port} {self.binding}\n"
def to_file_line(self) -> str:
return f"{self.path_hash} {self.pid} {self.port} {self.binding}\n"

def isActiveServer(self) -> bool:
def is_active_server(self) -> bool:
"""Returns whether the server represented by this object is active on the provided port"""
p = psutil.Process(self.pid)
if not p.is_running():
Expand All @@ -56,7 +61,7 @@ def terminate(self) -> None:
try:
log.info(f"Terminating {self.pid}")
psutil.Process(self.pid).terminate()
remove_server_entry(self.pathHash)
remove_server_entry(self.path_hash)
except Exception as e:
log.info(f"Terminate failed for {self.pid}.")
log.exception(e, exc_info=True)
Expand All @@ -73,71 +78,72 @@ def get_running_servers() -> t.List[RunningServerInfo]:
if not home_path().exists():
return []
try:
runningServersFile = home_path() / "running_servers"
if not runningServersFile.is_file():
running_servers_file = home_path() / "running_servers"
if not running_servers_file.is_file():
return []
with open(runningServersFile, "r") as f:
return [RunningServerInfo.fromFileLine(line) for line in f.readlines()]
with open(running_servers_file, "r") as f:
return [RunningServerInfo.from_file_line(line) for line in f.readlines()]
except IOError as e:
log.info("Unable to open running servers file.")
log.exception(e, exc_info=True)
return []


def save_running_servers(runningServers: t.List[RunningServerInfo]) -> None:
def save_running_servers(running_servers: t.List[RunningServerInfo]) -> None:
"""
Overwrites the ~/.ptx/running_servers file to store
the new list of running servers.
"""
# Ensure home path exists
os.makedirs(home_path(), exist_ok=True)
try:
runningServersFile = home_path() / "running_servers"
with open(runningServersFile, "w") as f:
running_servers_file = home_path() / "running_servers"
with open(running_servers_file, "w") as f:
# Write each server info to a new line
f.writelines([info.toFileLine() for info in runningServers])
f.writelines([info.to_file_line() for info in running_servers])
except IOError as e:
log.info("Unable to write running servers file.")
log.exception(e, exc_info=True)


def add_server_entry(pathHash: str, pid: int, port: int, binding: str) -> None:
def add_server_entry(path_hash: str, pid: int, port: int, binding: str) -> None:
"""Add a new server entry to ~/.ptx/running_servers.
This function does not attempt to ensure that an active server doesn't already exist.
"""
PURGE_LIMIT = 10 # If more servers active, try to clean up
runningServers = get_running_servers()
newEntry = RunningServerInfo(pathHash=pathHash, pid=pid, port=port, binding=binding)
runningServers.append(newEntry)
if len(runningServers) >= PURGE_LIMIT:
running_servers = get_running_servers()
new_entry = RunningServerInfo(
path_hash=path_hash, pid=pid, port=port, binding=binding
)
running_servers.append(new_entry)
if len(running_servers) >= PURGE_LIMIT:
log.info(f"There are {PURGE_LIMIT} or more servers on file. Cleaning up ...")
runningServers = list(stop_inactive_servers(runningServers))
save_running_servers(runningServers)
log.info(f"Added server entry {newEntry.toFileLine()}")
running_servers = list(stop_inactive_servers(running_servers))
save_running_servers(running_servers)
log.info(f"Added server entry {new_entry.to_file_line()}")


def remove_server_entry(pathHash: str) -> None:
remainingServers = [
info for info in get_running_servers() if info.pathHash != pathHash
def remove_server_entry(path_hash: str) -> None:
remaining_servers = [
info for info in get_running_servers() if info.path_hash != path_hash
]
save_running_servers(remainingServers)
save_running_servers(remaining_servers)


def stop_inactive_servers(
servers: t.List[RunningServerInfo],
) -> t.Iterator[RunningServerInfo]:
"""Stops any inactive servers and yields the active ones."""
for server in servers:
if server.isActiveServer():
if server.is_active_server():
yield server
else:
server.terminate()


def active_server_for_path_hash(pathHash: str) -> t.Optional[RunningServerInfo]:
def active_server_for_path_hash(path_hash: str) -> t.Optional[RunningServerInfo]:
return next(
(info for info in get_running_servers() if info.pathHash == pathHash),
(info for info in get_running_servers() if info.path_hash == path_hash),
None,
)

Expand All @@ -157,7 +163,7 @@ def start_server(
callback: t.Callable[[int], None] | None = None,
) -> None:
log.info("setting up ...")
pathHash = hash_path(base_dir)
path_hash = hash_path(base_dir)
pid = os.getpid()
binding = binding_for_access(access)
log.info("values set...")
Expand Down Expand Up @@ -186,7 +192,7 @@ class TCPServer(socketserver.TCPServer):
try:
with TCPServer((binding, port), RequestHandler) as httpd:
log.info("adding server entry")
add_server_entry(pathHash, pid, port, binding)
add_server_entry(path_hash, pid, port, binding)
log.info("Starting the server")
if callback is not None:
callback(port)
Expand All @@ -197,5 +203,5 @@ class TCPServer(socketserver.TCPServer):
log.warning(f"Trying port {port} instead.\n")
except KeyboardInterrupt:
log.info("Stopping server.")
remove_server_entry(pathHash)
remove_server_entry(path_hash)
return
12 changes: 6 additions & 6 deletions pretext/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
import psutil
import typing as t
from . import types as pt # PreTeXt types
from lxml import etree as ET
from lxml import etree as ET # noqa: N812
from lxml.etree import _ElementTree, _Element

try:
Expand Down Expand Up @@ -150,8 +150,8 @@ def home_path() -> Path:
return Path.home() / ".ptx"


def hash_path(projectPath: Path) -> str:
return sha256(str(projectPath).encode("utf-8")).hexdigest()[:10]
def hash_path(project_path: Path) -> str:
return sha256(str(project_path).encode("utf-8")).hexdigest()[:10]


# TODO: is this ever called?
Expand Down Expand Up @@ -766,7 +766,7 @@ def active_server_port() -> t.Optional[int]:
for proc in psutil.process_iter():
if proc is None:
continue
if isPretextProc(proc): # type: ignore
if is_pretext_proc(proc): # type: ignore
log.debug(f"Found pretext server running with pid {proc.pid}")
# Sometimes the process stops but doesn't get removed from the process list. We check if the process is still running by checking its status.
if proc.status() not in [psutil.STATUS_RUNNING, psutil.STATUS_SLEEPING]:
Expand Down Expand Up @@ -804,7 +804,7 @@ def stop_server(port: t.Optional[int] = None) -> None:
else:
# As before, we look for a pretext process that is a child of a pretext process. This time we terminate that process.
for proc in psutil.process_iter():
if isPretextProc(proc):
if is_pretext_proc(proc):
log.debug(f"Terminating process with PID {proc.pid}")
proc.terminate()

Expand Down Expand Up @@ -847,7 +847,7 @@ def latest_version() -> t.Optional[str]:
return None


def isPretextProc(proc: psutil.Process) -> bool:
def is_pretext_proc(proc: psutil.Process) -> bool:
if proc.name() == "pretext":
return False
parent = proc.parent()
Expand Down
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ toml = "^0"
# Misc
# ----
errorhandler = "^2.0.1"
pep8-naming = "^0.14.1"

[tool.poetry.extras]
homepage = ["pelican"]
Expand Down

0 comments on commit 074781d

Please sign in to comment.