OSDN Git Service

envsetup: include bash completion script from vendor/cm
[android-x86/build.git] / envsetup.sh
1 function hmm() {
2 cat <<EOF
3 Invoke ". build/envsetup.sh" from your shell to add the following functions to your environment:
4 - lunch:     lunch <product_name>-<build_variant>
5 - tapas:     tapas [<App1> <App2> ...] [arm|x86|mips|armv5|arm64|x86_64|mips64] [eng|userdebug|user]
6 - croot:     Changes directory to the top of the tree.
7 - m:         Makes from the top of the tree.
8 - mm:        Builds all of the modules in the current directory, but not their dependencies.
9 - mmm:       Builds all of the modules in the supplied directories, but not their dependencies.
10              To limit the modules being built use the syntax: mmm dir/:target1,target2.
11 - mma:       Builds all of the modules in the current directory, and their dependencies.
12 - mmma:      Builds all of the modules in the supplied directories, and their dependencies.
13 - mmp:       Builds all of the modules in the current directory and pushes them to the device.
14 - mmmp:      Builds all of the modules in the supplied directories and pushes them to the device.
15 - provision: Flash device with all required partitions. Options will be passed on to fastboot.
16 - cgrep:     Greps on all local C/C++ files.
17 - ggrep:     Greps on all local Gradle files.
18 - jgrep:     Greps on all local Java files.
19 - resgrep:   Greps on all local res/*.xml files.
20 - mangrep:   Greps on all local AndroidManifest.xml files.
21 - mgrep:     Greps on all local Makefiles files.
22 - sepgrep:   Greps on all local sepolicy files.
23 - sgrep:     Greps on all local source files.
24 - godir:     Go to the directory containing a file.
25 - cmremote:  Add git remote for CM Gerrit Review
26 - cmgerrit:  A Git wrapper that fetches/pushes patch from/to CM Gerrit Review
27 - aospremote: Add git remote for matching AOSP repository
28 - cmrebase:  Rebase a Gerrit change and push it again
29 - mka:       Builds using SCHED_BATCH on all processors
30 - reposync:  Parallel repo sync using ionice and SCHED_BATCH
31 - installboot: Installs a boot.img to the connected device.
32 - installrecovery: Installs a recovery.img to the connected device.
33 - repodiff:  Diff 2 different branches or tags within the same repo
34
35 Environment options:
36 - SANITIZE_HOST: Set to 'true' to use ASAN for all host modules. Note that
37                  ASAN_OPTIONS=detect_leaks=0 will be set by default until the
38                  build is leak-check clean.
39
40 Look at the source to view more functions. The complete list is:
41 EOF
42     T=$(gettop)
43     local A
44     A=""
45     for i in `cat $T/build/envsetup.sh | sed -n "/^[[:blank:]]*function /s/function \([a-z_]*\).*/\1/p" | sort | uniq`; do
46       A="$A $i"
47     done
48     echo $A
49 }
50
51 # Get all the build variables needed by this script in a single call to the build system.
52 function build_build_var_cache()
53 {
54     T=$(gettop)
55     # Grep out the variable names from the script.
56     cached_vars=`cat $T/build/envsetup.sh | tr '()' '  ' | awk '{for(i=1;i<=NF;i++) if($i~/get_build_var/) print $(i+1)}' | sort -u | tr '\n' ' '`
57     cached_abs_vars=`cat $T/build/envsetup.sh | tr '()' '  ' | awk '{for(i=1;i<=NF;i++) if($i~/get_abs_build_var/) print $(i+1)}' | sort -u | tr '\n' ' '`
58     # Call the build system to dump the "<val>=<value>" pairs as a shell script.
59     build_dicts_script=`\cd $T; CALLED_FROM_SETUP=true BUILD_SYSTEM=build/core \
60                         command make --no-print-directory -f build/core/config.mk \
61                         dump-many-vars \
62                         DUMP_MANY_VARS="$cached_vars" \
63                         DUMP_MANY_ABS_VARS="$cached_abs_vars" \
64                         DUMP_VAR_PREFIX="var_cache_" \
65                         DUMP_ABS_VAR_PREFIX="abs_var_cache_"`
66     local ret=$?
67     if [ $ret -ne 0 ]
68     then
69         unset build_dicts_script
70         return $ret
71     fi
72     # Excute the script to store the "<val>=<value>" pairs as shell variables.
73     eval "$build_dicts_script"
74     ret=$?
75     unset build_dicts_script
76     if [ $ret -ne 0 ]
77     then
78         return $ret
79     fi
80     BUILD_VAR_CACHE_READY="true"
81 }
82
83 # Delete the build var cache, so that we can still call into the build system
84 # to get build variables not listed in this script.
85 function destroy_build_var_cache()
86 {
87     unset BUILD_VAR_CACHE_READY
88     for v in $cached_vars; do
89       unset var_cache_$v
90     done
91     unset cached_vars
92     for v in $cached_abs_vars; do
93       unset abs_var_cache_$v
94     done
95     unset cached_abs_vars
96 }
97
98 # Get the value of a build variable as an absolute path.
99 function get_abs_build_var()
100 {
101     if [ "$BUILD_VAR_CACHE_READY" = "true" ]
102     then
103         eval echo \"\${abs_var_cache_$1}\"
104     return
105     fi
106
107     T=$(gettop)
108     if [ ! "$T" ]; then
109         echo "Couldn't locate the top of the tree.  Try setting TOP." >&2
110         return
111     fi
112     (\cd $T; CALLED_FROM_SETUP=true BUILD_SYSTEM=build/core \
113       command make --no-print-directory -f build/core/config.mk dumpvar-abs-$1)
114 }
115
116 # Get the exact value of a build variable.
117 function get_build_var()
118 {
119     if [ "$BUILD_VAR_CACHE_READY" = "true" ]
120     then
121         eval echo \"\${var_cache_$1}\"
122     return
123     fi
124
125     T=$(gettop)
126     if [ ! "$T" ]; then
127         echo "Couldn't locate the top of the tree.  Try setting TOP." >&2
128         return
129     fi
130     (\cd $T; CALLED_FROM_SETUP=true BUILD_SYSTEM=build/core \
131       command make --no-print-directory -f build/core/config.mk dumpvar-$1)
132 }
133
134 # check to see if the supplied product is one we can build
135 function check_product()
136 {
137     T=$(gettop)
138     if [ ! "$T" ]; then
139         echo "Couldn't locate the top of the tree.  Try setting TOP." >&2
140         return
141     fi
142
143     if (echo -n $1 | grep -q -e "^cm_") ; then
144        CM_BUILD=$(echo -n $1 | sed -e 's/^cm_//g')
145     else
146        CM_BUILD=
147     fi
148     export CM_BUILD
149
150         TARGET_PRODUCT=$1 \
151         TARGET_BUILD_VARIANT= \
152         TARGET_BUILD_TYPE= \
153         TARGET_BUILD_APPS= \
154         get_build_var TARGET_DEVICE > /dev/null
155     # hide successful answers, but allow the errors to show
156 }
157
158 VARIANT_CHOICES=(user userdebug eng)
159
160 # check to see if the supplied variant is valid
161 function check_variant()
162 {
163     for v in ${VARIANT_CHOICES[@]}
164     do
165         if [ "$v" = "$1" ]
166         then
167             return 0
168         fi
169     done
170     return 1
171 }
172
173 function setpaths()
174 {
175     T=$(gettop)
176     if [ ! "$T" ]; then
177         echo "Couldn't locate the top of the tree.  Try setting TOP."
178         return
179     fi
180
181     ##################################################################
182     #                                                                #
183     #              Read me before you modify this code               #
184     #                                                                #
185     #   This function sets ANDROID_BUILD_PATHS to what it is adding  #
186     #   to PATH, and the next time it is run, it removes that from   #
187     #   PATH.  This is required so lunch can be run more than once   #
188     #   and still have working paths.                                #
189     #                                                                #
190     ##################################################################
191
192     # Note: on windows/cygwin, ANDROID_BUILD_PATHS will contain spaces
193     # due to "C:\Program Files" being in the path.
194
195     # out with the old
196     if [ -n "$ANDROID_BUILD_PATHS" ] ; then
197         export PATH=${PATH/$ANDROID_BUILD_PATHS/}
198     fi
199     if [ -n "$ANDROID_PRE_BUILD_PATHS" ] ; then
200         export PATH=${PATH/$ANDROID_PRE_BUILD_PATHS/}
201         # strip leading ':', if any
202         export PATH=${PATH/:%/}
203     fi
204
205     # and in with the new
206     prebuiltdir=$(getprebuilt)
207     gccprebuiltdir=$(get_abs_build_var ANDROID_GCC_PREBUILTS)
208
209     # defined in core/config.mk
210     targetgccversion=$(get_build_var TARGET_GCC_VERSION)
211     targetgccversion2=$(get_build_var 2ND_TARGET_GCC_VERSION)
212     export TARGET_GCC_VERSION=$targetgccversion
213
214     # The gcc toolchain does not exists for windows/cygwin. In this case, do not reference it.
215     export ANDROID_TOOLCHAIN=
216     export ANDROID_TOOLCHAIN_2ND_ARCH=
217     local ARCH=$(get_build_var TARGET_ARCH)
218     case $ARCH in
219         x86) toolchaindir=x86/x86_64-linux-android-$targetgccversion/bin
220             ;;
221         x86_64) toolchaindir=x86/x86_64-linux-android-$targetgccversion/bin
222             ;;
223         arm) toolchaindir=arm/arm-linux-androideabi-$targetgccversion/bin
224             ;;
225         arm64) toolchaindir=aarch64/aarch64-linux-android-$targetgccversion/bin;
226                toolchaindir2=arm/arm-linux-androideabi-$targetgccversion2/bin
227             ;;
228         mips|mips64) toolchaindir=mips/mips64el-linux-android-$targetgccversion/bin
229             ;;
230         *)
231             echo "Can't find toolchain for unknown architecture: $ARCH"
232             toolchaindir=xxxxxxxxx
233             ;;
234     esac
235     if [ -d "$gccprebuiltdir/$toolchaindir" ]; then
236         export ANDROID_TOOLCHAIN=$gccprebuiltdir/$toolchaindir
237     fi
238
239     if [ -d "$gccprebuiltdir/$toolchaindir2" ]; then
240         export ANDROID_TOOLCHAIN_2ND_ARCH=$gccprebuiltdir/$toolchaindir2
241     fi
242
243     export ANDROID_DEV_SCRIPTS=$T/development/scripts:$T/prebuilts/devtools/tools:$T/external/selinux/prebuilts/bin
244     export ANDROID_BUILD_PATHS=$(get_build_var ANDROID_BUILD_PATHS):$ANDROID_TOOLCHAIN:$ANDROID_TOOLCHAIN_2ND_ARCH:$ANDROID_DEV_SCRIPTS:
245
246     # If prebuilts/android-emulator/<system>/ exists, prepend it to our PATH
247     # to ensure that the corresponding 'emulator' binaries are used.
248     case $(uname -s) in
249         Darwin)
250             ANDROID_EMULATOR_PREBUILTS=$T/prebuilts/android-emulator/darwin-x86_64
251             ;;
252         Linux)
253             ANDROID_EMULATOR_PREBUILTS=$T/prebuilts/android-emulator/linux-x86_64
254             ;;
255         *)
256             ANDROID_EMULATOR_PREBUILTS=
257             ;;
258     esac
259     if [ -n "$ANDROID_EMULATOR_PREBUILTS" -a -d "$ANDROID_EMULATOR_PREBUILTS" ]; then
260         ANDROID_BUILD_PATHS=$ANDROID_BUILD_PATHS$ANDROID_EMULATOR_PREBUILTS:
261         export ANDROID_EMULATOR_PREBUILTS
262     fi
263
264     export PATH=$ANDROID_BUILD_PATHS$PATH
265     export PYTHONPATH=$T/development/python-packages:$PYTHONPATH
266
267     unset ANDROID_JAVA_TOOLCHAIN
268     unset ANDROID_PRE_BUILD_PATHS
269     if [ -n "$JAVA_HOME" ]; then
270         export ANDROID_JAVA_TOOLCHAIN=$JAVA_HOME/bin
271         export ANDROID_PRE_BUILD_PATHS=$ANDROID_JAVA_TOOLCHAIN:
272         export PATH=$ANDROID_PRE_BUILD_PATHS$PATH
273     fi
274
275     unset ANDROID_PRODUCT_OUT
276     export ANDROID_PRODUCT_OUT=$(get_abs_build_var PRODUCT_OUT)
277     export OUT=$ANDROID_PRODUCT_OUT
278
279     unset ANDROID_HOST_OUT
280     export ANDROID_HOST_OUT=$(get_abs_build_var HOST_OUT)
281
282     # needed for building linux on MacOS
283     # TODO: fix the path
284     #export HOST_EXTRACFLAGS="-I "$T/system/kernel_headers/host_include
285 }
286
287 function printconfig()
288 {
289     T=$(gettop)
290     if [ ! "$T" ]; then
291         echo "Couldn't locate the top of the tree.  Try setting TOP." >&2
292         return
293     fi
294     get_build_var report_config
295 }
296
297 function set_stuff_for_environment()
298 {
299     settitle
300     set_java_home
301     setpaths
302     set_sequence_number
303
304     export ANDROID_BUILD_TOP=$(gettop)
305     # With this environment variable new GCC can apply colors to warnings/errors
306     export GCC_COLORS='error=01;31:warning=01;35:note=01;36:caret=01;32:locus=01:quote=01'
307     export ASAN_OPTIONS=detect_leaks=0
308 }
309
310 function set_sequence_number()
311 {
312     export BUILD_ENV_SEQUENCE_NUMBER=10
313 }
314
315 function settitle()
316 {
317     if [ "$STAY_OFF_MY_LAWN" = "" ]; then
318         local arch=$(gettargetarch)
319         local product=$TARGET_PRODUCT
320         local variant=$TARGET_BUILD_VARIANT
321         local apps=$TARGET_BUILD_APPS
322         if [ -z "$PROMPT_COMMAND"  ]; then
323             # No prompts
324             PROMPT_COMMAND="echo -ne \"\033]0;${USER}@${HOSTNAME}: ${PWD}\007\""
325         elif [ -z "$(echo $PROMPT_COMMAND | grep '033]0;')" ]; then
326             # Prompts exist, but no hardstatus
327             PROMPT_COMMAND="echo -ne \"\033]0;${USER}@${HOSTNAME}: ${PWD}\007\";${PROMPT_COMMAND}"
328         fi
329         if [ ! -z "$ANDROID_PROMPT_PREFIX" ]; then
330             PROMPT_COMMAND=$(echo $PROMPT_COMMAND | sed -e 's/$ANDROID_PROMPT_PREFIX //g')
331         fi
332
333         if [ -z "$apps" ]; then
334             ANDROID_PROMPT_PREFIX="[${arch}-${product}-${variant}]"
335         else
336             ANDROID_PROMPT_PREFIX="[$arch $apps $variant]"
337         fi
338         export ANDROID_PROMPT_PREFIX
339
340         # Inject build data into hardstatus
341         export PROMPT_COMMAND="$(echo $PROMPT_COMMAND | sed -e 's/\\033]0;\(.*\)\\007/\\033]0;$ANDROID_PROMPT_PREFIX \1\\007/g')"
342     fi
343 }
344
345 function addcompletions()
346 {
347     local T dir f
348
349     # Keep us from trying to run in something that isn't bash.
350     if [ -z "${BASH_VERSION}" ]; then
351         return
352     fi
353
354     # Keep us from trying to run in bash that's too old.
355     if [ ${BASH_VERSINFO[0]} -lt 3 ]; then
356         return
357     fi
358
359     dirs="sdk/bash_completion vendor/cm/bash_completion"
360     for dir in $dirs; do
361     if [ -d ${dir} ]; then
362         for f in `/bin/ls ${dir}/[a-z]*.bash 2> /dev/null`; do
363             echo "including $f"
364             . $f
365         done
366     fi
367     done
368 }
369
370 function choosetype()
371 {
372     echo "Build type choices are:"
373     echo "     1. release"
374     echo "     2. debug"
375     echo
376
377     local DEFAULT_NUM DEFAULT_VALUE
378     DEFAULT_NUM=1
379     DEFAULT_VALUE=release
380
381     export TARGET_BUILD_TYPE=
382     local ANSWER
383     while [ -z $TARGET_BUILD_TYPE ]
384     do
385         echo -n "Which would you like? ["$DEFAULT_NUM"] "
386         if [ -z "$1" ] ; then
387             read ANSWER
388         else
389             echo $1
390             ANSWER=$1
391         fi
392         case $ANSWER in
393         "")
394             export TARGET_BUILD_TYPE=$DEFAULT_VALUE
395             ;;
396         1)
397             export TARGET_BUILD_TYPE=release
398             ;;
399         release)
400             export TARGET_BUILD_TYPE=release
401             ;;
402         2)
403             export TARGET_BUILD_TYPE=debug
404             ;;
405         debug)
406             export TARGET_BUILD_TYPE=debug
407             ;;
408         *)
409             echo
410             echo "I didn't understand your response.  Please try again."
411             echo
412             ;;
413         esac
414         if [ -n "$1" ] ; then
415             break
416         fi
417     done
418
419     build_build_var_cache
420     set_stuff_for_environment
421     destroy_build_var_cache
422 }
423
424 #
425 # This function isn't really right:  It chooses a TARGET_PRODUCT
426 # based on the list of boards.  Usually, that gets you something
427 # that kinda works with a generic product, but really, you should
428 # pick a product by name.
429 #
430 function chooseproduct()
431 {
432     if [ "x$TARGET_PRODUCT" != x ] ; then
433         default_value=$TARGET_PRODUCT
434     else
435         default_value=aosp_arm
436     fi
437
438     export TARGET_BUILD_APPS=
439     export TARGET_PRODUCT=
440     local ANSWER
441     while [ -z "$TARGET_PRODUCT" ]
442     do
443         echo -n "Which product would you like? [$default_value] "
444         if [ -z "$1" ] ; then
445             read ANSWER
446         else
447             echo $1
448             ANSWER=$1
449         fi
450
451         if [ -z "$ANSWER" ] ; then
452             export TARGET_PRODUCT=$default_value
453         else
454             if check_product $ANSWER
455             then
456                 export TARGET_PRODUCT=$ANSWER
457             else
458                 echo "** Not a valid product: $ANSWER"
459             fi
460         fi
461         if [ -n "$1" ] ; then
462             break
463         fi
464     done
465
466     build_build_var_cache
467     set_stuff_for_environment
468     destroy_build_var_cache
469 }
470
471 function choosevariant()
472 {
473     echo "Variant choices are:"
474     local index=1
475     local v
476     for v in ${VARIANT_CHOICES[@]}
477     do
478         # The product name is the name of the directory containing
479         # the makefile we found, above.
480         echo "     $index. $v"
481         index=$(($index+1))
482     done
483
484     local default_value=eng
485     local ANSWER
486
487     export TARGET_BUILD_VARIANT=
488     while [ -z "$TARGET_BUILD_VARIANT" ]
489     do
490         echo -n "Which would you like? [$default_value] "
491         if [ -z "$1" ] ; then
492             read ANSWER
493         else
494             echo $1
495             ANSWER=$1
496         fi
497
498         if [ -z "$ANSWER" ] ; then
499             export TARGET_BUILD_VARIANT=$default_value
500         elif (echo -n $ANSWER | grep -q -e "^[0-9][0-9]*$") ; then
501             if [ "$ANSWER" -le "${#VARIANT_CHOICES[@]}" ] ; then
502                 export TARGET_BUILD_VARIANT=${VARIANT_CHOICES[$(($ANSWER-1))]}
503             fi
504         else
505             if check_variant $ANSWER
506             then
507                 export TARGET_BUILD_VARIANT=$ANSWER
508             else
509                 echo "** Not a valid variant: $ANSWER"
510             fi
511         fi
512         if [ -n "$1" ] ; then
513             break
514         fi
515     done
516 }
517
518 function choosecombo()
519 {
520     choosetype $1
521
522     echo
523     echo
524     chooseproduct $2
525
526     echo
527     echo
528     choosevariant $3
529
530     echo
531     build_build_var_cache
532     set_stuff_for_environment
533     printconfig
534     destroy_build_var_cache
535 }
536
537 # Clear this variable.  It will be built up again when the vendorsetup.sh
538 # files are included at the end of this file.
539 unset LUNCH_MENU_CHOICES
540 function add_lunch_combo()
541 {
542     local new_combo=$1
543     local c
544     for c in ${LUNCH_MENU_CHOICES[@]} ; do
545         if [ "$new_combo" = "$c" ] ; then
546             return
547         fi
548     done
549     LUNCH_MENU_CHOICES=(${LUNCH_MENU_CHOICES[@]} $new_combo)
550 }
551
552 # add the default one here
553 add_lunch_combo aosp_arm-eng
554 add_lunch_combo aosp_arm64-eng
555 add_lunch_combo aosp_mips-eng
556 add_lunch_combo aosp_mips64-eng
557 add_lunch_combo aosp_x86-eng
558 add_lunch_combo aosp_x86_64-eng
559
560 function print_lunch_menu()
561 {
562     local uname=$(uname)
563     echo
564     echo "You're building on" $uname
565     if [ "$(uname)" = "Darwin" ] ; then
566        echo "  (ohai, koush!)"
567     fi
568     echo
569     if [ "z${CM_DEVICES_ONLY}" != "z" ]; then
570        echo "Breakfast menu... pick a combo:"
571     else
572        echo "Lunch menu... pick a combo:"
573     fi
574
575     local i=1
576     local choice
577     for choice in ${LUNCH_MENU_CHOICES[@]}
578     do
579         echo "     $i. $choice"
580         i=$(($i+1))
581     done
582
583     if [ "z${CM_DEVICES_ONLY}" != "z" ]; then
584        echo "... and don't forget the bacon!"
585     fi
586
587     echo
588 }
589
590 function brunch()
591 {
592     breakfast $*
593     if [ $? -eq 0 ]; then
594         mka bacon
595     else
596         echo "No such item in brunch menu. Try 'breakfast'"
597         return 1
598     fi
599     return $?
600 }
601
602 function breakfast()
603 {
604     target=$1
605     CM_DEVICES_ONLY="true"
606     unset LUNCH_MENU_CHOICES
607     add_lunch_combo full-eng
608     for f in `/bin/ls vendor/cm/vendorsetup.sh 2> /dev/null`
609         do
610             echo "including $f"
611             . $f
612         done
613     unset f
614
615     if [ $# -eq 0 ]; then
616         # No arguments, so let's have the full menu
617         lunch
618     else
619         echo "z$target" | grep -q "-"
620         if [ $? -eq 0 ]; then
621             # A buildtype was specified, assume a full device name
622             lunch $target
623         else
624             # This is probably just the CM model name
625             lunch cm_$target-userdebug
626         fi
627     fi
628     return $?
629 }
630
631 alias bib=breakfast
632
633 function lunch()
634 {
635     local answer
636
637     if [ "$1" ] ; then
638         answer=$1
639     else
640         print_lunch_menu
641         echo -n "Which would you like? [aosp_arm-eng] "
642         read answer
643     fi
644
645     local selection=
646
647     if [ -z "$answer" ]
648     then
649         selection=aosp_arm-eng
650     elif (echo -n $answer | grep -q -e "^[0-9][0-9]*$")
651     then
652         if [ $answer -le ${#LUNCH_MENU_CHOICES[@]} ]
653         then
654             selection=${LUNCH_MENU_CHOICES[$(($answer-1))]}
655         fi
656     elif (echo -n $answer | grep -q -e "^[^\-][^\-]*-[^\-][^\-]*$")
657     then
658         selection=$answer
659     fi
660
661     if [ -z "$selection" ]
662     then
663         echo
664         echo "Invalid lunch combo: $answer"
665         return 1
666     fi
667
668     export TARGET_BUILD_APPS=
669
670     local variant=$(echo -n $selection | sed -e "s/^[^\-]*-//")
671     check_variant $variant
672     if [ $? -ne 0 ]
673     then
674         echo
675         echo "** Invalid variant: '$variant'"
676         echo "** Must be one of ${VARIANT_CHOICES[@]}"
677         variant=
678     fi
679
680     local product=$(echo -n $selection | sed -e "s/-.*$//")
681     TARGET_PRODUCT=$product \
682     TARGET_BUILD_VARIANT=$variant \
683     build_build_var_cache
684     if [ $? -ne 0 ]
685     then
686         # if we can't find a product, try to grab it off the CM github
687         T=$(gettop)
688         pushd $T > /dev/null
689         build/tools/roomservice.py $product
690         popd > /dev/null
691         check_product $product
692     else
693         build/tools/roomservice.py $product true
694     fi
695     if [ $? -ne 0 ]
696     then
697         echo
698         echo "** Don't have a product spec for: '$product'"
699         echo "** Do you have the right repo manifest?"
700         product=
701     fi
702
703     if [ -z "$product" -o -z "$variant" ]
704     then
705         echo
706         return 1
707     fi
708
709     export TARGET_PRODUCT=$product
710     export TARGET_BUILD_VARIANT=$variant
711     export TARGET_BUILD_TYPE=release
712
713     echo
714
715     set_stuff_for_environment
716     printconfig
717     destroy_build_var_cache
718 }
719
720 # Tab completion for lunch.
721 function _lunch()
722 {
723     local cur prev opts
724     COMPREPLY=()
725     cur="${COMP_WORDS[COMP_CWORD]}"
726     prev="${COMP_WORDS[COMP_CWORD-1]}"
727
728     COMPREPLY=( $(compgen -W "${LUNCH_MENU_CHOICES[*]}" -- ${cur}) )
729     return 0
730 }
731 complete -F _lunch lunch
732
733 # Configures the build to build unbundled apps.
734 # Run tapas with one or more app names (from LOCAL_PACKAGE_NAME)
735 function tapas()
736 {
737     local arch="$(echo $* | xargs -n 1 echo | \grep -E '^(arm|x86|mips|armv5|arm64|x86_64|mips64)$' | xargs)"
738     local variant="$(echo $* | xargs -n 1 echo | \grep -E '^(user|userdebug|eng)$' | xargs)"
739     local density="$(echo $* | xargs -n 1 echo | \grep -E '^(ldpi|mdpi|tvdpi|hdpi|xhdpi|xxhdpi|xxxhdpi|alldpi)$' | xargs)"
740     local apps="$(echo $* | xargs -n 1 echo | \grep -E -v '^(user|userdebug|eng|arm|x86|mips|armv5|arm64|x86_64|mips64|ldpi|mdpi|tvdpi|hdpi|xhdpi|xxhdpi|xxxhdpi|alldpi)$' | xargs)"
741
742     if [ $(echo $arch | wc -w) -gt 1 ]; then
743         echo "tapas: Error: Multiple build archs supplied: $arch"
744         return
745     fi
746     if [ $(echo $variant | wc -w) -gt 1 ]; then
747         echo "tapas: Error: Multiple build variants supplied: $variant"
748         return
749     fi
750     if [ $(echo $density | wc -w) -gt 1 ]; then
751         echo "tapas: Error: Multiple densities supplied: $density"
752         return
753     fi
754
755     local product=aosp_arm
756     case $arch in
757       x86)    product=aosp_x86;;
758       mips)   product=aosp_mips;;
759       armv5)  product=generic_armv5;;
760       arm64)  product=aosp_arm64;;
761       x86_64) product=aosp_x86_64;;
762       mips64)  product=aosp_mips64;;
763     esac
764     if [ -z "$variant" ]; then
765         variant=eng
766     fi
767     if [ -z "$apps" ]; then
768         apps=all
769     fi
770     if [ -z "$density" ]; then
771         density=alldpi
772     fi
773
774     export TARGET_PRODUCT=$product
775     export TARGET_BUILD_VARIANT=$variant
776     export TARGET_BUILD_DENSITY=$density
777     export TARGET_BUILD_TYPE=release
778     export TARGET_BUILD_APPS=$apps
779
780     build_build_var_cache
781     set_stuff_for_environment
782     printconfig
783     destroy_build_var_cache
784 }
785
786 function eat()
787 {
788     if [ "$OUT" ] ; then
789         MODVERSION=`sed -n -e'/ro\.cm\.version/s/.*=//p' $OUT/system/build.prop`
790         ZIPFILE=cm-$MODVERSION.zip
791         ZIPPATH=$OUT/$ZIPFILE
792         if [ ! -f $ZIPPATH ] ; then
793             echo "Nothing to eat"
794             return 1
795         fi
796         adb start-server # Prevent unexpected starting server message from adb get-state in the next line
797         if [ $(adb get-state) != device -a $(adb shell busybox test -e /sbin/recovery 2> /dev/null; echo $?) != 0 ] ; then
798             echo "No device is online. Waiting for one..."
799             echo "Please connect USB and/or enable USB debugging"
800             until [ $(adb get-state) = device -o $(adb shell busybox test -e /sbin/recovery 2> /dev/null; echo $?) = 0 ];do
801                 sleep 1
802             done
803             echo "Device Found.."
804         fi
805     if (adb shell cat /system/build.prop | grep -q "ro.cm.device=$CM_BUILD");
806     then
807         # if adbd isn't root we can't write to /cache/recovery/
808         adb root
809         sleep 1
810         adb wait-for-device
811         SZ=`stat -c %s $ZIPPATH`
812         CACHESIZE=`adb shell busybox df -PB1 /cache | grep /cache | tr -s ' ' | cut -d ' ' -f 4`
813         if [ $CACHESIZE -gt $SZ ];
814         then
815             PUSHDIR=/cache/
816             DIR=cache
817         else
818             PUSHDIR=/storage/sdcard0/
819              # Optional path for sdcard0 in recovery
820              [ -z "$1" ] && DIR=sdcard/0 || DIR=$1
821         fi
822         echo "Pushing $ZIPFILE to $PUSHDIR"
823         if adb push $ZIPPATH $PUSHDIR ; then
824             cat << EOF > /tmp/command
825 --update_package=/$DIR/$ZIPFILE
826 EOF
827             if adb push /tmp/command /cache/recovery/ ; then
828                 echo "Rebooting into recovery for installation"
829                 adb reboot recovery
830             fi
831             rm /tmp/command
832         fi
833     else
834         echo "Nothing to eat"
835         return 1
836     fi
837     return $?
838     else
839         echo "The connected device does not appear to be $CM_BUILD, run away!"
840     fi
841 }
842
843 function omnom
844 {
845     brunch $*
846     eat
847 }
848
849 function gettop
850 {
851     local TOPFILE=build/core/envsetup.mk
852     if [ -n "$TOP" -a -f "$TOP/$TOPFILE" ] ; then
853         # The following circumlocution ensures we remove symlinks from TOP.
854         (cd $TOP; PWD= /bin/pwd)
855     else
856         if [ -f $TOPFILE ] ; then
857             # The following circumlocution (repeated below as well) ensures
858             # that we record the true directory name and not one that is
859             # faked up with symlink names.
860             PWD= /bin/pwd
861         else
862             local HERE=$PWD
863             T=
864             while [ \( ! \( -f $TOPFILE \) \) -a \( $PWD != "/" \) ]; do
865                 \cd ..
866                 T=`PWD= /bin/pwd -P`
867             done
868             \cd $HERE
869             if [ -f "$T/$TOPFILE" ]; then
870                 echo $T
871             fi
872         fi
873     fi
874 }
875
876 # Return driver for "make", if any (eg. static analyzer)
877 function getdriver()
878 {
879     local T="$1"
880     test "$WITH_STATIC_ANALYZER" = "0" && unset WITH_STATIC_ANALYZER
881     if [ -n "$WITH_STATIC_ANALYZER" ]; then
882         echo "\
883 $T/prebuilts/misc/linux-x86/analyzer/tools/scan-build/scan-build \
884 --use-analyzer $T/prebuilts/misc/linux-x86/analyzer/bin/analyzer \
885 --status-bugs \
886 --top=$T"
887     fi
888 }
889
890 function m()
891 {
892     local T=$(gettop)
893     local DRV=$(getdriver $T)
894     if [ "$T" ]; then
895         $DRV make -C $T -f build/core/main.mk $@
896     else
897         echo "Couldn't locate the top of the tree.  Try setting TOP."
898         return 1
899     fi
900 }
901
902 function findmakefile()
903 {
904     TOPFILE=build/core/envsetup.mk
905     local HERE=$PWD
906     T=
907     while [ \( ! \( -f $TOPFILE \) \) -a \( $PWD != "/" \) ]; do
908         T=`PWD= /bin/pwd`
909         if [ -f "$T/Android.mk" ]; then
910             echo $T/Android.mk
911             \cd $HERE
912             return
913         fi
914         \cd ..
915     done
916     \cd $HERE
917 }
918
919 function mm()
920 {
921     local T=$(gettop)
922     local DRV=$(getdriver $T)
923     # If we're sitting in the root of the build tree, just do a
924     # normal make.
925     if [ -f build/core/envsetup.mk -a -f Makefile ]; then
926         $DRV make $@
927     else
928         # Find the closest Android.mk file.
929         local M=$(findmakefile)
930         local MODULES=
931         local GET_INSTALL_PATH=
932         local ARGS=
933         # Remove the path to top as the makefilepath needs to be relative
934         local M=`echo $M|sed 's:'$T'/::'`
935         if [ ! "$T" ]; then
936             echo "Couldn't locate the top of the tree.  Try setting TOP."
937             return 1
938         elif [ ! "$M" ]; then
939             echo "Couldn't locate a makefile from the current directory."
940             return 1
941         else
942             for ARG in $@; do
943                 case $ARG in
944                   GET-INSTALL-PATH) GET_INSTALL_PATH=$ARG;;
945                 esac
946             done
947             if [ -n "$GET_INSTALL_PATH" ]; then
948               MODULES=
949               ARGS=GET-INSTALL-PATH
950             else
951               MODULES=all_modules
952               ARGS=$@
953             fi
954             ONE_SHOT_MAKEFILE=$M $DRV make -C $T -f build/core/main.mk $MODULES $ARGS
955         fi
956     fi
957 }
958
959 function mmm()
960 {
961     local T=$(gettop)
962     local DRV=$(getdriver $T)
963     if [ "$T" ]; then
964         local MAKEFILE=
965         local MODULES=
966         local ARGS=
967         local DIR TO_CHOP
968         local GET_INSTALL_PATH=
969         local DASH_ARGS=$(echo "$@" | awk -v RS=" " -v ORS=" " '/^-.*$/')
970         local DIRS=$(echo "$@" | awk -v RS=" " -v ORS=" " '/^[^-].*$/')
971         for DIR in $DIRS ; do
972             MODULES=`echo $DIR | sed -n -e 's/.*:\(.*$\)/\1/p' | sed 's/,/ /'`
973             if [ "$MODULES" = "" ]; then
974                 MODULES=all_modules
975             fi
976             DIR=`echo $DIR | sed -e 's/:.*//' -e 's:/$::'`
977             if [ -f $DIR/Android.mk ]; then
978                 local TO_CHOP=`(\cd -P -- $T && pwd -P) | wc -c | tr -d ' '`
979                 local TO_CHOP=`expr $TO_CHOP + 1`
980                 local START=`PWD= /bin/pwd`
981                 local MFILE=`echo $START | cut -c${TO_CHOP}-`
982                 if [ "$MFILE" = "" ] ; then
983                     MFILE=$DIR/Android.mk
984                 else
985                     MFILE=$MFILE/$DIR/Android.mk
986                 fi
987                 MAKEFILE="$MAKEFILE $MFILE"
988             else
989                 case $DIR in
990                   showcommands | snod | dist | *=*) ARGS="$ARGS $DIR";;
991                   GET-INSTALL-PATH) GET_INSTALL_PATH=$DIR;;
992                   *) if [ -d $DIR ]; then
993                          echo "No Android.mk in $DIR.";
994                      else
995                          echo "Couldn't locate the directory $DIR";
996                      fi
997                      return 1;;
998                 esac
999             fi
1000         done
1001         if [ -n "$GET_INSTALL_PATH" ]; then
1002           ARGS=$GET_INSTALL_PATH
1003           MODULES=
1004         fi
1005         ONE_SHOT_MAKEFILE="$MAKEFILE" $DRV make -C $T -f build/core/main.mk $DASH_ARGS $MODULES $ARGS
1006     else
1007         echo "Couldn't locate the top of the tree.  Try setting TOP."
1008         return 1
1009     fi
1010 }
1011
1012 function mma()
1013 {
1014   local T=$(gettop)
1015   local DRV=$(getdriver $T)
1016   if [ -f build/core/envsetup.mk -a -f Makefile ]; then
1017     $DRV make $@
1018   else
1019     if [ ! "$T" ]; then
1020       echo "Couldn't locate the top of the tree.  Try setting TOP."
1021       return 1
1022     fi
1023     local MY_PWD=`PWD= /bin/pwd|sed 's:'$T'/::'`
1024     local MODULES_IN_PATHS=MODULES-IN-$MY_PWD
1025     # Convert "/" to "-".
1026     MODULES_IN_PATHS=${MODULES_IN_PATHS//\//-}
1027     $DRV make -C $T -f build/core/main.mk $@ $MODULES_IN_PATHS
1028   fi
1029 }
1030
1031 function mmma()
1032 {
1033   local T=$(gettop)
1034   local DRV=$(getdriver $T)
1035   if [ "$T" ]; then
1036     local DASH_ARGS=$(echo "$@" | awk -v RS=" " -v ORS=" " '/^-.*$/')
1037     local DIRS=$(echo "$@" | awk -v RS=" " -v ORS=" " '/^[^-].*$/')
1038     local MY_PWD=`PWD= /bin/pwd`
1039     if [ "$MY_PWD" = "$T" ]; then
1040       MY_PWD=
1041     else
1042       MY_PWD=`echo $MY_PWD|sed 's:'$T'/::'`
1043     fi
1044     local DIR=
1045     local MODULES_IN_PATHS=
1046     local ARGS=
1047     for DIR in $DIRS ; do
1048       if [ -d $DIR ]; then
1049         # Remove the leading ./ and trailing / if any exists.
1050         DIR=${DIR#./}
1051         DIR=${DIR%/}
1052         if [ "$MY_PWD" != "" ]; then
1053           DIR=$MY_PWD/$DIR
1054         fi
1055         MODULES_IN_PATHS="$MODULES_IN_PATHS MODULES-IN-$DIR"
1056       else
1057         case $DIR in
1058           showcommands | snod | dist | *=*) ARGS="$ARGS $DIR";;
1059           *) echo "Couldn't find directory $DIR"; return 1;;
1060         esac
1061       fi
1062     done
1063     # Convert "/" to "-".
1064     MODULES_IN_PATHS=${MODULES_IN_PATHS//\//-}
1065     $DRV make -C $T -f build/core/main.mk $DASH_ARGS $ARGS $MODULES_IN_PATHS
1066   else
1067     echo "Couldn't locate the top of the tree.  Try setting TOP."
1068     return 1
1069   fi
1070 }
1071
1072 function croot()
1073 {
1074     T=$(gettop)
1075     if [ "$T" ]; then
1076         \cd $(gettop)
1077     else
1078         echo "Couldn't locate the top of the tree.  Try setting TOP."
1079     fi
1080 }
1081
1082 function cproj()
1083 {
1084     TOPFILE=build/core/envsetup.mk
1085     local HERE=$PWD
1086     T=
1087     while [ \( ! \( -f $TOPFILE \) \) -a \( $PWD != "/" \) ]; do
1088         T=$PWD
1089         if [ -f "$T/Android.mk" ]; then
1090             \cd $T
1091             return
1092         fi
1093         \cd ..
1094     done
1095     \cd $HERE
1096     echo "can't find Android.mk"
1097 }
1098
1099 # simplified version of ps; output in the form
1100 # <pid> <procname>
1101 function qpid() {
1102     local prepend=''
1103     local append=''
1104     if [ "$1" = "--exact" ]; then
1105         prepend=' '
1106         append='$'
1107         shift
1108     elif [ "$1" = "--help" -o "$1" = "-h" ]; then
1109         echo "usage: qpid [[--exact] <process name|pid>"
1110         return 255
1111     fi
1112
1113     local EXE="$1"
1114     if [ "$EXE" ] ; then
1115         qpid | \grep "$prepend$EXE$append"
1116     else
1117         adb shell ps \
1118             | tr -d '\r' \
1119             | sed -e 1d -e 's/^[^ ]* *\([0-9]*\).* \([^ ]*\)$/\1 \2/'
1120     fi
1121 }
1122
1123 function pid()
1124 {
1125     local prepend=''
1126     local append=''
1127     if [ "$1" = "--exact" ]; then
1128         prepend=' '
1129         append='$'
1130         shift
1131     fi
1132     local EXE="$1"
1133     if [ "$EXE" ] ; then
1134         local PID=`adb shell ps \
1135             | tr -d '\r' \
1136             | \grep "$prepend$EXE$append" \
1137             | sed -e 's/^[^ ]* *\([0-9]*\).*$/\1/'`
1138         echo "$PID"
1139     else
1140         echo "usage: pid [--exact] <process name>"
1141         return 255
1142     fi
1143 }
1144
1145 # coredump_setup - enable core dumps globally for any process
1146 #                  that has the core-file-size limit set correctly
1147 #
1148 # NOTE: You must call also coredump_enable for a specific process
1149 #       if its core-file-size limit is not set already.
1150 # NOTE: Core dumps are written to ramdisk; they will not survive a reboot!
1151
1152 function coredump_setup()
1153 {
1154     echo "Getting root...";
1155     adb root;
1156     adb wait-for-device;
1157
1158     echo "Remounting root partition read-write...";
1159     adb shell mount -w -o remount -t rootfs rootfs;
1160     sleep 1;
1161     adb wait-for-device;
1162     adb shell mkdir -p /cores;
1163     adb shell mount -t tmpfs tmpfs /cores;
1164     adb shell chmod 0777 /cores;
1165
1166     echo "Granting SELinux permission to dump in /cores...";
1167     adb shell restorecon -R /cores;
1168
1169     echo "Set core pattern.";
1170     adb shell 'echo /cores/core.%p > /proc/sys/kernel/core_pattern';
1171
1172     echo "Done."
1173 }
1174
1175 # coredump_enable - enable core dumps for the specified process
1176 # $1 = PID of process (e.g., $(pid mediaserver))
1177 #
1178 # NOTE: coredump_setup must have been called as well for a core
1179 #       dump to actually be generated.
1180
1181 function coredump_enable()
1182 {
1183     local PID=$1;
1184     if [ -z "$PID" ]; then
1185         printf "Expecting a PID!\n";
1186         return;
1187     fi;
1188     echo "Setting core limit for $PID to infinite...";
1189     adb shell prlimit $PID 4 -1 -1
1190 }
1191
1192 # core - send SIGV and pull the core for process
1193 # $1 = PID of process (e.g., $(pid mediaserver))
1194 #
1195 # NOTE: coredump_setup must be called once per boot for core dumps to be
1196 #       enabled globally.
1197
1198 function core()
1199 {
1200     local PID=$1;
1201
1202     if [ -z "$PID" ]; then
1203         printf "Expecting a PID!\n";
1204         return;
1205     fi;
1206
1207     local CORENAME=core.$PID;
1208     local COREPATH=/cores/$CORENAME;
1209     local SIG=SEGV;
1210
1211     coredump_enable $1;
1212
1213     local done=0;
1214     while [ $(adb shell "[ -d /proc/$PID ] && echo -n yes") ]; do
1215         printf "\tSending SIG%s to %d...\n" $SIG $PID;
1216         adb shell kill -$SIG $PID;
1217         sleep 1;
1218     done;
1219
1220     adb shell "while [ ! -f $COREPATH ] ; do echo waiting for $COREPATH to be generated; sleep 1; done"
1221     echo "Done: core is under $COREPATH on device.";
1222 }
1223
1224 # systemstack - dump the current stack trace of all threads in the system process
1225 # to the usual ANR traces file
1226 function systemstack()
1227 {
1228     stacks system_server
1229 }
1230
1231 function stacks()
1232 {
1233     if [[ $1 =~ ^[0-9]+$ ]] ; then
1234         local PID="$1"
1235     elif [ "$1" ] ; then
1236         local PIDLIST="$(pid $1)"
1237         if [[ $PIDLIST =~ ^[0-9]+$ ]] ; then
1238             local PID="$PIDLIST"
1239         elif [ "$PIDLIST" ] ; then
1240             echo "more than one process: $1"
1241         else
1242             echo "no such process: $1"
1243         fi
1244     else
1245         echo "usage: stacks [pid|process name]"
1246     fi
1247
1248     if [ "$PID" ] ; then
1249         # Determine whether the process is native
1250         if adb shell ls -l /proc/$PID/exe | grep -q /system/bin/app_process ; then
1251             # Dump stacks of Dalvik process
1252             local TRACES=/data/anr/traces.txt
1253             local ORIG=/data/anr/traces.orig
1254             local TMP=/data/anr/traces.tmp
1255
1256             # Keep original traces to avoid clobbering
1257             adb shell mv $TRACES $ORIG
1258
1259             # Make sure we have a usable file
1260             adb shell touch $TRACES
1261             adb shell chmod 666 $TRACES
1262
1263             # Dump stacks and wait for dump to finish
1264             adb shell kill -3 $PID
1265             adb shell notify $TRACES >/dev/null
1266
1267             # Restore original stacks, and show current output
1268             adb shell mv $TRACES $TMP
1269             adb shell mv $ORIG $TRACES
1270             adb shell cat $TMP
1271         else
1272             # Dump stacks of native process
1273             local USE64BIT="$(is64bit $PID)"
1274             adb shell debuggerd$USE64BIT -b $PID
1275         fi
1276     fi
1277 }
1278
1279 # Read the ELF header from /proc/$PID/exe to determine if the process is
1280 # 64-bit.
1281 function is64bit()
1282 {
1283     local PID="$1"
1284     if [ "$PID" ] ; then
1285         if [[ "$(adb shell cat /proc/$PID/exe | xxd -l 1 -s 4 -ps)" -eq "02" ]] ; then
1286             echo "64"
1287         else
1288             echo ""
1289         fi
1290     else
1291         echo ""
1292     fi
1293 }
1294
1295 case `uname -s` in
1296     Darwin)
1297         function sgrep()
1298         {
1299             find -E . -name .repo -prune -o -name .git -prune -o  -type f -iregex '.*\.(c|h|cc|cpp|S|java|xml|sh|mk|aidl|vts)' \
1300                 -exec grep --color -n "$@" {} +
1301         }
1302
1303         ;;
1304     *)
1305         function sgrep()
1306         {
1307             find . -name .repo -prune -o -name .git -prune -o  -type f -iregex '.*\.\(c\|h\|cc\|cpp\|S\|java\|xml\|sh\|mk\|aidl\|vts\)' \
1308                 -exec grep --color -n "$@" {} +
1309         }
1310         ;;
1311 esac
1312
1313 function gettargetarch
1314 {
1315     get_build_var TARGET_ARCH
1316 }
1317
1318 function ggrep()
1319 {
1320     find . -name .repo -prune -o -name .git -prune -o -name out -prune -o -type f -name "*\.gradle" \
1321         -exec grep --color -n "$@" {} +
1322 }
1323
1324 function jgrep()
1325 {
1326     find . -name .repo -prune -o -name .git -prune -o -name out -prune -o -type f -name "*\.java" \
1327         -exec grep --color -n "$@" {} +
1328 }
1329
1330 function cgrep()
1331 {
1332     find . -name .repo -prune -o -name .git -prune -o -name out -prune -o -type f \( -name '*.c' -o -name '*.cc' -o -name '*.cpp' -o -name '*.h' -o -name '*.hpp' \) \
1333         -exec grep --color -n "$@" {} +
1334 }
1335
1336 function resgrep()
1337 {
1338     for dir in `find . -name .repo -prune -o -name .git -prune -o -name out -prune -o -name res -type d`; do
1339         find $dir -type f -name '*\.xml' -exec grep --color -n "$@" {} +
1340     done
1341 }
1342
1343 function mangrep()
1344 {
1345     find . -name .repo -prune -o -name .git -prune -o -path ./out -prune -o -type f -name 'AndroidManifest.xml' \
1346         -exec grep --color -n "$@" {} +
1347 }
1348
1349 function sepgrep()
1350 {
1351     find . -name .repo -prune -o -name .git -prune -o -path ./out -prune -o -name sepolicy -type d \
1352         -exec grep --color -n -r --exclude-dir=\.git "$@" {} +
1353 }
1354
1355 function rcgrep()
1356 {
1357     find . -name .repo -prune -o -name .git -prune -o -name out -prune -o -type f -name "*\.rc*" \
1358         -exec grep --color -n "$@" {} +
1359 }
1360
1361 case `uname -s` in
1362     Darwin)
1363         function mgrep()
1364         {
1365             find -E . -name .repo -prune -o -name .git -prune -o -path ./out -prune -o -type f -iregex '.*/(Makefile|Makefile\..*|.*\.make|.*\.mak|.*\.mk)' \
1366                 -exec grep --color -n "$@" {} +
1367         }
1368
1369         function treegrep()
1370         {
1371             find -E . -name .repo -prune -o -name .git -prune -o -type f -iregex '.*\.(c|h|cpp|S|java|xml)' \
1372                 -exec grep --color -n -i "$@" {} +
1373         }
1374
1375         ;;
1376     *)
1377         function mgrep()
1378         {
1379             find . -name .repo -prune -o -name .git -prune -o -path ./out -prune -o -regextype posix-egrep -iregex '(.*\/Makefile|.*\/Makefile\..*|.*\.make|.*\.mak|.*\.mk)' -type f \
1380                 -exec grep --color -n "$@" {} +
1381         }
1382
1383         function treegrep()
1384         {
1385             find . -name .repo -prune -o -name .git -prune -o -regextype posix-egrep -iregex '.*\.(c|h|cpp|S|java|xml)' -type f \
1386                 -exec grep --color -n -i "$@" {} +
1387         }
1388
1389         ;;
1390 esac
1391
1392 function getprebuilt
1393 {
1394     get_abs_build_var ANDROID_PREBUILTS
1395 }
1396
1397 function tracedmdump()
1398 {
1399     T=$(gettop)
1400     if [ ! "$T" ]; then
1401         echo "Couldn't locate the top of the tree.  Try setting TOP."
1402         return
1403     fi
1404     local prebuiltdir=$(getprebuilt)
1405     local arch=$(gettargetarch)
1406     local KERNEL=$T/prebuilts/qemu-kernel/$arch/vmlinux-qemu
1407
1408     local TRACE=$1
1409     if [ ! "$TRACE" ] ; then
1410         echo "usage:  tracedmdump  tracename"
1411         return
1412     fi
1413
1414     if [ ! -r "$KERNEL" ] ; then
1415         echo "Error: cannot find kernel: '$KERNEL'"
1416         return
1417     fi
1418
1419     local BASETRACE=$(basename $TRACE)
1420     if [ "$BASETRACE" = "$TRACE" ] ; then
1421         TRACE=$ANDROID_PRODUCT_OUT/traces/$TRACE
1422     fi
1423
1424     echo "post-processing traces..."
1425     rm -f $TRACE/qtrace.dexlist
1426     post_trace $TRACE
1427     if [ $? -ne 0 ]; then
1428         echo "***"
1429         echo "*** Error: malformed trace.  Did you remember to exit the emulator?"
1430         echo "***"
1431         return
1432     fi
1433     echo "generating dexlist output..."
1434     /bin/ls $ANDROID_PRODUCT_OUT/system/framework/*.jar $ANDROID_PRODUCT_OUT/system/app/*.apk $ANDROID_PRODUCT_OUT/data/app/*.apk 2>/dev/null | xargs dexlist > $TRACE/qtrace.dexlist
1435     echo "generating dmtrace data..."
1436     q2dm -r $ANDROID_PRODUCT_OUT/symbols $TRACE $KERNEL $TRACE/dmtrace || return
1437     echo "generating html file..."
1438     dmtracedump -h $TRACE/dmtrace >| $TRACE/dmtrace.html || return
1439     echo "done, see $TRACE/dmtrace.html for details"
1440     echo "or run:"
1441     echo "    traceview $TRACE/dmtrace"
1442 }
1443
1444 # communicate with a running device or emulator, set up necessary state,
1445 # and run the hat command.
1446 function runhat()
1447 {
1448     # process standard adb options
1449     local adbTarget=""
1450     if [ "$1" = "-d" -o "$1" = "-e" ]; then
1451         adbTarget=$1
1452         shift 1
1453     elif [ "$1" = "-s" ]; then
1454         adbTarget="$1 $2"
1455         shift 2
1456     fi
1457     local adbOptions=${adbTarget}
1458     #echo adbOptions = ${adbOptions}
1459
1460     # runhat options
1461     local targetPid=$1
1462
1463     if [ "$targetPid" = "" ]; then
1464         echo "Usage: runhat [ -d | -e | -s serial ] target-pid"
1465         return
1466     fi
1467
1468     # confirm hat is available
1469     if [ -z $(which hat) ]; then
1470         echo "hat is not available in this configuration."
1471         return
1472     fi
1473
1474     # issue "am" command to cause the hprof dump
1475     local devFile=/data/local/tmp/hprof-$targetPid
1476     echo "Poking $targetPid and waiting for data..."
1477     echo "Storing data at $devFile"
1478     adb ${adbOptions} shell am dumpheap $targetPid $devFile
1479     echo "Press enter when logcat shows \"hprof: heap dump completed\""
1480     echo -n "> "
1481     read
1482
1483     local localFile=/tmp/$$-hprof
1484
1485     echo "Retrieving file $devFile..."
1486     adb ${adbOptions} pull $devFile $localFile
1487
1488     adb ${adbOptions} shell rm $devFile
1489
1490     echo "Running hat on $localFile"
1491     echo "View the output by pointing your browser at http://localhost:7000/"
1492     echo ""
1493     hat -JXmx512m $localFile
1494 }
1495
1496 function getbugreports()
1497 {
1498     local reports=(`adb shell ls /sdcard/bugreports | tr -d '\r'`)
1499
1500     if [ ! "$reports" ]; then
1501         echo "Could not locate any bugreports."
1502         return
1503     fi
1504
1505     local report
1506     for report in ${reports[@]}
1507     do
1508         echo "/sdcard/bugreports/${report}"
1509         adb pull /sdcard/bugreports/${report} ${report}
1510         gunzip ${report}
1511     done
1512 }
1513
1514 function getsdcardpath()
1515 {
1516     adb ${adbOptions} shell echo -n \$\{EXTERNAL_STORAGE\}
1517 }
1518
1519 function getscreenshotpath()
1520 {
1521     echo "$(getsdcardpath)/Pictures/Screenshots"
1522 }
1523
1524 function getlastscreenshot()
1525 {
1526     local screenshot_path=$(getscreenshotpath)
1527     local screenshot=`adb ${adbOptions} ls ${screenshot_path} | grep Screenshot_[0-9-]*.*\.png | sort -rk 3 | cut -d " " -f 4 | head -n 1`
1528     if [ "$screenshot" = "" ]; then
1529         echo "No screenshots found."
1530         return
1531     fi
1532     echo "${screenshot}"
1533     adb ${adbOptions} pull ${screenshot_path}/${screenshot}
1534 }
1535
1536 function startviewserver()
1537 {
1538     local port=4939
1539     if [ $# -gt 0 ]; then
1540             port=$1
1541     fi
1542     adb shell service call window 1 i32 $port
1543 }
1544
1545 function stopviewserver()
1546 {
1547     adb shell service call window 2
1548 }
1549
1550 function isviewserverstarted()
1551 {
1552     adb shell service call window 3
1553 }
1554
1555 function key_home()
1556 {
1557     adb shell input keyevent 3
1558 }
1559
1560 function key_back()
1561 {
1562     adb shell input keyevent 4
1563 }
1564
1565 function key_menu()
1566 {
1567     adb shell input keyevent 82
1568 }
1569
1570 function smoketest()
1571 {
1572     if [ ! "$ANDROID_PRODUCT_OUT" ]; then
1573         echo "Couldn't locate output files.  Try running 'lunch' first." >&2
1574         return
1575     fi
1576     T=$(gettop)
1577     if [ ! "$T" ]; then
1578         echo "Couldn't locate the top of the tree.  Try setting TOP." >&2
1579         return
1580     fi
1581
1582     (\cd "$T" && mmm tests/SmokeTest) &&
1583       adb uninstall com.android.smoketest > /dev/null &&
1584       adb uninstall com.android.smoketest.tests > /dev/null &&
1585       adb install $ANDROID_PRODUCT_OUT/data/app/SmokeTestApp.apk &&
1586       adb install $ANDROID_PRODUCT_OUT/data/app/SmokeTest.apk &&
1587       adb shell am instrument -w com.android.smoketest.tests/android.test.InstrumentationTestRunner
1588 }
1589
1590 # simple shortcut to the runtest command
1591 function runtest()
1592 {
1593     T=$(gettop)
1594     if [ ! "$T" ]; then
1595         echo "Couldn't locate the top of the tree.  Try setting TOP." >&2
1596         return
1597     fi
1598     ("$T"/development/testrunner/runtest.py $@)
1599 }
1600
1601 function godir () {
1602     if [[ -z "$1" ]]; then
1603         echo "Usage: godir <regex>"
1604         return
1605     fi
1606     T=$(gettop)
1607     if [ ! "$OUT_DIR" = "" ]; then
1608         mkdir -p $OUT_DIR
1609         FILELIST=$OUT_DIR/filelist
1610     else
1611         FILELIST=$T/filelist
1612     fi
1613     if [[ ! -f $FILELIST ]]; then
1614         echo -n "Creating index..."
1615         (\cd $T; find . -wholename ./out -prune -o -wholename ./.repo -prune -o -type f > $FILELIST)
1616         echo " Done"
1617         echo ""
1618     fi
1619     local lines
1620     lines=($(\grep "$1" $FILELIST | sed -e 's/\/[^/]*$//' | sort | uniq))
1621     if [[ ${#lines[@]} = 0 ]]; then
1622         echo "Not found"
1623         return
1624     fi
1625     local pathname
1626     local choice
1627     if [[ ${#lines[@]} > 1 ]]; then
1628         while [[ -z "$pathname" ]]; do
1629             local index=1
1630             local line
1631             for line in ${lines[@]}; do
1632                 printf "%6s %s\n" "[$index]" $line
1633                 index=$(($index + 1))
1634             done
1635             echo
1636             echo -n "Select one: "
1637             unset choice
1638             read choice
1639             if [[ $choice -gt ${#lines[@]} || $choice -lt 1 ]]; then
1640                 echo "Invalid choice"
1641                 continue
1642             fi
1643             pathname=${lines[$(($choice-1))]}
1644         done
1645     else
1646         pathname=${lines[0]}
1647     fi
1648     \cd $T/$pathname
1649 }
1650
1651 function cmremote()
1652 {
1653     git remote rm cmremote 2> /dev/null
1654     if [ ! -d .git ]
1655     then
1656         echo .git directory not found. Please run this from the root directory of the Android repository you wish to set up.
1657     fi
1658     GERRIT_REMOTE=$(cat .git/config  | grep git://github.com | awk '{ print $NF }' | sed s#git://github.com/##g)
1659     if [ -z "$GERRIT_REMOTE" ]
1660     then
1661         GERRIT_REMOTE=$(cat .git/config  | grep http://github.com | awk '{ print $NF }' | sed s#http://github.com/##g)
1662         if [ -z "$GERRIT_REMOTE" ]
1663         then
1664           echo Unable to set up the git remote, are you in the root of the repo?
1665           return 0
1666         fi
1667     fi
1668     CMUSER=`git config --get review.review.cyanogenmod.org.username`
1669     if [ -z "$CMUSER" ]
1670     then
1671         git remote add cmremote ssh://review.cyanogenmod.org:29418/$GERRIT_REMOTE
1672     else
1673         git remote add cmremote ssh://$CMUSER@review.cyanogenmod.org:29418/$GERRIT_REMOTE
1674     fi
1675     echo You can now push to "cmremote".
1676 }
1677 export -f cmremote
1678
1679 function aospremote()
1680 {
1681     git remote rm aosp 2> /dev/null
1682     if [ ! -d .git ]
1683     then
1684         echo .git directory not found. Please run this from the root directory of the Android repository you wish to set up.
1685     fi
1686     PROJECT=`pwd | sed s#$ANDROID_BUILD_TOP/##g`
1687     if (echo $PROJECT | grep -qv "^device")
1688     then
1689         PFX="platform/"
1690     fi
1691     git remote add aosp https://android.googlesource.com/$PFX$PROJECT
1692     echo "Remote 'aosp' created"
1693 }
1694 export -f aospremote
1695
1696 function installboot()
1697 {
1698     if [ ! -e "$OUT/recovery/root/etc/recovery.fstab" ];
1699     then
1700         echo "No recovery.fstab found. Build recovery first."
1701         return 1
1702     fi
1703     if [ ! -e "$OUT/boot.img" ];
1704     then
1705         echo "No boot.img found. Run make bootimage first."
1706         return 1
1707     fi
1708     PARTITION=`grep "^\/boot" $OUT/recovery/root/etc/recovery.fstab | awk {'print $3'}`
1709     if [ -z "$PARTITION" ];
1710     then
1711         echo "Unable to determine boot partition."
1712         return 1
1713     fi
1714     adb start-server
1715     adb root
1716     sleep 1
1717     adb wait-for-device
1718     adb remount
1719     adb wait-for-device
1720     if (adb shell cat /system/build.prop | grep -q "ro.cm.device=$CM_BUILD");
1721     then
1722         adb push $OUT/boot.img /cache/
1723         for i in $OUT/system/lib/modules/*;
1724         do
1725             adb push $i /system/lib/modules/
1726         done
1727         adb shell dd if=/cache/boot.img of=$PARTITION
1728         adb shell chmod 644 /system/lib/modules/*
1729         echo "Installation complete."
1730     else
1731         echo "The connected device does not appear to be $CM_BUILD, run away!"
1732     fi
1733 }
1734
1735 function installrecovery()
1736 {
1737     if [ ! -e "$OUT/recovery/root/etc/recovery.fstab" ];
1738     then
1739         echo "No recovery.fstab found. Build recovery first."
1740         return 1
1741     fi
1742     if [ ! -e "$OUT/recovery.img" ];
1743     then
1744         echo "No recovery.img found. Run make recoveryimage first."
1745         return 1
1746     fi
1747     PARTITION=`grep "^\/recovery" $OUT/recovery/root/etc/recovery.fstab | awk {'print $3'}`
1748     if [ -z "$PARTITION" ];
1749     then
1750         echo "Unable to determine recovery partition."
1751         return 1
1752     fi
1753     adb start-server
1754     adb root
1755     sleep 1
1756     adb wait-for-device
1757     adb remount
1758     adb wait-for-device
1759     if (adb shell cat /system/build.prop | grep -q "ro.cm.device=$CM_BUILD");
1760     then
1761         adb push $OUT/recovery.img /cache/
1762         adb shell dd if=/cache/recovery.img of=$PARTITION
1763         echo "Installation complete."
1764     else
1765         echo "The connected device does not appear to be $CM_BUILD, run away!"
1766     fi
1767 }
1768
1769 function makerecipe() {
1770   if [ -z "$1" ]
1771   then
1772     echo "No branch name provided."
1773     return 1
1774   fi
1775   cd android
1776   sed -i s/'default revision=.*'/'default revision="refs\/heads\/'$1'"'/ default.xml
1777   git commit -a -m "$1"
1778   cd ..
1779
1780   repo forall -c '
1781
1782   if [ "$REPO_REMOTE" == "github" ]
1783   then
1784     pwd
1785     cmremote
1786     git push cmremote HEAD:refs/heads/'$1'
1787   fi
1788   '
1789 }
1790
1791 function cmgerrit() {
1792     if [ $# -eq 0 ]; then
1793         $FUNCNAME help
1794         return 1
1795     fi
1796     local user=`git config --get review.review.cyanogenmod.org.username`
1797     local review=`git config --get remote.github.review`
1798     local project=`git config --get remote.github.projectname`
1799     local command=$1
1800     shift
1801     case $command in
1802         help)
1803             if [ $# -eq 0 ]; then
1804                 cat <<EOF
1805 Usage:
1806     $FUNCNAME COMMAND [OPTIONS] [CHANGE-ID[/PATCH-SET]][{@|^|~|:}ARG] [-- ARGS]
1807
1808 Commands:
1809     fetch   Just fetch the change as FETCH_HEAD
1810     help    Show this help, or for a specific command
1811     pull    Pull a change into current branch
1812     push    Push HEAD or a local branch to Gerrit for a specific branch
1813
1814 Any other Git commands that support refname would work as:
1815     git fetch URL CHANGE && git COMMAND OPTIONS FETCH_HEAD{@|^|~|:}ARG -- ARGS
1816
1817 See '$FUNCNAME help COMMAND' for more information on a specific command.
1818
1819 Example:
1820     $FUNCNAME checkout -b topic 1234/5
1821 works as:
1822     git fetch http://DOMAIN/p/PROJECT refs/changes/34/1234/5 \\
1823       && git checkout -b topic FETCH_HEAD
1824 will checkout a new branch 'topic' base on patch-set 5 of change 1234.
1825 Patch-set 1 will be fetched if omitted.
1826 EOF
1827                 return
1828             fi
1829             case $1 in
1830                 __cmg_*) echo "For internal use only." ;;
1831                 changes|for)
1832                     if [ "$FUNCNAME" = "cmgerrit" ]; then
1833                         echo "'$FUNCNAME $1' is deprecated."
1834                     fi
1835                     ;;
1836                 help) $FUNCNAME help ;;
1837                 fetch|pull) cat <<EOF
1838 usage: $FUNCNAME $1 [OPTIONS] CHANGE-ID[/PATCH-SET]
1839
1840 works as:
1841     git $1 OPTIONS http://DOMAIN/p/PROJECT \\
1842       refs/changes/HASH/CHANGE-ID/{PATCH-SET|1}
1843
1844 Example:
1845     $FUNCNAME $1 1234
1846 will $1 patch-set 1 of change 1234
1847 EOF
1848                     ;;
1849                 push) cat <<EOF
1850 usage: $FUNCNAME push [OPTIONS] [LOCAL_BRANCH:]REMOTE_BRANCH
1851
1852 works as:
1853     git push OPTIONS ssh://USER@DOMAIN:29418/PROJECT \\
1854       {LOCAL_BRANCH|HEAD}:refs/for/REMOTE_BRANCH
1855
1856 Example:
1857     $FUNCNAME push fix6789:gingerbread
1858 will push local branch 'fix6789' to Gerrit for branch 'gingerbread'.
1859 HEAD will be pushed from local if omitted.
1860 EOF
1861                     ;;
1862                 *)
1863                     $FUNCNAME __cmg_err_not_supported $1 && return
1864                     cat <<EOF
1865 usage: $FUNCNAME $1 [OPTIONS] CHANGE-ID[/PATCH-SET][{@|^|~|:}ARG] [-- ARGS]
1866
1867 works as:
1868     git fetch http://DOMAIN/p/PROJECT \\
1869       refs/changes/HASH/CHANGE-ID/{PATCH-SET|1} \\
1870       && git $1 OPTIONS FETCH_HEAD{@|^|~|:}ARG -- ARGS
1871 EOF
1872                     ;;
1873             esac
1874             ;;
1875         __cmg_get_ref)
1876             $FUNCNAME __cmg_err_no_arg $command $# && return 1
1877             local change_id patchset_id hash
1878             case $1 in
1879                 */*)
1880                     change_id=${1%%/*}
1881                     patchset_id=${1#*/}
1882                     ;;
1883                 *)
1884                     change_id=$1
1885                     patchset_id=1
1886                     ;;
1887             esac
1888             hash=$(($change_id % 100))
1889             case $hash in
1890                 [0-9]) hash="0$hash" ;;
1891             esac
1892             echo "refs/changes/$hash/$change_id/$patchset_id"
1893             ;;
1894         fetch|pull)
1895             $FUNCNAME __cmg_err_no_arg $command $# help && return 1
1896             $FUNCNAME __cmg_err_not_repo && return 1
1897             local change=$1
1898             shift
1899             git $command $@ http://$review/p/$project \
1900                 $($FUNCNAME __cmg_get_ref $change) || return 1
1901             ;;
1902         push)
1903             $FUNCNAME __cmg_err_no_arg $command $# help && return 1
1904             $FUNCNAME __cmg_err_not_repo && return 1
1905             if [ -z "$user" ]; then
1906                 echo >&2 "Gerrit username not found."
1907                 return 1
1908             fi
1909             local local_branch remote_branch
1910             case $1 in
1911                 *:*)
1912                     local_branch=${1%:*}
1913                     remote_branch=${1##*:}
1914                     ;;
1915                 *)
1916                     local_branch=HEAD
1917                     remote_branch=$1
1918                     ;;
1919             esac
1920             shift
1921             git push $@ ssh://$user@$review:29418/$project \
1922                 $local_branch:refs/for/$remote_branch || return 1
1923             ;;
1924         changes|for)
1925             if [ "$FUNCNAME" = "cmgerrit" ]; then
1926                 echo >&2 "'$FUNCNAME $command' is deprecated."
1927             fi
1928             ;;
1929         __cmg_err_no_arg)
1930             if [ $# -lt 2 ]; then
1931                 echo >&2 "'$FUNCNAME $command' missing argument."
1932             elif [ $2 -eq 0 ]; then
1933                 if [ -n "$3" ]; then
1934                     $FUNCNAME help $1
1935                 else
1936                     echo >&2 "'$FUNCNAME $1' missing argument."
1937                 fi
1938             else
1939                 return 1
1940             fi
1941             ;;
1942         __cmg_err_not_repo)
1943             if [ -z "$review" -o -z "$project" ]; then
1944                 echo >&2 "Not currently in any reviewable repository."
1945             else
1946                 return 1
1947             fi
1948             ;;
1949         __cmg_err_not_supported)
1950             $FUNCNAME __cmg_err_no_arg $command $# && return
1951             case $1 in
1952                 #TODO: filter more git commands that don't use refname
1953                 init|add|rm|mv|status|clone|remote|bisect|config|stash)
1954                     echo >&2 "'$FUNCNAME $1' is not supported."
1955                     ;;
1956                 *) return 1 ;;
1957             esac
1958             ;;
1959     #TODO: other special cases?
1960         *)
1961             $FUNCNAME __cmg_err_not_supported $command && return 1
1962             $FUNCNAME __cmg_err_no_arg $command $# help && return 1
1963             $FUNCNAME __cmg_err_not_repo && return 1
1964             local args="$@"
1965             local change pre_args refs_arg post_args
1966             case "$args" in
1967                 *--\ *)
1968                     pre_args=${args%%-- *}
1969                     post_args="-- ${args#*-- }"
1970                     ;;
1971                 *) pre_args="$args" ;;
1972             esac
1973             args=($pre_args)
1974             pre_args=
1975             if [ ${#args[@]} -gt 0 ]; then
1976                 change=${args[${#args[@]}-1]}
1977             fi
1978             if [ ${#args[@]} -gt 1 ]; then
1979                 pre_args=${args[0]}
1980                 for ((i=1; i<${#args[@]}-1; i++)); do
1981                     pre_args="$pre_args ${args[$i]}"
1982                 done
1983             fi
1984             while ((1)); do
1985                 case $change in
1986                     ""|--)
1987                         $FUNCNAME help $command
1988                         return 1
1989                         ;;
1990                     *@*)
1991                         if [ -z "$refs_arg" ]; then
1992                             refs_arg="@${change#*@}"
1993                             change=${change%%@*}
1994                         fi
1995                         ;;
1996                     *~*)
1997                         if [ -z "$refs_arg" ]; then
1998                             refs_arg="~${change#*~}"
1999                             change=${change%%~*}
2000                         fi
2001                         ;;
2002                     *^*)
2003                         if [ -z "$refs_arg" ]; then
2004                             refs_arg="^${change#*^}"
2005                             change=${change%%^*}
2006                         fi
2007                         ;;
2008                     *:*)
2009                         if [ -z "$refs_arg" ]; then
2010                             refs_arg=":${change#*:}"
2011                             change=${change%%:*}
2012                         fi
2013                         ;;
2014                     *) break ;;
2015                 esac
2016             done
2017             $FUNCNAME fetch $change \
2018                 && git $command $pre_args FETCH_HEAD$refs_arg $post_args \
2019                 || return 1
2020             ;;
2021     esac
2022 }
2023
2024 function cmrebase() {
2025     local repo=$1
2026     local refs=$2
2027     local pwd="$(pwd)"
2028     local dir="$(gettop)/$repo"
2029
2030     if [ -z $repo ] || [ -z $refs ]; then
2031         echo "CyanogenMod Gerrit Rebase Usage: "
2032         echo "      cmrebase <path to project> <patch IDs on Gerrit>"
2033         echo "      The patch IDs appear on the Gerrit commands that are offered."
2034         echo "      They consist on a series of numbers and slashes, after the text"
2035         echo "      refs/changes. For example, the ID in the following command is 26/8126/2"
2036         echo ""
2037         echo "      git[...]ges_apps_Camera refs/changes/26/8126/2 && git cherry-pick FETCH_HEAD"
2038         echo ""
2039         return
2040     fi
2041
2042     if [ ! -d $dir ]; then
2043         echo "Directory $dir doesn't exist in tree."
2044         return
2045     fi
2046     cd $dir
2047     repo=$(cat .git/config  | grep git://github.com | awk '{ print $NF }' | sed s#git://github.com/##g)
2048     echo "Starting branch..."
2049     repo start tmprebase .
2050     echo "Bringing it up to date..."
2051     repo sync .
2052     echo "Fetching change..."
2053     git fetch "http://review.cyanogenmod.org/p/$repo" "refs/changes/$refs" && git cherry-pick FETCH_HEAD
2054     if [ "$?" != "0" ]; then
2055         echo "Error cherry-picking. Not uploading!"
2056         return
2057     fi
2058     echo "Uploading..."
2059     repo upload .
2060     echo "Cleaning up..."
2061     repo abandon tmprebase .
2062     cd $pwd
2063 }
2064
2065 function mka() {
2066     case `uname -s` in
2067         Darwin)
2068             make -j `sysctl hw.ncpu|cut -d" " -f2` "$@"
2069             ;;
2070         *)
2071             schedtool -B -n 1 -e ionice -n 1 make -j$(cat /proc/cpuinfo | grep "^processor" | wc -l) "$@"
2072             ;;
2073     esac
2074 }
2075
2076 function reposync() {
2077     case `uname -s` in
2078         Darwin)
2079             repo sync -j 4 "$@"
2080             ;;
2081         *)
2082             schedtool -B -n 1 -e ionice -n 1 `which repo` sync -j 4 "$@"
2083             ;;
2084     esac
2085 }
2086
2087 function repodiff() {
2088     if [ -z "$*" ]; then
2089         echo "Usage: repodiff <ref-from> [[ref-to] [--numstat]]"
2090         return
2091     fi
2092     diffopts=$* repo forall -c \
2093       'echo "$REPO_PATH ($REPO_REMOTE)"; git diff ${diffopts} 2>/dev/null ;'
2094 }
2095
2096 # Credit for color strip sed: http://goo.gl/BoIcm
2097 function dopush()
2098 {
2099     local func=$1
2100     shift
2101
2102     adb start-server # Prevent unexpected starting server message from adb get-state in the next line
2103     if [ $(adb get-state) != device -a $(adb shell busybox test -e /sbin/recovery 2> /dev/null; echo $?) != 0 ] ; then
2104         echo "No device is online. Waiting for one..."
2105         echo "Please connect USB and/or enable USB debugging"
2106         until [ $(adb get-state) = device -o $(adb shell busybox test -e /sbin/recovery 2> /dev/null; echo $?) = 0 ];do
2107             sleep 1
2108         done
2109         echo "Device Found."
2110     fi
2111
2112     if (adb shell cat /system/build.prop | grep -q "ro.cm.device=$CM_BUILD");
2113     then
2114     adb root &> /dev/null
2115     sleep 0.3
2116     adb wait-for-device &> /dev/null
2117     sleep 0.3
2118     adb remount &> /dev/null
2119
2120     $func $* | tee $OUT/.log
2121
2122     # Install: <file>
2123     LOC=$(cat $OUT/.log | sed -r 's/\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K]//g' | grep 'Install' | cut -d ':' -f 2)
2124
2125     # Copy: <file>
2126     LOC=$LOC $(cat $OUT/.log | sed -r 's/\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K]//g' | grep 'Copy' | cut -d ':' -f 2)
2127
2128     for FILE in $LOC; do
2129         # Get target file name (i.e. system/bin/adb)
2130         TARGET=$(echo $FILE | sed "s#$OUT/##")
2131
2132         # Don't send files that are not in /system.
2133         if ! echo $TARGET | egrep '^system\/' > /dev/null ; then
2134             continue
2135         else
2136             case $TARGET in
2137             system/app/SystemUI.apk|system/framework/*)
2138                 stop_n_start=true
2139             ;;
2140             *)
2141                 stop_n_start=false
2142             ;;
2143             esac
2144             if $stop_n_start ; then adb shell stop ; fi
2145             echo "Pushing: $TARGET"
2146             adb push $FILE $TARGET
2147             if $stop_n_start ; then adb shell start ; fi
2148         fi
2149     done
2150     rm -f $OUT/.log
2151     return 0
2152     else
2153         echo "The connected device does not appear to be $CM_BUILD, run away!"
2154     fi
2155 }
2156
2157 alias mmp='dopush mm'
2158 alias mmmp='dopush mmm'
2159 alias mkap='dopush mka'
2160 alias cmkap='dopush cmka'
2161
2162 # Force JAVA_HOME to point to java 1.7/1.8 if it isn't already set.
2163 function set_java_home() {
2164     # Clear the existing JAVA_HOME value if we set it ourselves, so that
2165     # we can reset it later, depending on the version of java the build
2166     # system needs.
2167     #
2168     # If we don't do this, the JAVA_HOME value set by the first call to
2169     # build/envsetup.sh will persist forever.
2170     if [ -n "$ANDROID_SET_JAVA_HOME" ]; then
2171       export JAVA_HOME=""
2172     fi
2173
2174     if [ ! "$JAVA_HOME" ]; then
2175       if [ -n "$LEGACY_USE_JAVA7" ]; then
2176         echo Warning: Support for JDK 7 will be dropped. Switch to JDK 8.
2177         case `uname -s` in
2178             Darwin)
2179                 export JAVA_HOME=$(/usr/libexec/java_home -v 1.7)
2180                 ;;
2181             *)
2182                 export JAVA_HOME=/usr/lib/jvm/java-7-openjdk-amd64
2183                 ;;
2184         esac
2185       else
2186         case `uname -s` in
2187             Darwin)
2188                 export JAVA_HOME=$(/usr/libexec/java_home -v 1.8)
2189                 ;;
2190             *)
2191                 export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64
2192                 ;;
2193         esac
2194       fi
2195
2196       # Keep track of the fact that we set JAVA_HOME ourselves, so that
2197       # we can change it on the next envsetup.sh, if required.
2198       export ANDROID_SET_JAVA_HOME=true
2199     fi
2200 }
2201
2202 # Print colored exit condition
2203 function pez {
2204     "$@"
2205     local retval=$?
2206     if [ $retval -ne 0 ]
2207     then
2208         echo $'\E'"[0;31mFAILURE\e[00m"
2209     else
2210         echo $'\E'"[0;32mSUCCESS\e[00m"
2211     fi
2212     return $retval
2213 }
2214
2215 function get_make_command()
2216 {
2217   echo command make
2218 }
2219
2220 function make()
2221 {
2222     local start_time=$(date +"%s")
2223     $(get_make_command) "$@"
2224     local ret=$?
2225     local end_time=$(date +"%s")
2226     local tdiff=$(($end_time-$start_time))
2227     local hours=$(($tdiff / 3600 ))
2228     local mins=$((($tdiff % 3600) / 60))
2229     local secs=$(($tdiff % 60))
2230     local ncolors=$(tput colors 2>/dev/null)
2231     if [ -n "$ncolors" ] && [ $ncolors -ge 8 ]; then
2232         color_failed=$'\E'"[0;31m"
2233         color_success=$'\E'"[0;32m"
2234         color_reset=$'\E'"[00m"
2235     else
2236         color_failed=""
2237         color_success=""
2238         color_reset=""
2239     fi
2240     echo
2241     if [ $ret -eq 0 ] ; then
2242         echo -n "${color_success}#### make completed successfully "
2243     else
2244         echo -n "${color_failed}#### make failed to build some targets "
2245     fi
2246     if [ $hours -gt 0 ] ; then
2247         printf "(%02g:%02g:%02g (hh:mm:ss))" $hours $mins $secs
2248     elif [ $mins -gt 0 ] ; then
2249         printf "(%02g:%02g (mm:ss))" $mins $secs
2250     elif [ $secs -gt 0 ] ; then
2251         printf "(%s seconds)" $secs
2252     fi
2253     echo " ####${color_reset}"
2254     echo
2255     return $ret
2256 }
2257
2258 function provision()
2259 {
2260     if [ ! "$ANDROID_PRODUCT_OUT" ]; then
2261         echo "Couldn't locate output files.  Try running 'lunch' first." >&2
2262         return 1
2263     fi
2264     if [ ! -e "$ANDROID_PRODUCT_OUT/provision-device" ]; then
2265         echo "There is no provisioning script for the device." >&2
2266         return 1
2267     fi
2268
2269     # Check if user really wants to do this.
2270     if [ "$1" = "--no-confirmation" ]; then
2271         shift 1
2272     else
2273         echo "This action will reflash your device."
2274         echo ""
2275         echo "ALL DATA ON THE DEVICE WILL BE IRREVOCABLY ERASED."
2276         echo ""
2277         echo -n "Are you sure you want to do this (yes/no)? "
2278         read
2279         if [[ "${REPLY}" != "yes" ]] ; then
2280             echo "Not taking any action. Exiting." >&2
2281             return 1
2282         fi
2283     fi
2284     "$ANDROID_PRODUCT_OUT/provision-device" "$@"
2285 }
2286
2287 if [ "x$SHELL" != "x/bin/bash" ]; then
2288     case `ps -o command -p $$` in
2289         *bash*)
2290             ;;
2291         *)
2292             echo "WARNING: Only bash is supported, use of other shell would lead to erroneous results"
2293             ;;
2294     esac
2295 fi
2296
2297 # Execute the contents of any vendorsetup.sh files we can find.
2298 for f in `test -d device && find -L device -maxdepth 4 -name 'vendorsetup.sh' 2> /dev/null | sort` \
2299          `test -d vendor && find -L vendor -maxdepth 4 -name 'vendorsetup.sh' 2> /dev/null | sort` \
2300          `test -d product && find -L product -maxdepth 4 -name 'vendorsetup.sh' 2> /dev/null | sort`
2301 do
2302     echo "including $f"
2303     . $f
2304 done
2305 unset f
2306
2307 addcompletions