aboutsummaryrefslogtreecommitdiffstats
path: root/regular_builtins.c
blob: 5cdb4fec6420ccf4c1f612e7624d46460963a907 (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
/* See LICENSE file for copyright and license details. */
#include "common.h"


int
true_main(int argc, char **argv)
{
	(void) argc;
	(void) argv;
	return 0;
}


int
false_main(int argc, char **argv)
{
	(void) argc;
	(void) argv;
	return 1;
}


BUILTIN_USAGE(pwd_usage, "[-L | -P]")
int
pwd_main(int argc, char **argv)
{
	void (*usage)(void) = pwd_usage;
        int physical = 0;
        char *cwd = NULL;
        size_t size = 64 / 2;
        const char *pwd;
	struct stat cst, pst;

	ARGBEGIN {
	case 'L':
		physical = 0;
		break;
	case 'P':
		physical = 1;
		break;
	default:
		usage();
	} ARGEND;

	if (argc)
		weprintf("ignoring operands"); /* other implementations either warn or are silent, they don't fail */

	for (;;) {
		cwd = erealloc(cwd, size *= 2);
		if (getcwd(cwd, size))
			break;
		if (errno != ERANGE)
			eprintf("getcwd %zu:", size);
	}

	if (physical || !(pwd = getenv("PWD")) || *pwd != '/' || stat(pwd, &pst) || stat(cwd, &cst))
		puts(cwd);
	else if (pst.st_dev == cst.st_dev && pst.st_ino == cst.st_ino)
		puts(pwd);
	else
		puts(cwd);

	free(cwd);
	if (fflush(stdout) || ferror(stdout))
		weprintf("fflush <stdout>:");
	return 0;
}