Serialize every process that writes ``skill_dir``. Install, uninstall and the CLI's stale-skill refresh (#1805) all write the same files and stage through fixed ``SKILL.md.tmp`` / ``references.tmp`` names, so two of them at once would write through each other - and an uninstall raci
(skill_dir: Path, *, wait: bool = True)
| 98 | |
| 99 | @contextlib.contextmanager |
| 100 | def _skill_lock(skill_dir: Path, *, wait: bool = True): |
| 101 | """Serialize every process that writes ``skill_dir``. |
| 102 | |
| 103 | Install, uninstall and the CLI's stale-skill refresh (#1805) all write the |
| 104 | same files and stage through fixed ``SKILL.md.tmp`` / ``references.tmp`` |
| 105 | names, so two of them at once would write through each other - and an |
| 106 | uninstall racing a refresh could see the refresh put the skill back. |
| 107 | |
| 108 | Yields True while this process holds the lock. With ``wait`` off (the |
| 109 | refresh) it yields False instead of waiting when another process holds it. |
| 110 | It yields None when locking is unavailable here (no writable cache |
| 111 | directory, a file system that refuses to lock): install and uninstall then |
| 112 | go ahead unlocked, as they did before the lock existed; the refresh skips. |
| 113 | |
| 114 | An OS lock (flock / msvcrt.locking): the OS releases it however the holder |
| 115 | exits, so a crash or a kill never leaves the directory locked and there is |
| 116 | no staleness timeout to guess. The lock file is never deleted. |
| 117 | """ |
| 118 | path = _skill_lock_path(skill_dir) |
| 119 | held = _held_skill_locks.__dict__.setdefault("paths", set()) |
| 120 | if path in held: |
| 121 | yield True |
| 122 | return |
| 123 | try: |
| 124 | path.parent.mkdir(parents=True, exist_ok=True) |
| 125 | fh = open(path, "a+b") |
| 126 | except OSError: |
| 127 | fh = None |
| 128 | if fh is None: |
| 129 | yield None |
| 130 | return |
| 131 | with fh: |
| 132 | try: |
| 133 | locked = _try_skill_lock(fh) |
| 134 | while not locked and wait: |
| 135 | time.sleep(0.05) |
| 136 | locked = _try_skill_lock(fh) |
| 137 | except OSError: |
| 138 | locked = None |
| 139 | if not locked: |
| 140 | yield locked |
| 141 | return |
| 142 | held.add(path) |
| 143 | try: |
| 144 | yield True |
| 145 | finally: |
| 146 | held.discard(path) |
| 147 | _release_skill_lock(fh) |
| 148 | |
| 149 | |
| 150 | def _write_version_stamp(skill_dst: Path, version: str) -> None: |
no test coverage detected