Skip to content

Commit 77b9194

Browse files
committed
tar: Split tar archive construction
Splitting the tar function makes it easier to unit test and to support multiple files in an archive later.
1 parent 5116cc4 commit 77b9194

File tree

1 file changed

+16
-5
lines changed

1 file changed

+16
-5
lines changed

Sources/Tar/tar.swift

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -143,12 +143,12 @@ let CONTTYPE = "7" // reserved
143143
let XHDTYPE = "x" // Extended header referring to the next file in the archive
144144
let XGLTYPE = "g" // Global extended header
145145

146-
/// Creates a tar archive containing a single file
146+
/// Creates a tar header for a single file
147147
/// - Parameters:
148-
/// - bytes: The file's body data
148+
/// - filesize: The size of the file
149149
/// - filename: The file's name in the archive
150-
/// - Returns: A tar archive containing the file
151-
public func tar(_ bytes: [UInt8], filename: String = "app") -> [UInt8] {
150+
/// - Returns: A tar header representing the file
151+
public func tarHeader(filesize: Int, filename: String = "app") -> [UInt8] {
152152
// A file entry consists of a file header followed by the
153153
// contents of the file. The header includes information such as
154154
// the file name, size and permissions. Different versions of
@@ -163,7 +163,7 @@ public func tar(_ bytes: [UInt8], filename: String = "app") -> [UInt8] {
163163
hdr.writeString(octal6(0o555), inField: mode, withTermination: .spaceAndNull)
164164
hdr.writeString(octal6(0o000000), inField: uid, withTermination: .spaceAndNull)
165165
hdr.writeString(octal6(0o000000), inField: gid, withTermination: .spaceAndNull)
166-
hdr.writeString(octal11(bytes.count), inField: size, withTermination: .space)
166+
hdr.writeString(octal11(filesize), inField: size, withTermination: .space)
167167
hdr.writeString(octal11(0), inField: mtime, withTermination: .space)
168168
hdr.writeString(INIT_CHECKSUM, inField: chksum, withTermination: .none)
169169
hdr.writeString(REGTYPE, inField: typeflag, withTermination: .none)
@@ -179,6 +179,17 @@ public func tar(_ bytes: [UInt8], filename: String = "app") -> [UInt8] {
179179
// Fill in the checksum.
180180
hdr.writeString(octal6(checksum(header: hdr)), inField: chksum, withTermination: .nullAndSpace)
181181

182+
return hdr
183+
}
184+
185+
/// Creates a tar archive containing a single file
186+
/// - Parameters:
187+
/// - bytes: The file's body data
188+
/// - filename: The file's name in the archive
189+
/// - Returns: A tar archive containing the file
190+
public func tar(_ bytes: [UInt8], filename: String = "app") -> [UInt8] {
191+
var hdr = tarHeader(filesize: bytes.count, filename: filename)
192+
182193
// Append the file data to the header
183194
hdr.append(contentsOf: bytes)
184195

0 commit comments

Comments
 (0)