protected function cleanDir($dir, $keep)
    {
        $finder = clone $this->finder;
        $finder->in($dir);
        $finder->depth(0);
        $this->doSort($finder);
        $items = iterator_to_array($finder->getIterator());
        if ($keep) {
            array_splice($items, -$keep);
        }
        while ($items) {
            $item = reset($items);
            try {
                $this->fs->chmod($item, 0777, 0000, true);
            } catch (IOException $e) {
                // If chmod didn't work and the exception contains a path, try
                // to remove anyway.
                $path = $e->getPath();
                if ($path && realpath($path) !== realpath($item)) {
                    $this->fs->remove($path);
                    continue;
                }
            }
            $this->fs->remove($item);
            array_shift($items);
        }
    }