-
Notifications
You must be signed in to change notification settings - Fork 16
/
Resources.scala
73 lines (58 loc) · 2.3 KB
/
Resources.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/*
* Copyright 2016 circe
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.circe.testing.golden
import java.io.File
import scala.io.Source
import scala.reflect.runtime.universe.Symbol
import scala.reflect.runtime.universe.Type
import scala.reflect.runtime.universe.TypeTag
import scala.util.Try
/**
* Miscellaneous utilities for guessing resource locations, names, etc.
*/
object Resources {
/**
* Attempt to guess the test resource root directory for the current project, creating it if it does not exist.
*/
lazy val inferRootDir: File = {
var current = new File(getClass.getResource("/").toURI)
while (current.ne(null) && current.getName != "target")
current = current.getParentFile
val resourceDir = new File(new File(new File(current.getParentFile, "src"), "test"), "resources")
resourceDir.mkdirs()
resourceDir
}
/**
* Attempt to guess the packaging of the type indicated by the provided type tag.
*/
def inferPackage[A](implicit A: TypeTag[A]): List[String] =
owners(A.tpe).collectFirst { case s if s.isPackage => s.fullName.split('.').toList }.getOrElse(List.empty)
private def owners(tpe: Type): Iterator[Symbol] =
Iterator.iterate(tpe.typeSymbol)(_.owner)
/**
* Attempt to guess the name of the type indicated by the provided type tag.
*/
def inferName[A](implicit A: TypeTag[A]): String = inferNameForType(A.tpe)
private def baseSymbols(tpe: Type): List[Symbol] =
owners(tpe).takeWhile(!_.isPackage).toList.reverse
private def inferNameForType(tpe: Type): String = {
val baseNames = baseSymbols(tpe).map(_.name.decodedName.toString)
(baseNames ::: tpe.typeArgs.map(inferNameForType)).mkString("_")
}
def open(path: String): Try[Source] = Try(
Source.fromInputStream(getClass.getResourceAsStream(path))
)
}