Refactor the code in clang to find a file in a PATH like environment variable into...
authorEhsan Akhgari <ehsan.akhgari@gmail.com>
Mon, 30 Jun 2014 19:54:20 +0000 (19:54 +0000)
committerEhsan Akhgari <ehsan.akhgari@gmail.com>
Mon, 30 Jun 2014 19:54:20 +0000 (19:54 +0000)
git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@212057 91177308-0d34-0410-b5e6-96231b3b80d8

include/llvm/Support/Process.h
lib/Support/Process.cpp

index 4f98e4de812513a44a7e9237560d1f114af9e1ff..30973de3aac4f6a48b13069051d506140a1af524 100644 (file)
@@ -171,6 +171,13 @@ public:
   // string. \arg Name is assumed to be in UTF-8 encoding too.
   static Optional<std::string> GetEnv(StringRef name);
 
+  /// This function searches for an existing file in the list of directories
+  /// in a PATH like environment variable, and returns the first file found,
+  /// according to the order of the entries in the PATH like environment
+  /// variable.
+  static Optional<std::string> FindInEnvPath(const std::string& EnvName,
+                                             const std::string& FileName);
+
   /// This function returns a SmallVector containing the arguments passed from
   /// the operating system to the program.  This function expects to be handed
   /// the vector passed in from main.
index 087c459e187e40e65fe464ff8d818a93e757a8c4..0d42e0e35b92e7e3691d7b6eb7092375efe03978 100644 (file)
 //
 //===----------------------------------------------------------------------===//
 
+#include "llvm/ADT/StringExtras.h"
 #include "llvm/Config/config.h"
 #include "llvm/Support/ErrorHandling.h"
+#include "llvm/Support/FileSystem.h"
 #include "llvm/Support/Process.h"
+#include "llvm/Support/Program.h"
 
 using namespace llvm;
 using namespace sys;
@@ -66,6 +69,33 @@ TimeValue self_process::get_wall_time() const {
   return getElapsedWallTime();
 }
 
+Optional<std::string> Process::FindInEnvPath(const std::string& EnvName,
+                                             const std::string& FileName)
+{
+  Optional<std::string> FoundPath;
+  Optional<std::string> OptPath = Process::GetEnv(EnvName);
+  if (!OptPath.hasValue())
+    return FoundPath;
+
+  const char EnvPathSeparatorStr[] = {EnvPathSeparator, '\0'};
+  SmallVector<StringRef, 8> Dirs;
+  SplitString(OptPath.getValue(), Dirs, EnvPathSeparatorStr);
+
+  for (const auto &Dir : Dirs) {
+    if (Dir.empty())
+      continue;
+
+    SmallString<128> FilePath(Dir);
+    path::append(FilePath, FileName);
+    if (fs::exists(Twine(FilePath))) {
+      FoundPath = FilePath.str();
+      break;
+    }
+  }
+
+  return FoundPath;
+}
+
 
 #define COLOR(FGBG, CODE, BOLD) "\033[0;" BOLD FGBG CODE "m"