Clemens Buchacher [off-list ref] writes:
+/* give path as relative to prefix */
+char *path_relative(const char *in, int len,
+ struct strbuf *out, const char *prefix, int prefix_len)
+{
if (len < 0)
len = strlen(in);
+ if (prefix && prefix_len < 0)
+ prefix_len = strlen(prefix);
strbuf_setlen(out, 0);
strbuf_grow(out, len);
+ if (prefix_len > 0) {
+ int off = 0, i = 0;
+ while (i < prefix_len && i < len && prefix[i] == in[i]) {
+ if (prefix[i] == '/')
+ off = i + 1;
+ i++;
+ }
+ in += off;
+ len -= off;
+
+ while (i < prefix_len) {
+ if (prefix[i] == '/')
strbuf_addstr(out, "../");
+ i++;
+ }
}
+ strbuf_add(out, in, len);
+
+ return out->buf;
+}
Hmm... I wonder if we really want to always make a copy of the string in
the majority of the case where there is no need to add ../ and the path
does not have any funny characters that needs quoting. In such a case,
shouldn't write_name() be just moving the pointers into the original
string to skip the $(cwd) part and writing the remainder of the string
out, without any extra allocation nor copy? IIUC, that is what the
original did using write_name_quoted().