sapling/eden/scm/edenscmnative/patchrmdir.pyx
Arun Kulshreshtha dd34889d43 py3: make patchrmdir work with Python 3
Summary: With this change `hg rm` works even with extensions enabled. Since this is a Cython extension, I did not bother adding type annotations since IIUC Pyre cannot type check Cython files.

Reviewed By: quark-zju

Differential Revision: D19652178

fbshipit-source-id: 2e03a0f241f80732bdae3f472a1e0576684b1911
2020-01-30 17:22:30 -08:00

69 lines
1.8 KiB
Cython

# Copyright (c) Facebook, Inc. and its affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
# cython: language_level=3str
"""patch rmdir
Check if a directory is empty before trying to call rmdir on it. This works
around some kernel issues.
Have no effect on Windows.
"""
IF UNAME_SYSNAME != "Windows":
from edenscm.mercurial import (
extensions,
pycompat,
)
import os
import errno
cdef extern from "dirent.h":
ctypedef struct DIR
struct dirent:
pass
DIR *opendir(const char *)
dirent *readdir(DIR *)
int closedir(DIR *)
cdef int _countdir(const char *path):
"""return min(3, the number of entries inside a directory).
return -1 if the directory cannot be opened.
"""
cdef DIR *d = opendir(path)
if d == NULL:
return -1
cdef dirent *e
cdef int n = 0
while True:
e = readdir(d)
if e == NULL:
break
else:
n += 1
if n > 2:
break
closedir(d)
return n
def _rmdir(orig, path):
path = pycompat.encodeutf8(path)
n = _countdir(path)
if n >= 3:
# The number 3 is because most systems have "." and "..". For systems
# without them, we fallback to the original rmdir, the behavior should
# still be correct.
# Choose a slightly different error message other than "Directory not
# empty" so the test could notice the difference.
raise OSError(errno.ENOTEMPTY, b'Non-empty directory: %r' % path)
else:
return orig(path)
def uisetup(ui):
extensions.wrapfunction(os, 'rmdir', _rmdir)