Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

improve exceptional behavior of sh.cd #68

Merged
merged 1 commit into from
Jan 19, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
53 changes: 27 additions & 26 deletions lib/sh/cd.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
#!/usr/bin/env py.test
from __future__ import annotations

import contextlib
from contextlib import contextmanager
from os import chdir
from os import environ

from lib import json as JSON
Expand All @@ -19,39 +20,39 @@
Command = tuple[object, ...]


@contextlib.contextmanager
@contextmanager
def cd(
dirname: OSPath, env: Environ = environ, *, direnv: bool = True
) -> Generator[OSPath]:
oldpwd = OSPath(env["PWD"])

# double-check that $PWD stays accurate:
assert oldpwd.samefile(OSPath.cwd()), (oldpwd, OSPath.cwd())

newpwd = oldpwd / dirname
if newpwd.samefile(oldpwd): # we're already there
cwd = OSPath.cwd()
if newpwd == oldpwd and cwd.samefile(newpwd): # we're already there
yield oldpwd
return

env["PWD"] = str(newpwd)
xtrace(("cd", dirname))
with contextlib.chdir(dirname):
if direnv:
run(("direnv", "allow"))
direnv_json: JSON.Value = json(("direnv", "export", "json"))
if direnv_json is None:
pass # nothing to do
elif isinstance(direnv_json, dict):
for key, value in direnv_json.items():
if value is None:
env.pop(key, None)
else:
assert isinstance(value, str), value
env[key] = value
else:
raise AssertionError(f"expected dict, got {type(direnv_json)}")
yield dirname

# show the un-cd, and reflect it in $PWD
env["PWD"] = str(newpwd)
chdir(dirname)
if direnv:
run(("direnv", "allow"))
direnv_json: JSON.Value = json(("direnv", "export", "json"))
if direnv_json is None:
pass # nothing to do
elif isinstance(direnv_json, dict):
for key, value in direnv_json.items():
if value is None:
env.pop(key, None)
else:
assert isinstance(value, str), value
env[key] = value
else:
raise AssertionError(f"expected dict, got {type(direnv_json)}")
try:
yield newpwd
finally: # undo the cd and log it
chdir(oldpwd)
env["PWD"] = str(oldpwd)
xtrace(("cd", oldpwd))
xtrace(("popd",))
info(oldpwd, "<-", newpwd)