-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathfilepath.gleam
More file actions
392 lines (353 loc) · 8.96 KB
/
filepath.gleam
File metadata and controls
392 lines (353 loc) · 8.96 KB
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
//// Work with file paths in Gleam!
////
//// This library expects paths to be valid unicode. If you need to work with
//// non-unicode paths you will need to convert them to unicode before using
//// this library.
// References:
// https://github.com/erlang/otp/blob/master/lib/stdlib/src/filename.erl
// https://github.com/elixir-lang/elixir/blob/main/lib/elixir/lib/path.ex
// https://github.com/elixir-lang/elixir/blob/main/lib/elixir/test/elixir/path_test.exs
// https://cs.opensource.google/go/go/+/refs/tags/go1.21.4:src/path/match.go
import gleam/list
import gleam/bool
import gleam/string
import gleam/result
import gleam/option.{type Option, None, Some}
@external(erlang, "filepath_ffi", "is_windows")
@external(javascript, "./filepath_ffi.mjs", "is_windows")
fn is_windows() -> Bool
/// Path separator for Unix platforms.
pub const path_separator_unix = "/"
/// Path separator for the Windows platform.
pub const path_separator_windows = "\\"
/// Returns the path separator for the operating system
/// which it's currently being run on.
///
/// For Windows, this will be `\`.
/// For any non-Windows platform, this will be `/`.
///
/// ## Examples
///
/// ```gleam
/// path_separator()
/// // -> "/"
/// ```
///
/// ```gleam
/// // Windows-only behavior:
/// path_separator()
/// // -> "\\"
/// ```
///
pub fn path_separator() -> String {
case is_windows() {
True -> path_separator_windows
False -> path_separator_unix
}
}
/// Join two paths together.
///
/// This function does not expand `..` or `.` segments, use the `expand`
/// function to do this.
///
/// ## Examples
///
/// ```gleam
/// join("/usr/local", "bin")
/// // -> "/usr/local/bin"
/// ```
///
pub fn join(left: String, right: String) -> String {
case left, right {
_, "/" -> left
"", _ -> relative(right)
"/", _ -> right
_, _ ->
remove_trailing_slash(left)
|> string.append("/")
|> string.append(relative(right))
}
|> remove_trailing_slash
}
fn relative(path: String) -> String {
case path {
"/" <> path -> relative(path)
_ -> path
}
}
fn remove_trailing_slash(path: String) -> String {
case string.ends_with(path, "/") {
True -> string.drop_right(path, 1)
False -> path
}
}
/// Split a path into its segments.
///
/// When running on Windows both `/` and `\` are treated as path separators, and
/// if the path starts with a drive letter then the drive letter is lowercased.
///
/// ## Examples
///
/// ```gleam
/// split("/usr/local/bin", "bin")
/// // -> ["/", "usr", "local", "bin"]
/// ```
///
pub fn split(path: String) -> List(String) {
case is_windows() {
True -> split_windows(path)
False -> split_unix(path)
}
}
/// Split a path into its segments, using `/` as the path separator.
///
/// Typically you would want to use `split` instead of this function, but if you
/// want non-Windows path behaviour on a Windows system then you can use this
/// function.
///
/// ## Examples
///
/// ```gleam
/// split("/usr/local/bin", "bin")
/// // -> ["/", "usr", "local", "bin"]
/// ```
///
pub fn split_unix(path: String) -> List(String) {
case string.split(path, "/") {
[""] -> []
["", ..rest] -> ["/", ..rest]
rest -> rest
}
|> list.filter(fn(x) { x != "" })
}
/// Split a path into its segments, using `/` and `\` as the path separators. If
/// there is a drive letter at the start of the path then it is lowercased.
///
/// Typically you would want to use `split` instead of this function, but if you
/// want Windows path behaviour on a non-Windows system then you can use this
/// function.
///
/// ## Examples
///
/// ```gleam
/// split("/usr/local/bin", "bin")
/// // -> ["/", "usr", "local", "bin"]
/// ```
///
pub fn split_windows(path: String) -> List(String) {
let #(drive, path) = pop_windows_drive_specifier(path)
let segments =
string.split(path, "/")
|> list.flat_map(string.split(_, "\\"))
let segments = case drive {
Some(drive) -> [drive, ..segments]
None -> segments
}
case segments {
[""] -> []
["", ..rest] -> ["/", ..rest]
rest -> rest
}
}
const codepoint_slash = 47
const codepoint_backslash = 92
const codepoint_colon = 58
const codepoint_a = 65
const codepoint_z = 90
const codepoint_a_up = 97
const codepoint_z_up = 122
fn pop_windows_drive_specifier(path: String) -> #(Option(String), String) {
let start = string.slice(from: path, at_index: 0, length: 3)
let codepoints = string.to_utf_codepoints(start)
case list.map(codepoints, string.utf_codepoint_to_int) {
[drive, colon, slash] if {
slash == codepoint_slash || slash == codepoint_backslash
} && colon == codepoint_colon && {
drive >= codepoint_a && drive <= codepoint_z || drive >= codepoint_a_up && drive <= codepoint_z_up
} -> {
let drive_letter = string.slice(from: path, at_index: 0, length: 1)
let drive = string.lowercase(drive_letter) <> ":/"
let path = string.drop_left(path, 3)
#(Some(drive), path)
}
_ -> #(None, path)
}
}
/// Get the file extension of a path.
///
/// ## Examples
///
/// ```gleam
/// extension("src/main.gleam")
/// // -> Ok("gleam")
/// ```
///
/// ```gleam
/// extension("package.tar.gz")
/// // -> Ok("gz")
/// ```
///
pub fn extension(path: String) -> Result(String, Nil) {
let file = base_name(path)
case string.split(file, ".") {
["", _] -> Error(Nil)
[_, extension] -> Ok(extension)
[_, ..rest] -> list.last(rest)
_ -> Error(Nil)
}
}
/// Remove the extension from a file, if it has any.
///
/// ## Examples
///
/// ```gleam
/// strip_extension("src/main.gleam")
/// // -> "src/main"
/// ```
///
/// ```gleam
/// strip_extension("package.tar.gz")
/// // -> "package.tar"
/// ```
///
/// ```gleam
/// strip_extension("src/gleam")
/// // -> "src/gleam"
/// ```
///
pub fn strip_extension(path: String) -> String {
case extension(path) {
Ok(extension) ->
// Since the extension string doesn't have a leading `.`
// we drop a grapheme more to remove that as well.
string.drop_right(path, string.length(extension) + 1)
Error(Nil) -> path
}
}
// TODO: windows support
/// Get the base name of a path, that is the name of the file without the
/// containing directory.
///
/// ## Examples
///
/// ```gleam
/// base_name("/usr/local/bin")
/// // -> "bin"
/// ```
///
pub fn base_name(path: String) -> String {
use <- bool.guard(when: path == "/", return: "")
path
|> split
|> list.last
|> result.unwrap("")
}
// TODO: windows support
/// Get the directory name of a path, that is the path without the file name.
///
/// ## Examples
///
/// ```gleam
/// directory_name("/usr/local/bin")
/// // -> "/usr/local"
/// ```
///
pub fn directory_name(path: String) -> String {
let path = remove_trailing_slash(path)
case path {
"/" <> rest -> get_directory_name(string.to_graphemes(rest), "/", "")
_ -> get_directory_name(string.to_graphemes(path), "", "")
}
}
fn get_directory_name(
path: List(String),
acc: String,
segment: String,
) -> String {
case path {
["/", ..rest] -> get_directory_name(rest, acc <> segment, "/")
[first, ..rest] -> get_directory_name(rest, acc, segment <> first)
[] -> acc
}
}
// TODO: windows support
/// Check if a path is absolute.
///
/// ## Examples
///
/// ```gleam
/// is_absolute("/usr/local/bin")
/// // -> True
/// ```
///
/// ```gleam
/// is_absolute("usr/local/bin")
/// // -> False
/// ```
///
pub fn is_absolute(path: String) -> Bool {
string.starts_with(path, "/")
}
//TODO: windows support
/// Expand `..` and `.` segments in a path.
///
/// If the path has a `..` segment that would go up past the root of the path
/// then an error is returned. This may be useful to example to ensure that a
/// path specified by a user does not go outside of a directory.
///
/// If the path is absolute then the result will always be absolute.
///
/// ## Examples
///
/// ```gleam
/// expand("/usr/local/../bin")
/// // -> Ok("/usr/bin")
/// ```
///
/// ```gleam
/// expand("/tmp/../..")
/// // -> Error(Nil)
/// ```
///
/// ```gleam
/// expand("src/../..")
/// // -> Error("..")
/// ```
///
pub fn expand(path: String) -> Result(String, Nil) {
let is_absolute = is_absolute(path)
let result =
path
|> split
|> root_slash_to_empty
|> expand_segments([])
case is_absolute && result == Ok("") {
True -> Ok("/")
False -> result
}
}
fn expand_segments(
path: List(String),
base: List(String),
) -> Result(String, Nil) {
case base, path {
// Going up past the root (empty string in this representation)
[""], ["..", ..] -> Error(Nil)
// Going up past the top of a relative path
[], ["..", ..] -> Error(Nil)
// Going up successfully
[_, ..base], ["..", ..path] -> expand_segments(path, base)
// Discarding `.`
_, [".", ..path] -> expand_segments(path, base)
// Adding a segment
_, [s, ..path] -> expand_segments(path, [s, ..base])
// Done!
_, [] -> Ok(string.join(list.reverse(base), "/"))
}
}
fn root_slash_to_empty(segments: List(String)) -> List(String) {
case segments {
["/", ..rest] -> ["", ..rest]
_ -> segments
}
}