Repository navigation
Expand file tree
/
Copy pathsettings.rs
More file actions
688 lines (633 loc) · 25 KB
/
Copy pathsettings.rs
File metadata and controls
688 lines (633 loc) · 25 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
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
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
use core::cmp;
use core::num::NonZeroI32;
use core::str::FromStr;
use lexopt::Arg::{Long, Short, Value};
use lexopt::ValueExt;
use rustpython_vm::{Settings, vm::CheckHashPycsMode};
use std::env;
pub enum RunMode {
Script(String),
Command(String),
Module(String),
InstallPip(InstallPipMode),
Repl,
}
pub enum InstallPipMode {
/// Install pip using the ensurepip pip module. This has a higher chance of
/// success, but may not install the latest version of pip.
Ensurepip,
/// Install pip using the get-pip.py script, which retrieves the latest pip version.
/// This can be broken due to incompatibilities with cpython.
GetPip,
}
impl FromStr for InstallPipMode {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"ensurepip" => Ok(Self::Ensurepip),
"get-pip" => Ok(Self::GetPip),
_ => Err("--install-pip takes ensurepip or get-pip as first argument"),
}
}
}
#[derive(Default)]
struct CliArgs {
bytes_warning: u8,
dont_write_bytecode: bool,
debug: u8,
ignore_environment: bool,
inspect: bool,
isolate: bool,
optimize: u8,
safe_path: bool,
quiet: bool,
random_hash_seed: bool,
no_user_site: bool,
no_site: bool,
unbuffered: bool,
verbose: u8,
warning_control: Vec<String>,
implementation_option: Vec<String>,
check_hash_based_pycs: CheckHashPycsMode,
#[cfg(feature = "flame-it")]
profile_output: Option<std::ffi::OsString>,
#[cfg(feature = "flame-it")]
profile_format: Option<String>,
}
const USAGE_STRING: &str = "\
usage: {PROG} [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options (and corresponding environment variables):
-b : issue warnings about converting bytes/bytearray to str and comparing
bytes/bytearray with str or bytes with int. (-bb: issue errors)
-B : don't write .pyc files on import; also PYTHONDONTWRITEBYTECODE=x
-c cmd : program passed in as string (terminates option list)
-d : turn on parser debugging output (for experts only, only works on
debug builds); also PYTHONDEBUG=x
-E : ignore PYTHON* environment variables (such as PYTHONPATH)
-h : print this help message and exit (also -? or --help)
-i : inspect interactively after running script; forces a prompt even
if stdin does not appear to be a terminal; also PYTHONINSPECT=x
-I : isolate Python from the user's environment (implies -E and -s)
-m mod : run library module as a script (terminates option list)
-O : remove assert and __debug__-dependent statements; add .opt-1 before
.pyc extension; also PYTHONOPTIMIZE=x
-OO : do -O changes and also discard docstrings; add .opt-2 before
.pyc extension
-P : don't prepend a potentially unsafe path to sys.path; also
PYTHONSAFEPATH
-q : don't print version and copyright messages on interactive startup
-s : don't add user site directory to sys.path; also PYTHONNOUSERSITE=x
-S : don't imply 'import site' on initialization
-u : force the stdout and stderr streams to be unbuffered;
this option has no effect on stdin; also PYTHONUNBUFFERED=x
-v : verbose (trace import statements); also PYTHONVERBOSE=x
can be supplied multiple times to increase verbosity
-V : print the Python version number and exit (also --version)
when given twice, print more information about the build
-W arg : warning control; arg is action:message:category:module:lineno
also PYTHONWARNINGS=arg
-x : skip first line of source, allowing use of non-Unix forms of #!cmd
-X opt : set implementation-specific option
-X lazy_imports=all|normal: control global lazy imports (default: normal);
also PYTHON_LAZY_IMPORTS
--check-hash-based-pycs always|default|never:
control how Python invalidates hash-based .pyc files
--help-env: print help about Python environment variables and exit
--help-xoptions: print help about implementation-specific -X options and exit
--help-all: print complete help information and exit
RustPython extensions:
Arguments:
file : program read from script file
- : program read from stdin (default; interactive mode if a tty)
arg ...: arguments passed to program in sys.argv[1:]
";
fn parse_args() -> Result<(CliArgs, RunMode, Vec<String>), lexopt::Error> {
let mut args = CliArgs::default();
let mut parser = lexopt::Parser::from_env();
fn argv(argv0: String, mut parser: lexopt::Parser) -> Result<Vec<String>, lexopt::Error> {
core::iter::once(Ok(argv0))
.chain(parser.raw_args()?.map(|arg| arg.string()))
.collect()
}
while let Some(arg) = parser.next()? {
match arg {
Short('b') => args.bytes_warning += 1,
Short('B') => args.dont_write_bytecode = true,
Short('c') => {
let cmd = parser.value()?.string()?;
return Ok((
args,
RunMode::Command(dedent(&cmd)),
argv("-c".to_owned(), parser)?,
));
}
Short('d') => args.debug += 1,
Short('E') => args.ignore_environment = true,
Short('h' | '?') | Long("help") => help(parser),
Short('i') => args.inspect = true,
Short('I') => args.isolate = true,
Short('m') => {
let module = parser.value()?.string()?;
let argv = argv("-m".to_owned(), parser)?;
return Ok((args, RunMode::Module(module), argv));
}
Short('O') => args.optimize += 1,
Short('P') => args.safe_path = true,
Short('q') => args.quiet = true,
Short('R') => args.random_hash_seed = true,
Short('S') => args.no_site = true,
Short('s') => args.no_user_site = true,
Short('u') => args.unbuffered = true,
Short('v') => args.verbose += 1,
Short('V') | Long("version") => version(),
Short('W') => args.warning_control.push(parser.value()?.string()?),
// TODO: Short('x') =>
Short('X') => args.implementation_option.push(parser.value()?.string()?),
Long("check-hash-based-pycs") => {
args.check_hash_based_pycs = parser.value()?.parse()?
}
// TODO: make these more specific
Long("help-env") => help(parser),
Long("help-xoptions") => help(parser),
Long("help-all") => help(parser),
#[cfg(feature = "flame-it")]
Long("profile-output") => args.profile_output = Some(parser.value()?),
#[cfg(feature = "flame-it")]
Long("profile-format") => args.profile_format = Some(parser.value()?.string()?),
Long("install-pip") => {
let (mode, argv) = if let Some(val) = parser.optional_value() {
(val.parse()?, vec![val.string()?])
} else if let Ok(argv0) = parser.value() {
let mode = argv0.parse()?;
(mode, argv(argv0.string()?, parser)?)
} else {
(
InstallPipMode::Ensurepip,
["ensurepip", "--upgrade", "--default-pip"]
.map(str::to_owned)
.into(),
)
};
return Ok((args, RunMode::InstallPip(mode), argv));
}
Value(script_name) => {
let script_name = script_name.string()?;
let mode = if script_name == "-" {
RunMode::Repl
} else {
RunMode::Script(script_name.clone())
};
return Ok((args, mode, argv(script_name, parser)?));
}
_ => return Err(arg.unexpected()),
}
}
Ok((args, RunMode::Repl, vec![]))
}
fn help(parser: lexopt::Parser) -> ! {
let usage = USAGE_STRING.replace("{PROG}", parser.bin_name().unwrap_or("rustpython"));
print!("{usage}");
std::process::exit(0);
}
fn version() -> ! {
println!("Python {}", rustpython_vm::version::RUSTPYTHON_VERSION);
std::process::exit(0);
}
/// Create settings by examining command line arguments and environment
/// variables.
pub fn parse_opts() -> Result<(Settings, RunMode), lexopt::Error> {
let (args, mode, argv) = parse_args()?;
let mut settings = Settings::default();
settings.isolated = args.isolate;
settings.ignore_environment = settings.isolated || args.ignore_environment;
settings.bytes_warning = args.bytes_warning.into();
settings.import_site = !args.no_site;
let ignore_environment = settings.ignore_environment;
if !ignore_environment {
settings.path_list.extend(get_paths("RUSTPYTHONPATH"));
settings.path_list.extend(get_paths("PYTHONPATH"));
}
// Now process command line flags:
let get_env = |env| (!ignore_environment).then(|| env::var_os(env)).flatten();
settings.home = get_env("PYTHONHOME")
.filter(|home| !home.is_empty())
.map(|home| home.to_string_lossy().into_owned());
let env_count = |env| {
get_env(env).filter(|v| !v.is_empty()).map_or(0, |val| {
val.to_str().and_then(|v| v.parse::<u8>().ok()).unwrap_or(1)
})
};
settings.optimize = cmp::max(args.optimize, env_count("PYTHONOPTIMIZE"));
settings.verbose = cmp::max(args.verbose, env_count("PYTHONVERBOSE"));
settings.debug = cmp::max(args.debug, env_count("PYTHONDEBUG"));
let env_bool = |env| get_env(env).is_some_and(|v| !v.is_empty());
settings.user_site_directory =
!(settings.isolated || args.no_user_site || env_bool("PYTHONNOUSERSITE"));
settings.quiet = args.quiet;
settings.write_bytecode = !(args.dont_write_bytecode || env_bool("PYTHONDONTWRITEBYTECODE"));
settings.safe_path = settings.isolated || args.safe_path || env_bool("PYTHONSAFEPATH");
settings.inspect = args.inspect || env_bool("PYTHONINSPECT");
settings.interactive = args.inspect;
settings.buffered_stdio = !args.unbuffered;
if let Some(val) = get_env("PYTHONINTMAXSTRDIGITS") {
settings.int_max_str_digits = match val.to_str().and_then(|s| s.parse().ok()) {
Some(digits @ (0 | 640..)) => digits,
_ => {
error!(
"Fatal Python error: config_init_int_max_str_digits: PYTHONINTMAXSTRDIGITS: invalid limit; must be >= 640 or 0 for unlimited.\nPython runtime state: preinitialized"
);
std::process::exit(1);
}
};
}
if let Some(val) = get_env("PYTHON_CPU_COUNT") {
settings.cpu_count = match parse_cpu_count(val.to_str()) {
Ok(cpu_count) => cpu_count,
Err(()) => {
error!(
"Fatal Python error: config_init_cpu_count: \
-X cpu_count=n option: n is missing or an invalid number, \
n must be greater than 0\n\
Python runtime state: preinitialized"
);
std::process::exit(1);
}
};
}
settings.check_hash_pycs_mode = args.check_hash_based_pycs;
if let Some(val) = get_env("PYTHONUTF8")
&& let Some(val_str) = val.to_str()
&& !val_str.is_empty()
{
settings.utf8_mode = match val_str {
"1" => 1,
"0" => 0,
_ => {
error!(
"Fatal Python error: config_init_utf8_mode: \
PYTHONUTF8=N: N is missing or invalid\n\
Python runtime state: preinitialized"
);
std::process::exit(1);
}
};
}
if let Some(val) = get_env("PYTHON_LAZY_IMPORTS").filter(|val| !val.is_empty()) {
settings.lazy_imports = parse_lazy_imports(val.to_str(), "PYTHON_LAZY_IMPORTS");
}
if let Some(value) = get_env("PYTHONPROFILEIMPORTTIME").filter(|value| !value.is_empty()) {
settings.import_time = parse_import_time(value.to_str(), "PYTHONPROFILEIMPORTTIME");
}
if let Some(value) = get_env("PYTHON_FROZEN_MODULES").filter(|value| !value.is_empty()) {
settings.use_frozen_modules =
parse_frozen_modules(Some(&value.to_string_lossy()), "PYTHON_FROZEN_MODULES");
}
// CPython uses the first occurrence of these -X options.
let mut lazy_imports_option_seen = false;
let mut import_time_option_seen = false;
let mut frozen_modules_option_seen = false;
let xopts = args.implementation_option.into_iter().map(|s| {
let (name, value) = match s.split_once('=') {
Some((name, value)) => (name.to_owned(), Some(value)),
None => (s, None),
};
match &*name {
"dev" => settings.dev_mode = true,
"importtime" if !import_time_option_seen => {
settings.import_time = parse_import_time(value, "-X importtime");
import_time_option_seen = true;
}
"frozen_modules" if !frozen_modules_option_seen => {
settings.use_frozen_modules =
parse_frozen_modules(value, "option -X frozen_modules");
frozen_modules_option_seen = true;
}
"faulthandler" => settings.faulthandler = true,
"warn_default_encoding" => settings.warn_default_encoding = true,
"utf8" => {
settings.utf8_mode = match value {
None => 1,
Some("1") => 1,
Some("0") => 0,
_ => {
error!(
"Fatal Python error: config_init_utf8_mode: \
-X utf8=n: n is missing or invalid\n\
Python runtime state: preinitialized"
);
std::process::exit(1);
}
};
}
"no_sig_int" => settings.install_signal_handlers = false,
"no_debug_ranges" => settings.code_debug_ranges = false,
"lazy_imports" if !lazy_imports_option_seen => {
settings.lazy_imports = parse_lazy_imports(value, "-X lazy_imports");
lazy_imports_option_seen = true;
}
"cpu_count" => {
settings.cpu_count = match parse_cpu_count(value) {
Ok(cpu_count) => cpu_count,
Err(()) => {
error!(
"Fatal Python error: config_init_cpu_count: \
-X cpu_count=n option: n is missing or an invalid \
number, n must be greater than 0\n\
Python runtime state: preinitialized"
);
std::process::exit(1);
}
};
}
"int_max_str_digits" => {
settings.int_max_str_digits = match value.and_then(|value| value.parse().ok()) {
Some(digits) if digits == 0 || digits >= 640 => digits,
_ => {
error!(
"Fatal Python error: config_init_int_max_str_digits: \
-X int_max_str_digits: \
invalid limit; must be >= 640 or 0 for unlimited.\n\
Python runtime state: preinitialized"
);
std::process::exit(1);
}
};
}
"thread_inherit_context" => {
settings.thread_inherit_context = match value {
Some("1") => true,
Some("0") => false,
_ => {
error!(
"Fatal Python error: config_init_thread_inherit_context: \
-X thread_inherit_context=n: n is missing or invalid\n\
Python runtime state: preinitialized"
);
std::process::exit(1);
}
};
}
_ => {}
}
(name, value.map(str::to_owned))
});
settings.xoptions.extend(xopts);
// CPython validates the first frozen_modules option before initialization,
// then getpath's config dictionary round-trip keeps the last occurrence.
if let Some((_, value)) = settings
.xoptions
.iter()
.rev()
.find(|(name, _)| name == "frozen_modules")
{
settings.use_frozen_modules =
parse_frozen_modules(value.as_deref(), "option -X frozen_modules");
}
// Resolve utf8_mode if not explicitly set by PYTHONUTF8 or -X utf8.
// Default to UTF-8 mode since RustPython's locale encoding detection
// is incomplete. Users can set PYTHONUTF8=0 or -X utf8=0 to disable.
if settings.utf8_mode < 0 {
settings.utf8_mode = 1;
}
settings.warn_default_encoding =
settings.warn_default_encoding || env_bool("PYTHONWARNDEFAULTENCODING");
settings.faulthandler = settings.faulthandler || env_bool("PYTHONFAULTHANDLER");
if env_bool("PYTHONNODEBUGRANGES") {
settings.code_debug_ranges = false;
}
if let Some(val) = get_env("PYTHON_THREAD_INHERIT_CONTEXT") {
settings.thread_inherit_context = match val.to_str() {
Some("1") => true,
Some("0") => false,
_ => {
error!(
"Fatal Python error: config_init_thread_inherit_context: \
PYTHON_THREAD_INHERIT_CONTEXT=N: N is missing or invalid\n\
Python runtime state: preinitialized"
);
std::process::exit(1);
}
};
}
// Parse PYTHONIOENCODING=encoding[:errors]
if let Some(val) = get_env("PYTHONIOENCODING")
&& let Some(val_str) = val.to_str()
&& !val_str.is_empty()
{
if let Some((enc, err)) = val_str.split_once(':') {
if !enc.is_empty() {
settings.stdio_encoding = Some(enc.to_owned());
}
if !err.is_empty() {
settings.stdio_errors = Some(err.to_owned());
}
} else {
settings.stdio_encoding = Some(val_str.to_owned());
}
}
if settings.dev_mode {
settings.warnoptions.push("default".to_owned());
settings.faulthandler = true;
}
if settings.bytes_warning > 0 {
let warn = if settings.bytes_warning > 1 {
"error::BytesWarning"
} else {
"default::BytesWarning"
};
settings.warnoptions.push(warn.to_owned());
}
if let Some(val) = get_env("PYTHONWARNINGS")
&& let Some(val_str) = val.to_str()
&& !val_str.is_empty()
{
for warning in val_str.split(',') {
let warning = warning.trim();
if !warning.is_empty() {
settings.warnoptions.push(warning.to_owned());
}
}
}
settings.warnoptions.extend(args.warning_control);
settings.hash_seed = match (!args.random_hash_seed)
.then(|| get_env("PYTHONHASHSEED"))
.flatten()
{
Some(s) if s == "random" || s.is_empty() => None,
Some(s) => {
let seed = s.parse_with(|s| {
s.parse::<u32>().map_err(|_| {
"Fatal Python init error: PYTHONHASHSEED must be \
\"random\" or an integer in range [0; 4294967295]"
})
})?;
Some(seed)
}
None => None,
};
settings.argv = argv;
#[cfg(feature = "flame-it")]
{
settings.profile_output = args.profile_output;
settings.profile_format = args.profile_format;
}
Ok((settings, mode))
}
/// `-X cpu_count` / `PYTHON_CPU_COUNT`: a count above zero, or `"default"`.
/// `Ok(None)` leaves the count to the host. Zero, negatives, and values above
/// `i32::MAX` are rejected.
/// = config_init_cpu_count
fn parse_cpu_count(value: Option<&str>) -> Result<Option<NonZeroI32>, ()> {
match value {
None => Err(()),
Some("default") => Ok(None),
Some(number) => number
.parse()
.ok()
.filter(|count: &NonZeroI32| count.get() > 0)
.map(Some)
.ok_or(()),
}
}
fn parse_frozen_modules(value: Option<&str>, source: &str) -> bool {
match value {
None | Some("" | "on") => true,
Some("off") => false,
_ => {
eprintln!(
"Fatal Python error: config_init_import: bad value for {source} (expected \"on\" or \"off\")"
);
std::process::exit(1);
}
}
}
/// = config_init_import_time
fn parse_import_time(value: Option<&str>, source: &str) -> u8 {
let value = value
.and_then(|value| {
value
.trim_start_matches([' ', '\t', '\n', '\r', '\x0b', '\x0c'])
.parse::<i32>()
.ok()
})
.unwrap_or(1);
if !(0..=2).contains(&value) {
let numeric = if source == "PYTHONPROFILEIMPORTTIME" {
"numeric "
} else {
""
};
eprintln!(
"Fatal Python error: config_init_import_time: {source}: \
{numeric}values other than 1 and 2 are reserved for future use.\n\
Python runtime state: preinitialized\n"
);
std::process::exit(1);
}
value as u8
}
/// = config_init_lazy_imports
fn parse_lazy_imports(value: Option<&str>, source: &str) -> i8 {
match value {
Some("normal") => -1,
Some("all") => 1,
_ => {
eprintln!(
"Fatal Python error: config_init_lazy_imports: \
{source}: invalid value; expected 'all' or 'normal'\n\
Python runtime state: preinitialized\n"
);
std::process::exit(1);
}
}
}
fn get_paths(env_variable_name: &str) -> impl Iterator<Item = String> + '_ {
env::var_os(env_variable_name)
.filter(|v| !v.is_empty())
.into_iter()
.flat_map(move |paths| {
split_paths(&paths)
.map(|path| {
path.into_os_string()
.into_string()
.unwrap_or_else(|_| panic!("{env_variable_name} isn't valid unicode"))
})
.collect::<Vec<_>>()
})
}
#[cfg(not(target_os = "wasi"))]
pub(crate) use env::split_paths;
#[cfg(target_os = "wasi")]
pub(crate) fn split_paths<T: AsRef<std::ffi::OsStr> + ?Sized>(
s: &T,
) -> impl Iterator<Item = std::path::PathBuf> + '_ {
let s = s.as_ref().as_encoded_bytes();
s.split(|b| *b == b':').map(|x| {
unsafe { std::ffi::OsStr::from_encoded_bytes_unchecked(x) }
.to_owned()
.into()
})
}
/// Remove common whitespace prefix from all lines in a string.
///
/// This is like textwrap.dedent, and is used to process -c's code
/// argument. It's different from ruff's dedent, which does not
/// distinguish between tab and space characters when dedenting.
fn dedent(input: &str) -> String {
let mut prefix: Option<String> = None;
let isspace = |c| c == ' ' || c == '\t';
// All-whitespace lines become empty.
let deblanked: Vec<&str> = input
.lines()
.map(|line| if line.chars().all(isspace) { "" } else { line })
.collect();
// Find maximum common whitespace prefix, if any.
for line in &deblanked {
if line.is_empty() {
continue;
}
if let Some(ref mut pstr) = prefix {
for (i, (c, pc)) in line.chars().zip(pstr.chars()).enumerate() {
// It's okay if `line` is shorter than `pstr`. At
// least one char in `line` must be non-whitespace,
// and if `line` is shorter than `pstr`, this
// non-whitespace char will be compared to a
// whitespace char, and loop will terminate.
if c != pc {
pstr.truncate(i);
break;
}
}
} else {
let mut pstr = String::new();
for c in line.chars() {
if isspace(c) {
pstr.push(c);
} else {
break;
}
}
prefix = Some(pstr);
continue;
}
}
if let Some(pstr) = prefix {
// Strip common prefix.
deblanked
.iter()
.map(|line| {
if line.is_empty() {
String::from("")
} else {
// All non-empty lines start with pstr, must be at
// least pstr.len() long.
String::from(line.get(pstr.len()..).unwrap())
}
})
.collect::<Vec<_>>()
.join("\n")
} else {
// No prefix found: all lines blank.
deblanked.join("\n")
}
}