ArArchiveKit

一个简单、零依赖的 Swift 包,用于读取和写入 ar 归档文件。灵感来自 ar

Swift 5.3 SPM Compatible Build and Test

目录

gh-md-toc 创建

文档可在此处查看:here

ar 变体

ArArchiveKit 支持 ar 的 "Common"、BSD 和 SVR4/GNU 变体,如 FreeBSD 手册页中所述。

对符号表的支持可能很快会到来。

安装

Swift Package Manager

将此添加到 Package.swift 文件中的 dependencies 数组中

.package(url: "https://github.com/LebJe/ArArchiveKit.git", from: "0.3.0")

同样,将此添加到上述文件中的 targets 数组中

.product(name: "ArArchiveKit", package: "ArArchiveKit")

用法

写入归档文件

要写入归档文件,您需要一个 ArArchiveWriter

var writer = ArArchiveWriter()

一旦有了 writer,您必须创建一个 Header,它描述了您希望添加到归档文件中的文件

var time: Int = 1615929568

// You can also use date
let date: Date = ...
time = Int(date.timeIntervalSince1970)

let header = Header(
	// `name` will be truncated to 16 characters.
	name: "hello.txt",
	modificationTime: time
)

一旦有了 Header,您就可以将其以及文件的内容写入到归档文件中

// Without Foundation
var contents = [
	UInt8(ascii: "H"),
	UInt8(ascii: "e"),
	UInt8(ascii: "l"),
	UInt8(ascii: "l"),
	UInt8(ascii: "o"),
]

// With Foundation

let myData: Data = "Hello".data(using .utf8)!

contents = Array<UInt8>(myData)

writer.addFile(header: header, contents: contents)

如果您有一个文本文件,请使用 addFile 的重载版本

writer.addFile(header: header, contents: "Hello")

添加文件后,您可以像这样获取归档文件

// Call finalize to get the binary representation (Array<UInt8>) of the archive.
let bytes = writer.finalize()

// You convert it to data like this:
let data = Data(bytes)

// And write it:
try data.write(to: URL(fileURLWithPath: "myArchive.a"))

读取归档文件

要读取归档文件,您需要一个 ArArchiveReader

// myData is the bytes of the archive.
let myData: Data = ...

let reader = ArArchiveReader(archive: Array<UInt8>(myData))

一旦有了 reader,您可以通过几种方式检索数据

迭代

您可以像这样迭代归档文件中的所有文件

for (header, data) in reader {
   // `data` is `Array<UInt8>` that contains the raw bytes of the file in the archive.
   // `header` is the `Header` that describes the `data`.

   // if you know `data` is a `String`, then you can use this initializer:
   let str = String(data)
}

下标

当您只需要访问大型归档文件中的几个项目时,通过 subscript 访问数据非常有用

// The subscript provides you with random access to any file in the archive:
let firstFile = reader[0]
let fifthFile = reader[6]

您还可以使用采用 Header 的 subscript 版本 - 当您有一个 Header,但没有该 header 的索引时,这非常有用。

let header = reader.headers.first(where: { $0.name.contains(".swift") })!
let data = reader[header: header]

示例

其他平台

ArArchiveKit 不依赖于任何库、FoundationDarwin/Glibc/ucrt - 仅依赖于 Swift 标准库。它应该可以在标准库编译的任何平台上编译。

Windows

ArArchiveKit 目前正在 Windows 上构建,但尚未经过测试,因为 Swift Package Manager Resources 似乎在 Windows 上不起作用(或不可用)。

贡献

在提交之前,请安装 pre-commitswift-format 并安装 pre-commit hook

$ brew bundle # install the packages specified in Brewfile
$ pre-commit install

# Commit your changes.

要在其他平台上安装 pre-commit,请参阅 documentation