
cat-file 명령어는 개체에 저장된 내용, 개체의 타입, 개체 사이즈 등을 불러올 수 있음
내용을 불러오는 -p 옵션, 타입을 출력해주는 -t, 개체 사이즈를 출력해주는 -s 옵션 3개를 구현해보고자 함
일단 Blob 개체에 대하여 -p 옵션만 구현을 해보았음
// geet/commands/plumbin/GeetCatFile.kt
package geet.commands.plumbing
import geet.exception.BadRequestException
import geet.util.catGeetObject
data class GeetCatFileOptions( // 입력된 옵션들을 받아오기위한 데이터 클래스
var pretty: Boolean = false,
var printType: Boolean = false,
var printSize: Boolean = false,
var objectPath: String = ""
)
fun geetCatFile(commandLines: Array<String>): Unit {
val options: GeetCatFileOptions = getCatFileOptions(commandLines)
catGeetObject(options) // GeetUtil.kt에 정의된 함수
}
fun getCatFileOptions(commandLines: Array<String>): GeetCatFileOptions {
val options = GeetCatFileOptions()
var index: Int = 1
while (index < commandLines.size) {
when (commandLines[index]) {
"-p" -> {
options.pretty = true
index += 1
}
"-t" -> {
options.printType = true
index += 1
}
"-s" -> {
options.printSize = true
index += 1
}
else -> {
if (options.objectPath != "") {
throw BadRequestException("지원하지 않는 옵션이거나 중복된 객체 SHA-1 값입니다. : ${commandLines[index]}")
}
options.objectPath = commandLines[index]
index += 1
}
}
}
if (options.objectPath == "") { // 객체 해시값이 지정되지 않은 경우
throw BadRequestException("객체 SHA-1 값이 지정되지 않았습니다.")
}
// 옵션이 지정되지 않은 경우
if (!options.pretty && !options.printType && !options.printSize) {
throw BadRequestException("'-p', '-t', '-s' 옵션 중 하나 이상이 지정되지 않았습니다.")
}
// 옵션을 2개 이상 사용한 경우
if ((options.pretty && options.printSize) || (options.pretty && options.printType) || (options.printType && options.printSize)) {
throw BadRequestException("'-p', '-t', '-s' 옵션 중 하나만 지정되어야 합니다.")
}
return options
}
여기서 사용된 catGeetObject 함수는 GeetUtil.kt에 정의하였다.
// geet/util/GeetUtil.kt
fun catGeetObject(catFileOptions: GeetCatFileOptions) {
if (catFileOptions.objectPath == "") { // 개체 경로가 지정되지 않은 경우
throw BadRequestException("개체 경로가 지정되지 않았습니다.")
}
val dirPath = ".geet/objects/${catFileOptions.objectPath.substring(0, 2)}"
val fileName = catFileOptions.objectPath.substring(2)
val file = File("$dirPath/$fileName")
if (!file.exists()) { // 해당 개체가 존재하지 않는 경우
throw NotFoundException("개체를 찾을 수 없습니다. : ${catFileOptions.objectPath}")
}
if (catFileOptions.pretty) { // -p 옵션인 경우 개체 압축을 해제하여 출력
print(decompressFromZlib(file.readText()))
}
}
그 결과 아래 예시와 같이 원래 내용이 잘 출력되었다.

-s, -t 옵션은 tree, commit 개체를 구현한 후 다시 구현할 예정