在学习别人的代码时,有的代码我们不知道它是如何运行的,或者会被调用到哪里,给每个函数加一行LOG,是一个笨的选择,却也是很有效的办法。
当然这样做的前提是代码可以编译通过并可以运行。
本代码可以给JAVA语言加LOG,使用方式是 a.sh sourcefile>targetfile
#!/bin/bash
i=1;
LEFT_CLOSE="{"
RIGHT_CLOSE="}"
IMPORT_LOG_LINE="import android.util.Log;"
CLASS="class"
new="new"
INTERFACE="interface"
level=0
ok=0
thisleft=0
thisright=0
subclass=0
lastsubclasslevel=0
in_interface=0
log_imported=0
IFS=''
cat $1 |
while read CURRET_LINE
do
((k++))
thisleft=0
thisright=0
if [ $log_imported -eq 0 -a $level -eq 0 ]
then
echo "$CURRET_LINE" | grep -q "$IMPORT_LOG_LINE"
if [ $? -eq 0 ]; then
((log_imported++))
fi
fi
if [ $level -eq 0 ]
then
echo "$CURRET_LINE" | grep -q "$CLASS"
if [ $? -eq 0 ]; then
if [ $log_imported -eq 0 ]
then
echo "$IMPORT_LOG_LINE"
fi
fi
fi
echo "$CURRET_LINE"
echo "$CURRET_LINE" | grep -q "$LEFT_CLOSE"
if [ $? -eq 0 ]; then
((level++))
thisleft=1
fi
echo "$CURRET_LINE" | grep -q "$RIGHT_CLOSE"
if [ $? -eq 0 ]; then
((level--))
thisright=1
if [ $in_interface -eq 1 ]
then
in_interface=0
fi
fi
if [ $thisleft -eq 1 ]
then
if [ $in_interface -ne 1 ]; then
echo "$CURRET_LINE" | grep -q "$INTERFACE"
if [ $? -eq 0 ]; then
in_interface=1
fi
fi
if [ $in_interface -ne 1 ]; then
echo "$CURRET_LINE" | grep -q "$CLASS"
if [ $? -eq 0 -a $level -eq 2 ]; then
((subclass++))
lastsubclasslevel=$level
fi
echo "$CURRET_LINE" | grep -q "$new"
if [ $? -eq 0 -a $level -eq 2 ]; then
((subclass++))
lastsubclasslevel=$level
fi
if [ $subclass -eq 1 -a $level -eq 3 ]
then
echo " Log.i(TAG,\"$CURRET_LINE\");"
elif [ $subclass -eq 0 -a $level -eq 2 ]
then
echo " Log.i(TAG,\"$CURRET_LINE\");"
fi
fi
fi
if [ $thisright -eq 1 ]
then
if [ $subclass -eq 1 -a $level -lt $lastsubclasslevel ]
then
subclass=0
lastsubclasslevel=0
fi
fi
done