scripts/functions
author "Yann E. MORIN" <yann.morin.1998@anciens.enib.fr>
Tue May 08 12:54:06 2007 +0000 (2007-05-08)
changeset 76 5f84983926e9
parent 63 89b41dbffe8d
child 77 ccb2d742e917
permissions -rw-r--r--
Print the elapsed time alongside with the progress bar, such as below:
[02:27] \
     1 # This file contains some usefull common functions
     2 # Copyright 2007 Yann E. MORIN
     3 # Licensed under the GPL v2. See COPYING in the root of this package
     4 
     5 CT_OnError() {
     6     ret=$?
     7     CT_DoLog ERROR "Build failed in step \"${CT_STEP_MESSAGE[${CT_STEP_COUNT}]}\""
     8     for((step=(CT_STEP_COUNT-1); step>1; step--)); do
     9         CT_DoLog ERROR "      called in step \"${CT_STEP_MESSAGE[${step}]}\""
    10     done
    11     CT_DoLog ERROR "Error happened in \"${BASH_SOURCE[1]}\" in function \"${FUNCNAME[1]}\" (line unknown, sorry)"
    12     for((depth=2; ${BASH_LINENO[$((${depth}-1))]}>0; depth++)); do
    13         CT_DoLog ERROR "      called from \"${BASH_SOURCE[${depth}]}\" at line # ${BASH_LINENO[${depth}-1]} in function \"${FUNCNAME[${depth}]}\""
    14     done
    15     CT_DoLog ERROR "Look at \"${CT_ACTUAL_LOG_FILE}\" for more info on this error."
    16     exit $ret
    17 }
    18 trap CT_OnError ERR
    19 
    20 set -E
    21 set -o pipefail
    22 
    23 # This is crosstool-ng-0.0.1
    24 CT_VERSION=ng-0.0.1
    25 
    26 # The different log levels:
    27 CT_LOG_LEVEL_ERROR=0
    28 CT_LOG_LEVEL_WARN=1
    29 CT_LOG_LEVEL_INFO=2
    30 CT_LOG_LEVEL_EXTRA=3
    31 CT_LOG_LEVEL_DEBUG=4
    32 
    33 # Attributes
    34 _A_NOR="\\033[0m"
    35 _A_BRI="\\033[1m"
    36 _A_DIM="\\033[2m"
    37 _A_UND="\\033[4m"
    38 _A_BRB="\\033[5m"
    39 _A_REV="\\033[7m"
    40 _A_HID="\\033[8m"
    41 
    42 # Fore colors
    43 _F_BLK="\\033[30m"
    44 _F_RED="\\033[31m"
    45 _F_GRN="\\033[32m"
    46 _F_YEL="\\033[33m"
    47 _F_BLU="\\033[34m"
    48 _F_MAG="\\033[35m"
    49 _F_CYA="\\033[36m"
    50 _F_WHI="\\033[37m"
    51 
    52 # A function to log what is happening
    53 # Different log level are available:
    54 #   - ERROR:   A serious, fatal error occurred
    55 #   - WARN:    A non fatal, non serious error occurred, take your responsbility with the generated build
    56 #   - INFO:    Informational messages
    57 #   - EXTRA:   Extra informational messages
    58 #   - DEBUG:   Debug messages
    59 # Usage: CT_DoLog <level> [message]
    60 # If message is empty, then stdin will be logged.
    61 CT_DoLog() {
    62     local max_level LEVEL level cur_l cur_L
    63     local l
    64     eval max_level="\${CT_LOG_LEVEL_${CT_LOG_LEVEL_MAX}}"
    65     # Set the maximum log level to DEBUG if we have none
    66     [ -z ${max_level} ] && max_level=${CT_LOG_LEVEL_DEBUG}
    67 
    68     LEVEL="$1"; shift
    69     eval level="\${CT_LOG_LEVEL_${LEVEL}}"
    70 
    71     if [ $# -eq 0 ]; then
    72         cat -
    73     else
    74         echo "${1}"
    75     fi |( IFS="\n" # We want the full lines, even leading spaces
    76           cpt=0
    77           indent=$((2*CT_STEP_COUNT))
    78           while read line; do
    79               case "${CT_LOG_SEE_TOOLS_WARN},${line}" in
    80                 y,*"warning:"*)         cur_L=WARN; cur_l=${CT_LOG_LEVEL_WARN};;
    81                 *"error:"*)             cur_L=ERROR; cur_l=${CT_LOG_LEVEL_ERROR};;
    82                 "make["?*"]:"*"Stop.")  cur_L=ERROR; cur_l=${CT_LOG_LEVEL_ERROR};;
    83                 *)                      cur_L="${LEVEL}"; cur_l="${level}";;
    84               esac
    85               l="`printf \"[%-5s]%*s%s%s\" \"${cur_L}\" \"${indent}\" \" \" \"${line}\"`"
    86               # There will always be a log file, be it /dev/null
    87               echo -e "${l}" >>"${CT_ACTUAL_LOG_FILE}"
    88               color="CT_${cur_L}_COLOR"
    89               normal="CT_NORMAL_COLOR"
    90               if [ ${cur_l} -le ${max_level} ]; then
    91                   echo -e "\r${!color}${l}${!normal}"
    92               else
    93                   ${CT_PROG_BAR}
    94               fi
    95           done
    96         )
    97 
    98     return 0
    99 }
   100 
   101 # Abort the execution with a error message
   102 # Usage: CT_Abort <message>
   103 CT_Abort() {
   104     CT_DoLog ERROR "$1" >&2
   105     exit 1
   106 }
   107 
   108 # Test a condition, and print a message if satisfied
   109 # Usage: CT_Test <message> <tests>
   110 CT_Test() {
   111     local ret
   112     local m="$1"
   113     shift
   114     test "$@" && CT_DoLog WARN "$m"
   115     return 0
   116 }
   117 
   118 # Test a condition, and abort with an error message if satisfied
   119 # Usage: CT_TestAndAbort <message> <tests>
   120 CT_TestAndAbort() {
   121     local m="$1"
   122     shift
   123     test "$@" && CT_Abort "$m"
   124     return 0
   125 }
   126 
   127 # Test a condition, and abort with an error message if not satisfied
   128 # Usage: CT_TestAndAbort <message> <tests>
   129 CT_TestOrAbort() {
   130     local m="$1"
   131     shift
   132     test "$@" || CT_Abort "$m"
   133     return 0
   134 }
   135 
   136 # Test the presence of a tool, or abort if not found
   137 # Usage: CT_HasOrAbort <tool>
   138 CT_HasOrAbort() {
   139     CT_TestAndAbort "\"${1}\" not found and needed for successfull toolchain build." -z "`which \"${1}\"`"
   140     return 0
   141 }
   142 
   143 # Get current date with nanosecond precision
   144 # On those system not supporting nanosecond precision, faked with rounding down
   145 # to the highest entire second
   146 # Usage: CT_DoDate <fmt>
   147 CT_DoDate() {
   148     date "$1" |sed -r -e 's/%N$/000000000/;'
   149 }
   150 
   151 CT_STEP_COUNT=1
   152 CT_STEP_MESSAGE[${CT_STEP_COUNT}]="<none>"
   153 # Memorise a step being done so that any error is caught
   154 # Usage: CT_DoStep <loglevel> <message>
   155 CT_DoStep() {
   156     local start=`CT_DoDate +%s%N`
   157     CT_DoLog "$1" "================================================================="
   158     CT_DoLog "$1" "$2"
   159     CT_STEP_COUNT=$((CT_STEP_COUNT+1))
   160     CT_STEP_LEVEL[${CT_STEP_COUNT}]="$1"; shift
   161     CT_STEP_START[${CT_STEP_COUNT}]="${start}"
   162     CT_STEP_MESSAGE[${CT_STEP_COUNT}]="$1"
   163     return 0
   164 }
   165 
   166 # End the step just being done
   167 # Usage: CT_EndStep
   168 CT_EndStep() {
   169     local stop=`CT_DoDate +%s%N`
   170     local duration=`printf "%032d" $((stop-${CT_STEP_START[${CT_STEP_COUNT}]})) |sed -r -e 's/([[:digit:]]{2})[[:digit:]]{7}$/\.\1/; s/^0+//; s/^\./0\./;'`
   171     local level="${CT_STEP_LEVEL[${CT_STEP_COUNT}]}"
   172     local message="${CT_STEP_MESSAGE[${CT_STEP_COUNT}]}"
   173     CT_STEP_COUNT=$((CT_STEP_COUNT-1))
   174     CT_DoLog "${level}" "${message}: done in ${duration}s"
   175     return 0
   176 }
   177 
   178 # Pushes into a directory, and pops back
   179 CT_Pushd() {
   180     pushd "$1" >/dev/null 2>&1
   181 }
   182 CT_Popd() {
   183     popd >/dev/null 2>&1
   184 }
   185 
   186 # Makes a path absolute
   187 # Usage: CT_MakeAbsolutePath path
   188 CT_MakeAbsolutePath() {
   189     # Try to cd in that directory
   190     if [ -d "$1" ]; then
   191         CT_Pushd "$1"
   192         pwd
   193         CT_Popd
   194     else
   195         # No such directory, fail back to guessing
   196         case "$1" in
   197             /*)  echo "$1";;
   198             *)   echo "`pwd`/$1";;
   199         esac
   200     fi
   201     
   202     return 0
   203 }
   204 
   205 # Creates a temporary directory
   206 # $1: variable to assign to
   207 # Usage: CT_MktempDir foo
   208 CT_MktempDir() {
   209     # Some mktemp do not allow more than 6 Xs
   210     eval "$1"="`mktemp -q -d \"${CT_BUILD_DIR}/.XXXXXX\"`"
   211     CT_TestOrAbort "Could not make temporary directory" -n "${!1}" -a -d "${!1}"
   212 }
   213 
   214 # Echoes the specified string on stdout until the pipe breaks.
   215 # Doesn't fail
   216 # $1: string to echo
   217 # Usage: CT_DoYes "" |make oldconfig
   218 CT_DoYes() {
   219     yes "$1" || true
   220 }
   221 
   222 # Download an URL using wget
   223 # Usage: CT_DoGetFileWget <URL>
   224 CT_DoGetFileWget() {
   225     # Need to return true because it is legitimate to not find the tarball at
   226     # some of the provided URLs (think about snapshots, different layouts for
   227     # different gcc versions, etc...)
   228     # Some (very old!) FTP server might not support the passive mode, thus
   229     # retry without
   230     # With automated download as we are doing, it can be very dangerous to use
   231     # -c to continue the downloads. It's far better to simply overwrite the
   232     # destination file
   233     wget -nc --progress=dot:binary --tries=3 --passive-ftp "$1" || wget -nc --progress=dot:binary --tries=3 "$1" || true
   234 }
   235 
   236 # Download an URL using curl
   237 # Usage: CT_DoGetFileCurl <URL>
   238 CT_DoGetFileCurl() {
   239 	# Note: comments about wget method are also valid here
   240 	# Plus: no good progreess indicator is available with curl,
   241 	#       so output is consigned to oblivion
   242 	curl --ftp-pasv -O --retry 3 "$1" >/dev/null || curl -O --retry 3 "$1" >/dev/null || true
   243 }
   244 
   245 # Wrapper function to call one of curl or wget
   246 # Usage: CT_DoGetFile <URL>
   247 CT_DoGetFile() {
   248     local _wget=`which wget`
   249     local _curl=`which curl`
   250     case "${_wget},${_curl}" in
   251         ,)  CT_DoError "Could find neither wget nor curl";;
   252         ,*) CT_DoGetFileCurl "$1";;
   253         *)  CT_DoGetFileWget "$1";;
   254     esac
   255 }
   256 
   257 # Download the file from one of the URLs passed as argument
   258 # Usage: CT_GetFile <filename> <url> [<url> ...]
   259 CT_GetFile() {
   260     local got_it
   261     local ext
   262     local url
   263     local file="$1"
   264     shift
   265 
   266     # Do we already have it?
   267     ext=`CT_GetFileExtension "${file}"`
   268     if [ -n "${ext}" ]; then
   269         if [ "${CT_FORCE_DOWNLOAD}" = "y" ]; then
   270             CT_DoLog DEBUG "Removing already present \"${file}\""
   271             rm -f "${CT_TARBALLS_DIR}/${file}${ext}"
   272         else
   273             CT_DoLog EXTRA "Already have \"${file}\""
   274             return 0
   275         fi
   276     fi
   277 
   278     CT_DoLog EXTRA "Retrieving \"${file}\""
   279     CT_Pushd "${CT_TARBALLS_DIR}"
   280     # File not yet downloaded, try to get it
   281     got_it=0
   282     if [ "${got_it}" != "y" ]; then
   283         # We'd rather have a bzip2'ed tarball, then gzipped, and finally plain tar.
   284         for ext in .tar.bz2 .tar.gz .tgz .tar; do
   285             # Try all urls in turn
   286             for url in "$@"; do
   287                 case "${url}" in
   288                     *)  CT_DoLog EXTRA "Trying \"${url}/${file}${ext}\""
   289                         CT_DoGetFile "${url}/${file}${ext}" 2>&1 |CT_DoLog DEBUG
   290                         ;;
   291                 esac
   292                 [ -f "${file}${ext}" ] && got_it=1 && break 2 || true
   293             done
   294         done
   295     fi
   296     CT_Popd
   297 
   298     CT_TestAndAbort "Could not download \"${file}\", and not present in \"${CT_TARBALLS_DIR}\"" ${got_it} -eq 0
   299 }
   300 
   301 # Get the file name extension of a component
   302 # Usage: CT_GetFileExtension <component_name-component_version>
   303 # If found, echoes the extension to stdout
   304 # If not found, echoes nothing on stdout.
   305 CT_GetFileExtension() {
   306     local ext
   307     local file="$1"
   308     local got_it=1
   309 
   310     CT_Pushd "${CT_TARBALLS_DIR}"
   311     for ext in .tar.gz .tar.bz2 .tgz .tar; do
   312         if [ -f "${file}${ext}" ]; then
   313             echo "${ext}"
   314             got_it=0
   315             break
   316         fi
   317     done
   318     CT_Popd
   319 
   320     return 0
   321 }
   322 
   323 # Extract a tarball and patch the resulting sources if necessary.
   324 # Some tarballs need to be extracted in specific places. Eg.: glibc addons
   325 # must be extracted in the glibc directory; uCLibc locales must be extracted
   326 # in the extra/locale sub-directory of uClibc.
   327 CT_ExtractAndPatch() {
   328     local file="$1"
   329     local base_file=`echo "${file}" |cut -d - -f 1`
   330     local ver_file=`echo "${file}" |cut -d - -f 2-`
   331     local official_patch_dir
   332     local custom_patch_dir
   333     local libc_addon
   334     local ext=`CT_GetFileExtension "${file}"`
   335     CT_TestAndAbort "\"${file}\" not found in \"${CT_TARBALLS_DIR}\"" -z "${ext}"
   336     local full_file="${CT_TARBALLS_DIR}/${file}${ext}"
   337 
   338     CT_Pushd "${CT_SRC_DIR}"
   339 
   340     # Add-ons need a little love, really.
   341     case "${file}" in
   342         glibc-[a-z]*-*)
   343             CT_TestAndAbort "Trying to extract the C-library addon/locales \"${file}\" when C-library not yet extracted" ! -d "${CT_LIBC_FILE}"
   344             cd "${CT_LIBC_FILE}"
   345             libc_addon=y
   346             [ -f ".${file}.extracted" ] && return 0
   347             touch ".${file}.extracted"
   348             ;;
   349         uClibc-locale-*)
   350             CT_TestAndAbort "Trying to extract the C-library addon/locales \"${file}\" when C-library not yet extracted" ! -d "${CT_LIBC_FILE}"
   351             cd "${CT_LIBC_FILE}/extra/locale"
   352             libc_addon=y
   353             [ -f ".${file}.extracted" ] && return 0
   354             touch ".${file}.extracted"
   355             ;;
   356     esac
   357 
   358     # If the directory exists, then consider extraction and patching done
   359     [ -d "${file}" ] && return 0
   360 
   361     CT_DoLog EXTRA "Extracting \"${file}\""
   362     case "${ext}" in
   363         .tar.bz2)     tar xvjf "${full_file}" |CT_DoLog DEBUG;;
   364         .tar.gz|.tgz) tar xvzf "${full_file}" |CT_DoLog DEBUG;;
   365         .tar)         tar xvf  "${full_file}" |CT_DoLog DEBUG;;
   366         *)            CT_Abort "Don't know how to handle \"${file}\": unknown extension" ;;
   367     esac
   368 
   369     # Snapshots might not have the version number in the extracted directory
   370     # name. This is also the case for some (old) packages, such as libfloat.
   371     # Overcome this issue by symlink'ing the directory.
   372     if [ ! -d "${file}" -a "${libc_addon}" != "y" ]; then
   373         case "${ext}" in
   374             .tar.bz2)     base=`tar tjf "${full_file}" |head -n 1 |cut -d / -f 1 || true`;;
   375             .tar.gz|.tgz) base=`tar tzf "${full_file}" |head -n 1 |cut -d / -f 1 || true`;;
   376             .tar)         base=`tar tf  "${full_file}" |head -n 1 |cut -d / -f 1 || true`;;
   377         esac
   378         CT_TestOrAbort "There was a problem when extracting \"${file}\"" -d "${base}" -o "${base}" != "${file}"
   379         ln -s "${base}" "${file}"
   380     fi
   381 
   382     # Kludge: outside this function, we wouldn't know if we had just extracted
   383     # a libc addon, or a plain package. Apply patches now.
   384     CT_DoLog EXTRA "Patching \"${file}\""
   385 
   386     # If libc addon, we're already in the correct place.
   387     [ -z "${libc_addon}" ] && cd "${file}"
   388 
   389     [ "${CUSTOM_PATCH_ONLY}" = "y" ] || official_patch_dir="${CT_TOP_DIR}/patches/${base_file}/${ver_file}"
   390     [ "${CT_CUSTOM_PATCH}" = "y" ] && custom_patch_dir="${CT_CUSTOM_PATCH_DIR}/${base_file}/${ver_file}"
   391     for patch_dir in "${official_patch_dir}" "${custom_patch_dir}"; do
   392         if [ -n "${patch_dir}" -a -d "${patch_dir}" ]; then
   393             for p in "${patch_dir}"/*.patch; do
   394                 if [ -f "${p}" ]; then
   395                     CT_DoLog DEBUG "Applying patch \"${p}\""
   396                     patch -g0 -F1 -p1 -f <"${p}" |CT_DoLog DEBUG
   397                     CT_TestAndAbort "Failed while applying patch file \"${p}\"" ${PIPESTATUS[0]} -ne 0
   398                 fi
   399             done
   400         fi
   401     done
   402 
   403     CT_Popd
   404 }
   405 
   406 # Compute the target triplet from what is provided by the user
   407 # Usage: CT_DoBuildTargetTriplet
   408 # In fact this function takes the environment variables to build the target
   409 # triplet. It is needed both by the normal build sequence, as well as the
   410 # sample saving sequence.
   411 CT_DoBuildTargetTriplet() {
   412     case "${CT_ARCH_BE},${CT_ARCH_LE}" in
   413         y,) target_endian_eb=eb; target_endian_el=;;
   414         ,y) target_endian_eb=; target_endian_el=el;;
   415     esac
   416     case "${CT_ARCH}" in
   417         arm)  CT_TARGET="${CT_ARCH}${target_endian_eb}";;
   418         mips) CT_TARGET="${CT_ARCH}${target_endian_el}";;
   419         x86*) # Much love for this one :-(
   420               # Ultimately, we should use config.sub to output the correct
   421               # procesor name. Work for later...
   422               arch="${CT_ARCH_ARCH}"
   423               [ -z "${arch}" ] && arch="${CT_ARCH_TUNE}"
   424               case "${CT_ARCH}" in
   425                   x86_64)      CT_TARGET=x86_64;;
   426               	  *)  case "${arch}" in
   427                           "")                                       CT_TARGET=i386;;
   428                           i386|i486|i586|i686)                      CT_TARGET="${arch}";;
   429                           winchip*)                                 CT_TARGET=i486;;
   430                           pentium|pentium-mmx|c3*)                  CT_TARGET=i586;;
   431                           nocona|athlon*64|k8|athlon-fx|opteron)    CT_TARGET=x86_64;;
   432                           pentiumpro|pentium*|athlon*)              CT_TARGET=i686;;
   433                           *)                                        CT_TARGET=i586;;
   434                       esac;;
   435               esac;;
   436     esac
   437     case "${CT_TARGET_VENDOR}" in
   438         "") CT_TARGET="${CT_TARGET}-unknown";;
   439         *)  CT_TARGET="${CT_TARGET}-${CT_TARGET_VENDOR}";;
   440     esac
   441     case "${CT_KERNEL}" in
   442         linux*)  CT_TARGET="${CT_TARGET}-linux";;
   443         cygwin*) CT_TARGET="${CT_TARGET}-cygwin";;
   444     esac
   445     case "${CT_LIBC}" in
   446         glibc)  CT_TARGET="${CT_TARGET}-gnu";;
   447         uClibc) CT_TARGET="${CT_TARGET}-uclibc";;
   448     esac
   449     case "${CT_ARCH_ABI}" in
   450         eabi)   CT_TARGET="${CT_TARGET}eabi";;
   451     esac
   452     CT_TARGET="`${CT_TOP_DIR}/tools/config.sub ${CT_TARGET}`"
   453 }