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