update envs for better XDG base directory support

This commit is contained in:
grassblock 2024-07-24 15:27:48 +08:00
parent f84a7005a5
commit 9f275c64c4
3 changed files with 72 additions and 2 deletions

View file

@ -0,0 +1,37 @@
#!/usr/bin/env python3
# This entire thing is unnecessary post v3.13.0a3
# https://github.com/python/cpython/issues/73965
def is_vanilla() -> bool:
""" :return: whether running "vanilla" Python """
import sys
return not hasattr(__builtins__, '__IPYTHON__') and 'bpython' not in sys.argv[0]
def setup_history():
""" read and write history from state file """
import os
import atexit
import readline
from pathlib import Path
# https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html#variables
if state_home := os.environ.get('XDG_STATE_HOME'):
state_home = Path(state_home)
else:
state_home = Path.home() / '.local' / 'state'
if not state_home.is_dir():
print("Error: XDG_STATE_HOME does not exist at", state_home)
history: Path = state_home / 'python_history'
# https://github.com/python/cpython/issues/105694
if not history.is_file():
readline.write_history_file(str(history)) # breaks on macos + python3 without this.
readline.read_history_file(history)
atexit.register(readline.write_history_file, history)
if is_vanilla():
setup_history()