@@ -42,7 +42,6 @@ import (
42
42
type Archive struct {
43
43
Comment []byte
44
44
Files []File
45
- UseCRLF bool
46
45
}
47
46
48
47
// A File is a single file in an archive.
@@ -55,21 +54,41 @@ type File struct {
55
54
// It is assumed that the Archive data structure is well-formed:
56
55
// a.Comment and all a.File[i].Data contain no file marker lines,
57
56
// 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 .
59
58
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
+ }
63
67
}
68
+
64
69
var buf bytes.Buffer
65
- buf .Write (fixNL (a .Comment , lineSeparator ))
70
+ buf .Write (fixNL (a .Comment , firstSep ))
66
71
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 ))
69
74
}
70
75
return buf .Bytes ()
71
76
}
72
77
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
+
73
92
// ParseFile parses the named file as an archive.
74
93
func ParseFile (file string ) (* Archive , error ) {
75
94
data , err := os .ReadFile (file )
0 commit comments