Skip to content

Commit dba6204

Browse files
committed
Provide util method to better remap lines in a File
1 parent c4b5a92 commit dba6204

File tree

1 file changed

+32
-0
lines changed
  • buildSrc/src/main/java/com/google/firebase/gradle/plugins

1 file changed

+32
-0
lines changed

buildSrc/src/main/java/com/google/firebase/gradle/plugins/GradleUtils.kt

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,38 @@ fun Provider<File>.childFile(path: String) = map { File("${it.path}/$path") }
5757
*/
5858
fun File.childFile(childPath: String) = File("$path/$childPath")
5959

60+
/**
61+
* Rewrites the lines of a file.
62+
*
63+
* The lines of the file are first read and then transformed by the provided `block` function. The
64+
* transformed lines are then joined together with a newline character and written back to the file.
65+
*
66+
* If the `terminateWithNewline` parameter is set to `false`, the file will not be terminated with a
67+
* newline character.
68+
*
69+
* @param terminateWithNewline Whether to terminate the file with a newline character. Defaults to
70+
* `true`.
71+
* @param block A function that takes a string as input and returns a new string. This function is
72+
* used to transform the lines of the file before they are rewritten.
73+
*
74+
* ```
75+
* val file = File("my-file.txt")
76+
*
77+
* // Rewrite the lines of the file, replacing all spaces with tabs.
78+
* file.rewriteLines { it.replace(" ", "\t") }
79+
*
80+
* // Rewrite the lines of the file, capitalizing the first letter of each word.
81+
* file.rewriteLines { it.capitalizeWords() }
82+
* ```
83+
*
84+
* @see [readLines]
85+
* @see [writeText]
86+
*/
87+
fun File.rewriteLines(terminateWithNewline: Boolean = true, block: (String) -> String) {
88+
val newLines = readLines().map(block)
89+
writeText(newLines.joinToString("\n").let { if (terminateWithNewline) it + "\n" else it })
90+
}
91+
6092
/**
6193
* Provides a temporary file for use during the task.
6294
*

0 commit comments

Comments
 (0)