path.pony

  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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
use "time"
use @pony_os_realpath[Pointer[U8] iso^](path: Pointer[U8] tag)
use @pony_os_cwd[Pointer[U8]]()

primitive _PathSep
primitive _PathDot
primitive _PathDot2
primitive _PathOther

type _PathState is (_PathSep | _PathDot | _PathDot2 | _PathOther)

primitive Path
  """
  Operations on paths that do not require a capability. The operations can be
  used to manipulate path names, but give no access to the resulting paths.
  """
  fun is_sep(c: U8): Bool =>
    """
    Determine if a byte is a path separator.
    """
    ifdef windows then
      (c == '/') or (c == '\\')
    else
      c == '/'
    end

  fun tag sep(): String =>
    """
    Return the path separator as a string.
    """
    ifdef windows then "\\" else "/" end

  fun is_abs(path: String): Bool =>
    """
    Return true if the path is an absolute path.
    """
    try
      ifdef windows then
        is_sep(path(0)?) or _drive_letter(path)
      else
        is_sep(path(0)?)
      end
    else
      false
    end

  fun join(path: String, next_path: String): String =>
    """
    Join two paths together. If the next_path is absolute, simply return it.
    The returned path will be cleaned.
    """
    if path.size() == 0 then
      clean(next_path)
    elseif next_path.size() == 0 then
      clean(path)
    elseif is_abs(next_path) then
      clean(next_path)
    else
      try
        if is_sep(path(path.size()-1)?) then
          if is_sep(next_path(0)?) then
            return clean(path + next_path.trim(1))
          else
            return clean(path + next_path)
          end
        end
      end
      clean(path + sep() + next_path)
    end

  fun clean(path: String): String =>
    """
    Replace multiple separators with a single separator.
    Convert / to the OS separator.
    Remove instances of . from the path.
    Remove instances of .. and the preceding path element from the path.
    The result will have no trailing slash unless it is a root directory.
    If the result would be empty, "." will be returned instead.
    """
    let s = recover String(path.size()) end
    let vol = volume(path)
    s.append(vol)

    var state: _PathState = _PathOther
    var i = vol.size()
    var backtrack = ISize(-1)
    let n = path.size()

    try
      var c = path(i)?

      if is_sep(c) then
        s.append(sep())
        i = i + 1
        state = _PathSep
      elseif c == '.' then
        i = i + 1
        state = _PathDot
      else
        backtrack = s.size().isize()
      end

      while i < n do
        c = path(i)?

        if is_sep(c) then
          match state
          | _PathDot2 =>
            if backtrack == -1 then
              s.append("..")
              s.append(sep())
            else
              s.delete(backtrack, -1)

              try
                backtrack = s.rfind(sep(), backtrack - 2)? + 1
              else
                backtrack = vol.size().isize()
              end

              if
                (s.size() == 0) or
                (s.compare_sub("../", 3, backtrack) is Equal) or
                ifdef windows then
                  s.compare_sub("..\\", 3, backtrack) is Equal
                else
                  false
                end
              then
                backtrack = -1
              end
            end
          | _PathOther =>
            s.append(sep())
          end
          state = _PathSep
        elseif c == '.' then
          match state
          | _PathSep =>
            state = _PathDot
          | _PathDot =>
            state = _PathDot2
          | _PathDot2 =>
            backtrack = s.size().isize()
            s.append("...")
            state = _PathOther
          | _PathOther =>
            s.append(".")
          end
        else
          match state
          | _PathSep =>
            backtrack = s.size().isize()
          | _PathDot =>
            backtrack = s.size().isize()
            s.append(".")
          | _PathDot2 =>
            backtrack = s.size().isize()
            s.append("..")
          end
          s.push(c)
          state = _PathOther
        end

        i = i + 1
      end
    end

    match state
    | _PathDot2 =>
      if backtrack == -1 then
        s.append("..")
      else
        s.delete(backtrack, -1)
      end
    end

    try
      if is_sep(s(s.size()-1)?) and (s.size() > 1) then
        s.delete(-1, sep().size())
      end
    end

    if s.size() > 0 then
      s
    else
      "."
    end

  fun normcase(path: String): String =>
    """
    Normalizes the case of path for the runtime platform.
    """
    if Platform.windows() then
      recover val path.lower() .> replace("/", "\\") end
    elseif Platform.osx() then
      path.lower()
    else
      path
    end

  fun cwd(): String =>
    """
    Returns the program's working directory. Setting the working directory is
    not supported, as it is not concurrency-safe.
    """
    recover String.from_cstring(@pony_os_cwd()) end

  fun abs(path: String): String =>
    """
    Returns a cleaned, absolute path.
    """
    if is_abs(path) then
      clean(path)
    else
      join(cwd(), path)
    end

  fun rel(to: String, target: String): String ? =>
    """
    Returns a path such that Path.join(to, Path.rel(to, target)) == target.
    Raises an error if this isn't possible.
    """
    var to_clean = clean(to)
    var target_clean = clean(target)

    if to_clean == target_clean then
      return "."
    end

    var to_i: ISize = 0

    ifdef windows then
      to_clean = abs(to_clean)
      target_clean = abs(target_clean)

      let to_vol = volume(to_clean)
      let target_vol = volume(target_clean)

      if to_vol != target_vol then
        error
      end

      to_i = to_vol.size().isize()
    end

    var to_0 = to_i
    var target_i = to_i
    var target_0 = target_i

    while true do
      to_i = try
        to_clean.find(sep(), to_i)?
      else
        to_clean.size().isize()
      end

      target_i = try
        target_clean.find(sep(), target_i)?
      else
        target_clean.size().isize()
      end

      if
        (to_i != target_i) or
        (to_clean.compare_sub(target_clean, target_i.usize()) isnt Equal)
      then
        break
      end

      if to_i < to_clean.size().isize() then
        to_i = to_i + 1
      end

      if target_i < target_clean.size().isize() then
        target_i = target_i + 1
      end

      to_0 = to_i
      target_0 = target_i
    end

    if
      ((to_i - to_0) == 2)
        and (to_clean.compare_sub("..", 2, to_0) is Equal)
    then
      error
    end

    if to_0.usize() != to_clean.size() then
      let result = recover String end

      try
        while true do
          to_i = to_clean.find(sep(), to_i)? + 1
          result.append("..")
          result.append(sep())
        end
      end

      result.append("..")
      result.append(sep())
      result.append(target_clean.trim(target_0.usize()))
      result
    else
      target_clean.trim(target_0.usize())
    end

  fun split(path: String, separator: String = Path.sep()): (String, String) =>
    """
    Splits the path into a pair, (head, tail) where tail is the last pathname
    component and head is everything leading up to that. The tail part will
    never contain a slash; if path ends in a slash, tail will be empty. If
    there is no slash in path, head will be empty. If path is empty, both head
    and tail are empty. The path in head will be cleaned before it is returned.
    In all cases, join(head, tail) returns a path to the same location as path
    (but the strings may differ). Also see the functions dir() and base().
    """
    try
      let i = path.rfind(separator)?.usize()
      (clean(path.trim(0, i)), path.trim(i+separator.size()))
    else
      ("", path)
    end

  fun base(path: String, with_ext: Bool = true): String =>
    """
    Return the path after the last separator, or the whole path if there is no
    separator.
    If `with_ext` is `false`, the extension as defined by the `ext()` method
    will be omitted from the result.
    """
    let b = try
      path.trim(path.rfind(sep())?.usize() + 1)
    else
      path
    end

    if with_ext then
      b
    else
      let e_size = ext(b).size()

      if e_size > 0 then
        b.trim(0, b.size() - e_size - 1)
      else
        b
      end
    end

  fun dir(path: String): String =>
    """
    Return a cleaned path before the last separator, or the whole path if there
    is no separator.
    """
    try
      clean(path.trim(0, path.rfind(sep())?.usize()))
    else
      path
    end

  fun ext(path: String): String =>
    """
    Return the file extension, i.e. the part after the last dot as long as that
    dot is after all separators. Return an empty string for no extension.
    """
    try
      let i = path.rfind(".")?

      let j = try
        path.rfind(sep())?
      else
        i
      end

      if i >= j then
        return path.trim(i.usize() + 1)
      end
    end
    ""

  fun volume(path: String): String =>
    """
    On Windows, this returns the drive letter or UNC base at the beginning of
    the path, if there is one. Otherwise, this returns an empty string.
    """
    ifdef windows then
      var offset = ISize(0)

      if path.compare_sub("""\\?\""", 4) is Equal then
        offset = 4

        if path.compare_sub("""UNC\""", 4, offset) is Equal then
          return _network_share(path, offset + 4)
        end
      end

      if _drive_letter(path, offset) then
        return path.trim(0, offset.usize() + 2)
      end

      try
        if
          is_sep(path.at_offset(offset)?) and
          is_sep(path.at_offset(offset + 1)?)
        then
          return _network_share(path, offset + 3)
        end
      end
    end
    ""

  fun _drive_letter(path: String, offset: ISize = 0): Bool =>
    """
    Look for a drive letter followed by a ':', returning true if we find it.
    """
    try
      let c = path.at_offset(offset)?

      (((c >= 'A') and (c <= 'Z')) or ((c >= 'a') and (c <= 'z')))
        and (path.at_offset(offset + 1)? == ':')
    else
      false
    end

  fun _network_share(path: String, offset: ISize = 0): String =>
    """
    Look for a host, a \, and a resource. Return the path up to that point if
    we found one, otherwise an empty String.
    """
    try
      let next = path.find("\\", offset)? + 1

      try
        path.trim(0, path.find("\\", next)?.usize())
      else
        path
      end
    else
      ""
    end

  fun from_slash(path: String): String =>
    """
    Changes each / in the path to the OS specific separator.
    """
    ifdef windows then
      let s = path.clone()
      let len = s.size()
      var i = USize(0)

      try
        while i < len do
          if s(i)? == '/' then
            s(i)? = '\\'
          end

          i = i + 1
        end
      end

      s
    else
      path
    end

  fun to_slash(path: String): String =>
    """
    Changes each OS specific separator in the path to /.
    """
    ifdef windows then
      let s = path.clone()
      let len = s.size()
      var i = USize(0)

      try
        while i < len do
          if s(i)? == '\\' then
            s(i)? = '/'
          end

          i = i + 1
        end
      end

      s
    else
      path
    end

  fun canonical(path: String): String ? =>
    """
    Return the equivalent canonical absolute path. Raise an error if there
    isn't one.
    """
    let cstring = @pony_os_realpath(path.cstring())

    if cstring.is_null() then
      error
    else
      recover String.from_cstring(consume cstring) end
    end

  fun is_list_sep(c: U8): Bool =>
    """
    Determine if a byte is a path list separator.
    """
    ifdef windows then c == ';' else c == ':' end

  fun list_sep(): String =>
    """
    Return the path list separator as a string.
    """
    ifdef windows then ";" else ":" end

  fun split_list(path: String): Array[String] iso^ =>
    """
    Separate a list of paths into an array of cleaned paths.
    """
    let array = recover Array[String] end
    var offset: ISize = 0

    try
      while true do
        let next = path.find(list_sep(), offset)?
        array.push(clean(path.trim(offset.usize(), next.usize())))
        offset = next + 1
      end
    else
      array.push(clean(path.trim(offset.usize())))
    end

    array

  fun random(len: USize = 6): String =>
    """
    Returns a pseudo-random base, suitable as a temporary file name or
    directory name, but not guaranteed to not already exist.
    """
    let letters =
      "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    let s = recover String(len) end
    var n = USize(0)
    var r = Time.nanos().usize()

    try
      while n < len do
        let c = letters(r % letters.size())?
        r = r / letters.size()
        s.push(c)
        n = n + 1
      end
    end
    s