1 /*
2  * Copyright 2017 Google Inc.
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  *     https://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 trebuchet.extras
18 
19 import trebuchet.model.Model
20 import trebuchet.task.ImportTask
21 import trebuchet.util.PrintlnImportFeedback
22 import java.io.File
23 
formatnull24 fun Double.format(digits: Int) = String.format("%.${digits}f", this)
25 
26 fun reportImportProgress(read: Long, total: Long) {
27     if (total > 0) {
28         val progress = read.toDouble() / total.toDouble() * 100.0
29         print("\rProgress: ${progress.format(2)}%")
30         if (progress >= 100) { print("\n") }
31     }
32 }
33 
parseTracenull34 fun parseTrace(file: File, verbose : Boolean = true): Model {
35     val before = System.nanoTime()
36     val task = ImportTask(PrintlnImportFeedback())
37     val model = task.import(InputStreamAdapter(file, if (verbose) ::reportImportProgress else null))
38     val after = System.nanoTime()
39 
40     if (verbose) {
41         val duration = (after - before) / 1000000
42         println("Parsing ${file.name} took ${duration}ms")
43     }
44 
45     return model
46 }
47 
findSampleDatanull48 fun findSampleData(): String {
49     var dir = File(".").absoluteFile
50     while (!File(dir, "sample_data").exists()) {
51         dir = dir.parentFile
52         if (dir == null) {
53             throw IllegalStateException("Can't find sample_data")
54         }
55     }
56     return File(dir, "sample_data").absolutePath
57 }
58 
openSamplenull59 fun openSample(name: String): Model {
60     return parseTrace(File(findSampleData(), name))
61 }