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