Debian Codegraph @

src/analyze/analyze-compare-versions.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <stdio.h>
4
5 #include "analyze-compare-versions.h"
6 #include "compare-operator.h"
7 #include "log.h"
8 #include "string-util.h"
9
10 int verb_compare_versions(int argc, char *argv[], uintptr_t _data, void *userdata) {
11 const char *v1 = ASSERT_PTR(argv[1]), *v2 = ASSERT_PTR(argv[argc-1]);
12 int r;
13
14 assert(IN_SET(argc, 3, 4));
15 assert(argv);
16
17 /* We only output a warning on invalid version strings (instead of failing), since the comparison
18 * functions try to handle invalid strings gracefully and it's still interesting to see what the
19 * comparison result will be. */
20 if (!version_is_valid_versionspec(v1))
21 log_warning("Version string 1 contains disallowed characters, they will be treated as separators: %s", v1);
22 if (!version_is_valid_versionspec(v2))
23 log_warning("Version string 2 contains disallowed characters, they will be treated as separators: %s", v2);
24
25 if (argc == 3) {
26 r = strverscmp_improved(v1, v2);
27 printf("%s %s %s\n",
28 isempty(v1) ? "''" : v1,
29 comparison_operator(r),
30 isempty(v2) ? "''" : v2);
31
32 /* This matches the exit convention used by rpmdev-vercmp.
33 * We don't use named values because 11 and 12 don't have names. */
34 return r < 0 ? 12 : r > 0 ? 11 : 0;
35
36 } else {
37 const char *op = ASSERT_PTR(argv[2]);
38 CompareOperator operator;
39 assert(argc == 4);
40
41 operator = parse_compare_operator(&op, COMPARE_ALLOW_TEXTUAL);
42 if (operator < 0 || !isempty(op))
43 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Unknown operator \"%s\".", op);
44
45 r = version_or_fnmatch_compare(operator, v1, v2);
46 if (r < 0)
47 return log_error_errno(r, "Failed to compare versions: %m");
48
49 return r ? EXIT_SUCCESS : EXIT_FAILURE;
50 }
51 }