/*
 * Copyright 2016 higherfrequencytrading.com
 *
 */

package net.openhft.chronicle.queue;

import net.openhft.chronicle.core.OS;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;

public class DirectoryUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(DirectoryUtils.class);
    private static final AtomicLong TIMESTAMPER = new AtomicLong(System.currentTimeMillis());

    /**
     * Beware, this can give different results depending on whether you are
     * a) running inside maven
     * b) are running in a clean directory (without a "target" dir)
     * See OS.TARGET
     */
    @NotNull
    public static File tempDir(String name) {
        final File tmpDir = new File(OS.TARGET, name + "-" + Long.toString(TIMESTAMPER.getAndIncrement(), 36));

        DeleteStatic.INSTANCE.add(tmpDir);

        // Log the temporary directory in OSX as it is quite obscure
        if (OS.isMacOSX()) {
            LOGGER.info("Tmp dir: {}", tmpDir);
        }

        return tmpDir;
    }

    public static void deleteDir(@NotNull File dir) {
        if (dir.isDirectory()) {
            File[] files = dir.listFiles();
            if (files != null) {
                for (File file : files) {
                    if (file.isDirectory()) {
                        deleteDir(file);
                    } else if (!file.delete()) {
                        LOGGER.warn("... unable to delete {}", file);
                    }
                }
            }
        }

        dir.delete();
    }

    // TODO: why not deleteOnExit?
    enum DeleteStatic {
        INSTANCE;
        final Set<File> toDeleteList = Collections.synchronizedSet(new LinkedHashSet<>());

        {
            Runtime.getRuntime().addShutdownHook(new Thread(
                    () -> toDeleteList.forEach(DirectoryUtils::deleteDir)
            ));
        }

        synchronized void add(File path) {
            toDeleteList.add(path);
        }
    }
}

@@ -125,16 +125,62 @@
 ore.OS;%0A
+import net.openhft.chronicle.core.io.IOTools;%0A
 import o
@@ -1319,486 +1319,51 @@
     
-if (dir.isDirectory()) %7B%0A            File%5B%5D files = dir.listFiles();%0A            if (files != null) %7B%0A                for (File file : files) %7B%0A                    if (file.isDirectory()) %7B%0A                        deleteDir(file);%0A                    %7D else if (!file.delete()) %7B%0A                        LOGGER.warn(%22... unable to delete %7B%7D%22, file);%0A                    %7D%0A                %7D%0A            %7D%0A        %7D%0A%0A        dir.delete();%0A    %7D%0A%0A    // TODO: why not deleteOnExit?
+IOTools.deleteDirWithFiles(dir, 20);%0A    %7D%0A
 %0A   

tidy directory delete