11package kscript
22
3+ import java.io.BufferedReader
34import java.io.File
5+ import java.io.FileReader
46import kotlin.system.exitProcess
57
68
7- // todo maybe it should also become part of the kscript code repository once ready
8-
99// for top-level vs member extensions see https://kotlinlang.org/docs/reference/extensions.html#scope-of-extensions
1010// object KscriptHelpers {}
1111
1212val stdin = generateSequence() { readLine() }
1313
14- fun Sequence<String>.print () = forEach { println (it) }
1514
15+ /* * Read lines stdin or a file argument. Example 'argLines(1).map { it+"foo"}'. could be used either with "-" or file argument. */
16+ fun argLines (arg : String , stdinNames : List <String > = listOf("-", "stdin")): Sequence <String > {
17+ if (stdinNames.contains(arg)) return stdin
1618
17- fun processStdin (trafo : (String ) -> String ) {
18- generateSequence() { readLine() }.map {
19- println (trafo(it))
20- }
21- }
19+ val inputFile = File (arg)
2220
23- @Deprecated(" use mapLines instead" )
24- fun File.processLines (trafo : (String ) -> String ) {
25- useLines {
26- it.map { println (trafo(it)) }
27- }
28- }
21+ stopIfNot(inputFile.canRead()) { " Can not read from '${arg} '" }
2922
30- fun <T > File.mapLines (trafo : (String ) -> T ) {
31- return useLines {
32- it.map { trafo(it) }
33- }
23+ // not we don't close the buffer with this approach
24+ // BufferedReader(FileReader(inputFile )).use { return it }
25+ return BufferedReader (FileReader (inputFile)).lineSequence()
3426}
3527
36- fun String.processLines (trafo : (String ) -> String ) {
37- split(" \n " ).map { println (trafo(it)) }
38- }
3928
4029
41- public inline fun stopIfNot (value : Boolean , lazyMessage : () -> Any ): Unit {
42- if (! value) {
43- System .err.println (" ERROR: " + lazyMessage().toString())
44- exitProcess(1 )
30+ fun Sequence<String>.print () = forEach { println (it) }
31+
32+
33+ fun processStdin (trafo : (String ) -> String ) {
34+ generateSequence() { readLine() }.map {
35+ println (trafo(it))
4536 }
46- }
37+ }
0 commit comments