shithub: git9

ref: 90998569dab18d59d81bc63c84f692e1f7052904
dir: /branch/

View raw version
#!/bin/rc -e

rfork en

fn usage{
	echo usage: $0 '[-b base] [-o origin] new
	-b base:	use "base" for branch (default: current branch)
	-o origin:	use "origin" for remote branch
	-u:		update branch if it exists
	new:	name of new branch' >[1=2]
	exit usage
}

if(! cd `{git/conf -r}){
	exit 'not in git repository'
	exit notgit
}
git/fs

nl='
'
stay=()
create=()
update=()
base=`{awk '$1=="branch"{print $2}' < /mnt/git/ctl}
while(~ $1 -* && ! ~ $1 --){
	switch($1){
	case -c; create=true
	case -s; stay=true
	case -b; shift; base=$1
	case -u; update=true
	case *
		usage
	}
	shift
}
if(~ $1 --) shift

if(~ $#* 0){
	echo $base
	exit
}

if(! ~ $#* 1)
	usage
if(~ $1 refs/heads/*)
	new=$1
if not if(~ $1 heads/*)
	new=refs/$1
if not
	new=refs/heads/$1

if(! ~ $#create 0){
	if(! test -e .git/$new){
		echo branch $new: does not exist >[1=2]
		exit exists
	}
}
if not{
	if(~ $#update 0 && test -e .git/$new){
		echo could not create $1: already exists >[1=2]
		exit exists
	}
	branched=()
	remotes=`$nl{cd .git/refs/remotes && ls}
	candidates=(.git/refs/$base .git/refs/heads/$base .git/refs/remotes/$base .git/refs/remotes/$remotes/$base)
	for(br in $candidates){
		if(~ $#branched 0 && test -f $br){
			echo $base '=>' $1
			cp $br .git/$new
			branched=true
		}
	}
	if(~ $#branched 0){
		echo 'could not find branch '$base >[1=2]
		exit notfound
	}
}

if(! ~ $#stay 0)
	exit

echo ref: $new > .git/HEAD

modified=`$nl{git/query -c HEAD $base | grep '^[+~]' | sed 's/^..//'}
deleted=`$nl{git/query -c HEAD $base | grep '^-' | sed 's/^..//'}
if(! ~ $#modified 0 || ! ~ $#deleted 0){
	if(! git/walk -q $modified $deleted){
		echo remote changes would clobber local changes >[1=2]
		exit dirty
	}
}

if(! ~ $#modified 0){
	# Modifications can turn a file into
	# a directory, so we need to walk to
	# check the blobs out correctly.
	for(gm in `{cd /mnt/git/HEAD/tree/ && walk -f $modified}){
		m=`{sed s@^/mnt/git/HEAD/tree/@@}
		d=`{basename -d $m}
		mkdir -p $d
		mkdir -p .git/index9/tracked/$d
		cp  $gm $m
		walk -eq $m > .git/index9/tracked/$m
	}
}
if(! ~ $#deleted 0){
	rm -f $deleted
	rm -f .git/index9/tracked/$deleted
}