]> git.donarmstrong.com Git - lilypond.git/commitdiff
Issue 5077/2: Improve portability of get_working_directory()
authorMasamichi Hosoda <trueroad@trueroad.jp>
Sat, 11 Mar 2017 10:12:15 +0000 (19:12 +0900)
committerMasamichi Hosoda <trueroad@trueroad.jp>
Sun, 19 Mar 2017 14:45:34 +0000 (23:45 +0900)
We used `getcwd()` with `PATH_MAX` to get the current directory.
However, `PATH_MAX` does not exist in environments such as GNU Hurd.
Debian developers avoided `PATH_MAX`
by using `get_current_dir_name()` instead of `getcwd()`.
It needed to protected with `#ifdef _GNU_SOURCE`
since `get_current_dir_name()` is glibc specific.
So `PATH_MAX` was still required in non-glibc environments.

There is a `getcwd()` extention that can avoid `PATH_MAX`
by setting the first argument to NULL.
The extension can be used in many environments, including glibc,
but POSIX does not recommend it in conforming applications.

This commit improves portability
by obtaining the current directory
with a method conforming to the standard.

flower/file-name.cc

index e5dd6f61602369773f53406d56bc4bd1ef12c4fa..990e3d6d9161d983860b0c380e1a1139b17edf9c 100644 (file)
@@ -77,16 +77,21 @@ dir_name (const string &file_name)
 string
 get_working_directory ()
 {
-#ifdef _GNU_SOURCE
-  char *cwd = get_current_dir_name();
-  string scwd(cwd);
-  free(cwd);
-  return scwd;
+#ifdef PATH_MAX
+  vector<char> cwd (PATH_MAX);
 #else
-  char cwd[PATH_MAX];
-  // getcwd returns NULL upon a failure, contents of cwd would be undefined!
-  return string (getcwd (cwd, PATH_MAX));
+  vector<char> cwd (1024);
 #endif
+  while (getcwd (cwd.data (), cwd.size ()) == NULL)
+    {
+      if (errno != ERANGE)
+        {
+          // getcwd () fails.
+          return "";
+        }
+      cwd.resize (cwd.size () * 2);
+    }
+  return string (cwd.data ());
 }
 
 /* Join components to full file_name. */