aboutsummaryrefslogtreecommitdiff
path: root/src/path.cc
blob: 103e2c58428c9841ae9952d0558487d5dabf1114 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71

#include "path.h"

namespace ov4
{

using namespace std;

string find_cmd(const char * s)
{
    const string tmp = s;
    return find_cmd(tmp);
}

string find_cmd(const string &s)
{
    string unified = path_unifier(s, true);
    LOG << unified << endl;
    return unified;
}

string path_unifier(const string &s, bool is_cmd)
{
    if (s.size() == 0) return "";

    if (s[0] == '/') return s;
    if (s[0] == '.')
    {
        return get_current_dir() + s.substr(1);
    }

    // single word, use path
    if (is_cmd && (s.find("/") == string::npos))
    {
        string path = safe_str(getenv("PATH"));
        size_t i = 0, j = 0, l = path.size();
        while (true)
        {
            for (; j < l; j++)
                if (path[j] == ':')
                    break;
            
            string cmd = path.substr(i, j-i) + '/' +s;
            if (access(cmd.c_str(), F_OK) == 0)
                return cmd;

            if (j == l)
                return "";

            j++;
            i=j;

        }
    }

    return get_current_dir() + "/" + s;

}

int set_current_dir(const string &s)
{
    return chdir(s.c_str());
}

string get_current_dir()
{
    char buf[MAXLINE];
    return safe_str(getcwd(buf, MAXLINE));
}


}