~sircmpwn/shit

shit/hash-object -rwxr-xr-x 1.3 KiB
4bd181c7Drew DeVault Remove obsolete TODO comment 8 months ago
                                                                                
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
#!/bin/sh -eu
SHIT_PATH=$(dirname "$0")
. $SHIT_PATH/common.sh

header() (
	objtype="$1"
	case "$objtype" in
		blob|tree|commit)
			len="$2"
			printf '%s %d\u0000' "$objtype" "$len"
			;;
		*)
			printf 'Unknown object type %s\n' "$1" >&2
			exit 1
			;;
	esac
)

write_object() (
	object_type="$1"
	path="$2"
	len=$(wc -c "$path" | cut -d' ' -f1)
	header "$object_type" "$len"
	cat "$path"
)

object_type=blob
write=0

while getopts t:w opt
do
	case $opt in
		t)
			object_type="$OPTARG"
			;;
		w)
			write=1
			;;
		?)
			printf "Usage: %s [-t <type>] [-w] <files...>\n" "$0" >&2
			exit 1
			;;
	esac
done

shift $((OPTIND-1))

process() {
	path="$1"
	if [ $write -eq 1 ]
	then
		sha=$(write_object "$object_type" "$path" | sha1sum | cut -d' ' -f1)
		prefix=$(printf "%s" "$sha" | cut -c1-2)
		suffix=$(printf "%s" "$sha" | cut -c3-)
		mkdir -p "$GIT_DIR"/objects/"$prefix"
		if ! [ -e "$GIT_DIR"/objects/"$prefix"/"$suffix" ]
		then
			write_object "$object_type" "$path" | "$SHIT_PATH"/zlib \
				>"$GIT_DIR"/objects/"$prefix"/"$suffix"
		fi
	else
		sha=$(write_object "$object_type" "$path" | sha1sum | cut -d' ' -f1)
	fi
	printf '%s\n' "$sha"
}

for path in "$@"
do
	process "$path"
done

if [ $# -eq 0 ]
then
	tee > "$GIT_DIR"/objects/NEW_OBJECT
	trap "rm '$GIT_DIR/objects/NEW_OBJECT'" EXIT
	process "$GIT_DIR"/objects/NEW_OBJECT
fi