Wednesday 8 February 2017

SCALA Scripting in UNIX to count the translated files, and also it’s size - Beginners

Scala is a simple scripting language. Just enter some scala code in a text file, and execute it with “scala file.scala“.

The below is a simple scala script to count the translated files, and also it’s size.

Basic Terminologies to be learnt before scripting are below :

1.Classes and type interfaces
2. How to work with collections
3. Higher Order Functions
4. Functional versus imperative : To var or not to Var
5. Default parameters and passing functions as arguments.

Coding starts from here:

#!/bin/sh
exec scala "$0" "$@"
!#

import java.io._

val docs = new File(".").listFiles
  .filter(_.getName.endsWith(".textile"))   // process only textile files
  .map(new DocumentationFile(_))

val translated = docs.filter(_.isTranslated)    // only already translated files

val translatedLength = translated.map(_.length).sum
val docsLength = docs.map(_.length).sum

println( 
  status("translated size", translatedLength, docsLength, (length) => asKB(length) ) 
)

println( 
  status("translated files", translated.length, docs.length) 
)

def status(
  title: String = "status", 
  current: Long, total: Long, 
  format: (Long) => String = (x) => x.toString): String = {

  val percent = current * 100 / total

  title + ": " + format(current) + "/" + format(total) + " " +
  percent + "%" +
  " (pending " + format(total - current) + " " +
  (100-percent) + "%)"
}

def asKB(length: Long) = (length / 1000) + "kb"

class DocumentationFile(val file: File) {

  val name = file.getName
  val length = file.length
  val isTranslated = (firstLine.indexOf("Esta página todavía no ha sido traducida al castellano") == -1)

  override def toString = "name: " + name + ", length: " + length + ", isTranslated: " + isTranslated
  
def firstLine = new BufferedReader(new FileReader(file)).readLine

}


OUTPUT : 

translated size: 256kb/612kb 41% 

translated files: 24/64 37% 

No comments:

Post a Comment