1+ package com.dengzii.plugin.auc
2+
3+ import java.io.File
4+
5+ /* *
6+ * <pre>
7+ * author : dengzi
8+ * e-mail : denua@foxmail.com
9+ * github : https://github.com/dengzii
10+ * time : 2019/1/1
11+ * desc :
12+ </pre> */
13+ class FileTree private constructor() {
14+
15+ var name = " "
16+ var isDir = true
17+ private var parent: FileTree ? = null
18+ private val children by lazy { mutableListOf<FileTree >() }
19+
20+ companion object {
21+ private val TAG = FileTree ::class .java.simpleName
22+
23+ fun root (path : String ): FileTree {
24+ val root = File (path)
25+ if (! root.isDirectory) {
26+ throw RuntimeException (" The root must be a directory." )
27+ }
28+ return with (FileTree (null , path, true )) {
29+ this .parent = this
30+ this
31+ }
32+ }
33+ }
34+
35+ constructor (block: FileTree .() -> Unit ) : this () {
36+ invoke(block)
37+ }
38+
39+ constructor (parent: FileTree ? , name: String , isDir: Boolean ) : this () {
40+ this .name = name
41+ this .parent = parent
42+ this .isDir = isDir
43+ }
44+
45+ operator fun invoke (block : FileTree .() -> Unit ): FileTree {
46+ this .block()
47+ return this
48+ }
49+
50+ fun setRoot (path : String ): FileTree {
51+ if (! File (path).isDirectory) {
52+ throw RuntimeException (" The root must be a directory." )
53+ }
54+ parent = this
55+ name = path
56+ return this
57+ }
58+
59+ fun create () {
60+ if (! isRoot()) {
61+ throw RuntimeException (" Must create structure from root node." )
62+ }
63+ createChild()
64+ }
65+
66+ fun forEach (block : (it: FileTree ) -> Unit ) {
67+ children.forEach(block)
68+ }
69+
70+ fun dir (name : String , block : FileTree .() -> Unit = {}) {
71+ val dir = FileTree (this , name, true )
72+ children.add(dir)
73+ dir(block)
74+ }
75+
76+ fun file (name : String ) {
77+ children.add(FileTree (this , name, false ))
78+ }
79+
80+ fun getPath (): String {
81+ if (isRoot() || parent == null ) {
82+ return name
83+ }
84+ return parent!! .getPath() + File .separator + name
85+ }
86+
87+ private fun isRoot (): Boolean {
88+ return this == parent
89+ }
90+
91+ private fun createChild () {
92+ children.forEach {
93+ val file = File (it.getPath())
94+ if (file.exists()) {
95+ Logger .d(TAG , " ${file.absolutePath} already exists." )
96+ } else {
97+ Logger .d(TAG , " create ${file.absolutePath} " )
98+ if (it.isDir) {
99+ file.mkdir()
100+ } else {
101+ file.createNewFile()
102+ }
103+ }
104+ if (it.isDir) {
105+ it.createChild()
106+ }
107+ }
108+ }
109+ }
0 commit comments