#!/bin/bash
#
# args: file depotPath {Message}
#
usageMsg ()
{
echo "Usage: $0 file depotDir {'Message'}"
echo ' file must be in current directory'
echo ' depotDir must begin with //'
echo ' depotDir must not end in / or ...'
echo ' optional message must quoted'
echo ''
echo ' You must be logged into Perforce'
exit 1
}
validateP4Login ()
{
p4user=$(p4 set | grep P4USER | sed -e 's/^P4USER=//')
p4port=$(p4 set | grep P4PORT | sed -e 's/^P4PORT=//')
if [ "$p4user" == '' ] || [ "$p4port" == '' ]; then
if [ "$p4user" == '' ]; then
p4user="$USER"
fi
if [ "$p4port" == '' ]; then
p4port='perforce:1666'
fi
echo 'Please define P4USER and P4PORT, then login'
echo "e.g., export P4PORT=$p4port"
echo " export P4USER=$p4user"
echo ' p4 login'
exit 1
fi
logged=$(p4 login -s 2>&1 | grep -c ' ticket expires in ')
if [ "$logged" -ne 1 ]; then
echo 'Target Perforce server:'
echo " P4USER=$p4user"
echo " P4PORT=$p4port"
echo 'Please run "p4 login" for the target Perforce server'
exit 1
fi
}
# Call validation
if [ "$1" == '' ] || [ "$2" == '' ] || [ ! -f "$PWD/$1" ] || [ "$4" != '' ]; then
usageMsg
fi
validateP4Login
# Do the work
export P4CLIENT="$(HOSTNAME)-$$"
clientRoot="$PWD"
if [ "$3" == '' ]; then
msg='Auto submit of a single file'
else
msg="$3"
fi
# depotDir must start with //
# define a target directory
p4 client -i > /dev/null 2>&1 <<BOO
Client: $P4CLIENT
Owner: $P4USER
Description:
Temp client created for single file submital
Root: $clientRoot
Options: allwrite noclobber nocompress unlocked nomodtime normdir
SubmitOptions: submitunchanged
LineEnd: local
View:
$2/... //$P4CLIENT/...
BOO
if [ $? -ne 0 ]; then
echo 'Failed creating client'
usageMsg
fi
newFile=$(p4 fstat "$1" 2>&1 | grep -c ' no such file')
if [ "$newFile" -ne 0 ]; then
p4 add "$1"
else
read -p 'Overwrite existing file? (y/n) ' answer
if [ "$answer" == '' ] || [ "$answer" != 'y' ]; then
echo 'Aborting...'
p4 client -d "$P4CLIENT" > /dev/null 2>&1
exit 1
fi
p4 sync -k "$1" > /dev/null 2>&1
p4 edit "$1" > /dev/null 2>&1
p4 revert -a "$1" > /dev/null 2>&1
fi
changedFlag=$(p4 opened 2>&1 | grep -c ' not opened on ')
if [ "$changedFlag" -gt 0 ]; then
echo 'No changes to existing file'
p4 client -d "$P4CLIENT" > /dev/null 2>&1
exit 0
fi
p4 submit -d "$msg"
result=$?
if [ $result -ne 0 ]; then
echo 'Failed submitting file'
p4 revert -k "$1" > /dev/null 2>&1
fi
p4 client -d "$P4CLIENT" > /dev/null 2>&1
if [ $? -ne 0 ]; then
echo 'Failed to delete client'
echo "Clean up using P4CLIENT=$P4CLIENT"
exit 1
fi
exit $result