aboutsummaryrefslogtreecommitdiff
path: root/lib/compat/getopt.c
blob: 23ede4c5fd7b6031b943c4476b54d7274b5649be (plain)
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
/* SPDX-License-Identifier: GPL-3.0-or-later */
/*
 * getopt.c
 *
 * Copyright (C) 2019 David Oberhollenzer <goliath@infraroot.at>
 */
#include "config.h"
#include "compat.h"

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

#ifndef HAVE_GETOPT
static char *current = "";
int optind = 1;
char *optarg = NULL;

int getopt(int argc, char *const argv[], const char *optstr)
{
	char optchr, *ptr;

	if (*current == '\0') {
		if (optind >= argc || argv[optind][0] != '-')
			return -1;

		if (argv[optind][1] == '-' && argv[optind][2] == '\0') {
			++optind;
			return -1;
		}

		if (argv[optind][1] == '\0')
			return -1;

		current = argv[optind] + 1;
	}

	optchr = *(current++);
	if (optchr == ':' || (ptr = strchr(optstr, optchr)) == NULL)
		goto fail_unknown;

	if (ptr[1] == ':') {
		if (*current != '\0') {
			optarg = current;
		} else {
			if (++optind >= argc)
				goto fail_arg;

			optarg = argv[optind];
		}

		current = "";
		++optind;
	} else {
		optarg = NULL;

		if (*current == '\0')
			++optind;
	}

	return optchr;
fail_unknown:
	fprintf(stderr, "%s: unknown option `-%c`\n", argv[0], optchr);
	return '?';
fail_arg:
	fprintf(stderr, "%s: missing argument for option `-%c`\n",
		argv[0], optchr);
	return '?';
}
#endif