aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/src/cmd_line.c
blob: fee18d422bbd07e27d19de9228a1a9b06aea8e2f (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
70
71
72
73
/*
 * Copyright (c) 2023 Egor Tensin <Egor.Tensin@gmail.com>
 * 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 "file.h"
#include "log.h"

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

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

static char *get_current_binary_name()
{
	char *path, *name, *result;

	path = get_current_binary_path();
	if (!path)
		return NULL;

	name = basename(path);

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

free_path:
	free(path);

	return result;
}

void exit_with_usage(int ec)
{
	char *binary;
	FILE *dest;

	dest = stdout;
	if (ec)
		dest = stderr;

	binary = get_current_binary_name();

	fprintf(dest, "usage: %s %s\n", 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()
{
	char *binary = get_current_binary_name();

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