aboutsummaryrefslogtreecommitdiff
path: root/butl/path.txx
blob: 5bcaea0ae00ed49ea06ce618d31e797a190806ec (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
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
// file      : butl/path.txx -*- C++ -*-
// copyright : Copyright (c) 2014-2016 Code Synthesis Ltd
// license   : MIT; see accompanying LICENSE file

#include <vector>
#include <cassert>

#ifdef _WIN32
#  include <algorithm> // replace()
#endif

namespace butl
{
  template <typename C, typename K>
  basic_path<C, K> basic_path<C, K>::
  leaf (basic_path<C, K> const& d) const
  {
    size_type dn (d.path_.size ());

    if (dn == 0)
      return *this;

    const string_type& s (this->path_);

    if (!sub (d))
      throw invalid_basic_path<C> (s);

    // If there is implied trailing slash, add it to count. Unless it is
    // "matched" by the implied slash on the other side.
    //
    if (d.tsep_ > 0 && dn < s.size ())
      dn++;

    // Preserve trailing slash.
    //
    return basic_path (data_type (string_type (s, dn, s.size () - dn),
                                  this->tsep_));
  }

  template <typename C, typename K>
  typename basic_path<C, K>::dir_type basic_path<C, K>::
  directory (basic_path<C, K> const& l) const
  {
    size_type ln (l.path_.size ());

    const string_type& s (this->path_);

    if (ln == 0)
    {
      if (this->tsep_ == 0) // Must be a directory.
        throw invalid_basic_path<C> (s);

      return dir_type (data_type (string_type (s), this->tsep_));
    }

    if (!sup (l))
      throw invalid_basic_path<C> (s);

    return dir_type (
      data_type (string_type (s, 0, s.size () - ln))); // Include slash.
  }

#ifdef _WIN32
  template <typename C, typename K>
  typename basic_path<C, K>::string_type basic_path<C, K>::
  posix_string () const&
  {
    if (absolute ())
      throw invalid_basic_path<C> (this->path_);

    string_type r (string ());
    replace (r.begin (), r.end (), '\\', '/');
    return r;
  }

  template <typename C, typename K>
  typename basic_path<C, K>::string_type basic_path<C, K>::
  posix_string () &&
  {
    if (absolute ())
      throw invalid_basic_path<C> (this->path_);

    string_type r (std::move (*this).string ());
    replace (r.begin (), r.end (), '\\', '/');
    return r;
  }

  template <typename C, typename K>
  typename basic_path<C, K>::string_type basic_path<C, K>::
  posix_representation () const&
  {
    if (absolute ())
      throw invalid_basic_path<C> (this->path_);

    string_type r (representation ());
    replace (r.begin (), r.end (), '\\', '/');
    return r;
  }

  template <typename C, typename K>
  typename basic_path<C, K>::string_type basic_path<C, K>::
  posix_representation () &&
  {
    if (absolute ())
      throw invalid_basic_path<C> (this->path_);

    string_type r (std::move (*this).representation ());
    replace (r.begin (), r.end (), '\\', '/');
    return r;
  }
#endif

  template <typename C, typename K>
  basic_path<C, K> basic_path<C, K>::
  relative (basic_path<C, K> d) const
  {
    dir_type r;

    for (;; d = d.directory ())
    {
      if (sub (d))
        break;

      r /= "..";

      // Roots of the paths do not match.
      //
      if (d.root ())
        throw invalid_basic_path<C> (this->path_);
    }

    return r / leaf (d);
  }

#ifdef _WIN32
  // Find the actual spelling of a name in the specified dir. If the name is
  // found, append it to the result and return true. Otherwise, return false.
  // Throw system_error in case of other failures. Result and dir can be the
  // same instance.
  //
  template <typename C>
  bool
  basic_path_append_actual_name (std::basic_string<C>& result,
                                 const std::basic_string<C>& dir,
                                 const std::basic_string<C>& name);
#endif

  template <typename C, typename K>
  basic_path<C, K>& basic_path<C, K>::
  normalize (bool actual)
  {
    if (empty ())
      return *this;

    bool abs (absolute ());
    assert (!actual || abs); // Only absolue can be actualized.

    string_type& s (this->path_);
    difference_type& ts (this->tsep_);

    typedef std::vector<string_type> paths;
    paths ps;

    bool tsep (ts != 0); // Trailing directory separator.
    {
      size_type n (_size ());

      for (size_type b (0), e (traits::find_separator (s, 0, n));
           ;
           e = traits::find_separator (s, b, n))
      {
        ps.push_back (
          string_type (s, b, (e == string_type::npos ? n : e) - b));

        if (e == string_type::npos)
          break;

        ++e;

        // Skip consecutive directory separators.
        //
        while (e != n && traits::is_separator (s[e]))
          ++e;

        if (e == n)
          break;

        b = e;
      }

      // If the last component is "." or ".." then this is a directory.
      //
      if (!tsep)
      {
        const string_type& l (ps.back ());
        size_type ln (l.size ());

        if ((ln == 1 && l[0] == '.') ||
            (ln == 2 && l[0] == '.' && l[1] == '.'))
          tsep = true;
      }
    }

    // Collapse "." and "..".
    //
    paths r;

    for (typename paths::iterator i (ps.begin ()), e (ps.end ()); i != e; ++i)
    {
      string_type& s (*i);
      size_type n (s.size ());

      if (n == 1 && s[0] == '.')
        continue;

      if (n == 2 && s[0] == '.' && s[1] == '.')
      {
        // Pop the last directory from r unless it is '..'.
        //
        if (!r.empty ())
        {
          string_type const& s1 (r.back ());

          if (!(s1.size () == 2 && s1[0] == '.' && s1[1] == '.'))
          {
            // Cannot go past the root directory.
            //
            if (abs && r.size () == 1)
              throw invalid_basic_path<C> (this->path_);

            r.pop_back ();
            continue;
          }
        }
      }

      r.push_back (std::move (s));
    }

    // Reassemble the path, actualizing each component if requested.
    //
    string_type p;

    for (typename paths::const_iterator b (r.begin ()), i (b), e (r.end ());
         i != e;)
    {
#ifdef _WIN32
      if (actual)
      {
        if (i == b)
        {
          // The first component (the drive letter) we have to actualize
          // ourselves. Capital seems to be canonical. This is, for example,
          // what getcwd() returns.
          //
          p = *i;
          p[0] = traits::toupper (p[0]);
        }
        else
        {
          if (!basic_path_append_actual_name (p, p, *i))
          {
            p += *i;
            actual = false; // Ignore for all subsequent components.
          }
        }
      }
      else
#endif
        p += *i;

      if (++i != e)
        p += traits::directory_separator;
    }

    if (tsep && (!p.empty () || abs)) // Distinguish "/"-empty and "."-empty.
    {
      if (p.empty ())
      {
        p += traits::directory_separator;
        ts = -1;
      }
      else
        ts = 1; // Canonical separator is always first.
    }
    else
      ts = 0;

    s.swap (p);
    return *this;
  }

  template <typename C, typename K>
  void basic_path<C, K>::
  current (basic_path const& p)
  {
    const string_type& s (p.string ());

    if (s.empty ())
      throw invalid_basic_path<char> (s);

    traits::current (s);
  }

  template <typename C>
  auto any_path_kind<C>::
  init (string_type&& s, bool exact) -> data_type
  {
    using size_type = typename string_type::size_type;
    using difference_type = typename string_type::difference_type;

    size_type n (s.size ());

#ifdef _WIN32
    // We do not support any special Windows path name notations like in C:abc,
    // \\?\c:\abc, \\server\abc and \\?\UNC\server\abc (more about them at
    // https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247.aspx).
    //
    if ((n > 2 && s[1] == ':' && s[2] != '\\' && s[2] != '/') ||
        (n > 1 && s[0] == '\\' && s[1] == '\\'))
    {
      if (exact)
        return data_type ();
      else
        throw invalid_basic_path<C> (s);
    }
#endif

    // Strip trailing slashes.
    //
    size_type m (n), di (0);
    for (size_type i;
         m != 0 && (i = path_traits<C>::separator_index (s[m - 1])) != 0;
         --m) di = i;

    difference_type ts (0);
    if (size_t k = n - m)
    {
      // We can only accomodate one trailing slash in the exact mode.
      //
      if (exact && k > 1)
        return data_type ();

      if (m == 0) // The "/" case.
      {
        ++m; // Keep one slash in the string.
        ts = -1;
      }
      else
        ts = di;

      s.resize (m);
    }

    return data_type (std::move (s), ts);
  }

  template <typename C>
  auto dir_path_kind<C>::
  init (string_type&& s, bool exact) -> data_type
  {
    // If we don't already have the separator then this can't be the exact
    // initialization.
    //
    if (exact && !s.empty () && !path_traits<C>::is_separator (s.back ()))
      return data_type ();

    data_type r (any_path_kind<C>::init (std::move (s), exact));

    // Unless the result is empty, make sure we have the trailing slash.
    //
    if (!r.path_.empty () && r.tsep_ == 0)
      r.tsep_ = 1; // Canonical separator is always first.

    return r;
  }
}