aboutsummaryrefslogtreecommitdiff
path: root/toys/other/readlink.c
blob: bae09536f7d679b94df6b5a5c329c43c78cb5e3b (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
/* readlink.c - Return string representation of a symbolic link.
 *
 * Copyright 2007 Rob Landley <rob@landley.net>

USE_READLINK(NEWTOY(readlink, "<1nqmef(canonicalize)[-mef]", TOYFLAG_USR|TOYFLAG_BIN))
USE_REALPATH(NEWTOY(realpath, "<1", TOYFLAG_USR|TOYFLAG_BIN))

config READLINK
  bool "readlink"
  default y
  help
    usage: readlink FILE...

    With no options, show what symlink points to, return error if not symlink.

    Options for producing canonical paths (all symlinks/./.. resolved):

    -e	Canonical path to existing entry (fail if missing)
    -f	Full path (fail if directory missing)
    -m	Ignore missing entries, show where it would be
    -n	No trailing newline
    -q	Quiet (no output, just error code)

config REALPATH
  bool "realpath"
  default y
  help
    usage: realpath FILE...

    Display the canonical absolute pathname
*/

#define FOR_readlink
#define FORCE_FLAGS
#include "toys.h"

void readlink_main(void)
{
  char **arg, *s;

  for (arg = toys.optargs; *arg; arg++) {
    // Calculating full canonical path?
    // Take advantage of flag positions to calculate m = -1, f = 0, e = 1
    if (toys.optflags & (FLAG_f|FLAG_e|FLAG_m))
      s = xabspath(*arg, (toys.optflags&(FLAG_f|FLAG_e))-1);
    else s = xreadlink(*arg);

    if (s) {
      if (!FLAG(q)) xprintf(FLAG(n) ? "%s" : "%s\n", s);
      if (CFG_TOYBOX_FREE) free(s);
    } else toys.exitval = 1;
  }
}

void realpath_main(void)
{
  toys.optflags = FLAG_f;
  readlink_main();
}