Skip to content

Instantly share code, notes, and snippets.

@alvinj
Created December 16, 2022 21:03
Show Gist options
  • Save alvinj/b4a8a9460e696e03abeceebf41b35c85 to your computer and use it in GitHub Desktop.
Save alvinj/b4a8a9460e696e03abeceebf41b35c85 to your computer and use it in GitHub Desktop.
Script to update the next/prev/num header fields in the Scala Book markdown files
//> using scala "2.12"
//> using jar "sed_2.12-0.4.jar"
import scala.util.matching.Regex
import com.alvinalexander.sed.tostring._
import scala.io.Source
import java.io._
// RUN: scala-cli UpdateAllMdFiles.scala --main-class UpdateAllMdFiles
/**
* Requirements:
* - this script expects to be run in the same directory as the MD files
* - this script depends on the OrderedListOfFiles file
*
* 1 - get the list of filenames
* 2 - figure out the NextPage & PrevPage values
* 3 - go through the files and update the desired fields
*/
object UpdateAllMdFiles extends App {
val filenames = Source.fromFile("OrderedListOfMdFiles")
.getLines
.filter(_.trim != "")
.toList
// loop through those filenames and replace/update everything
var fileCounter = 1
for (inputFile <- filenames) {
// figure out prevPage and nextPage
var prevPage = ""
var nextPage = ""
if (fileCounter == 1) {
prevPage = ""
nextPage = filenames(1)
}
else if (fileCounter == filenames.size) {
prevPage = filenames(fileCounter-2)
nextPage = ""
}
else {
prevPage = filenames(fileCounter-2)
nextPage = filenames(fileCounter)
}
// rm the trailing ".scala" from the filenames
prevPage = prevPage.split("\\.")(0)
nextPage = nextPage.split("\\.")(0)
val mapNeededBySedFunction = Map(
"num" -> s"$fileCounter",
"next-page" -> nextPage,
"prev-page" -> prevPage
)
println(s"working on $inputFile ...")
val source = Source.fromFile(inputFile)
val sed: SedTrait = SedFactory.getSed(
source,
updateHeaderFields _,
mapNeededBySedFunction
)
val sedOutput: String = sed.run
// now have `newLines`. write the content back to the file.
writeFile(inputFile, sedOutput)
fileCounter += 1
}
def updateHeaderFields(
currentLine: String,
currentLineNum: Int,
kvMap: Map[String, String]
): SedAction = currentLine match {
case _ if (new Regex("^num:.*")).findAllIn(currentLine).hasNext =>
val fileNumber = kvMap("num")
UpdateLine(s"num: $fileNumber")
case _ if (new Regex("^next-page:.*")).findAllIn(currentLine).hasNext =>
val nextPage = kvMap("next-page")
UpdateLine(s"next-page: $nextPage")
case _ if (new Regex("^previous-page:.*")).findAllIn(currentLine).hasNext =>
val prevPage = kvMap("prev-page")
UpdateLine(s"previous-page: $prevPage")
case _ => UpdateLine(currentLine)
}
def writeFile(filename: String, s: String): Unit = {
val file = new File(filename)
val bw = new BufferedWriter(new FileWriter(file))
bw.write(s)
bw.close()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment