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.io.FileNotFoundException 21 import java.nio.file.Path 22 23 object resources { 24 25 private val resourceCache = mutableMapOf<String, String>() //name(path) => contents 26 readResourceTextnull27 fun readResourceText(name: String): String { 28 return resourceCache.getOrElse(name) { 29 val input = javaClass.getResourceAsStream(name) 30 ?: throw FileNotFoundException("Unable to locate file resource: $name") 31 32 val contents = input.bufferedReader().use { it.readText() } 33 resourceCache[name] = contents 34 contents 35 } 36 } 37 copyToFilenull38 fun copyToFile(resourceName: String, outPath: Path): Boolean { 39 val contents = readResourceText(resourceName) 40 41 if (config.lintMode) { 42 return false 43 } else { 44 val dir = outPath.parent.toFile() //dir name 45 if (!dir.exists()) dir.mkdirs() 46 if (!dir.canWrite()) throw FileSystemException(dir, reason = "No write access to output directory") 47 48 val fp = outPath.toFile() 49 fp.bufferedWriter().use { it.write(contents) } 50 if (!fp.isFile) throw FileSystemException(fp, reason = "Error writing file") 51 return true 52 } 53 } 54 }