Skip to content

Commit 14f617b

Browse files
committed
* removed flag from Archive struct
1 parent 481bd73 commit 14f617b

File tree

2 files changed

+27
-11
lines changed

2 files changed

+27
-11
lines changed

txtar/archive.go

Lines changed: 27 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,6 @@ import (
4242
type Archive struct {
4343
Comment []byte
4444
Files []File
45-
UseCRLF bool
4645
}
4746

4847
// A File is a single file in an archive.
@@ -55,21 +54,41 @@ type File struct {
5554
// It is assumed that the Archive data structure is well-formed:
5655
// a.Comment and all a.File[i].Data contain no file marker lines,
5756
// and all a.File[i].Name is non-empty. Format uses line separators
58-
// based on a.UseCRLF field.
57+
// based on the first line separator encountered in the comment section.
5958
func Format(a *Archive) []byte {
60-
lineSeparator := lf
61-
if a.UseCRLF {
62-
lineSeparator = crlf
59+
firstSep, ok := lineEnd(a.Comment)
60+
if !ok {
61+
for _, f := range a.Files {
62+
firstSep, ok = lineEnd(f.Data)
63+
if ok {
64+
break
65+
}
66+
}
6367
}
68+
6469
var buf bytes.Buffer
65-
buf.Write(fixNL(a.Comment, lineSeparator))
70+
buf.Write(fixNL(a.Comment, firstSep))
6671
for _, f := range a.Files {
67-
fmt.Fprintf(&buf, "-- %s --%s", f.Name, lineSeparator)
68-
buf.Write(fixNL(f.Data, lineSeparator))
72+
fmt.Fprintf(&buf, "-- %s --%s", f.Name, firstSep)
73+
buf.Write(fixNL(f.Data, firstSep))
6974
}
7075
return buf.Bytes()
7176
}
7277

78+
// lineEnd returns the line separator that was used at the end
79+
// of the passed byte slice and a bool flag that says if the line separator
80+
// was really found or it is a default value (lf).
81+
func lineEnd(b []byte) ([]byte, bool) {
82+
switch {
83+
case bytes.HasSuffix(b, crlf):
84+
return crlf, true
85+
case bytes.HasSuffix(b, lf):
86+
return lf, true
87+
default:
88+
return lf, false
89+
}
90+
}
91+
7392
// ParseFile parses the named file as an archive.
7493
func ParseFile(file string) (*Archive, error) {
7594
data, err := os.ReadFile(file)

txtar/archive_test.go

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,6 @@ func TestFormat(t *testing.T) {
135135
{"empty", []byte{}},
136136
{"noNL", []byte("hello world")},
137137
},
138-
UseCRLF: false,
139138
},
140139
wanted: `comment1
141140
comment2
@@ -160,7 +159,6 @@ hello world
160159
{"empty", []byte{}},
161160
{"noNL", []byte("hello world")},
162161
},
163-
UseCRLF: true,
164162
},
165163
wanted: "comment1\r\n" +
166164
"comment2\r\n" +
@@ -186,7 +184,6 @@ hello world
186184
{"noNL", []byte("hello world\r\n")},
187185
{"empty filename line", []byte("some content\r\n-- --\n")},
188186
},
189-
UseCRLF: true,
190187
},
191188
wanted: "comment1\n" +
192189
"comment2\r\n" +

0 commit comments

Comments
 (0)