-
Notifications
You must be signed in to change notification settings - Fork 369
Expand file tree
/
Copy pathparse_import.rs
More file actions
445 lines (415 loc) · 14.9 KB
/
Copy pathparse_import.rs
File metadata and controls
445 lines (415 loc) · 14.9 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
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
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is dual-licensed under either the MIT license found in the
* LICENSE-MIT file in the root directory of this source tree or the Apache
* License, Version 2.0 found in the LICENSE-APACHE file in the root directory
* of this source tree. You may select, at your option, one of the
* above-listed licenses.
*/
//! Parses imports for load_file() calls in build files.
use buck2_core::bzl::ImportPath;
use buck2_core::cells::CellAliasResolver;
use buck2_core::cells::build_file_cell::BuildFileCell;
use buck2_core::cells::cell_path::CellPath;
use buck2_core::cells::cell_path_with_allowed_relative_dir::CellPathWithAllowedRelativeDir;
use buck2_core::cells::paths::CellRelativePath;
use buck2_core::cells::paths::CellRelativePathBuf;
use buck2_fs::paths::RelativePath;
use buck2_fs::paths::file_name::FileName;
/// Format hint parsed from `?as=toml` or `?as=json` suffix in load() strings.
/// Allows loading a file as a specific format regardless of its extension,
/// e.g. `load(":blah.lock?as=toml", "value")`.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum FormatHint {
Json,
Toml,
}
/// Strip a `?as=toml` or `?as=json` format hint from a load string.
/// Returns the stripped string and the format hint if present.
pub fn strip_format_hint(import: &str) -> (&str, Option<FormatHint>) {
if let Some(base) = import.strip_suffix("?as=toml") {
(base, Some(FormatHint::Toml))
} else if let Some(base) = import.strip_suffix("?as=json") {
(base, Some(FormatHint::Json))
} else {
(import, None)
}
}
#[derive(buck2_error::Error, Debug)]
#[buck2(input)]
enum ImportParseError {
#[error(
"Unable to parse import spec. Expected format `(@<cell>)//package/name:filename.bzl` or `:filename.bzl`. Got `{0}`"
)]
MatchFailed(String),
#[error(
"Unable to parse import spec. Expected format `(@<cell>)//package/name:filename.bzl` or `:filename.bzl`, but got an empty filename. Got `{0}`"
)]
EmptyFileName(String),
#[error("Unexpected relative import spec. Got `{0}`")]
ProhibitedRelativeImport(String),
#[error(
"Unable to parse import spec. Expected format `(@<cell>)//package/name:filename.bzl` or `:filename.bzl`, but got a path. Got `{0}`"
)]
NotAFileName(String),
}
pub enum RelativeImports<'a> {
Allow {
current_dir_with_allowed_relative: &'a CellPathWithAllowedRelativeDir,
},
Disallow,
}
/// Extra options for parsing a load() or load-like path into a `BuckPath`
pub struct ParseImportOptions<'a> {
/// Whether '@' is required at the beginning of the import.
pub allow_missing_at_symbol: bool,
/// Whether relative imports (':bar.bzl') are allowed.
pub relative_import_option: RelativeImports<'a>,
}
// Parses a string of the form `(@<cell>)//dir/name` to the corresponding
// alias and cell relative path.
fn parse_import_cell_path_parts(path: &str, allow_missing_at_symbol: bool) -> Option<(&str, &str)> {
let (alias, cell_rel_path) = path.split_once("//")?;
let alias = if alias.is_empty() {
alias
} else if !alias.starts_with('@') {
if !allow_missing_at_symbol {
return None;
}
alias
} else {
&alias[1..]
};
Some((alias, cell_rel_path))
}
pub fn parse_import(
cell_resolver: &CellAliasResolver,
relative_import_option: RelativeImports,
import: &str,
) -> buck2_error::Result<CellPath> {
let opts: ParseImportOptions = ParseImportOptions {
allow_missing_at_symbol: false,
relative_import_option,
};
parse_import_with_config(cell_resolver, import, &opts)
}
/// Parse import string into a BuckPath, but potentially be more or less flexible with what is
/// accepted.
///
/// Common use case is e.g. allowing "cell//foo:bar.bzl" to be passed on the command line
/// and letting that be turned into an ImportPath eventually, or disallowing relative imports
/// from command line arguments.
///
/// Strings for the `load()` statement in starlark files should use [`parse_import`]
pub fn parse_import_with_config(
cell_resolver: &CellAliasResolver,
import: &str,
opts: &ParseImportOptions,
) -> buck2_error::Result<CellPath> {
match import.split_once(':') {
None => {
// import without `:`, so just try to parse the cell and cell relative paths
match parse_import_cell_path_parts(import, opts.allow_missing_at_symbol) {
None => {
if let RelativeImports::Allow {
current_dir_with_allowed_relative,
} = opts.relative_import_option
{
current_dir_with_allowed_relative
.join_normalized(RelativePath::from_path(import)?)
} else {
Err(ImportParseError::ProhibitedRelativeImport(import.to_owned()).into())
}
}
Some((alias, cell_relative_path)) => {
let cell = cell_resolver.resolve(alias)?;
Ok(CellPath::new(
cell,
CellRelativePathBuf::try_from(cell_relative_path.to_owned())?,
))
}
}
}
Some((path, filename)) => {
if filename.is_empty() {
return Err(ImportParseError::EmptyFileName(import.to_owned()).into());
}
let filename = FileName::new(filename)
.map_err(|_| ImportParseError::NotAFileName(import.to_owned()))?;
if path.is_empty() {
if let RelativeImports::Allow {
current_dir_with_allowed_relative,
} = opts.relative_import_option
{
Ok(current_dir_with_allowed_relative.join(filename))
} else {
Err(ImportParseError::ProhibitedRelativeImport(import.to_owned()).into())
}
} else {
let (alias, cell_relative_path) =
parse_import_cell_path_parts(path, opts.allow_missing_at_symbol)
.ok_or_else(|| ImportParseError::MatchFailed(import.to_owned()))?;
let cell = cell_resolver.resolve(alias)?;
Ok(CellPath::new(
cell,
<&CellRelativePath>::try_from(cell_relative_path)?.join(filename),
))
}
}
}
}
pub fn parse_bzl_path_with_config(
cell_resolver: &CellAliasResolver,
import: &str,
opts: &ParseImportOptions,
build_cell_path: BuildFileCell,
) -> buck2_error::Result<ImportPath> {
let path = parse_import_with_config(cell_resolver, import, opts)?;
ImportPath::new_with_build_file_cells(path, build_cell_path)
}
#[cfg(test)]
mod tests {
use buck2_core::cells::alias::NonEmptyCellAlias;
use buck2_core::cells::name::CellName;
use buck2_hash::StdBuckHashMap;
use super::*;
fn resolver() -> CellAliasResolver {
let mut m = StdBuckHashMap::default();
m.insert(
NonEmptyCellAlias::new("cell1".to_owned()).unwrap(),
CellName::testing_new("cell1"),
);
m.insert(
NonEmptyCellAlias::new("alias2".to_owned()).unwrap(),
CellName::testing_new("cell2"),
);
CellAliasResolver::new(CellName::testing_new("root"), m).expect("valid resolver")
}
fn path(cell: &str, dir: &str, filename: &str) -> CellPath {
CellPath::new(
CellName::testing_new(cell),
CellRelativePath::unchecked_new(dir).join(FileName::unchecked_new(filename)),
)
}
#[test]
fn root_package() -> buck2_error::Result<()> {
assert_eq!(
path("root", "package/path", "import.bzl"),
parse_import(
&resolver(),
RelativeImports::Allow {
current_dir_with_allowed_relative: &CellPathWithAllowedRelativeDir::new(
CellPath::testing_new("passport//"),
None,
),
},
"//package/path:import.bzl"
)?
);
Ok(())
}
#[test]
fn cell_package() -> buck2_error::Result<()> {
assert_eq!(
path("cell1", "package/path", "import.bzl"),
parse_import(
&resolver(),
RelativeImports::Allow {
current_dir_with_allowed_relative: &CellPathWithAllowedRelativeDir::new(
CellPath::testing_new("root//"),
None,
),
},
"@cell1//package/path:import.bzl"
)?
);
Ok(())
}
#[test]
fn package_relative() -> buck2_error::Result<()> {
assert_eq!(
path("cell1", "package/path", "import.bzl"),
parse_import(
&resolver(),
RelativeImports::Allow {
current_dir_with_allowed_relative: &CellPathWithAllowedRelativeDir::new(
CellPath::testing_new("cell1//package/path"),
None,
),
},
":import.bzl"
)?
);
Ok(())
}
#[test]
fn missing_colon() -> buck2_error::Result<()> {
let import = "//package/path/import.bzl".to_owned();
assert_eq!(
parse_import(
&resolver(),
RelativeImports::Allow {
current_dir_with_allowed_relative: &CellPathWithAllowedRelativeDir::new(
CellPath::testing_new("lighter//"),
None,
),
},
&import
)?,
path("root", "package/path", "import.bzl")
);
Ok(())
}
#[test]
fn empty_filename() -> buck2_error::Result<()> {
let path = "//package/path:".to_owned();
match parse_import(
&resolver(),
RelativeImports::Allow {
current_dir_with_allowed_relative: &CellPathWithAllowedRelativeDir::new(
CellPath::testing_new("root//"),
None,
),
},
&path,
) {
Ok(import) => panic!("Expected parse failure for {path}, got result {import}"),
Err(e) => {
assert_eq!(
format!("{e:#}"),
ImportParseError::EmptyFileName(path.to_owned()).to_string()
);
}
}
Ok(())
}
#[test]
fn bad_alias() -> buck2_error::Result<()> {
let path = "bad_alias//package/path:".to_owned();
match parse_import(
&resolver(),
RelativeImports::Allow {
current_dir_with_allowed_relative: &CellPathWithAllowedRelativeDir::new(
CellPath::testing_new("root//"),
None,
),
},
&path,
) {
Ok(import) => panic!("Expected parse failure for {path}, got result {import}"),
Err(_) => {
// TODO: should we verify the contents of the error?
}
}
Ok(())
}
#[test]
fn file_relative_import_given_relative_paths_allowed() -> buck2_error::Result<()> {
assert_eq!(
path("cell1", "package/path", "bar.bzl"),
parse_import(
&resolver(),
RelativeImports::Allow {
current_dir_with_allowed_relative: &CellPathWithAllowedRelativeDir::new(
CellPath::testing_new("cell1//package/path"),
None,
),
},
"bar.bzl",
)?
);
assert_eq!(
path("cell1", "package/path", "foo/bar.bzl"),
parse_import(
&resolver(),
RelativeImports::Allow {
current_dir_with_allowed_relative: &CellPathWithAllowedRelativeDir::new(
CellPath::testing_new("cell1//package/path"),
None,
),
},
"foo/bar.bzl",
)?
);
Ok(())
}
#[test]
fn cell_relative_import_given_relative_paths_allowed() -> buck2_error::Result<()> {
let importer = CellPath::testing_new("cell1//package/path");
let importee = "foo/bar.bzl";
assert_eq!(
parse_import(
&resolver(),
RelativeImports::Allow {
current_dir_with_allowed_relative: &CellPathWithAllowedRelativeDir::new(
importer, None,
),
},
importee
)?,
path("cell1", "package/path/foo", "bar.bzl")
);
Ok(())
}
#[test]
fn regular_import_given_relative_paths_allowed() -> buck2_error::Result<()> {
assert_eq!(
path("cell1", "package/path", "import.bzl"),
parse_import(
&resolver(),
RelativeImports::Allow {
current_dir_with_allowed_relative: &CellPathWithAllowedRelativeDir::new(
CellPath::testing_new("root//foo/bar"),
None,
),
},
"@cell1//package/path:import.bzl",
)?
);
Ok(())
}
#[test]
fn allows_non_at_symbols() -> buck2_error::Result<()> {
assert_eq!(
path("cell1", "package/path", "import.bzl"),
parse_import_with_config(
&resolver(),
"cell1//package/path:import.bzl",
&ParseImportOptions {
allow_missing_at_symbol: true,
relative_import_option: RelativeImports::Allow {
current_dir_with_allowed_relative: &CellPathWithAllowedRelativeDir::new(
CellPath::testing_new("root//"),
None,
),
},
}
)?,
);
Ok(())
}
#[test]
fn fails_relative_import_if_disallowed() -> buck2_error::Result<()> {
let imported_file = ":bar.bzl";
let res = parse_import_with_config(
&resolver(),
imported_file,
&ParseImportOptions {
allow_missing_at_symbol: false,
relative_import_option: RelativeImports::Disallow,
},
);
match res {
Ok(res) => panic!("Expected parse failure for {imported_file}, got result {res}"),
Err(e) => {
assert_eq!(
format!("{e:#}"),
ImportParseError::ProhibitedRelativeImport(imported_file.to_owned())
.to_string()
);
}
};
Ok(())
}
}