|
| 1 | +import os |
| 2 | +import json |
| 3 | + |
| 4 | +def ensure_drafts_file(drafts_file: str) -> str: |
| 5 | + """ |
| 6 | + Ensure the drafts file exists following these rules: |
| 7 | +
|
| 8 | + - If the provided drafts_file does not exist and it is a simple filename (i.e., it does not contain |
| 9 | + any path separator), then use the XDG Base Directory Specification to determine a cache directory: |
| 10 | + * It checks for the XDG_CACHE_HOME environment variable. |
| 11 | + * If not set, defaults to HOME/.cache. |
| 12 | + Then, a sub-folder named "threads-cli" is created within that cache directory, and |
| 13 | + drafts_file is placed inside that sub-folder. |
| 14 | + |
| 15 | + - If drafts_file is a simple filename, but a file does not exist at that location, or if it is given as a full |
| 16 | + path, the application uses that path exactly as given. |
| 17 | + |
| 18 | + - If the drafts file does not exist, create an empty JSON file (with an empty dict as content by default). |
| 19 | +
|
| 20 | + Returns: |
| 21 | + The final path to the drafts file. |
| 22 | + |
| 23 | + Raises: |
| 24 | + EnvironmentError: If the required HOME environment variable is not set when needed. |
| 25 | + """ |
| 26 | + # Check if drafts_file doesn't exist and is a simple filename (without path separator). |
| 27 | + if not os.path.exists(drafts_file) and os.path.sep not in drafts_file: |
| 28 | + # Determine the cache directory using XDG_CACHE_HOME if available, |
| 29 | + # otherwise default to HOME/.cache. |
| 30 | + xdg_cache_home = os.getenv('XDG_CACHE_HOME') |
| 31 | + if not xdg_cache_home: |
| 32 | + home = os.getenv('HOME') |
| 33 | + if not home: |
| 34 | + raise EnvironmentError("HOME environment variable is not set.") |
| 35 | + xdg_cache_home = os.path.join(home, '.cache') |
| 36 | + # Define the final path: XDG_CACHE_HOME/threads-cli/drafts_file |
| 37 | + drafts_dir = os.path.join(xdg_cache_home, "threads-cli") |
| 38 | + os.makedirs(drafts_dir, exist_ok=True) |
| 39 | + drafts_file = os.path.join(drafts_dir, drafts_file) |
| 40 | + |
| 41 | + # If the drafts file still does not exist, create an empty JSON file. |
| 42 | + if not os.path.exists(drafts_file): |
| 43 | + with open(drafts_file, "w") as f: |
| 44 | + json.dump({}, f) |
| 45 | + |
| 46 | + return drafts_file |
0 commit comments