Tuesday 13 January 2009

Search PHP function from terminal

Hi,

Last week I bought some unix books, beacuse I almost blowed up with the new Slackware. It is happened, that it didn't recognized my wifi network ... I am not aware of unix network layer. So I thought it is the right time to digg in the topic. By the way, my first issue is a shell script, which can find a php function with its phpdoc and exact location.
How it works?

# Usage: ./pfs <your dev. dir> <function name>, eg.:
./pfs ./project1 user_get


And the code itself (pfs):

#!/bin/bash
# Check params
if [ $# -lt 2 ]
then
echo "Missing parameters.\nUsage: php_function_search [path] [function name]\n"
exit 1
fi

echo

for extension in php inc php3 html htpl
do
for file in `find $1 -type f -name "*$extension"`
do
if [ -f $file ]
then
# Find function line
function_line_array=`cat $file -n | grep "function $2" | awk '{print $1}'`
for function_line in $function_line_array
do
comment_end=`expr $function_line - 1`
# Find the 1st comment line
comment_start=`cat $file -n | sed -n "1,$function_line p" | sed -n '/\/\*\*/ p' | tail -n 1 | awk '{print $1}'`
non_comment_start=`cat $file -n | sed -n "1,$comment_end p" | grep "^[^*]*$" | tail -n 1 | awk '{print $1}'`
if [ $comment_start ]
then
# Print doc
echo -ne "\033[00;32;40m"
echo "Found in <$file> on line ($function_line)."
if [ $comment_start -gt $non_comment_start ]
then
echo -ne "\033[00;36;40m"
sed -n "$comment_start,$comment_end p" $file
fi
echo -ne "\033[00;33;40m"
sed -n "$function_line p" $file
echo -e "\033[00;37;40m"
fi
done
fi
done
done


Some aspects. Function name covers the first part of the function name. For example 'pfs ./ user_get' will match to user_get, user_get_name, user_get_all ...etc. First, the directory given is walked recursively to find all files. Search in each file the function pattern. It gives the line numbers those are in. Then until! that line the script searches the last line starts with '/**' (phpdoc block start). And there is another barbarian hack. It searches the last noncomment line, because if the last noncomment line num is bigger than the last comment line till the function, that means the comment don't relate to the function. So we shouldn't list it. After all, all block displayed width different colors: echo -ne "\033[00;36;40m". Sometimes when you need to know, what parameters a specific function requires, or what is the functions exact name, or whether exists any alternative copies of the function... it seems useful.
Just try it, and if you find a bug, please report it, a fixed it immediately.



Cheers

No comments:

Post a Comment

Note: only a member of this blog may post a comment.