Attached is a mergeable version.
I'd be inclined to include this in the
imminent release given the unlikely impact
on existing code?

cheers,
Pádraig.
>From d8889826af3f5eec1e19ef10f964c9b037f4b5a5 Mon Sep 17 00:00:00 2001
From: Harald Hoyer <[email protected]>
Date: Thu, 23 Feb 2012 20:50:27 +0100
Subject: [PATCH] ln: add the --relative option
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

With the "--relative --symbolic" options, ln computes the relative
symbolic link for the user.

So, ln works just as cp, but creates relative symbolic links instead
of copying the file.

I miss this feature since the beginning of using ln.

$ tree ./
/
`-- usr
    |-- bin
    `-- lib
        `-- foo
            `-- foo

4 directories, 1 file

$ ln -s -v --relative usr/lib/foo/foo usr/bin/foo
‘usr/bin/foo’ -> ‘../lib/foo/foo’

$ tree ./
/
`-- usr
    |-- bin
    |   `-- foo -> ../lib/foo/foo
    `-- lib
        `-- foo
            `-- foo

4 directories, 2 files

$ ln -s -v --relative usr/bin/foo usr/lib/foo/link-to-foo
‘usr/lib/foo/link-to-foo’ -> ‘foo’

$ tree ./
/
`-- usr
    |-- bin
    |   `-- foo -> ../lib/foo/foo
    `-- lib
        `-- foo
            |-- link-to-foo -> foo
            `-- foo

4 directories, 3 files

* src/relpath.c: Refactored from realpath.c and adjusted
to support returning the relative path rather than just outputting.
* src/relpath.h: Export the relpath function.
* src/Makefile.am: Reference the refactored relpath module.
* po/POTFILES.in: Likewise.
* src/ln.c (usage): Mention the new option.
(do_link): Call the relative conversion is specified.
(convert_abs_rel): Perform the relative conversion
using the refactored relpath module.
* src/realpath.c: Adjust to the refactored relpath module.
* tests/ln/relative: Add a new test.
* tests/Makefile.am: Reference the new test.
* doc/coreutils.texi: Document the new feature.
* NEWS: Mention the new feature.
---
 NEWS               |    3 +
 doc/coreutils.texi |    8 +++
 po/POTFILES.in     |    1 +
 src/Makefile.am    |    2 +
 src/ln.c           |   56 +++++++++++++++++++++-
 src/realpath.c     |   96 ++-----------------------------------
 src/relpath.c      |  134 ++++++++++++++++++++++++++++++++++++++++++++++++++++
 src/relpath.h      |   25 ++++++++++
 tests/Makefile.am  |    1 +
 tests/ln/relative  |   32 ++++++++++++
 10 files changed, 265 insertions(+), 93 deletions(-)
 create mode 100644 src/relpath.c
 create mode 100644 src/relpath.h
 create mode 100755 tests/ln/relative

diff --git a/NEWS b/NEWS
index 5b53eb8..0fe75e5 100644
--- a/NEWS
+++ b/NEWS
@@ -25,6 +25,9 @@ GNU coreutils NEWS                                    -*- outline -*-
   dd now accepts the conv=sparse flag to attempt to create sparse
   output, by seeking rather than writing to the output file.
 
+  ln now accepts the --relative option, to generate relative
+  symbolic links to a target, irrespective of how the target is specified.
+
   split now accepts an optional "from" argument to --numeric-suffixes,
   which changes the start number from the default of 0.
 
diff --git a/doc/coreutils.texi b/doc/coreutils.texi
index 10be715..a8ed050 100644
--- a/doc/coreutils.texi
+++ b/doc/coreutils.texi
@@ -9389,6 +9389,14 @@ symbolic link with identical contents; since symbolic link contents
 cannot be edited, any file name resolution performed through either
 link will be the same as if a hard link had been created.
 
+@item -r
+@itemx --relative
+@opindex -r
+@opindex --relative
+Make symbolic links relative to the link location.
+@xref{realpath invocation}, which gives greater control
+over relative path generation.
+
 @item -s
 @itemx --symbolic
 @opindex -s
diff --git a/po/POTFILES.in b/po/POTFILES.in
index c92dd3c..7b3de0b 100644
--- a/po/POTFILES.in
+++ b/po/POTFILES.in
@@ -103,6 +103,7 @@ src/ptx.c
 src/pwd.c
 src/readlink.c
 src/realpath.c
+src/relpath.c
 src/remove.c
 src/rm.c
 src/rmdir.c
diff --git a/src/Makefile.am b/src/Makefile.am
index b124064..06ab615 100644
--- a/src/Makefile.am
+++ b/src/Makefile.am
@@ -474,9 +474,11 @@ vdir_SOURCES = ls.c ls-vdir.c
 id_SOURCES = id.c group-list.c
 groups_SOURCES = groups.c group-list.c
 ls_SOURCES = ls.c ls-ls.c
+ln_SOURCES = ln.c relpath.c relpath.h
 chown_SOURCES = chown.c chown-core.c
 chgrp_SOURCES = chgrp.c chown-core.c
 kill_SOURCES = kill.c operand2sig.c
+realpath_SOURCES = realpath.c relpath.c relpath.h
 timeout_SOURCES = timeout.c operand2sig.c
 
 mv_SOURCES = mv.c remove.c $(copy_sources)
diff --git a/src/ln.c b/src/ln.c
index d984fd7..95b3be3 100644
--- a/src/ln.c
+++ b/src/ln.c
@@ -29,8 +29,10 @@
 #include "hash.h"
 #include "hash-triple.h"
 #include "quote.h"
+#include "relpath.h"
 #include "same.h"
 #include "yesno.h"
+#include "canonicalize.h"
 
 /* The official name of this program (e.g., no 'g' prefix).  */
 #define PROGRAM_NAME "ln"
@@ -45,6 +47,9 @@ static enum backup_type backup_type;
 /* If true, make symbolic links; otherwise, make hard links.  */
 static bool symbolic_link;
 
+/* If true, make symbolic links relative  */
+static bool relative;
+
 /* If true, hard links are logical rather than physical.  */
 static bool logical = !!LINK_FOLLOWS_SYMLINKS;
 
@@ -90,6 +95,7 @@ static struct option const long_options[] =
   {"target-directory", required_argument, NULL, 't'},
   {"logical", no_argument, NULL, 'L'},
   {"physical", no_argument, NULL, 'P'},
+  {"relative", no_argument, NULL, 'r'},
   {"symbolic", no_argument, NULL, 's'},
   {"verbose", no_argument, NULL, 'v'},
   {GETOPT_HELP_OPTION_DECL},
@@ -120,6 +126,37 @@ target_directory_operand (char const *file)
   return is_a_dir;
 }
 
+/* Return FROM represented as relative to the dir of TARGET.
+   The result is malloced.  */
+
+static char *
+convert_abs_rel (const char *from, const char *target)
+{
+  char *realtarget = canonicalize_filename_mode (target, CAN_MISSING);
+  char *realfrom = canonicalize_filename_mode (from, CAN_MISSING);
+
+  /* Write to a PATH_MAX buffer, guarding against very large values.  */
+  size_t nalloc = MIN (PATH_MAX, 32 * 1024);
+  char *relative_from = xmalloc (nalloc);
+
+  /* Get dirname to generate paths relative to.  */
+  realtarget[dir_len (realtarget)] = '\0';
+
+  if (!relpath (realfrom, realtarget, relative_from, nalloc))
+    {
+      free (relative_from);
+      relative_from = NULL;
+    }
+
+  free (realtarget);
+  free (realfrom);
+
+  if (relative_from)
+    return relative_from;
+  else
+    return xstrdup (from);
+}
+
 /* Make a link DEST to the (usually) existing file SOURCE.
    Symbolic links to nonexistent files are allowed.
    Return true if successful.  */
@@ -130,6 +167,7 @@ do_link (const char *source, const char *dest)
   struct stat source_stats;
   struct stat dest_stats;
   char *dest_backup = NULL;
+  char *rel_source = NULL;
   bool dest_lstat_ok = false;
   bool source_is_dir = false;
   bool ok;
@@ -246,6 +284,9 @@ do_link (const char *source, const char *dest)
         }
     }
 
+  if (relative)
+    source = rel_source = convert_abs_rel (source, dest);
+
   ok = ((symbolic_link ? symlink (source, dest)
          : linkat (AT_FDCWD, source, AT_FDCWD, dest,
                    logical ? AT_SYMLINK_FOLLOW : 0))
@@ -276,6 +317,7 @@ do_link (const char *source, const char *dest)
         {
           error (0, errno, _("cannot remove %s"), quote (dest));
           free (dest_backup);
+          free (rel_source);
           return false;
         }
 
@@ -322,6 +364,7 @@ do_link (const char *source, const char *dest)
     }
 
   free (dest_backup);
+  free (rel_source);
   return ok;
 }
 
@@ -367,6 +410,7 @@ Mandatory arguments to long options are mandatory for short options too.\n\
   -n, --no-dereference        treat LINK_NAME as a normal file if\n\
                                 it is a symbolic link to a directory\n\
   -P, --physical              make hard links directly to symbolic links\n\
+  -r, --relative              create symbolic links relative to link location\n\
   -s, --symbolic              make symbolic links instead of hard links\n\
 "), stdout);
       fputs (_("\
@@ -429,7 +473,7 @@ main (int argc, char **argv)
   symbolic_link = remove_existing_files = interactive = verbose
     = hard_dir_link = false;
 
-  while ((c = getopt_long (argc, argv, "bdfinst:vFLPS:T", long_options, NULL))
+  while ((c = getopt_long (argc, argv, "bdfinrst:vFLPS:T", long_options, NULL))
          != -1)
     {
       switch (c)
@@ -460,6 +504,9 @@ main (int argc, char **argv)
         case 'P':
           logical = false;
           break;
+        case 'r':
+          relative = true;
+          break;
         case 's':
           symbolic_link = true;
           break;
@@ -539,6 +586,13 @@ main (int argc, char **argv)
                  ? xget_version (_("backup type"), version_control_string)
                  : no_backups);
 
+  if (relative && !symbolic_link)
+    {
+        error (EXIT_FAILURE, 0,
+               _("cannot do --relative without --symbolic"));
+    }
+
+
   if (target_directory)
     {
       int i;
diff --git a/src/realpath.c b/src/realpath.c
index 206f800..cd595b8 100644
--- a/src/realpath.c
+++ b/src/realpath.c
@@ -25,6 +25,7 @@
 #include "canonicalize.h"
 #include "error.h"
 #include "quote.h"
+#include "relpath.h"
 
 /* The official name of this program (e.g., no 'g' prefix).  */
 #define PROGRAM_NAME "realpath"
@@ -136,97 +137,6 @@ path_prefix (const char *prefix, const char *path)
   return (!*prefix && (*path == '/' || !*path));
 }
 
-/* Return the length of the longest common prefix
-   of canonical PATH1 and PATH2, ensuring only full path components
-   are matched.  Return 0 on no match.  */
-static int _GL_ATTRIBUTE_PURE
-path_common_prefix (const char *path1, const char *path2)
-{
-  int i = 0;
-  int ret = 0;
-
-  /* We already know path1[0] and path2[0] are '/'.  Special case
-     '//', which is only present in a canonical name on platforms
-     where it is distinct.  */
-  if ((path1[1] == '/') != (path2[1] == '/'))
-    return 0;
-
-  while (*path1 && *path2)
-    {
-      if (*path1 != *path2)
-        break;
-      if (*path1 == '/')
-        ret = i + 1;
-      path1++;
-      path2++;
-      i++;
-    }
-
-  if (!*path1 && !*path2)
-    ret = i;
-  if (!*path1 && *path2 == '/')
-    ret = i;
-  if (!*path2 && *path1 == '/')
-    ret = i;
-
-  return ret;
-}
-
-/* Output the relative representation if requested.  */
-static bool
-relpath (const char *can_fname)
-{
-  if (can_relative_to)
-    {
-      /* Enforce --relative-base.  */
-      if (can_relative_base && !path_prefix (can_relative_base, can_fname))
-        return false;
-
-      /* Skip the prefix common to --relative-to and path.  */
-      int common_index = path_common_prefix (can_relative_to, can_fname);
-      if (!common_index)
-        return false;
-
-      const char *relto_suffix = can_relative_to + common_index;
-      const char *fname_suffix = can_fname + common_index;
-
-      /* skip over extraneous '/'.  */
-      if (*relto_suffix == '/')
-        relto_suffix++;
-      if (*fname_suffix == '/')
-        fname_suffix++;
-
-      /* Replace remaining components of --relative-to with '..', to get
-         to a common directory.  Then output the remainder of fname.  */
-      if (*relto_suffix)
-        {
-          fputs ("..", stdout);
-          for (; *relto_suffix; ++relto_suffix)
-            {
-              if (*relto_suffix == '/')
-                fputs ("/..", stdout);
-            }
-
-          if (*fname_suffix)
-            {
-              putchar ('/');
-              fputs (fname_suffix, stdout);
-            }
-        }
-      else
-        {
-          if (*fname_suffix)
-            fputs (fname_suffix, stdout);
-          else
-            putchar ('.');
-        }
-
-      return true;
-    }
-
-  return false;
-}
-
 static bool
 isdir (const char *path)
 {
@@ -247,7 +157,9 @@ process_path (const char *fname, int can_mode)
       return false;
     }
 
-  if (!relpath (can_fname))
+  if (!can_relative_to
+      || (can_relative_base && !path_prefix (can_relative_base, can_fname))
+      || (can_relative_to && !relpath (can_fname, can_relative_to, NULL, 0)))
     fputs (can_fname, stdout);
 
   putchar (use_nuls ? '\0' : '\n');
diff --git a/src/relpath.c b/src/relpath.c
new file mode 100644
index 0000000..75cd9ea
--- /dev/null
+++ b/src/relpath.c
@@ -0,0 +1,134 @@
+/* relpath - print the relative path
+   Copyright (C) 2012 Free Software Foundation, Inc.
+
+   This program is free software: you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation, either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+/* Written by Pádraig Brady.  */
+
+#include <config.h>
+
+#include "error.h"
+#include "system.h"
+#include "relpath.h"
+
+
+/* Return the length of the longest common prefix
+   of canonical PATH1 and PATH2, ensuring only full path components
+   are matched.  Return 0 on no match.  */
+static int _GL_ATTRIBUTE_PURE
+path_common_prefix (const char *path1, const char *path2)
+{
+  int i = 0;
+  int ret = 0;
+
+  /* We already know path1[0] and path2[0] are '/'.  Special case
+     '//', which is only present in a canonical name on platforms
+     where it is distinct.  */
+  if ((path1[1] == '/') != (path2[1] == '/'))
+    return 0;
+
+  while (*path1 && *path2)
+    {
+      if (*path1 != *path2)
+        break;
+      if (*path1 == '/')
+        ret = i + 1;
+      path1++;
+      path2++;
+      i++;
+    }
+
+  if (!*path1 && !*path2)
+    ret = i;
+  if (!*path1 && *path2 == '/')
+    ret = i;
+  if (!*path2 && *path1 == '/')
+    ret = i;
+
+  return ret;
+}
+
+/* Either output STR to stdout or
+   if *PBUF is not NULL then append STR to *PBUF
+   and update *PBUF to point to the end of the buffer
+   and adjust *PLEN to reflect the remaining space.  */
+static bool
+buffer_or_output (const char* str, char **pbuf, size_t *plen)
+{
+  if (*pbuf)
+    {
+      size_t slen = strlen (str);
+      if (slen >= *plen)
+        return true;
+      memcpy (*pbuf, str, slen + 1);
+      *pbuf += slen;
+      *plen -= slen;
+    }
+  else
+    fputs (str, stdout);
+
+  return false;
+}
+
+/* Output the relative representation if possible.
+   If BUF is non NULL, output is to that buffer rather than stdout.  */
+bool
+relpath (const char *can_fname, const char *can_reldir, char *buf, size_t len)
+{
+  bool buf_err = false;
+
+  /* Skip the prefix common to --relative-to and path.  */
+  int common_index = path_common_prefix (can_reldir, can_fname);
+  if (!common_index)
+    return false;
+
+  const char *relto_suffix = can_reldir + common_index;
+  const char *fname_suffix = can_fname + common_index;
+
+  /* skip over extraneous '/'.  */
+  if (*relto_suffix == '/')
+    relto_suffix++;
+  if (*fname_suffix == '/')
+    fname_suffix++;
+
+  /* Replace remaining components of --relative-to with '..', to get
+     to a common directory.  Then output the remainder of fname.  */
+  if (*relto_suffix)
+    {
+      buf_err |= buffer_or_output ("..", &buf, &len);
+      for (; *relto_suffix; ++relto_suffix)
+        {
+          if (*relto_suffix == '/')
+            buf_err |= buffer_or_output ("/..", &buf, &len);
+        }
+
+      if (*fname_suffix)
+        {
+          buf_err |= buffer_or_output ("/", &buf, &len);
+          buf_err |= buffer_or_output (fname_suffix, &buf, &len);
+        }
+    }
+  else
+    {
+      if (*fname_suffix)
+        buf_err |= buffer_or_output (fname_suffix, &buf, &len);
+      else
+        buf_err |= buffer_or_output (".", &buf, &len);
+    }
+
+  if (buf_err)
+    error (0, ENAMETOOLONG, "%s", _("generating relative path"));
+
+  return !buf_err;
+}
diff --git a/src/relpath.h b/src/relpath.h
new file mode 100644
index 0000000..e25f82b
--- /dev/null
+++ b/src/relpath.h
@@ -0,0 +1,25 @@
+/* relpath - print the relative path
+   Copyright (C) 2012 Free Software Foundation, Inc.
+
+   This program is free software: you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation, either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+/* Written by Pádraig Brady.  */
+
+#ifndef _RELPATH_H
+# define _RELPATH_H
+
+extern bool
+relpath (const char *can_fname, const char *can_reldir, char *buf, size_t len);
+
+#endif
diff --git a/tests/Makefile.am b/tests/Makefile.am
index c72b175..011051a 100644
--- a/tests/Makefile.am
+++ b/tests/Makefile.am
@@ -420,6 +420,7 @@ TESTS =						\
   ln/hard-backup				\
   ln/hard-to-sym				\
   ln/misc					\
+  ln/relative					\
   ln/sf-1					\
   ln/slash-decorated-nonexistent-dest		\
   ln/target-1					\
diff --git a/tests/ln/relative b/tests/ln/relative
new file mode 100755
index 0000000..cfc3469
--- /dev/null
+++ b/tests/ln/relative
@@ -0,0 +1,32 @@
+#!/bin/sh
+# Test "ln --relative".
+
+# Copyright (C) 2012 Free Software Foundation, Inc.
+
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+
+# You should have received a copy of the GNU General Public License
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+. "${srcdir=.}/init.sh"; path_prepend_ ../src
+print_ver_ ln
+
+mkdir -p usr/bin || framework_failure_
+mkdir -p usr/lib/foo || framework_failure_
+touch usr/lib/foo/foo || framework_failure_
+
+ln -sr usr/lib/foo/foo usr/bin/foo
+test $(readlink usr/bin/foo) = '../lib/foo/foo' || fail=1
+
+ln -sr usr/bin/foo usr/lib/foo/link-to-foo
+test $(readlink usr/lib/foo/link-to-foo) = 'foo' || fail=1
+
+Exit $fail
-- 
1.7.6.4

Reply via email to