Repository navigation
Expand file tree
/
Copy pathwrite.rs
More file actions
1529 lines (1410 loc) · 55 KB
/
Copy pathwrite.rs
File metadata and controls
1529 lines (1410 loc) · 55 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
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Atomic write, final newline, EOL normalization, trailing-whitespace trimming.
//!
//! size-waiver: atomic write + hardlink + symlink + Windows named-stream persist (#1230 / #1733 / #1408 / #2341).
use std::path::Path;
use anyhow::Context;
use tempfile::NamedTempFile;
/// Detect the dominant line ending in `text`.
///
/// Returns `"\r\n"` when CRLF sequences are present and at least as common
/// as bare LF; otherwise returns `"\n"`.
///
/// This is the canonical implementation used by all AST and ops modules
/// to preserve the original file's line ending style during content
/// reconstruction.
pub fn detect_eol(text: &str) -> &'static str {
let crlf = text.matches("\r\n").count();
let lf_only = text.matches('\n').count().saturating_sub(crlf);
let cr_only = text.matches('\r').count().saturating_sub(crlf);
if crlf > 0 && crlf >= lf_only && crlf >= cr_only {
"\r\n"
} else if cr_only > 0 && cr_only >= lf_only {
"\r"
} else {
"\n"
}
}
/// True when `data` contains both CRLF and a bare LF.
pub fn has_mixed_eol(data: &[u8]) -> bool {
let has_crlf = memchr::memmem::find(data, b"\r\n").is_some();
let has_bare_lf = memchr::memchr_iter(b'\n', data).any(|i| i == 0 || data[i - 1] != b'\r');
has_crlf && has_bare_lf
}
/// If the file mixes line endings, normalize to the dominant style.
///
/// Uniform LF or CRLF is left unchanged. Used by default `tidy fix` so
/// a follow-up `tidy check` is clean.
pub fn unmix_eol(content: &str) -> std::borrow::Cow<'_, str> {
if !has_mixed_eol(content.as_bytes()) {
return std::borrow::Cow::Borrowed(content);
}
let mode = match detect_eol(content) {
"\r\n" => EolMode::Crlf,
"\r" => EolMode::Cr,
_ => EolMode::Lf,
};
normalize_eol(content, mode)
}
/// Line ending normalization mode.
///
/// This type is re-exported at the crate root level of `write` for library use
/// (independent of the optional `cli` feature).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[cfg_attr(feature = "cli", derive(clap::ValueEnum))]
pub enum EolMode {
/// Keep existing line endings.
#[default]
Keep,
/// Normalize to LF.
Lf,
/// Normalize to CRLF.
Crlf,
/// Normalize to CR (classic Mac).
Cr,
}
/// EditorConfig `charset` handling for text writes.
///
/// Patchloom is a UTF-8 text tool. `utf-8` / `latin1` never insert a BOM;
/// `utf-8-bom` ensures a leading U+FEFF. UTF-16 variants are refused.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum CharsetMode {
/// Leave any existing BOM (or lack of one) unchanged.
#[default]
Keep,
/// UTF-8 without BOM: strip a leading U+FEFF if present.
Utf8,
/// UTF-8 with BOM: ensure a leading U+FEFF.
Utf8Bom,
/// EditorConfig charset this process cannot apply (`utf-16le`, `utf-16be`).
Unsupported(&'static str),
}
/// Controls which transformations are applied before writing a file.
///
/// `#[non_exhaustive]`: new knobs may appear in a minor release. Construct
/// with [`WritePolicy::default`] and update fields, or use
/// [`crate::api::make_write_policy`].
#[non_exhaustive]
pub struct WritePolicy {
pub ensure_final_newline: bool,
pub normalize_eol: EolMode,
pub trim_trailing_whitespace: bool,
pub collapse_blanks: bool,
pub charset: CharsetMode,
}
impl WritePolicy {
/// Returns `true` when no transformations are configured, meaning content
/// can be written (or moved) byte-for-byte without interpretation.
pub fn is_noop(&self) -> bool {
!self.ensure_final_newline
&& matches!(self.normalize_eol, EolMode::Keep)
&& !self.trim_trailing_whitespace
&& !self.collapse_blanks
&& matches!(self.charset, CharsetMode::Keep)
}
/// EditorConfig charset this write cannot apply, if any.
pub fn unsupported_charset(&self) -> Option<&'static str> {
match self.charset {
CharsetMode::Unsupported(name) => Some(name),
_ => None,
}
}
/// Fail closed when EditorConfig asks for a charset we cannot write.
pub fn refuse_unsupported_charset(&self) -> anyhow::Result<()> {
if let Some(name) = self.unsupported_charset() {
return Err(crate::exit::InvalidInputError {
msg: format!(
"editorconfig charset '{name}' is not supported; use utf-8 or utf-8-bom"
),
}
.into());
}
Ok(())
}
/// Apply an override, setting only the fields that are `Some`.
/// Validates all fields before mutating to avoid partial state on error.
pub fn apply_override(&mut self, ov: &WritePolicyOverride) -> anyhow::Result<()> {
// Validate first: parse normalize_eol before touching any field.
let parsed_eol = match ov.normalize_eol {
Some(ref s) => Some(parse_eol_mode(s)?),
None => None,
};
// All validation passed; now mutate.
if let Some(v) = ov.ensure_final_newline {
self.ensure_final_newline = v;
}
if let Some(eol) = parsed_eol {
self.normalize_eol = eol;
}
if let Some(v) = ov.trim_trailing_whitespace {
self.trim_trailing_whitespace = v;
}
if let Some(v) = ov.collapse_blanks {
self.collapse_blanks = v;
}
Ok(())
}
}
impl Default for WritePolicy {
fn default() -> Self {
Self {
ensure_final_newline: false,
normalize_eol: EolMode::Keep,
trim_trailing_whitespace: false,
collapse_blanks: false,
charset: CharsetMode::Keep,
}
}
}
/// Partially-specified write policy for config files, plans, and overrides.
///
/// Each field is optional; only `Some` values override the base [`WritePolicy`].
/// Used by `.patchloom.toml` config, tx plan `write_policy`, and any context
/// that needs to partially override write transformations.
#[derive(Debug, Default, Clone, serde::Deserialize, serde::Serialize, schemars::JsonSchema)]
#[serde(default)]
pub struct WritePolicyOverride {
pub ensure_final_newline: Option<bool>,
pub normalize_eol: Option<String>,
pub trim_trailing_whitespace: Option<bool>,
pub collapse_blanks: Option<bool>,
pub respect_editorconfig: Option<bool>,
}
/// Parse a string EOL mode value into [`EolMode`].
pub fn parse_eol_mode(mode: &str) -> anyhow::Result<EolMode> {
match mode {
"lf" => Ok(EolMode::Lf),
"crlf" => Ok(EolMode::Crlf),
"cr" => Ok(EolMode::Cr),
"keep" => Ok(EolMode::Keep),
_ => Err(anyhow::Error::new(crate::exit::InvalidInputError {
msg: format!(
"invalid normalize_eol value '{mode}': expected 'lf', 'crlf', 'cr', or 'keep'"
),
})),
}
}
/// A validated `--dedent` / `--indent` specification.
///
/// Parsed by [`parse_dedent_spec`] and [`parse_indent_spec`] so that an
/// unusable value is rejected once, up front, instead of silently degrading to
/// a no-op (#2378).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IndentSpec {
/// Dedent only: strip the smallest non-zero indent found in range.
Auto,
/// One leading tab.
Tab,
/// N whitespace characters (dedent) or N spaces (indent). Zero is a no-op.
Spaces(usize),
}
fn invalid_spec(flag: &str, spec: &str, accepted: &str) -> anyhow::Error {
anyhow::Error::new(crate::exit::InvalidInputError {
msg: format!("invalid {flag} value '{spec}': expected {accepted}"),
})
}
/// Parse a `--dedent` spec: `"auto"`, `"tab"`, or a non-negative integer.
///
/// `"0"` parses to `IndentSpec::Spaces(0)`, which is a deliberate no-op.
pub fn parse_dedent_spec(spec: &str) -> anyhow::Result<IndentSpec> {
match spec {
"auto" => Ok(IndentSpec::Auto),
"tab" => Ok(IndentSpec::Tab),
n => n.parse::<usize>().map(IndentSpec::Spaces).map_err(|_| {
invalid_spec("--dedent", spec, "'auto', 'tab', or a non-negative integer")
}),
}
}
/// Parse an `--indent` spec: `"tab"` or a non-negative integer.
///
/// `"auto"` is rejected: there is nothing to infer when adding indentation.
pub fn parse_indent_spec(spec: &str) -> anyhow::Result<IndentSpec> {
match spec {
"tab" => Ok(IndentSpec::Tab),
"auto" => Err(invalid_spec(
"--indent",
spec,
"'tab' or a non-negative integer ('auto' applies to --dedent only)",
)),
n => n
.parse::<usize>()
.map(IndentSpec::Spaces)
.map_err(|_| invalid_spec("--indent", spec, "'tab' or a non-negative integer")),
}
}
/// If `content` is non-empty and does not already end with the appropriate
/// line terminator for `eol`, append one. Empty content is returned unchanged.
///
/// The terminator depends on `eol`:
/// - `Lf` / `Keep` => `\n`
/// - `Crlf` => `\r\n`
/// - `Cr` => `\r`
///
/// Returns `Cow::Borrowed` when no change is needed, avoiding allocation.
pub fn ensure_final_newline(content: &str, eol: EolMode) -> std::borrow::Cow<'_, str> {
use std::borrow::Cow;
let (suffix, already_ok) = match eol {
EolMode::Cr => ("\r", content.ends_with('\r')),
EolMode::Crlf => ("\r\n", content.ends_with("\r\n")),
EolMode::Lf => ("\n", content.ends_with('\n')),
EolMode::Keep => {
// Use the file's dominant line ending so we don't introduce
// mixed endings (#1175).
let detected = detect_eol(content);
(detected, content.ends_with(detected))
}
};
if content.is_empty() || already_ok {
Cow::Borrowed(content)
} else {
let mut s = String::with_capacity(content.len() + suffix.len());
s.push_str(content);
s.push_str(suffix);
Cow::Owned(s)
}
}
/// Normalize line endings according to `mode`.
///
/// - `Keep` – return content unchanged.
/// - `Lf` – replace every `\r\n` with `\n`, and every bare `\r` with `\n`.
/// - `Crlf` – replace every lone `\n` (not preceded by `\r`) with `\r\n`.
/// - `Cr` – replace every `\r\n` with `\r`, and every bare `\n` with `\r`.
///
/// Returns `Cow::Borrowed` when no change is needed, avoiding allocation.
/// CRLF mode uses a single-pass scan with `memchr` instead of two
/// `.replace()` calls.
pub fn normalize_eol(content: &str, mode: EolMode) -> std::borrow::Cow<'_, str> {
use std::borrow::Cow;
match mode {
EolMode::Keep => Cow::Borrowed(content),
EolMode::Lf => {
let bytes = content.as_bytes();
let has_cr = memchr::memchr(b'\r', bytes).is_some();
if !has_cr {
Cow::Borrowed(content)
} else {
// Replace \r\n with \n, then any remaining bare \r with \n.
let without_crlf = content.replace("\r\n", "\n");
Cow::Owned(without_crlf.replace('\r', "\n"))
}
}
EolMode::Crlf => {
let bytes = content.as_bytes();
// Check for bare \r (not followed by \n) in addition to bare \n.
let has_bare_cr = memchr::memchr_iter(b'\r', bytes)
.any(|i| i + 1 >= bytes.len() || bytes[i + 1] != b'\n');
if has_bare_cr {
// Normalize all line endings to \n first, then convert to \r\n.
let lf_first = content.replace("\r\n", "\n").replace('\r', "\n");
Cow::Owned(lf_first.replace('\n', "\r\n"))
} else {
let has_bare_lf =
memchr::memchr_iter(b'\n', bytes).any(|i| i == 0 || bytes[i - 1] != b'\r');
if !has_bare_lf {
Cow::Borrowed(content)
} else {
// Single-pass: copy slices between \n positions, inserting
// \r before bare \n characters.
let mut result = String::with_capacity(content.len() + content.len() / 10);
let mut last = 0;
for i in memchr::memchr_iter(b'\n', bytes) {
if i == 0 || bytes[i - 1] != b'\r' {
result.push_str(&content[last..i]);
result.push_str("\r\n");
} else {
result.push_str(&content[last..=i]);
}
last = i + 1;
}
if last < content.len() {
result.push_str(&content[last..]);
}
Cow::Owned(result)
}
}
}
EolMode::Cr => {
let bytes = content.as_bytes();
let has_lf = memchr::memchr(b'\n', bytes).is_some();
if !has_lf {
Cow::Borrowed(content)
} else {
// Replace \r\n with \r, then any remaining bare \n with \r.
let without_crlf = content.replace("\r\n", "\r");
Cow::Owned(without_crlf.replace('\n', "\r"))
}
}
}
}
/// Remove trailing spaces and tabs from every line, preserving line endings.
///
/// Returns `Cow::Borrowed` when no trailing whitespace exists, avoiding
/// allocation in the common case of clean files.
pub fn trim_trailing_whitespace(content: &str) -> std::borrow::Cow<'_, str> {
use std::borrow::Cow;
// Fast check: scan for any trailing whitespace before a newline or at EOF.
let bytes = content.as_bytes();
let has_trailing = memchr::memchr2_iter(b'\r', b'\n', bytes).any(|i| {
// Skip the \n of a \r\n pair (already handled at the \r position).
if bytes[i] == b'\n' && i > 0 && bytes[i - 1] == b'\r' {
return false;
}
let prev = i.wrapping_sub(1);
prev < bytes.len() && matches!(bytes[prev], b' ' | b'\t')
}) || (!content.is_empty()
&& !matches!(bytes[bytes.len() - 1], b'\r' | b'\n')
&& matches!(bytes[bytes.len() - 1], b' ' | b'\t'));
if !has_trailing {
return Cow::Borrowed(content);
}
let mut result = String::with_capacity(content.len());
let mut rest = content;
while !rest.is_empty() {
// Find the next line-ending sequence (\n, \r\n, or bare \r).
let rest_bytes = rest.as_bytes();
if let Some(pos) = memchr::memchr2(b'\r', b'\n', rest_bytes) {
let (line, ending, advance) = if rest_bytes[pos] == b'\n' {
(&rest[..pos], "\n", pos + 1)
} else if pos + 1 < rest_bytes.len() && rest_bytes[pos + 1] == b'\n' {
(&rest[..pos], "\r\n", pos + 2)
} else {
(&rest[..pos], "\r", pos + 1)
};
result.push_str(line.trim_end_matches([' ', '\t']));
result.push_str(ending);
rest = &rest[advance..];
} else {
// Last line without a trailing line ending.
result.push_str(rest.trim_end_matches([' ', '\t']));
break;
}
}
Cow::Owned(result)
}
/// Collapse consecutive blank lines into a single blank line.
///
/// A blank line is one that contains only whitespace. Two or more consecutive
/// blank lines are reduced to one. Returns `Cow::Borrowed` when no collapsing
/// is needed, avoiding allocation.
pub fn collapse_blanks(content: &str) -> std::borrow::Cow<'_, str> {
use std::borrow::Cow;
let bytes = content.as_bytes();
// Quick scan: look for two consecutive line endings with only whitespace between.
let mut prev_blank = false;
let mut needs_collapse = false;
let mut scan = content.as_bytes();
while let Some(pos) = memchr::memchr2(b'\r', b'\n', scan) {
let end = if scan[pos] == b'\n' {
pos + 1
} else if pos + 1 < scan.len() && scan[pos + 1] == b'\n' {
pos + 2
} else {
pos + 1
};
let line = &content[content.len() - scan.len()..content.len() - scan.len() + pos];
let is_blank = line.trim().is_empty();
if is_blank && prev_blank {
needs_collapse = true;
break;
}
prev_blank = is_blank;
scan = &scan[end..];
}
// Check trailing content after the last newline: if the remainder is
// blank and the previous line was also blank, we still need to collapse.
if !needs_collapse && prev_blank && !scan.is_empty() {
let trailing = std::str::from_utf8(scan).unwrap_or("");
if trailing.trim().is_empty() {
needs_collapse = true;
}
}
if !needs_collapse {
return Cow::Borrowed(content);
}
let mut result = String::with_capacity(bytes.len());
let mut prev_blank = false;
let mut rest = content;
while !rest.is_empty() {
let rest_bytes = rest.as_bytes();
if let Some(pos) = memchr::memchr2(b'\r', b'\n', rest_bytes) {
let end = if rest_bytes[pos] == b'\n' {
pos + 1
} else if pos + 1 < rest_bytes.len() && rest_bytes[pos + 1] == b'\n' {
pos + 2
} else {
pos + 1
};
let line_content = &rest[..pos];
let line_with_ending = &rest[..end];
let is_blank = line_content.trim().is_empty();
if is_blank && prev_blank {
// Skip this consecutive blank line.
} else {
result.push_str(line_with_ending);
}
prev_blank = is_blank;
rest = &rest[end..];
} else {
// Last line without trailing newline.
let is_blank = rest.trim().is_empty();
if !(is_blank && prev_blank) {
result.push_str(rest);
}
break;
}
}
Cow::Owned(result)
}
/// Peel at most one leading U+FEFF, map the remainder, then restore the mark.
/// BOM is not whitespace, so indent/dedent must not treat it as line text.
fn with_leading_bom_peeled(content: &str, f: impl FnOnce(&str) -> String) -> String {
const BOM: char = '\u{feff}';
match content.strip_prefix(BOM) {
Some(rest) => {
let mut out = String::with_capacity(BOM.len_utf8() + rest.len());
out.push(BOM);
out.push_str(&f(rest));
out
}
None => f(content),
}
}
/// Number of leading whitespace **characters** on `line`.
///
/// [`str::trim_start`] strips all Unicode whitespace, so the common idiom
/// `line.len() - line.trim_start().len()` yields a *byte* count. Byte counts
/// are not comparable between lines that indent with different characters, and
/// slicing at one is not a char boundary. Indent widths are therefore measured
/// in characters throughout (#2377).
pub(crate) fn indent_char_count(line: &str) -> usize {
line.chars().take_while(|c| c.is_whitespace()).count()
}
/// Byte offset into `line` after skipping at most `n` leading whitespace
/// characters.
///
/// The result is always a char boundary, so `&line[indent_strip_offset(l, n)..]`
/// is safe for any input — including indents made of multi-byte whitespace such
/// as U+00A0, U+3000, or U+202F. Skips fewer than `n` characters when the
/// line's indent is shorter (#2377).
pub(crate) fn indent_strip_offset(line: &str, n: usize) -> usize {
let mut offset = 0;
for (i, c) in line.char_indices().take(n) {
if !c.is_whitespace() {
break;
}
offset = i + c.len_utf8();
}
offset
}
/// Dedent content by removing leading whitespace.
///
/// `spec` accepts:
/// - A numeric string (e.g. `"4"`) — remove up to N leading whitespace
/// *characters* per line (#2377; for ASCII space/tab indents this is the
/// same as N bytes).
/// - `"tab"` — remove one leading tab per line.
/// - `"auto"` — find the minimum non-zero indentation and remove that much.
///
/// If `line_range` is `Some((start, end))`, only lines in that 1-based inclusive
/// range are affected. Blank lines are never modified.
///
/// A single leading UTF-8 BOM (`U+FEFF`) is peeled, then restored at byte 0, so
/// it is not treated as line text (`charset = utf-8-bom`).
pub fn dedent_content(
content: &str,
spec: &str,
line_range: Option<(usize, Option<usize>)>,
) -> String {
// Callers that can report an error validate with `parse_dedent_spec` first;
// an unparseable spec is a no-op here only to keep this signature
// infallible for existing library users (#2378).
let Ok(spec) = parse_dedent_spec(spec) else {
return content.to_string();
};
with_leading_bom_peeled(content, |content| {
let lines: Vec<&str> = content.split('\n').collect();
let (start, end) = match line_range {
Some((s, e)) => (s.max(1), e.unwrap_or(lines.len())),
None => (1, lines.len()),
};
let in_range = |i: usize| {
let line_num = i + 1; // 1-based
line_num >= start && line_num <= end
};
match spec {
IndentSpec::Auto => {
// Find minimum non-zero indentation in the range.
let min_indent = lines
.iter()
.enumerate()
.filter(|&(i, _)| in_range(i))
.filter(|&(_, line)| !line.trim().is_empty())
.map(|(_, line)| indent_char_count(line))
.filter(|&n| n > 0)
.min()
.unwrap_or(0);
if min_indent == 0 {
return content.to_string();
}
dedent_by_n(&lines, min_indent, &in_range)
}
IndentSpec::Tab => {
let result: Vec<String> = lines
.iter()
.enumerate()
.map(|(i, line)| {
if !in_range(i) || line.trim().is_empty() {
line.to_string()
} else if let Some(rest) = line.strip_prefix('\t') {
rest.to_string()
} else {
line.to_string()
}
})
.collect();
result.join("\n")
}
IndentSpec::Spaces(0) => content.to_string(),
IndentSpec::Spaces(n) => dedent_by_n(&lines, n, &in_range),
}
})
}
fn dedent_by_n(lines: &[&str], n: usize, in_range: &dyn Fn(usize) -> bool) -> String {
let result: Vec<String> = lines
.iter()
.enumerate()
.map(|(i, line)| {
if !in_range(i) || line.trim().is_empty() {
line.to_string()
} else {
line[indent_strip_offset(line, n)..].to_string()
}
})
.collect();
result.join("\n")
}
/// Indent content by adding leading whitespace.
///
/// `spec` accepts:
/// - A numeric string (e.g. `"4"`) — add N leading spaces to each non-blank line.
/// - `"tab"` — add one leading tab to each non-blank line.
///
/// If `line_range` is `Some((start, end))`, only lines in that 1-based inclusive
/// range are affected. Blank lines are never modified.
///
/// A single leading UTF-8 BOM (`U+FEFF`) is peeled, then restored at byte 0, so
/// indent does not emit a mid-line mark.
pub fn indent_content(
content: &str,
spec: &str,
line_range: Option<(usize, Option<usize>)>,
) -> String {
// See `dedent_content`: entry points validate with `parse_indent_spec`.
let Ok(spec) = parse_indent_spec(spec) else {
return content.to_string();
};
with_leading_bom_peeled(content, |content| {
let lines: Vec<&str> = content.split('\n').collect();
let (start, end) = match line_range {
Some((s, e)) => (s.max(1), e.unwrap_or(lines.len())),
None => (1, lines.len()),
};
let prefix = match spec {
IndentSpec::Tab => "\t".to_string(),
// `parse_indent_spec` rejects Auto, so this arm is unreachable via
// the public entry points; treat it as a no-op rather than panic.
IndentSpec::Auto => String::new(),
IndentSpec::Spaces(n) => " ".repeat(n),
};
if prefix.is_empty() {
return content.to_string();
}
let result: Vec<String> = lines
.iter()
.enumerate()
.map(|(i, line)| {
let line_num = i + 1;
if line_num < start || line_num > end || line.trim().is_empty() {
line.to_string()
} else {
format!("{prefix}{line}")
}
})
.collect();
result.join("\n")
})
}
/// Apply a [`WritePolicy`] to `content`: trim, then EOL normalise, then final newline.
///
/// Returns `Cow::Borrowed` when the policy is a no-op, avoiding allocation.
pub fn apply_policy<'a>(content: &'a str, policy: &WritePolicy) -> std::borrow::Cow<'a, str> {
use std::borrow::Cow;
if policy.is_noop() {
return Cow::Borrowed(content);
}
let mut s = if policy.trim_trailing_whitespace {
trim_trailing_whitespace(content)
} else {
Cow::Borrowed(content)
};
if !matches!(policy.normalize_eol, EolMode::Keep)
&& let Cow::Owned(new) = normalize_eol(&s, policy.normalize_eol)
{
s = Cow::Owned(new);
}
if policy.collapse_blanks
&& let Cow::Owned(new) = collapse_blanks(&s)
{
s = Cow::Owned(new);
}
// Charset before final newline so an empty file with utf-8-bom
// becomes "\u{feff}" then gets the required trailing EOL in one pass.
if let Cow::Owned(new) = apply_charset(&s, policy.charset) {
s = Cow::Owned(new);
}
if policy.ensure_final_newline
&& let Cow::Owned(new) = ensure_final_newline(&s, policy.normalize_eol)
{
s = Cow::Owned(new);
}
s
}
/// Apply EditorConfig `charset` to UTF-8 text. Unsupported modes are a no-op
/// here; callers must [`WritePolicy::refuse_unsupported_charset`] first.
pub fn apply_charset(content: &str, mode: CharsetMode) -> std::borrow::Cow<'_, str> {
const BOM: char = '\u{feff}';
match mode {
CharsetMode::Keep | CharsetMode::Unsupported(_) => std::borrow::Cow::Borrowed(content),
CharsetMode::Utf8 => {
if let Some(rest) = content.strip_prefix(BOM) {
std::borrow::Cow::Owned(rest.to_string())
} else {
std::borrow::Cow::Borrowed(content)
}
}
CharsetMode::Utf8Bom => {
if content.starts_with(BOM) {
std::borrow::Cow::Borrowed(content)
} else {
let mut out = String::with_capacity(content.len() + BOM.len_utf8());
out.push(BOM);
out.push_str(content);
std::borrow::Cow::Owned(out)
}
}
}
}
/// Build a [`WritePolicy`] from [`GlobalFlags`](crate::cli::global::GlobalFlags), optionally merging
/// EditorConfig properties for the given file path.
///
/// Explicit CLI flags always win. When `--respect-editorconfig` is set and
/// `file_path` is provided, EditorConfig values fill in any flag that was not
/// explicitly set by the user.
///
/// Build WritePolicy from GlobalFlags (and EditorConfig if respect_editorconfig).
/// Usable from library tx execution paths as well (GlobalFlags can be simulated).
pub fn policy_from_flags(
global: &crate::cli::global::GlobalFlags,
#[allow(unused_variables)] file_path: Option<&std::path::Path>,
) -> WritePolicy {
let efn = global.ensure_final_newline;
let eol = global.normalize_eol;
let ttw = global.trim_trailing_whitespace;
let respect_ec = if cfg!(feature = "cli") {
global.respect_editorconfig
} else {
false
};
let (efn, eol, ttw, charset) = if respect_ec {
#[cfg(feature = "cli")]
if let Some(p) = file_path {
#[allow(unused_variables)]
if let Ok(props) = ec4rs::properties_of(p) {
let mut new_efn = efn;
let mut new_eol = eol;
let mut new_ttw = ttw;
// insert_final_newline
if !global.ensure_final_newline
&& let Ok(ec4rs::property::FinalNewline::Value(true)) =
props.get::<ec4rs::property::FinalNewline>()
{
new_efn = true;
}
// end_of_line
if global.normalize_eol.is_none()
&& let Ok(val) = props.get::<ec4rs::property::EndOfLine>()
{
new_eol = Some(match val {
ec4rs::property::EndOfLine::Lf => EolMode::Lf,
ec4rs::property::EndOfLine::CrLf => EolMode::Crlf,
ec4rs::property::EndOfLine::Cr => EolMode::Cr,
});
}
// trim_trailing_whitespace
if !global.trim_trailing_whitespace
&& let Ok(ec4rs::property::TrimTrailingWs::Value(true)) =
props.get::<ec4rs::property::TrimTrailingWs>()
{
new_ttw = true;
}
let charset = charset_from_editorconfig_props(&props);
(new_efn, new_eol, new_ttw, charset)
} else {
(efn, eol, ttw, CharsetMode::Keep)
}
} else {
(efn, eol, ttw, CharsetMode::Keep)
}
#[cfg(not(feature = "cli"))]
{
(efn, eol, ttw, CharsetMode::Keep)
}
} else {
(efn, eol, ttw, CharsetMode::Keep)
};
WritePolicy {
ensure_final_newline: efn,
normalize_eol: eol.unwrap_or(EolMode::Keep),
trim_trailing_whitespace: ttw,
collapse_blanks: global.collapse_blanks,
charset,
}
}
#[cfg(feature = "cli")]
pub(crate) fn charset_from_editorconfig_props(props: &ec4rs::Properties) -> CharsetMode {
match props.get::<ec4rs::property::Charset>() {
Ok(ec4rs::property::Charset::Utf8) | Ok(ec4rs::property::Charset::Latin1) => {
CharsetMode::Utf8
}
Ok(ec4rs::property::Charset::Utf8Bom) => CharsetMode::Utf8Bom,
Ok(ec4rs::property::Charset::Utf16Le) => CharsetMode::Unsupported("utf-16le"),
Ok(ec4rs::property::Charset::Utf16Be) => CharsetMode::Unsupported("utf-16be"),
Err(_) => CharsetMode::Keep,
}
}
/// Create a new file at `path` after applying `policy`, failing if the file
/// already exists.
///
/// Uses `tempfile::NamedTempFile` + `persist_noclobber` so the write is
/// crash-safe. The target file either has full content or does not exist;
/// partial content is never visible. `persist_noclobber` uses
/// `link` + `unlink` (or platform equivalent) to fail if the target already
/// exists, preserving the exclusive-create semantics.
pub(crate) fn atomic_create_new(
path: &Path,
content: &str,
policy: &WritePolicy,
) -> anyhow::Result<()> {
policy.refuse_unsupported_charset()?;
let final_content = apply_policy(content, policy);
let dest = persist_dest(path);
let parent = dest
.parent()
.context("cannot determine parent directory of target path")?;
let tmp = NamedTempFile::new_in(parent)
.with_context(|| format!("failed to create tempfile in {}", parent.display()))?;
std::fs::write(tmp.path(), final_content.as_bytes())
.with_context(|| format!("failed to write to tempfile {}", tmp.path().display()))?;
// NamedTempFile creates files with 0o600; apply standard 0o644 so
// new files are group/world-readable as users expect (#1161).
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let perms = std::fs::Permissions::from_mode(0o644);
std::fs::set_permissions(tmp.path(), perms)
.with_context(|| format!("failed to set permissions on {}", tmp.path().display()))?;
}
tmp.persist_noclobber(&dest).map_err(|e| {
if e.error.kind() == std::io::ErrorKind::AlreadyExists {
anyhow::Error::new(crate::exit::AlreadyExistsError {
msg: format!("file already exists: {}", path.display()),
})
} else {
anyhow::Error::from(e.error)
.context(format!("failed to persist tempfile to {}", path.display()))
}
})?;
Ok(())
}
/// Atomically write `content` to `path` after applying `policy`.
///
/// Default path (single hard link or new file): a temporary file is created in
/// the same directory as `path`, written to, then renamed over `path`.
///
/// The guarantee is **atomicity, not durability**: because the replacement is a
/// single `rename`, no reader — this process, another process, or a crashed
/// run of this one — ever observes a partially written `path`. It is not a
/// promise about power loss. The temp file is not fsynced before the rename, so
/// after a machine-level crash a filesystem may expose the new directory entry
/// with unwritten data blocks. That trade is deliberate: a per-write fsync would
/// dominate the cost of bulk operations that rewrite thousands of files
/// (#2389).
///
/// When the resolved target is a regular file with **more than one hard link**
/// (`nlink > 1` / Windows `nNumberOfLinks > 1`), rename would
/// break siblings (they would keep the old inode). In that case the full
/// payload is staged to a same-dir temp first, then written into the
/// **existing** inode so all hardlink paths stay in sync (#1733).
/// Symlinks are resolved first (#1230); the
/// hardlink rule applies to the resolved path.
pub(crate) fn atomic_write(path: &Path, content: &str, policy: &WritePolicy) -> anyhow::Result<()> {
policy.refuse_unsupported_charset()?;
let final_content = apply_policy(content, policy);
// Resolve live symlinks: write to the target file, not the symlink entry
// (#1230). Without this, persist() (rename) replaces the symlink directory
// entry with a regular file, destroying the symlink and leaving the target
// unchanged.
//
// Dangling symlinks cannot be resolved. Force-create / overwrite must still
// materialize a regular file at `path` (agent recreate after bad rename).
// Unlink the broken link entry, then write to `path` itself.
let resolved;
let write_path = if path.is_symlink() {
match crate::containment::safe_canonicalize(path) {
Ok(p) => {
// dunce: strip Windows \\?\ so display and multi-link checks stay clean.
resolved = p;
resolved.as_path()
}
Err(_) => {
std::fs::remove_file(path).with_context(|| {
format!("failed to replace dangling symlink {}", path.display())
})?;
path
}
}
} else if path.is_file() {
// Windows 8.3 names (LONGFI~1.TXT) alias the long directory entry.
// persist() rename using the short spelling replaces that entry
// (LongFileName.txt vanishes; a new LONGFI~1.TXT file appears).
match crate::containment::safe_canonicalize(path) {
Ok(p) => {
resolved = p;
resolved.as_path()
}
Err(_) => path,
}
} else {
path
};
// Capture the original file's permissions before overwriting.
let original_meta = std::fs::metadata(write_path).ok();
let original_perms = original_meta.as_ref().map(|m| m.permissions());
// Preserve hardlinks when the resolved target is multi-linked (#1733).
if let Some(ref meta) = original_meta
&& meta.is_file()
&& hard_link_count(write_path, meta) > 1
{
return write_preserving_hardlinks(write_path, final_content.as_bytes(), original_perms);
}
let dest = persist_dest(write_path);
let parent = dest
.parent()
.context("cannot determine parent directory of target path")?;
// Create a named tempfile in the same directory so the rename is atomic.
let tmp = NamedTempFile::new_in(parent)
.with_context(|| format!("failed to create tempfile in {}", parent.display()))?;
std::fs::write(tmp.path(), final_content.as_bytes())
.with_context(|| format!("failed to write to tempfile {}", tmp.path().display()))?;
// Copy NTFS MOTW onto the tempfile before applying dest permissions.
// A readonly dest would make `path:Zone.Identifier` unwritable if we
// set_permissions first. Hardlink in-place writes already keep streams.
#[cfg(windows)]
copy_windows_named_streams(write_path, tmp.path())?;
// Restore the original permissions on the temp file before renaming.
if let Some(perms) = original_perms {
std::fs::set_permissions(tmp.path(), perms)
.with_context(|| format!("failed to set permissions on {}", tmp.path().display()))?;
}