Directory: | src/ |
---|---|
File: | src/cmd_line.c |
Date: | 2024-04-25 03:45:42 |
Exec | Total | Coverage | |
---|---|---|---|
Lines: | 28 | 31 | 90.3% |
Branches: | 7 | 14 | 50.0% |
Line | Branch | Exec | Source |
---|---|---|---|
1 | /* | ||
2 | * Copyright (c) 2023 Egor Tensin <egor@tensin.name> | ||
3 | * This file is part of the "cimple" project. | ||
4 | * For details, see https://github.com/egor-tensin/cimple. | ||
5 | * Distributed under the MIT License. | ||
6 | */ | ||
7 | |||
8 | #include "cmd_line.h" | ||
9 | #include "const.h" | ||
10 | #include "file.h" | ||
11 | #include "log.h" | ||
12 | |||
13 | #include <stdio.h> | ||
14 | #include <stdlib.h> | ||
15 | #include <string.h> | ||
16 | |||
17 | 20 | static char *get_current_binary_path(void) | |
18 | { | ||
19 | 20 | return my_readlink("/proc/self/exe"); | |
20 | } | ||
21 | |||
22 | 20 | static char *get_current_binary_name(void) | |
23 | { | ||
24 | 20 | char *path = get_current_binary_path(); | |
25 |
1/2✗ Branch 0 not taken.
✓ Branch 1 taken 20 times.
|
20 | if (!path) |
26 | ✗ | return NULL; | |
27 | |||
28 | 20 | char *name = basename(path); | |
29 | |||
30 | 20 | char *result = strdup(name); | |
31 |
1/2✓ Branch 0 taken 20 times.
✗ Branch 1 not taken.
|
20 | if (!result) { |
32 | ✗ | log_errno("strdup"); | |
33 | ✗ | goto free_path; | |
34 | } | ||
35 | |||
36 | 20 | free_path: | |
37 | 20 | free(path); | |
38 | |||
39 | 20 | return result; | |
40 | } | ||
41 | |||
42 | 14 | void exit_with_usage(int ec) | |
43 | { | ||
44 | 14 | FILE *dest = stdout; | |
45 |
2/2✓ Branch 0 taken 8 times.
✓ Branch 1 taken 6 times.
|
14 | if (ec) |
46 | 8 | dest = stderr; | |
47 | |||
48 | 14 | char *binary = get_current_binary_name(); | |
49 | |||
50 |
1/2✓ Branch 1 taken 14 times.
✗ Branch 2 not taken.
|
14 | fprintf(dest, "usage: %s %s\n", binary ? binary : "prog", get_usage_string()); |
51 | 14 | free(binary); | |
52 | 14 | exit(ec); | |
53 | } | ||
54 | |||
55 | 2 | void exit_with_usage_err(const char *msg) | |
56 | { | ||
57 |
1/2✓ Branch 0 taken 2 times.
✗ Branch 1 not taken.
|
2 | if (msg) |
58 | 2 | fprintf(stderr, "usage error: %s\n", msg); | |
59 | 2 | exit_with_usage(1); | |
60 | } | ||
61 | |||
62 | 6 | void exit_with_version(void) | |
63 | { | ||
64 | 6 | char *binary = get_current_binary_name(); | |
65 | |||
66 |
1/2✓ Branch 0 taken 6 times.
✗ Branch 1 not taken.
|
6 | printf("%s v%s (%s)\n", binary ? binary : "prog", project_version, project_rev); |
67 | 6 | free(binary); | |
68 | 6 | exit(0); | |
69 | } | ||
70 |