# Buggy code
def atomic_directory(target_dir, source=None):
    """A context manager that yields a new empty work directory path it will move to `target_dir`.

    :param str target_dir: The target directory to atomically update.
    :param str source: An optional source offset into the work directory to use for the atomic update
                       of the target directory. By default the whole work directory is used.

    If the `target_dir` already exists the enclosed block will be yielded `None` to signal there is
    no work to do.

    If the enclosed block fails the `target_dir` will be undisturbed.

    The new work directory will be cleaned up regardless of whether or not the enclosed block
    succeeds.
    """
    atomic_dir = AtomicDirectory(target_dir=target_dir)
    if atomic_dir.is_finalized:
        yield None
        return

    safe_mkdir(atomic_dir.work_dir)
    try:
        yield atomic_dir.work_dir
        atomic_dir.finalize(source=source)
    finally:
        atomic_dir.cleanup()


# Traceback (pants.engine.internals.scheduler.ExecutionError)
23:06:05.36 [INFO] Starting: Resolving 3rdparty/python/constraints.txt
23:06:05.38 [WARN] /home/toolchain/.cache/pants/setup/bootstrap-Linux-x86_64/2.0.0b2_py38/lib/python3.8/site-packages/pants/base/exception_sink.py:313: DeprecationWarning: PY_SSIZE_T_CLEAN will be required for '#' formats
process_title=setproctitle.getproctitle(),
23:06:05.38 [ERROR] 1 Exception encountered:
Engine traceback:
in select
in `typecheck` goal
in Typecheck using MyPy
in pants.backend.python.typecheck.mypy.rules.mypy_typecheck_partition
in pants.backend.python.util_rules.pex.create_pex
in pants.engine.process.fallible_to_exec_result_or_raise
Traceback (most recent call last):
File "/home/toolchain/.cache/pants/setup/bootstrap-Linux-x86_64/2.0.0b2_py38/lib/python3.8/site-packages/pants/engine/process.py", line 241, in fallible_to_exec_result_or_raise
raise ProcessExecutionFailure(
pants.engine.process.ProcessExecutionFailure: Process 'Building mypy.pex with 1 requirement: mypy==0.782' failed with exit code 1.
stdout:
stderr:
Failed to spawn a job for DistributionTarget(interpreter=PythonInterpreter('/usr/local/bin/python3.8', PythonIdentity('/usr/local/bin/python3.8', 'cp38', 'cp38', 'manylinux2014_x86_64', (3, 8, 5)))): [Errno 2] No such file or directory: '/home/toolchain/.pex/unzipped_pexes/49b4b32295a60a0a4dfc0659c3a44f93560c4a81/.deps/pex-2.1.16-py2.py3-none-any.whl/pex/__pycache__/variables.cpython-37.pyc.139923989690656'
Traceback (most recent call last):
File "/home/toolchain/.cache/pants/setup/bootstrap-Linux-x86_64/2.0.0b2_py38/lib/python3.8/site-packages/pants/bin/local_pants_runner.py", line 256, in run
engine_result = self._run_v2()
File "/home/toolchain/.cache/pants/setup/bootstrap-Linux-x86_64/2.0.0b2_py38/lib/python3.8/site-packages/pants/bin/local_pants_runner.py", line 168, in _run_v2
return self._maybe_run_v2_body(goals, poll=False)
File "/home/toolchain/.cache/pants/setup/bootstrap-Linux-x86_64/2.0.0b2_py38/lib/python3.8/site-packages/pants/bin/local_pants_runner.py", line 185, in _maybe_run_v2_body
return self.graph_session.run_goal_rules(
File "/home/toolchain/.cache/pants/setup/bootstrap-Linux-x86_64/2.0.0b2_py38/lib/python3.8/site-packages/pants/init/engine_initializer.py", line 125, in run_goal_rules
exit_code = self.scheduler_session.run_goal_rule(
File "/home/toolchain/.cache/pants/setup/bootstrap-Linux-x86_64/2.0.0b2_py38/lib/python3.8/site-packages/pants/engine/internals/scheduler.py", line 568, in run_goal_rule
self._raise_on_error([t for _, t in throws])
File "/home/toolchain/.cache/pants/setup/bootstrap-Linux-x86_64/2.0.0b2_py38/lib/python3.8/site-packages/pants/engine/internals/scheduler.py", line 527, in _raise_on_error
raise ExecutionError(
pants.engine.internals.scheduler.ExecutionError: 1 Exception encountered:
Engine traceback:
in select
in `typecheck` goal
in Typecheck using MyPy
in pants.backend.python.typecheck.mypy.rules.mypy_typecheck_partition
in pants.backend.python.util_rules.pex.create_pex
in pants.engine.process.fallible_to_exec_result_or_raise
Traceback (most recent call last):
File "/home/toolchain/.cache/pants/setup/bootstrap-Linux-x86_64/2.0.0b2_py38/lib/python3.8/site-packages/pants/engine/process.py", line 241, in fallible_to_exec_result_or_raise
raise ProcessExecutionFailure(
pants.engine.process.ProcessExecutionFailure: Process 'Building mypy.pex with 1 requirement: mypy==0.782' failed with exit code 1.
stdout:
stderr:
Failed to spawn a job for DistributionTarget(interpreter=PythonInterpreter('/usr/local/bin/python3.8', PythonIdentity('/usr/local/bin/python3.8', 'cp38', 'cp38', 'manylinux2014_x86_64', (3, 8, 5)))): [Errno 2] No such file or directory: '/home/toolchain/.pex/unzipped_pexes/49b4b32295a60a0a4dfc0659c3a44f93560c4a81/.deps/pex-2.1.16-py2.py3-none-any.whl/pex/__pycache__/variables.cpython-37.pyc.139923989690656'

# Fixed code
def atomic_directory(target_dir, exclusive, source=None):
    # type: (str, bool, Optional[str]) -> Iterator[Optional[str]]
    """A context manager that yields a new empty work directory path it will move to `target_dir`.

    :param target_dir: The target directory to atomically update.
    :param exclusive: If `True`, its guaranteed that only one process will be yielded a non `None`
                      workdir; otherwise two or more processes might be yielded unique non-`None`
                      workdirs with the last process to finish "winning".
    :param source: An optional source offset into the work directory to use for the atomic update
                   of the target directory. By default the whole work directory is used.

    If the `target_dir` already exists the enclosed block will be yielded `None` to signal there is
    no work to do.

    If the enclosed block fails the `target_dir` will be undisturbed.

    The new work directory will be cleaned up regardless of whether or not the enclosed block
    succeeds.

    If the contents of the resulting directory will be subsequently mutated it's probably correct to
    pass `exclusive=True` to ensure mutations that race the creation process are not lost.
    """
    atomic_dir = AtomicDirectory(target_dir=target_dir)
    if atomic_dir.is_finalized:
        # Our work is already done for us so exit early.
        yield None
        return

    lock_fd = None  # type: Optional[int]
    if exclusive:
        head, tail = os.path.split(atomic_dir.target_dir)
        if head:
            safe_mkdir(head)
        # N.B.: We don't actually write anything to the lock file but the fcntl file locking
        # operations only work on files opened for at least write.
        lock_fd = os.open(
            os.path.join(head, ".{}.atomic_directory.lck".format(tail or "here")),
            os.O_CREAT | os.O_WRONLY,
        )
        # N.B.: Since lockf operates on an open file descriptor and these are guaranteed to be
        # closed by the operating system when the owning process exits, this lock is immune to
        # staleness.
        fcntl.lockf(lock_fd, fcntl.LOCK_EX)  # A blocking write lock.
        if atomic_dir.is_finalized:
            # We lost the double-checked locking race and our work was done for us by the race
            # winner so exit early.
            yield None
            return

    safe_mkdir(atomic_dir.work_dir)
    try:
        yield atomic_dir.work_dir
        atomic_dir.finalize(source=source)
    finally:
        if lock_fd is not None:
            fcntl.lockf(lock_fd, fcntl.LOCK_UN)
            os.close(lock_fd)
        atomic_dir.cleanup()