Drop $Id$ per council decision in bug #611234.
[gentoo.git] / eclass / versionator.eclass
1 # Copyright 1999-2014 Gentoo Foundation
2 # Distributed under the terms of the GNU General Public License v2
3
4 # @ECLASS: versionator.eclass
5 # @MAINTAINER:
6 # Jonathan Callen <jcallen@gentoo.org>
7 # base-system@gentoo.org
8 # @BLURB: functions which simplify manipulation of ${PV} and similar version strings
9 # @DESCRIPTION:
10 # This eclass provides functions which simplify manipulating $PV and similar
11 # variables. Most functions default to working with $PV, although other
12 # values can be used.
13 # @EXAMPLE:
14 # Simple Example 1: $PV is 1.2.3b, we want 1_2.3b:
15 #     MY_PV=$(replace_version_separator 1 '_' )
16 #
17 # Simple Example 2: $PV is 1.4.5, we want 1:
18 #     MY_MAJORV=$(get_major_version )
19 #
20 # Rather than being a number, the index parameter can be a separator character
21 # such as '-', '.' or '_'. In this case, the first separator of this kind is
22 # selected.
23 #
24 # There's also:
25 #     version_is_at_least             want      have
26 #  which may be buggy, so use with caution.
27
28 if [[ -z ${_VERSIONATOR_ECLASS} ]]; then
29 _VERSIONATOR_ECLASS=1
30
31 inherit eutils
32
33 # @FUNCTION: get_all_version_components
34 # @USAGE: [version]
35 # @DESCRIPTION:
36 # Split up a version string into its component parts. If no parameter is
37 # supplied, defaults to $PV.
38 #     0.8.3       ->  0 . 8 . 3
39 #     7c          ->  7 c
40 #     3.0_p2      ->  3 . 0 _ p2
41 #     20040905    ->  20040905
42 #     3.0c-r1     ->  3 . 0 c - r1
43 get_all_version_components() {
44         eshopts_push -s extglob
45         local ver_str=${1:-${PV}} result
46         result=()
47
48         # sneaky cache trick cache to avoid having to parse the same thing several
49         # times.
50         if [[ ${VERSIONATOR_CACHE_VER_STR} == ${ver_str} ]] ; then
51                 echo ${VERSIONATOR_CACHE_RESULT}
52                 eshopts_pop
53                 return
54         fi
55         export VERSIONATOR_CACHE_VER_STR=${ver_str}
56
57         while [[ -n $ver_str ]] ; do
58                 case "${ver_str::1}" in
59                         # number: parse whilst we have a number
60                         [[:digit:]])
61                                 result+=("${ver_str%%[^[:digit:]]*}")
62                                 ver_str=${ver_str##+([[:digit:]])}
63                                 ;;
64
65                         # separator: single character
66                         [-_.])
67                                 result+=("${ver_str::1}")
68                                 ver_str=${ver_str:1}
69                                 ;;
70
71                         # letter: grab the letters plus any following numbers
72                         [[:alpha:]])
73                                 local not_match=${ver_str##+([[:alpha:]])*([[:digit:]])}
74                                 # Can't say "${ver_str::-${#not_match}}" in Bash 3.2
75                                 result+=("${ver_str::${#ver_str} - ${#not_match}}")
76                                 ver_str=${not_match}
77                                 ;;
78
79                         # huh?
80                         *)
81                                 result+=("${ver_str::1}")
82                                 ver_str=${ver_str:1}
83                                 ;;
84                 esac
85         done
86
87         export VERSIONATOR_CACHE_RESULT=${result[*]}
88         echo ${result[@]}
89         eshopts_pop
90 }
91
92 # @FUNCTION: get_version_components
93 # @USAGE: [version]
94 # @DESCRIPTION:
95 # Get the important version components, excluding '.', '-' and '_'. Defaults to
96 # $PV if no parameter is supplied.
97 #     0.8.3       ->  0 8 3
98 #     7c          ->  7 c
99 #     3.0_p2      ->  3 0 p2
100 #     20040905    ->  20040905
101 #     3.0c-r1     ->  3 0 c r1
102 get_version_components() {
103         local c=$(get_all_version_components "${1:-${PV}}")
104         echo ${c//[-._]/ }
105 }
106
107 # @FUNCTION: get_major_version
108 # @USAGE: [version]
109 # @DESCRIPTION:
110 # Get the major version of a value. Defaults to $PV if no parameter is supplied.
111 #     0.8.3       ->  0
112 #     7c          ->  7
113 #     3.0_p2      ->  3
114 #     20040905    ->  20040905
115 #     3.0c-r1     ->  3
116 get_major_version() {
117         local c=($(get_all_version_components "${1:-${PV}}"))
118         echo ${c[0]}
119 }
120
121 # @FUNCTION: get_version_component_range
122 # @USAGE: <range> [version]
123 # @DESCRIPTION:
124 # Get a particular component or range of components from the version. If no
125 # version parameter is supplied, defaults to $PV.
126 #    1      1.2.3       -> 1
127 #    1-2    1.2.3       -> 1.2
128 #    2-     1.2.3       -> 2.3
129 get_version_component_range() {
130         eshopts_push -s extglob
131         local c v="${2:-${PV}}" range="${1}" range_start range_end
132         local -i i=-1 j=0
133         c=($(get_all_version_components "${v}"))
134         range_start=${range%-*}; range_start=${range_start:-1}
135         range_end=${range#*-}  ; range_end=${range_end:-${#c[@]}}
136
137         while ((j < range_start)); do
138                 i+=1
139                 ((i > ${#c[@]})) && eshopts_pop && return
140                 [[ -n "${c[i]//[-._]}" ]] && j+=1
141         done
142
143         while ((j <= range_end)); do
144                 echo -n ${c[i]}
145                 ((i > ${#c[@]})) && eshopts_pop && return
146                 [[ -n "${c[i]//[-._]}" ]] && j+=1
147                 i+=1
148         done
149         eshopts_pop
150 }
151
152 # @FUNCTION: get_after_major_version
153 # @USAGE: [version]
154 # @DESCRIPTION:
155 # Get everything after the major version and its separator (if present) of a
156 # value. Defaults to $PV if no parameter is supplied.
157 #     0.8.3       ->  8.3
158 #     7c          ->  c
159 #     3.0_p2      ->  0_p2
160 #     20040905    ->  (empty string)
161 #     3.0c-r1     ->  0c-r1
162 get_after_major_version() {
163         echo $(get_version_component_range 2- "${1:-${PV}}")
164 }
165
166 # @FUNCTION: replace_version_separator
167 # @USAGE: <search> <replacement> [subject]
168 # @DESCRIPTION:
169 # Replace the $1th separator with $2 in $3 (defaults to $PV if $3 is not
170 # supplied). If there are fewer than $1 separators, don't change anything.
171 #     1 '_' 1.2.3       -> 1_2.3
172 #     2 '_' 1.2.3       -> 1.2_3
173 #     1 '_' 1b-2.3      -> 1b_2.3
174 # Rather than being a number, $1 can be a separator character such as '-', '.'
175 # or '_'. In this case, the first separator of this kind is selected.
176 replace_version_separator() {
177         eshopts_push -s extglob
178         local w c v="${3:-${PV}}"
179         declare -i i found=0
180         w=${1:-1}
181         c=($(get_all_version_components ${v}))
182         if [[ ${w} != *[[:digit:]]* ]] ; then
183                 # it's a character, not an index
184                 for ((i = 0; i < ${#c[@]}; i++)); do
185                         if [[ ${c[i]} == ${w} ]]; then
186                                 c[i]=${2}
187                                 break
188                         fi
189                 done
190         else
191                 for ((i = 0; i < ${#c[@]}; i++)); do
192                         if [[ -n "${c[i]//[^-._]}" ]]; then
193                                 found+=1
194                                 if ((found == w)); then
195                                         c[i]=${2}
196                                         break
197                                 fi
198                         fi
199                 done
200         fi
201         c=${c[*]}
202         echo ${c// }
203         eshopts_pop
204 }
205
206 # @FUNCTION: replace_all_version_separators
207 # @USAGE: <replacement> [subject]
208 # @DESCRIPTION:
209 # Replace all version separators in $2 (defaults to $PV) with $1.
210 #     '_' 1b.2.3        -> 1b_2_3
211 replace_all_version_separators() {
212         local c=($(get_all_version_components "${2:-${PV}}"))
213         c=${c[@]//[-._]/$1}
214         echo ${c// }
215 }
216
217 # @FUNCTION: delete_version_separator
218 # @USAGE: <search> [subject]
219 # @DESCRIPTION:
220 # Delete the $1th separator in $2 (defaults to $PV if $2 is not supplied). If
221 # there are fewer than $1 separators, don't change anything.
222 #     1 1.2.3       -> 12.3
223 #     2 1.2.3       -> 1.23
224 #     1 1b-2.3      -> 1b2.3
225 # Rather than being a number, $1 can be a separator character such as '-', '.'
226 # or '_'. In this case, the first separator of this kind is deleted.
227 delete_version_separator() {
228         replace_version_separator "${1}" "" "${2}"
229 }
230
231 # @FUNCTION: delete_all_version_separators
232 # @USAGE: [subject]
233 # @DESCRIPTION:
234 # Delete all version separators in $1 (defaults to $PV).
235 #     1b.2.3        -> 1b23
236 delete_all_version_separators() {
237         replace_all_version_separators "" "${1}"
238 }
239
240 # @FUNCTION: get_version_component_count
241 # @USAGE: [version]
242 # @DESCRIPTION:
243 # How many version components are there in $1 (defaults to $PV)?
244 #     1.0.1       ->  3
245 #     3.0c-r1     ->  4
246 get_version_component_count() {
247         local a=($(get_version_components "${1:-${PV}}"))
248         echo ${#a[@]}
249 }
250
251 # @FUNCTION: get_last_version_component_index
252 # @USAGE: [version]
253 # @DESCRIPTION:
254 # What is the index of the last version component in $1 (defaults to $PV)?
255 # Equivalent to get_version_component_count - 1.
256 #     1.0.1       ->  2
257 #     3.0c-r1     ->  3
258 get_last_version_component_index() {
259         echo $(($(get_version_component_count "${1:-${PV}}" ) - 1))
260 }
261
262 # @FUNCTION: version_is_at_least
263 # @USAGE: <want> [have]
264 # @DESCRIPTION:
265 # Is $2 (defaults to $PVR) at least version $1? Intended for use in eclasses
266 # only. May not be reliable, be sure to do very careful testing before actually
267 # using this.
268 version_is_at_least() {
269         local want_s="$1" have_s="${2:-${PVR}}" r
270         version_compare "${want_s}" "${have_s}"
271         r=$?
272         case $r in
273                 1|2)
274                         return 0
275                         ;;
276                 3)
277                         return 1
278                         ;;
279                 *)
280                         die "versionator compare bug [atleast, ${want_s}, ${have_s}, ${r}]"
281                         ;;
282         esac
283 }
284
285 # @FUNCTION: version_compare
286 # @USAGE: <A> <B>
287 # @DESCRIPTION:
288 # Takes two parameters (A, B) which are versions. If A is an earlier version
289 # than B, returns 1. If A is identical to B, return 2. If A is later than B,
290 # return 3. You probably want version_is_at_least rather than this function.
291 # May not be very reliable. Test carefully before using this.
292 version_compare() {
293         eshopts_push -s extglob
294         local ver_a=${1} ver_b=${2} parts_a parts_b
295         local cur_tok_a cur_tok_b num_part_a num_part_b
296         local -i cur_idx_a=0 cur_idx_b=0 prev_idx_a prev_idx_b
297         parts_a=( $(get_all_version_components "${ver_a}" ) )
298         parts_b=( $(get_all_version_components "${ver_b}" ) )
299
300         ### compare number parts.
301         local -i inf_loop=0
302         while true; do
303                 inf_loop+=1
304                 ((inf_loop > 20)) && \
305                         die "versionator compare bug [numbers, ${ver_a}, ${ver_b}]"
306
307                 # Store the current index to test later
308                 prev_idx_a=cur_idx_a
309                 prev_idx_b=cur_idx_b
310
311                 # grab the current number components
312                 cur_tok_a=${parts_a[cur_idx_a]}
313                 cur_tok_b=${parts_b[cur_idx_b]}
314
315                 # number?
316                 if [[ -n ${cur_tok_a} ]] && [[ -z ${cur_tok_a//[[:digit:]]} ]] ; then
317                         cur_idx_a+=1
318                         [[ ${parts_a[cur_idx_a]} == . ]] \
319                                 && cur_idx_a+=1
320                 else
321                         cur_tok_a=
322                 fi
323
324                 if [[ -n ${cur_tok_b} ]] && [[ -z ${cur_tok_b//[[:digit:]]} ]] ; then
325                         cur_idx_b+=1
326                         [[ ${parts_b[cur_idx_b]} == . ]] \
327                                 && cur_idx_b+=1
328                 else
329                         cur_tok_b=
330                 fi
331
332                 # done with number components?
333                 [[ -z ${cur_tok_a} && -z ${cur_tok_b} ]] && break
334
335                 # if a component is blank, then it is the lesser value
336                 [[ -z ${cur_tok_a} ]] && eshopts_pop && return 1
337                 [[ -z ${cur_tok_b} ]] && eshopts_pop && return 3
338
339                 # According to PMS, if we are *not* in the first number part, and either
340                 # token begins with "0", then we use a different algorithm (that
341                 # effectively does floating point comparison)
342                 if (( prev_idx_a != 0 && prev_idx_b != 0 )) \
343                         && [[ ${cur_tok_a} == 0* || ${cur_tok_b} == 0* ]] ; then
344
345                         # strip trailing zeros
346                         cur_tok_a=${cur_tok_a%%+(0)}
347                         cur_tok_b=${cur_tok_b%%+(0)}
348
349                         # do a *string* comparison of the resulting values: 2 > 11
350                         [[ ${cur_tok_a} < ${cur_tok_b} ]] && eshopts_pop && return 1
351                         [[ ${cur_tok_a} > ${cur_tok_b} ]] && eshopts_pop && return 3
352                 else
353                         # to avoid going into octal mode, strip any leading zeros. otherwise
354                         # bash will throw a hissy fit on versions like 6.3.068.
355                         cur_tok_a=${cur_tok_a##+(0)}
356                         cur_tok_b=${cur_tok_b##+(0)}
357
358                         # now if a component is blank, it was originally 0 -- make it so
359                         : ${cur_tok_a:=0}
360                         : ${cur_tok_b:=0}
361
362                         # compare
363                         ((cur_tok_a < cur_tok_b)) && eshopts_pop && return 1
364                         ((cur_tok_a > cur_tok_b)) && eshopts_pop && return 3
365                 fi
366         done
367
368         ### number parts equal. compare letter parts.
369         local letter_a=
370         letter_a=${parts_a[cur_idx_a]}
371         if [[ ${#letter_a} -eq 1 && -z ${letter_a/[a-z]} ]] ; then
372                 cur_idx_a+=1
373         else
374                 letter_a=@
375         fi
376
377         local letter_b=
378         letter_b=${parts_b[cur_idx_b]}
379         if [[ ${#letter_b} -eq 1 && -z ${letter_b/[a-z]} ]] ; then
380                 cur_idx_b+=1
381         else
382                 letter_b=@
383         fi
384
385         # compare
386         [[ ${letter_a} < ${letter_b} ]] && eshopts_pop && return 1
387         [[ ${letter_a} > ${letter_b} ]] && eshopts_pop && return 3
388
389         ### letter parts equal. compare suffixes in order.
390         inf_loop=0
391         while true ; do
392                 inf_loop+=1
393                 ((inf_loop > 20)) && \
394                         die "versionator compare bug [numbers, ${ver_a}, ${ver_b}]"
395                 [[ ${parts_a[cur_idx_a]} == _ ]] && ((cur_idx_a++))
396                 [[ ${parts_b[cur_idx_b]} == _ ]] && ((cur_idx_b++))
397
398                 cur_tok_a=${parts_a[cur_idx_a]}
399                 cur_tok_b=${parts_b[cur_idx_b]}
400                 num_part_a=0
401                 num_part_b=0
402
403                 if has ${cur_tok_a%%+([0-9])} "alpha" "beta" "pre" "rc" "p"; then
404                         cur_idx_a+=1
405                         num_part_a=${cur_tok_a##+([a-z])}
406                         # I don't like octal
407                         num_part_a=${num_part_a##+(0)}
408                         : ${num_part_a:=0}
409                         cur_tok_a=${cur_tok_a%%+([0-9])}
410                 else
411                         cur_tok_a=
412                 fi
413
414                 if has ${cur_tok_b%%+([0-9])} alpha beta pre rc p; then
415                         cur_idx_b+=1
416                         num_part_b=${cur_tok_b##+([a-z])}
417                         # I still don't like octal
418                         num_part_b=${num_part_b##+(0)}
419                         : ${num_part_b:=0}
420                         cur_tok_b=${cur_tok_b%%+([0-9])}
421                 else
422                         cur_tok_b=
423                 fi
424
425                 if [[ ${cur_tok_a} != ${cur_tok_b} ]]; then
426                         local suffix
427                         for suffix in alpha beta pre rc "" p; do
428                                 [[ ${cur_tok_a} == ${suffix} ]] && eshopts_pop && return 1
429                                 [[ ${cur_tok_b} == ${suffix} ]] && eshopts_pop && return 3
430                         done
431                 elif [[ -z ${cur_tok_a} && -z ${cur_tok_b} ]]; then
432                         break
433                 else
434                         ((num_part_a < num_part_b)) && eshopts_pop && return 1
435                         ((num_part_a > num_part_b)) && eshopts_pop && return 3
436                 fi
437         done
438
439         # At this point, the only thing that should be left is the -r# part
440         [[ ${parts_a[cur_idx_a]} == - ]] && ((cur_idx_a++))
441         [[ ${parts_b[cur_idx_b]} == - ]] && ((cur_idx_b++))
442
443         # Sanity check
444         if [[ ${parts_a[cur_idx_a]/r+([0-9])} || ${parts_b[cur_idx_b]/r+([0-9])} ]]; then
445                 die "versionator compare bug [revisions, ${ver_a}, ${ver_b}]"
446         fi
447
448         num_part_a=${parts_a[cur_idx_a]#r}
449         num_part_a=${num_part_a##+(0)}
450         : ${num_part_a:=0}
451         num_part_b=${parts_b[cur_idx_b]#r}
452         num_part_b=${num_part_b##+(0)}
453         : ${num_part_b:=0}
454
455         ((num_part_a < num_part_b)) && eshopts_pop && return 1
456         ((num_part_a > num_part_b)) && eshopts_pop && return 3
457
458         ### no differences.
459         eshopts_pop
460         return 2
461 }
462
463 # @FUNCTION: version_sort
464 # @USAGE: <version> [more versions...]
465 # @DESCRIPTION:
466 # Returns its parameters sorted, highest version last. We're using a quadratic
467 # algorithm for simplicity, so don't call it with more than a few dozen items.
468 # Uses version_compare, so be careful.
469 version_sort() {
470         eshopts_push -s extglob
471         local items=
472         local -i left=0
473         items=("$@")
474         while ((left < ${#items[@]})); do
475                 local -i lowest_idx=left
476                 local -i idx=lowest_idx+1
477                 while ((idx < ${#items[@]})); do
478                         version_compare "${items[lowest_idx]}" "${items[idx]}"
479                         [[ $? -eq 3 ]] && lowest_idx=idx
480                         idx+=1
481                 done
482                 local tmp=${items[lowest_idx]}
483                 items[lowest_idx]=${items[left]}
484                 items[left]=${tmp}
485                 left+=1
486         done
487         echo ${items[@]}
488         eshopts_pop
489 }
490
491 # @FUNCTION: version_format_string
492 # @USAGE: <format> [version]
493 # @DESCRIPTION:
494 # Reformat complicated version strings.  The first argument is the string
495 # to reformat with while the rest of the args are passed on to the
496 # get_version_components function.  You should make sure to single quote
497 # the first argument since it'll have variables that get delayed expansions.
498 # @EXAMPLE:
499 # P="cow-hat-1.2.3_p4"
500 # MY_P=$(version_format_string '${PN}_source_$1_$2-$3_$4')
501 # Now MY_P will be: cow-hat_source_1_2-3_p4
502 version_format_string() {
503         local fstr=$1
504         shift
505         set -- $(get_version_components "$@")
506         eval echo "${fstr}"
507 }
508
509 fi