# File locking

import warnings

try:
    import fcntl
    import errno

    def exclusive_lock(f):
        """Acquire an exclusive lock.  Returns True on successful
        lock, or False on error."""
        try:
            fcntl.flock(f.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
        except IOError as e:
            if e.errno in (errno.EACCES, errno.EAGAIN):
                return False
            else: # pragma: no cover
                raise
        return True

    def exclusive_unlock(f):
        """Release an exclusive lock."""
        fcntl.flock(f.fileno(), fcntl.LOCK_UN)

except ImportError: # pragma: no cover
    def exclusive_lock(f):
        """Dummy lock function -- does not lock!"""
        warnings.warn("Pretending to lock " + str(f))
        return True

    def exclusive_unlock(f):
        """Release an exclusive lock."""
        return
