Path2.cc 2.2 KB
Newer Older
Elemer Lelik's avatar
Elemer Lelik committed
1
/******************************************************************************
Adam Knapp's avatar
Adam Knapp committed
2
 * Copyright (c) 2000-2021 Ericsson Telecom AB
Elemer Lelik's avatar
Elemer Lelik committed
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v2.0
Elemer Lelik's avatar
Elemer Lelik committed
5
 * which accompanies this distribution, and is available at
6
 * https://www.eclipse.org/org/documents/epl-2.0/EPL-2.0.html
Elemer Lelik's avatar
Elemer Lelik committed
7
8
9
10
11
12
 *
 * Contributors:
 *   Balasko, Jeno
 *   Beres, Szabolcs
 *
 ******************************************************************************/
Elemer Lelik's avatar
Elemer Lelik committed
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#include "Path2.hh"

#include "path.h"
//#include "dbgnew.hh"

using std::string;

const char Path::SEPARATOR = '/';

std::string Path::normalize(const std::string& original) {
  std::string result;
  bool last_slash = false;
  for (size_t i = 0; i < original.size(); ++i) {
    if (original[i] != SEPARATOR) {
      result += original[i];
      last_slash = false;
      continue;
    }

    if (!last_slash) {
      last_slash = true;
      result += original[i];
    } 
  }
  return result;
}

std::string Path::get_abs_path(const std::string& fname) {
  if (fname.empty()) {
    return std::string(1, SEPARATOR);
  }

  if (fname[0] == SEPARATOR) {
    return normalize(fname);
  }

  expstring_t working_dir = get_working_dir();
  std::string work_dir(working_dir);
  Free(working_dir);
  work_dir += SEPARATOR;
  work_dir.append(fname);
  return normalize(work_dir);
}

std::string Path::get_file(const std::string& path) {
  size_t idx = path.rfind(SEPARATOR);

  if (idx == string::npos) {
    return path;
  } 
  if (idx == path.size() - 1) {
    return string();
  }

  return path.substr(idx + 1);
}

string Path::get_dir(const string& path) {
  size_t idx = path.rfind(SEPARATOR);

  if (idx == string::npos) {
    return string();
  } 
  return path.substr(0, idx + 1);
}

string Path::compose(const string& path1, const string& path2) {
  if (path1.empty()) {
    return path2;
  }

  if (path2.empty()) {
    return path1;
  }

  string result = path1;
  if (result[result.size() - 1] != SEPARATOR
      && path2[0] != SEPARATOR) {
    result += SEPARATOR;
  }

  result.append(path2);

  return result;
}

bool Path::is_absolute(const string& path) {
  return (!path.empty() && path[0] == SEPARATOR);
}