summaryrefslogtreecommitdiff
path: root/src/main/kotlin/moe/nea89/website/KFiles.kt
blob: aad3036c534411d9a3af0b6dbc72292c8415172e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
package moe.nea89.website

sealed class KFile {
    /**
     * Only be empty for the root fs
     * */
    var parent: Directory? = null
        private set

    val name: List<String>
        get() =
            parent?.let { it.name + it.files.filter { it.value == this }.keys.first() } ?: emptyList()

    fun linkTo(parent: Directory) {
        if (this.parent == null)
            this.parent = parent
    }

    val fileType: String
        get() = when (this) {
            is Directory -> "directory"
            is Download -> "download"
            is Image -> "image"
            is Text -> "text file"
        }

    data class Text(val text: String) : KFile()
    data class Image(val url: String) : KFile()
    data class Download(val url: String) : KFile()
    data class Directory(val files: Map<String, KFile>) : KFile()
}

data class KFileSystem(val root: KFile.Directory) {
    init {
        if (!verifyHierarchy(root)) {
            throw RuntimeException("File system had missing links. Use linkTo with the primary parent directory")
        }
    }

    private fun verifyHierarchy(el: KFile.Directory): Boolean =
        el.files.values.all {
            it.parent == el && (it !is KFile.Directory || verifyHierarchy(it))
        }


    /**
     * Uses normalized paths
     * */
    fun resolve(parts: List<String>): KFile? =
        parts.fold<String, KFile?>(root) { current, part ->
            if (part == "." || part == "")
                current
            else if (part == "..")
                current?.parent
            else if (current is KFile.Directory) {
                current.files[part]
            } else
                null
        }
}


enum class FSError {
    ENOENT, EISNOTDIR
}

class FileAccessor(val fileSystem: KFileSystem, var implicitPushD: Boolean = false) { // TODO implicit pushd support
    val dirStack = mutableListOf<List<String>>()
    var currentDir = listOf<String>()

    fun cd(path: String): FSError? {
        val file = resolve(path) ?: return FSError.ENOENT
        return when (file) {
            !is KFile.Directory -> FSError.EISNOTDIR
            else -> {
                currentDir = file.name
                null
            }
        }
    }

    fun resolve(path: String): KFile? {
        val parts = path.split("/").filter { it.isNotEmpty() && it != "." }
        return if (path.startsWith("/")) {
            fileSystem.resolve(parts)
        } else {
            fileSystem.resolve(currentDir + parts)
        }
    }

    fun pushD() {
        dirStack.add(currentDir)
    }

    fun useD(block: () -> Unit) {
        val d = currentDir
        try {
            block()
        } finally {
            currentDir = d
        }
    }

    fun popD(): Boolean {
        currentDir = dirStack.removeLastOrNull() ?: return false
        return true
    }
}

@DslMarker
annotation class KFileDsl

fun fileSystem(block: FileSystemBuilder.() -> Unit): KFileSystem =
    KFileSystem(FileSystemBuilder().also(block).build())


@KFileDsl
class FileSystemBuilder {
    private val files = mutableMapOf<String, KFile>()

    fun addNode(name: String, file: KFile): FileSystemBuilder {
        val parts = name.split("/", limit = 2)
        if (parts.size != 1) {
            return addNode(parts[0], FileSystemBuilder().addNode(parts[1], file).build())
        }
        if (files.containsKey(name)) {
            throw RuntimeException("Tried to double set file: $name")
        }
        files[name] = file
        return this
    }

    infix fun String.text(rawText: String) {
        addNode(this, KFile.Text(rawText))
    }

    infix fun String.image(dataUrl: String) {
        addNode(this, KFile.Image(dataUrl))
    }

    infix fun String.download(url: String) {
        addNode(this, KFile.Download(url))
    }

    operator fun String.invoke(block: FileSystemBuilder.() -> Unit) {
        addNode(this, FileSystemBuilder().also(block).build())
    }

    fun build() = KFile.Directory(files).also { dir ->
        files.values.forEach { file -> file.linkTo(dir) }
    }
}

suspend fun ShellExecutionContext.requireFileAccessor(): FileAccessor {
    val fa = console.fileAccessor
    if (fa == null) {
        console.addLine("There is no file accessor present :(")
        exit()
    }
    return fa
}