installed pty
[VSoRC/.git] / node_modules / node-pty / src / win / path_util.cc
1 /**
2  * Copyright (c) 2013-2015, Christopher Jeffrey, Peter Sunde (MIT License)
3  * Copyright (c) 2016, Daniel Imms (MIT License).
4  * Copyright (c) 2018, Microsoft Corporation (MIT License).
5  */
6
7 #include <nan.h>
8 #include <Shlwapi.h> // PathCombine
9
10 #include "path_util.h"
11
12 namespace path_util {
13
14 const wchar_t* to_wstring(const Nan::Utf8String& str) {
15   const char *bytes = *str;
16   unsigned int sizeOfStr = MultiByteToWideChar(CP_UTF8, 0, bytes, -1, NULL, 0);
17   wchar_t *output = new wchar_t[sizeOfStr];
18   MultiByteToWideChar(CP_UTF8, 0, bytes, -1, output, sizeOfStr);
19   return output;
20 }
21
22 bool file_exists(std::wstring filename) {
23   DWORD attr = ::GetFileAttributesW(filename.c_str());
24   if (attr == INVALID_FILE_ATTRIBUTES || (attr & FILE_ATTRIBUTE_DIRECTORY)) {
25     return false;
26   }
27   return true;
28 }
29
30 // cmd.exe -> C:\Windows\system32\cmd.exe
31 std::wstring get_shell_path(std::wstring filename) {
32   std::wstring shellpath;
33
34   if (file_exists(filename)) {
35     return shellpath;
36   }
37
38   wchar_t buffer_[MAX_ENV];
39   int read = ::GetEnvironmentVariableW(L"Path", buffer_, MAX_ENV);
40   if (!read) {
41     return shellpath;
42   }
43
44   std::wstring delimiter = L";";
45   size_t pos = 0;
46   std::vector<std::wstring> paths;
47   std::wstring buffer(buffer_);
48   while ((pos = buffer.find(delimiter)) != std::wstring::npos) {
49     paths.push_back(buffer.substr(0, pos));
50     buffer.erase(0, pos + delimiter.length());
51   }
52
53   const wchar_t *filename_ = filename.c_str();
54
55   for (int i = 0; i < paths.size(); ++i) {
56     std::wstring path = paths[i];
57     wchar_t searchPath[MAX_PATH];
58     ::PathCombineW(searchPath, const_cast<wchar_t*>(path.c_str()), filename_);
59
60     if (searchPath == NULL) {
61       continue;
62     }
63
64     if (file_exists(searchPath)) {
65       shellpath = searchPath;
66       break;
67     }
68   }
69
70   return shellpath;
71 }
72
73 }  // namespace path_util