1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2 
3 #include <stdio.h>
4 
5 #include "sd-id128.h"
6 
7 #include "alloc-util.h"
8 #include "id128-print.h"
9 #include "log.h"
10 #include "pretty-print.h"
11 #include "terminal-util.h"
12 
id128_pretty_print_sample(const char * name,sd_id128_t id)13 int id128_pretty_print_sample(const char *name, sd_id128_t id) {
14        _cleanup_free_ char *man_link = NULL, *mod_link = NULL;
15         const char *on, *off;
16         unsigned i;
17 
18         on = ansi_highlight();
19         off = ansi_normal();
20 
21         if (terminal_urlify("man:systemd-id128(1)", "systemd-id128(1)", &man_link) < 0)
22                 return log_oom();
23 
24         if (terminal_urlify("https://docs.python.org/3/library/uuid.html", "uuid", &mod_link) < 0)
25                 return log_oom();
26 
27         printf("As string:\n"
28                "%s" SD_ID128_FORMAT_STR "%s\n\n"
29                "As UUID:\n"
30                "%s" SD_ID128_UUID_FORMAT_STR "%s\n\n"
31                "As %s macro:\n"
32                "%s#define %s SD_ID128_MAKE(",
33                on, SD_ID128_FORMAT_VAL(id), off,
34                on, SD_ID128_FORMAT_VAL(id), off,
35                man_link,
36                on, name);
37         for (i = 0; i < 16; i++)
38                 printf("%02x%s", id.bytes[i], i != 15 ? "," : "");
39         printf(")%s\n\n", off);
40 
41         printf("As Python constant:\n"
42                ">>> import %s\n"
43                ">>> %s%s = uuid.UUID('" SD_ID128_FORMAT_STR "')%s\n",
44                mod_link,
45                on, name, SD_ID128_FORMAT_VAL(id), off);
46 
47         return 0;
48 }
49 
50 
id128_pretty_print(sd_id128_t id,Id128PrettyPrintMode mode)51 int id128_pretty_print(sd_id128_t id, Id128PrettyPrintMode mode) {
52         assert(mode >= 0);
53         assert(mode < _ID128_PRETTY_PRINT_MODE_MAX);
54 
55         if (mode == ID128_PRINT_ID128) {
56                 printf(SD_ID128_FORMAT_STR "\n",
57                        SD_ID128_FORMAT_VAL(id));
58                 return 0;
59         } else if (mode == ID128_PRINT_UUID) {
60                 printf(SD_ID128_UUID_FORMAT_STR "\n",
61                        SD_ID128_FORMAT_VAL(id));
62                 return 0;
63         } else
64                 return id128_pretty_print_sample("XYZ", id);
65 }
66 
id128_print_new(Id128PrettyPrintMode mode)67 int id128_print_new(Id128PrettyPrintMode mode) {
68         sd_id128_t id;
69         int r;
70 
71         r = sd_id128_randomize(&id);
72         if (r < 0)
73                 return log_error_errno(r, "Failed to generate ID: %m");
74 
75         return id128_pretty_print(id, mode);
76 }
77