fun cleanup()

in bunch-cli/src/main/kotlin/org/jetbrains/bunches/cleanup.kt [65:109]


fun cleanup(settings: Settings) {
    if (!settings.isNoCommit) {
        uncommittedChanges(settings.repoPath).checkAndExitIfNeeded {
            exitWithError("Can not commit changes for cleanup with uncommitted changes.")
        }
    }

    val extensions = if (settings.extension != null) {
        setOf(settings.extension)
    } else {
        readExtensionsFromFile(settings.bunchPath).resultWithExit().toSet()
    }.map { ".$it" }

    val root = File(settings.repoPath)

    if (!isGitRoot(root)) {
        exitWithError("Repository directory with branch is expected")
    }

    val gitignoreParseResult = parseGitIgnore(root)

    val filesWithExtensions = root
        .walkTopDown()
        .onEnter { dir -> !shouldIgnoreDir(dir, root, gitignoreParseResult) }
        .filter { child -> extensions.any { child.name.endsWith(it) } }
        .toList()

    val changedFiles = ArrayList<FileChange>()
    for (cleanupFile in filesWithExtensions) {
        if (cleanupFile.isDirectory) {
            exitWithError("Bunch directories are not supported: $cleanupFile")
        }

        cleanupFile.delete()
        changedFiles.add(FileChange(ChangeType.REMOVE, cleanupFile))
    }

    if (settings.isNoCommit) {
        return
    }

    val extValue = settings.extension ?: ""
    val commitTitle = settings.commitTitle!!.replace(EXT_PATTERN, extValue)
    commitChanges(settings.repoPath, changedFiles, commitTitle)
}