• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2017 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package writer.files
18 
19 import parser.config
20 import java.nio.file.Path
21 
22 abstract class AbstractFileWriter() {
23     abstract val baseName: String
24     abstract val templateResource: String
25     abstract val path: Path
26 
27     //init with template file contents on first use
28     var outStr: String = ""
29         get() = if (field.isEmpty()) resources.readResourceText(this.templateResource) else field
30 
replaceVarsnull31     open fun replaceVars() {}
32 
replaceVarnull33     fun replaceVar(varName: String, newValue: String) {
34         outStr = outStr.replace(Regex("\\\$\\{?$varName}?"), newValue)
35     }
36 
replaceVarnull37     fun replaceVar(varName: String, newValue: () -> String) {
38         replaceVar(varName, newValue())
39     }
40 
writeToFilenull41     fun writeToFile(): Boolean {
42         replaceVars()
43         onWrite()
44 
45         if (config.lintMode) {
46             return false
47         } else {
48             val dir = this.path.parent.toFile() //dir name
49             if (!dir.exists()) dir.mkdirs()
50             if (!dir.canWrite()) throw FileSystemException(dir, reason = "No write access to output directory")
51 
52             val fp = this.path.toFile()
53             fp.bufferedWriter().use { it.write(this.outStr) }
54             if (!fp.isFile) throw FileSystemException(fp, reason = "Error writing file")
55             return true
56         }
57     }
58 
onWritenull59     open fun onWrite() {}
60 
printInfonull61     open fun printInfo() {
62         println("Name: ${this.baseName}")
63         println(" AbstractFileWriter:")
64         println("  class: ${javaClass.simpleName}")
65         println("  dest: ${this.path}")
66     }
67 }