This instance will be upgraded to Heptapod 0.21.0rc2 on 2021-04-16 at 11:00 UTC+2 (a few minutes of down time)

purge.py 9.53 KB
Newer Older
Steve Borho's avatar
Steve Borho committed
1
# purge.py - working copy purge dialog, based on Mercurial purge extension
2 3 4 5 6 7
#
# Copyright 2010 Steve Borho <steve@borho.org>
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2, incorporated herein by reference.

8 9
from __future__ import absolute_import

10
import os
11
import shutil
12
import stat
13

14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
from .qtcore import (
    QSettings,
    QThread,
    QTimer,
    Qt,
    pyqtSignal,
    pyqtSlot,
)
from .qtgui import (
    QCheckBox,
    QDialog,
    QDialogButtonBox,
    QVBoxLayout,
    qApp,
)
29

30 31 32 33
from hgext.largefiles import (
    lfutil,
)

34 35 36 37
from mercurial import (
    hg,
    scmutil,
)
38

39 40 41 42 43 44
from ..util import hglib
from ..util.i18n import _, ngettext
from . import (
    cmdui,
    qtlib,
)
45

Steve Borho's avatar
Steve Borho committed
46
class PurgeDialog(QDialog):
47

48 49
    progress = pyqtSignal(str, object, str, str, object)
    showMessage = pyqtSignal(str)
50

51
    def __init__(self, repoagent, parent=None):
52
        QDialog.__init__(self, parent)
53 54
        f = self.windowFlags()
        self.setWindowFlags(f & ~Qt.WindowContextHelpButtonHint)
55 56 57

        self._repoagent = repoagent

58
        layout = QVBoxLayout()
59
        layout.setContentsMargins(0, 0, 0, 0)
60 61
        layout.setSpacing(0)
        self.setLayout(layout)
62

63
        toplayout = QVBoxLayout()
64
        toplayout.setContentsMargins(10, 10, 10, 10)
65 66
        toplayout.setSpacing(5)
        layout.addLayout(toplayout)
67

68 69 70
        cb = QCheckBox(_('No unknown files found'))
        cb.setChecked(False)
        cb.setEnabled(False)
71
        toplayout.addWidget(cb)
72
        self.ucb = cb
73

74 75 76
        cb = QCheckBox(_('No ignored files found'))
        cb.setChecked(False)
        cb.setEnabled(False)
77
        toplayout.addWidget(cb)
78
        self.icb = cb
79 80 81 82

        cb = QCheckBox(_('No trash files found'))
        cb.setChecked(False)
        cb.setEnabled(False)
83
        toplayout.addWidget(cb)
84 85
        self.tcb = cb

86 87
        self.foldercb = QCheckBox(_('Delete empty folders'))
        self.foldercb.setChecked(True)
88
        toplayout.addWidget(self.foldercb)
89 90
        self.hgfilecb = QCheckBox(_('Preserve files beginning with .hg'))
        self.hgfilecb.setChecked(True)
91
        toplayout.addWidget(self.hgfilecb)
Steve Borho's avatar
Steve Borho committed
92

93 94 95 96 97
        BB = QDialogButtonBox
        bb = QDialogButtonBox(BB.Ok|BB.Cancel)
        bb.accepted.connect(self.accept)
        bb.rejected.connect(self.reject)
        self.bb = bb
98 99 100 101 102 103 104
        toplayout.addStretch()
        toplayout.addWidget(bb)

        self.stbar = cmdui.ThgStatusBar(self)
        self.progress.connect(self.stbar.progress)
        self.showMessage.connect(self.stbar.showMessage)
        layout.addWidget(self.stbar)
105

106
        self.setWindowTitle(_('%s - purge') % repoagent.displayName())
107
        self.setWindowIcon(qtlib.geticon('hg-purge'))
108

109 110
        self.bb.setEnabled(False)
        self.progress.emit(*cmdui.startProgress(_('Checking'), '...'))
111 112 113
        s = QSettings()
        desktopgeom = qApp.desktop().availableGeometry()
        self.resize(desktopgeom.size() * 0.25)
114
        self.restoreGeometry(qtlib.readByteArray(s, 'purge/geom'))
115 116

        self.th = None
117 118
        QTimer.singleShot(0, self.checkStatus)

119 120 121 122
    @property
    def repo(self):
        return self._repoagent.rawRepo()

123 124 125 126 127 128 129 130 131 132
    def checkStatus(self):
        repo = self.repo
        class CheckThread(QThread):
            def __init__(self, parent):
                QThread.__init__(self, parent)
                self.files = (None, None)
                self.error = None

            def run(self):
                try:
133 134
                    with lfutil.lfstatus(repo):
                        stat = repo.status(ignored=True, unknown=True)
135
                    trashcan = repo.vfs.join(b'Trashcan')
136 137 138 139
                    if os.path.isdir(trashcan):
                        trash = os.listdir(trashcan)
                    else:
                        trash = []
140
                    self.files = stat.unknown, stat.ignored, trash
141
                except Exception as e:
142 143 144
                    self.error = str(e)

        self.th = CheckThread(self)
145
        self.th.finished.connect(self._checkCompleted)
146 147
        self.th.start()

148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
    @pyqtSlot()
    def _checkCompleted(self):
        self.th.wait()
        self.files = self.th.files
        self.bb.setEnabled(True)
        self.progress.emit(*cmdui.stopProgress(_('Checking')))
        if self.th.error:
            self.showMessage.emit(hglib.tounicode(self.th.error))
        else:
            self.showMessage.emit(_('Ready to purge.'))
            U, I, T = self.files
            if U:
                self.ucb.setText(ngettext(
                    'Delete %d unknown file',
                    'Delete %d unknown files', len(U)) % len(U))
                self.ucb.setChecked(True)
                self.ucb.setEnabled(True)
            if I:
                self.icb.setText(ngettext(
                   'Delete %d ignored file',
                   'Delete %d ignored files', len(I)) % len(I))
                self.icb.setChecked(True)
                self.icb.setEnabled(True)
            if T:
                self.tcb.setText(ngettext(
                    'Delete %d file in .hg/Trashcan',
                    'Delete %d files in .hg/Trashcan', len(T)) % len(T))
                self.tcb.setChecked(True)
                self.tcb.setEnabled(True)

178
    def reject(self):
179 180
        if self.th and self.th.isRunning():
            return
181 182 183 184
        s = QSettings()
        s.setValue('purge/geom', self.saveGeometry())
        super(PurgeDialog, self).reject()

185
    def accept(self):
186 187
        unknown = self.ucb.isChecked()
        ignored = self.icb.isChecked()
188
        trash = self.tcb.isChecked()
189 190
        delfolders = self.foldercb.isChecked()
        keephg = self.hgfilecb.isChecked()
191

192
        if not (unknown or ignored or trash or delfolders):
193 194 195
            QDialog.accept(self)
            return
        if not qtlib.QuestionMsgBox(_('Confirm file deletions'),
196 197
            _('Are you sure you want to delete these files and/or folders?'),
            parent=self):
198 199
            return

200 201 202 203
        opts = dict(unknown=unknown, ignored=ignored, trash=trash,
                    delfolders=delfolders, keephg=keephg)

        self.th = PurgeThread(self.repo, opts, self)
204 205
        self.th.progress.connect(self.progress)
        self.th.showMessage.connect(self.showMessage)
206
        self.th.finished.connect(self._purgeCompleted)
207 208
        self.th.start()

209 210 211 212 213 214 215 216 217 218 219 220
    @pyqtSlot()
    def _purgeCompleted(self):
        self.th.wait()
        F = self.th.failures
        if F:
            qtlib.InfoMsgBox(_('Deletion failures'), ngettext(
                'Unable to delete %d file or folder',
                'Unable to delete %d files or folders', len(F)) % len(F),
                parent=self)
        if F is not None:
            self.reject()

221
class PurgeThread(QThread):
222 223
    progress = pyqtSignal(str, object, str, str, object)
    showMessage = pyqtSignal(str)
224

225
    def __init__(self, repo, opts, parent):
226 227
        super(PurgeThread, self).__init__(parent)
        self.failures = 0
228 229
        self.root = repo.root
        self.opts = opts
230 231

    def run(self):
232 233
        try:
            self.failures = self.purge(self.root, self.opts)
234
        except Exception as e:
235 236 237 238
            self.failures = None
            self.showMessage.emit(hglib.tounicode(str(e)))

    def purge(self, root, opts):
239
        repo = hg.repository(hglib.loadui(), self.root)
240
        keephg = opts['keephg']
Steve Borho's avatar
Steve Borho committed
241 242 243
        directories = []
        failures = []

244
        if opts['trash']:
245
            self.showMessage.emit(_('Deleting trash folder...'))
246
            trashcan = repo.vfs.join(b'Trashcan')
247 248 249 250 251
            try:
                shutil.rmtree(trashcan)
            except EnvironmentError:
                failures.append(trashcan)

252
        self.showMessage.emit('')
253
        match = scmutil.matchall(repo)
254
        match.explicitdir = match.traversedir = directories.append
255 256 257
        with lfutil.lfstatus(repo):
            status = repo.status(match=match, ignored=opts['ignored'],
                                 unknown=opts['unknown'], clean=False)
258
        files = []
259 260 261 262
        if opts['unknown']:
            files.extend(status.unknown)
        if opts['ignored']:
            files.extend(status.ignored)
Steve Borho's avatar
Steve Borho committed
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283

        def remove(remove_func, name):
            try:
                if keephg and name.startswith('.hg'):
                    return
                remove_func(repo.wjoin(name))
            except EnvironmentError:
                failures.append(name)

        def removefile(path):
            try:
                os.remove(path)
            except OSError:
                # read-only files cannot be unlinked under Windows
                s = os.stat(path)
                if (s.st_mode & stat.S_IWRITE) != 0:
                    raise
                os.chmod(path, stat.S_IMODE(s.st_mode) | stat.S_IWRITE)
                os.remove(path)

        for i, f in enumerate(sorted(files)):
284 285
            data = ('deleting', i, f, '', len(files))
            self.progress.emit(*data)
Steve Borho's avatar
Steve Borho committed
286
            remove(removefile, f)
287 288
        data = ('deleting', None, '', '', len(files))
        self.progress.emit(*data)
289
        self.showMessage.emit(_('Deleted %d files') % len(files))
Steve Borho's avatar
Steve Borho committed
290

291
        if opts['delfolders'] and directories:
Steve Borho's avatar
Steve Borho committed
292
            for i, f in enumerate(sorted(directories, reverse=True)):
293
                if match(f) and not os.listdir(repo.wjoin(f)):
294 295
                    data = ('rmdir', i, f, '', len(directories))
                    self.progress.emit(*data)
Steve Borho's avatar
Steve Borho committed
296
                    remove(os.rmdir, f)
297 298
            data = ('rmdir', None, f, '', len(directories))
            self.progress.emit(*data)
299 300
            self.showMessage.emit(_('Deleted %d files and %d folders') % (
                                  len(files), len(directories)))
Steve Borho's avatar
Steve Borho committed
301
        return failures