/
FileUtil.scala
99 lines (81 loc) · 2.48 KB
/
FileUtil.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package gitbucket.core.util
import org.apache.commons.io.FileUtils
import org.apache.tika.Tika
import java.io.File
import SyntaxSugars._
import scala.util.Random
object FileUtil {
def getMimeType(name: String): String =
defining(new Tika()) { tika =>
tika.detect(name) match {
case null => "application/octet-stream"
case mimeType => mimeType
}
}
def getMimeType(name: String, bytes: Array[Byte]): String = {
defining(getMimeType(name)) { mimeType =>
if (mimeType == "application/octet-stream" && isText(bytes)) {
"text/plain"
} else {
mimeType
}
}
}
def getSafeMimeType(name: String): String = {
getMimeType(name).replace("text/html", "text/plain")
}
def isImage(name: String): Boolean = getMimeType(name).startsWith("image/")
def isLarge(size: Long): Boolean = (size > 1024 * 1000)
def isText(content: Array[Byte]): Boolean = !content.contains(0)
def generateFileId: String = System.currentTimeMillis + Random.alphanumeric.take(10).mkString
def getExtension(name: String): String =
name.lastIndexOf('.') match {
case i if (i >= 0) => name.substring(i + 1)
case _ => ""
}
def withTmpDir[A](dir: File)(action: File => A): A = {
if (dir.exists()) {
FileUtils.deleteDirectory(dir)
}
try {
action(dir)
} finally {
FileUtils.deleteDirectory(dir)
}
}
def getLfsFilePath(owner: String, repository: String, oid: String): String =
Directory.getLfsDir(owner, repository) + "/" + checkFilename(oid)
def readableSize(size: Long): String = FileUtils.byteCountToDisplaySize(size)
/**
* Delete the given directory if it's empty.
* Do nothing if the given File is not a directory or not empty.
*/
def deleteDirectoryIfEmpty(dir: File): Unit = {
if (dir.isDirectory() && dir.list().isEmpty) {
FileUtils.deleteDirectory(dir)
}
}
/**
* Delete file or directory forcibly.
*/
def deleteIfExists(file: java.io.File): java.io.File = {
if (file.exists) {
FileUtils.forceDelete(file)
}
file
}
/**
* Create an instance of java.io.File safely.
*/
def checkFilename(name: String): String = {
if (name.contains("..")) {
throw new IllegalArgumentException(s"Invalid file name: ${name}")
}
name
}
lazy val MaxFileSize =
if (System.getProperty("gitbucket.maxFileSize") != null)
System.getProperty("gitbucket.maxFileSize").toLong
else
3 * 1024 * 1024
}