aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/src/cmd_line.c
blob: 35b27a7933f773cbb34021ef50e86bb35081196d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/*
 * Copyright (c) 2023 Egor Tensin <egor@tensin.name>
 * This file is part of the "cimple" project.
 * For details, see https://github.com/egor-tensin/cimple.
 * Distributed under the MIT License.
 */

#include "cmd_line.h"
#include "const.h"
#include "file.h"
#include "log.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static char *get_current_binary_path(void)
{
	return my_readlink("/proc/self/exe");
}

static char *get_current_binary_name(void)
{
	char *path = get_current_binary_path();
	if (!path)
		return NULL;

	char *name = basename(path);

	char *result = strdup(name);
	if (!result) {
		log_errno("strdup");
		goto free_path;
	}

free_path:
	free(path);

	return result;
}

void exit_with_usage(int ec)
{
	FILE *dest = stdout;
	if (ec)
		dest = stderr;

	char *binary = get_current_binary_name();

	fprintf(dest, "usage: %s %s\n", binary ? binary : "prog", get_usage_string());
	free(binary);
	exit(ec);
}

void exit_with_usage_err(const char *msg)
{
	if (msg)
		fprintf(stderr, "usage error: %s\n", msg);
	exit_with_usage(1);
}

void exit_with_version(void)
{
	char *binary = get_current_binary_name();

	printf("%s v%s (%s)\n", binary ? binary : "prog", project_version, project_rev);
	free(binary);
	exit(0);
}