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