package com.urbancode.air.plugin.scm

import java.text.*;

public class SCMCleanup extends SCMStep {

    //**************************************************************************
    // CLASS
    //**************************************************************************

    //**************************************************************************
    // INSTANCE
    //**************************************************************************

    public void execute() {
        setupWorkDir()
        
        loadRules.eachLine { fileName ->
            while (fileName.startsWith("\\") || fileName.startsWith("/")) {
                fileName = fileName.substring(1)
            }
            removeViewPrivateFiles(fileName)
        }
    }

    private def removeViewPrivateFiles(def fileName) {
        if (fileName && fileName.trim()) {
            File file = new File(directory, fileName);
            if (file.exists()) {
                def command = [scmCommand, "ls", "-recurse", "-view_only", "-visible", fileName]
                ch.runCommand("Cleaning up ${fileName}", command) { Process proc ->
                    proc.in.eachLine { filePath ->
                        File ccFile = new File(directory, filePath)
                        if (ccFile.exists()) {
                            boolean deleted = ccFile.delete()
                            if (deleted) {
                                println("Deleted: " + filePath);
                            }
                            else {
                                println("Could not delete: " + filePath);
                            }
                        }
                    }
                }
            }
        }
    }
}
