aboutsummaryrefslogtreecommitdiff
path: root/toys/posix/ln.c
blob: d69aabf43d0b30f80a13f3cda8f822b5f0f29d01 (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
/* ln.c - Create filesystem links
 *
 * Copyright 2012 Andre Renaud <andre@bluewatersys.com>
 *
 * See http://opengroup.org/onlinepubs/9699919799/utilities/ln.html

USE_LN(NEWTOY(ln, "<1nfs", TOYFLAG_BIN))

config LN
  bool "ln"
  default y
  help
    usage: ln [-sfn] [FROM...] TO

    Create a link between FROM and TO.
    With only one argument, create link in current directory.

    -s	Create a symbolic link
    -f	Force the creation of the link, even if TO already exists
    -n	Symlink at destination treated as file
*/

#define FOR_ln
#include "toys.h"

void ln_main(void)
{
  char *dest = toys.optargs[--toys.optc], *new;
  struct stat buf;
  int i;

  // With one argument, create link in current directory.
  if (!toys.optc) {
    toys.optc++;
    dest=".";
  }

  // Is destination a directory?
  if (((toys.optflags&FLAG_n) ? lstat : stat)(dest, &buf)
    || !S_ISDIR(buf.st_mode))
  {
    if (toys.optc>1) error_exit("'%s' not a directory");
    buf.st_mode = 0;
  }

  for (i=0; i<toys.optc; i++) {
    int rc;
    char *try = toys.optargs[i];

    if (S_ISDIR(buf.st_mode)) new = xmsprintf("%s/%s", dest, basename(try));
    else new = dest;
    /* Silently unlink the existing target. If it doesn't exist,
     * then we just move on */
    if (toys.optflags & FLAG_f) unlink(new);

    rc = (toys.optflags & FLAG_s) ? symlink(try, new) : link(try, new);
    if (rc)
      perror_exit("cannot create %s link from '%s' to '%s'",
        (toys.optflags & FLAG_s) ? "symbolic" : "hard", try, new);
    if (new != dest) free(new);
  }
}