mirror of
https://github.com/apple/swift-nio-imap
synced 2026-11-22 04:30:43 +00:00
Add a imperative IMAP client and an imap-tool CLI (#841)
This commit is contained in:
1 parent
8fd34eaff7
commit
6c8cfaddcc
164 files changed
+28347
-61
No files matched your search
@@ -14,6 +14,8 @@ jobs:
|
||||
name: Unit tests
|
||||
uses: apple/swift-nio/.github/workflows/unit_tests.yml@main
|
||||
with:
|
||||
# `Package.swift` requires Swift 6.2, so the older matrix entries cannot build this
|
||||
# package and are not configured here.
|
||||
linux_6_2_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error"
|
||||
linux_6_3_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error"
|
||||
linux_nightly_main_arguments_override: "--explicit-target-dependency-import-check error"
|
||||
@@ -38,7 +40,7 @@ jobs:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
example: [CLI, Proxy, Fuzzer, PerformanceTester]
|
||||
example: [IMAPTool, CLI, Proxy, Fuzzer, PerformanceTester]
|
||||
container:
|
||||
image: swift:6.2
|
||||
steps:
|
||||
@@ -49,5 +51,5 @@ jobs:
|
||||
- name: Build
|
||||
run: swift build --package-path "Examples/${{ matrix.example }}"
|
||||
- name: Test
|
||||
if: matrix.example == 'CLI'
|
||||
run: swift test --package-path "Examples/CLI"
|
||||
if: matrix.example == 'CLI' || matrix.example == 'IMAPTool'
|
||||
run: swift test --package-path "Examples/${{ matrix.example }}"
|
||||
@@ -18,6 +18,8 @@ jobs:
|
||||
name: Unit tests
|
||||
uses: apple/swift-nio/.github/workflows/unit_tests.yml@main
|
||||
with:
|
||||
# `Package.swift` requires Swift 6.2, so the older matrix entries cannot build this
|
||||
# package and are not configured here.
|
||||
linux_6_2_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error"
|
||||
linux_6_3_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error"
|
||||
linux_nightly_main_arguments_override: "--explicit-target-dependency-import-check error"
|
||||
@@ -41,7 +43,13 @@ jobs:
|
||||
uses: apple/swift-nio/.github/workflows/macos_tests.yml@main
|
||||
with:
|
||||
runner_pool: general
|
||||
build_scheme: swift-nio-imap
|
||||
# Xcode auto-generates the schemes for this package (`.swiftpm` is not checked in).
|
||||
# A package with two or more products gets one scheme per product plus an aggregate
|
||||
# `<package>-Package` scheme; a package with a single product gets just one scheme,
|
||||
# named `<package>`. Since this package vends both `NIOIMAP` and `IMAPCommands`, the
|
||||
# aggregate scheme is `swift-nio-imap-Package`. Verify with `xcodebuild -list` in a
|
||||
# clean checkout if the product list ever changes.
|
||||
build_scheme: swift-nio-imap-Package
|
||||
# macos_tests.yml requires explicit disable of 6.1.
|
||||
swift_6_1_enabled: false
|
||||
swift_6_2_build_arguments_override: "-Xswiftc -Xfrontend -Xswiftc -require-explicit-sendable -Xswiftc -warnings-as-errors"
|
||||
@@ -53,7 +61,7 @@ jobs:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
example: [CLI, Proxy, Fuzzer, PerformanceTester]
|
||||
example: [IMAPTool, CLI, Proxy, Fuzzer, PerformanceTester]
|
||||
container:
|
||||
image: swift:6.2
|
||||
steps:
|
||||
@@ -64,5 +72,5 @@ jobs:
|
||||
- name: Build
|
||||
run: swift build --package-path "Examples/${{ matrix.example }}"
|
||||
- name: Test
|
||||
if: matrix.example == 'CLI'
|
||||
run: swift test --package-path "Examples/CLI"
|
||||
if: matrix.example == 'CLI' || matrix.example == 'IMAPTool'
|
||||
run: swift test --package-path "Examples/${{ matrix.example }}"
|
||||
@@ -0,0 +1,71 @@
|
||||
// swift-tools-version:6.2
|
||||
// The swift-tools-version declares the minimum version of Swift required to build this package.
|
||||
// 6.2 to match the root package, which this example depends on by path.
|
||||
|
||||
import PackageDescription
|
||||
|
||||
let package = Package(
|
||||
name: "imap-tool-example",
|
||||
platforms: [
|
||||
.macOS(.v15)
|
||||
],
|
||||
products: [
|
||||
.library(name: "IMAPToolLib", targets: ["IMAPToolLib"]),
|
||||
.executable(name: "imap-tool", targets: ["IMAPTool"]),
|
||||
],
|
||||
dependencies: [
|
||||
.package(name: "swift-nio-imap", path: "../.."),
|
||||
.package(url: "https://github.com/apple/swift-argument-parser", .upToNextMinor(from: "1.7.0")),
|
||||
.package(url: "https://github.com/apple/swift-async-algorithms", from: "1.1.0"),
|
||||
.package(url: "https://github.com/apple/swift-collections", "1.4.0"..<"2.0.0"),
|
||||
.package(url: "https://github.com/apple/swift-nio", from: "2.64.0"),
|
||||
.package(url: "https://github.com/apple/swift-system", from: "1.6.0"),
|
||||
.package(url: "https://github.com/apple/swift-numerics", from: "1.0.0"),
|
||||
],
|
||||
targets: [
|
||||
.target(
|
||||
name: "IMAPToolLib",
|
||||
dependencies: [
|
||||
.product(name: "NIOIMAP", package: "swift-nio-imap"),
|
||||
.product(name: "IMAPCommands", package: "swift-nio-imap"),
|
||||
.product(name: "ArgumentParser", package: "swift-argument-parser"),
|
||||
.product(name: "AsyncAlgorithms", package: "swift-async-algorithms"),
|
||||
.product(name: "SystemPackage", package: "swift-system"),
|
||||
.product(name: "NIO", package: "swift-nio"),
|
||||
.product(name: "_NIOFileSystem", package: "swift-nio"),
|
||||
.product(name: "NIOConcurrencyHelpers", package: "swift-nio"),
|
||||
.product(name: "OrderedCollections", package: "swift-collections"),
|
||||
.product(name: "DequeModule", package: "swift-collections"),
|
||||
],
|
||||
swiftSettings: [
|
||||
// `IMAPCommands`' closure-taking APIs are caller-isolated, and so are this
|
||||
// library's operations that wrap them.
|
||||
.enableUpcomingFeature("NonisolatedNonsendingByDefault")
|
||||
]
|
||||
),
|
||||
.executableTarget(
|
||||
name: "IMAPTool",
|
||||
dependencies: [
|
||||
.target(name: "IMAPToolLib"),
|
||||
.product(name: "ArgumentParser", package: "swift-argument-parser"),
|
||||
],
|
||||
swiftSettings: [
|
||||
.enableUpcomingFeature("NonisolatedNonsendingByDefault")
|
||||
]
|
||||
),
|
||||
.testTarget(
|
||||
name: "IMAPToolLibTests",
|
||||
dependencies: [
|
||||
.target(name: "IMAPToolLib"),
|
||||
.product(name: "IMAPCommands", package: "swift-nio-imap"),
|
||||
.product(name: "NIOIMAP", package: "swift-nio-imap"),
|
||||
.product(name: "NIO", package: "swift-nio"),
|
||||
.product(name: "Numerics", package: "swift-numerics"),
|
||||
.product(name: "SystemPackage", package: "swift-system"),
|
||||
],
|
||||
swiftSettings: [
|
||||
.enableUpcomingFeature("NonisolatedNonsendingByDefault")
|
||||
]
|
||||
),
|
||||
]
|
||||
)
|
||||
@@ -0,0 +1,17 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import IMAPToolLib
|
||||
|
||||
await IMAPToolLib.main()
|
||||
@@ -0,0 +1,174 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import ArgumentParser
|
||||
import IMAPCommands
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
import NIO
|
||||
import NIOIMAP
|
||||
import SystemPackage
|
||||
|
||||
struct AppendCommand: AsyncParsableCommand {
|
||||
static let configuration = CommandConfiguration(
|
||||
commandName: "append",
|
||||
abstract: "Upload messages to the server."
|
||||
)
|
||||
|
||||
@OptionGroup()
|
||||
var connectionInfo: ConnectionInfo
|
||||
|
||||
@Option(help: "The mailbox to APPEND into.")
|
||||
var mailbox: MailboxName = .inbox
|
||||
|
||||
@Option(help: "How to format the result.")
|
||||
var outputFormat: ResultFormat = .text
|
||||
|
||||
@ArgumentParser.Flag(
|
||||
name: .customLong("skip-unreadable"),
|
||||
inversion: .prefixedNo,
|
||||
help: "Skip input files that can not be parsed as emails"
|
||||
)
|
||||
var skipUnreadable = true
|
||||
|
||||
@ArgumentParser.Flag(
|
||||
name: .customLong("sort-by-date"),
|
||||
inversion: .prefixedNo,
|
||||
help: "Sort the input files by message date, upload oldest messages first"
|
||||
)
|
||||
var sortByDate = true
|
||||
|
||||
@ArgumentParser.Flag(
|
||||
inversion: .prefixedNo,
|
||||
help: "Create the mailbox if it does not exist"
|
||||
)
|
||||
var createMailbox = false
|
||||
|
||||
@Option(
|
||||
name: .customLong("flag"),
|
||||
help: .init(
|
||||
"IMAP flag to set on uploaded messages.",
|
||||
discussion: #"""
|
||||
Allows specifying flags to be set on an appended message.
|
||||
|
||||
This can be repeated multiple times to set multiple flags.
|
||||
|
||||
Valid values: \#(MessageFlag.allCases.map { $0.rawValue }.joined(separator: ", "))
|
||||
"""#
|
||||
)
|
||||
)
|
||||
var flags: [MessageFlag] = []
|
||||
|
||||
@Argument(
|
||||
help: .init(
|
||||
"Message file or directory with messages.",
|
||||
discussion: #"""
|
||||
Specify one or multiple messages to be uploaded.
|
||||
|
||||
Each path can either be a path to an RFC 5288 email message or a path to directory containing RFC 5288 email messages.
|
||||
|
||||
Note: the messages must have a valid 'date' header.
|
||||
"""#,
|
||||
valueName: "path"
|
||||
),
|
||||
completion: .file(extensions: ["eml", "emlx", "message"])
|
||||
)
|
||||
var input: [String] = []
|
||||
|
||||
func run() async throws {
|
||||
guard
|
||||
!input.isEmpty
|
||||
else {
|
||||
throw ValidationError("Need to specify at least one input (file).")
|
||||
}
|
||||
|
||||
struct Result: Encodable {
|
||||
var id: Identity
|
||||
var messages: [Message]
|
||||
|
||||
struct Message: Encodable {
|
||||
var filename: String
|
||||
var id: String
|
||||
var uid: UInt32?
|
||||
}
|
||||
}
|
||||
|
||||
let result: Result = try await IMAPConnection.withAuthenticatedConnection(info: connectionInfo) {
|
||||
id,
|
||||
connection in
|
||||
let uids = try await connection.append(
|
||||
messages: input.map { FilePath($0) },
|
||||
options: appendOptions,
|
||||
into: mailbox
|
||||
)
|
||||
return Result(
|
||||
id: id,
|
||||
messages: uids.map {
|
||||
Result.Message(
|
||||
filename: $0.filePath.lastComponent.map { String(decoding: $0) } ?? "",
|
||||
id: String($0.messageID),
|
||||
uid: $0.uid.map { UInt32($0) }
|
||||
)
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
writeResult(result: result, format: outputFormat)
|
||||
}
|
||||
}
|
||||
|
||||
extension AppendCommand {
|
||||
var appendOptions: Set<AppendOption> {
|
||||
return Set<AppendOption>(
|
||||
skipUnreadable: skipUnreadable,
|
||||
sortByDate: sortByDate,
|
||||
createMailbox: createMailbox,
|
||||
flags: imapFlags
|
||||
)
|
||||
}
|
||||
|
||||
var imapFlags: [NIOIMAP.Flag] {
|
||||
flags
|
||||
.reduce(into: Set<NIOIMAP.Flag>()) {
|
||||
$0.formUnion($1.flagsToSet)
|
||||
}
|
||||
.sorted(by: { "\($0)" < "\($1)" })
|
||||
}
|
||||
}
|
||||
|
||||
extension Set<AppendOption> {
|
||||
init(
|
||||
skipUnreadable: Bool,
|
||||
sortByDate: Bool,
|
||||
createMailbox: Bool,
|
||||
flags: [NIOIMAP.Flag] = []
|
||||
) {
|
||||
self = []
|
||||
if skipUnreadable {
|
||||
self.insert(.skipErrors)
|
||||
}
|
||||
if sortByDate {
|
||||
self.insert(.sort)
|
||||
}
|
||||
if createMailbox {
|
||||
self.insert(.createMailbox([]))
|
||||
}
|
||||
if !flags.isEmpty {
|
||||
self.insert(.flags(flags))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import ArgumentParser
|
||||
import IMAPCommands
|
||||
import Synchronization
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
|
||||
/// Command-line arguments for establishing an IMAP connection and authenticating.
|
||||
public struct ConnectionInfo: ParsableArguments, Sendable {
|
||||
public init() {}
|
||||
|
||||
init(
|
||||
server: String? = nil,
|
||||
sasl: String? = nil,
|
||||
disableSASLIR: Bool = false,
|
||||
forceLogin: Bool = false,
|
||||
username: String? = nil,
|
||||
) {
|
||||
self.server = server
|
||||
self.sasl = sasl
|
||||
self.disableSASLIR = disableSASLIR
|
||||
self.forceLogin = forceLogin
|
||||
self.username = username
|
||||
}
|
||||
|
||||
@Option(help: "The server to connect to.")
|
||||
var server: String?
|
||||
|
||||
@Option(help: "Use SASL to authenticate (for example, 'plain:foobar').")
|
||||
var sasl: String?
|
||||
|
||||
@Flag(name: .customLong("disable-sasl-ir"), help: "Disable the use of SASL-IR (RFC 4959).")
|
||||
var disableSASLIR: Bool = false
|
||||
|
||||
@Flag(help: "Use the LOGIN command instead of AUTHENTICATE.")
|
||||
var forceLogin: Bool = false
|
||||
|
||||
var authenticationMethod: AuthenticationMethod {
|
||||
forceLogin ? .login : .automatic
|
||||
}
|
||||
|
||||
@Option(help: ArgumentHelp("Use LOGIN or AUTH PLAIN to authenticate.", valueName: "user:password"))
|
||||
var username: String?
|
||||
|
||||
/// An opaque account identifier resolved by the embedding tool.
|
||||
///
|
||||
/// `IMAPToolLib` itself does not know how to resolve accounts. An embedder
|
||||
/// can install an ``ConnectionInfo/accountResolver`` that maps this
|
||||
/// identifier to a connection configuration and credential (for example,
|
||||
/// by looking it up in the system's account store). When no resolver is
|
||||
/// installed this option is inert.
|
||||
@Option(
|
||||
help: ArgumentHelp(
|
||||
"An account identifier resolved by the embedding tool.",
|
||||
visibility: .private
|
||||
)
|
||||
)
|
||||
var account: String?
|
||||
|
||||
@Flag(
|
||||
name: .customLong("connection-logging"),
|
||||
help: ArgumentHelp(
|
||||
"Log connection (debug) activity.",
|
||||
visibility: .private
|
||||
)
|
||||
)
|
||||
var _connectionLogging: Bool = false
|
||||
|
||||
var connectionLogging: IMAPConnection.Configuration.Logging {
|
||||
_connectionLogging ? .logging : .noLogging
|
||||
}
|
||||
|
||||
public mutating func validate() throws {
|
||||
// A SASL response carries no password, so there is nothing to put in a LOGIN.
|
||||
// `--account` can resolve to a SASL credential too, but only at connect time;
|
||||
// ``IMAPConnection/login(credential:capabilities:method:)`` catches that case.
|
||||
if forceLogin, sasl != nil {
|
||||
throw ValidationError("'--force-login' needs a username and password, so it can not be used with '--sasl'.")
|
||||
}
|
||||
_ = try self.makeConfiguration()
|
||||
}
|
||||
|
||||
/// The resolved connection endpoint and credential for an account identifier.
|
||||
///
|
||||
/// Only the connection endpoint is provided here; the `logging` setting is
|
||||
/// applied by ``ConnectionInfo`` itself so that `--connection-logging` keeps
|
||||
/// working for account-based connections.
|
||||
public struct ResolvedAccount: Sendable {
|
||||
public var hostname: String
|
||||
public var port: UInt16
|
||||
public var useTLS: Bool
|
||||
public var credential: IMAPCredential
|
||||
|
||||
public init(hostname: String, port: UInt16, useTLS: Bool, credential: IMAPCredential) {
|
||||
self.hostname = hostname
|
||||
self.port = port
|
||||
self.useTLS = useTLS
|
||||
self.credential = credential
|
||||
}
|
||||
}
|
||||
|
||||
/// A closure that resolves an account identifier (see ``ConnectionInfo/account``)
|
||||
/// into a connection endpoint and credential, or returns `nil` if the
|
||||
/// identifier is unknown.
|
||||
public typealias AccountResolver = @Sendable (_ identifier: String) throws -> ResolvedAccount?
|
||||
|
||||
private static let _accountResolver = Mutex<AccountResolver?>(nil)
|
||||
|
||||
/// Installs a resolver used to turn an ``ConnectionInfo/account`` identifier into a
|
||||
/// connection endpoint and credential. Passing `nil` removes any installed resolver.
|
||||
///
|
||||
/// This is the seam an embedding tool uses to support account-based authentication
|
||||
/// (for example, tokens sourced from the system account store) without `IMAPToolLib`
|
||||
/// having to know anything about where those accounts come from.
|
||||
public static func setAccountResolver(_ resolver: AccountResolver?) {
|
||||
_accountResolver.withLock { $0 = resolver }
|
||||
}
|
||||
|
||||
private func resolveAccount() throws -> ResolvedAccount? {
|
||||
guard let account else { return nil }
|
||||
guard let resolver = Self._accountResolver.withLock({ $0 }) else {
|
||||
throw ValidationError("No account resolver is installed for '--account \(account)'.")
|
||||
}
|
||||
guard let resolved = try resolver(account) else {
|
||||
throw ValidationError("Unknown account '\(account)'.")
|
||||
}
|
||||
return resolved
|
||||
}
|
||||
|
||||
/// Creates a ``IMAPConnection.Configuration`` from the parsed server argument.
|
||||
func makeConfiguration() throws -> IMAPConnection.Configuration {
|
||||
if let resolved = try resolveAccount() {
|
||||
return IMAPConnection.Configuration(
|
||||
hostname: resolved.hostname,
|
||||
port: resolved.port,
|
||||
useTLS: resolved.useTLS,
|
||||
logging: connectionLogging
|
||||
)
|
||||
}
|
||||
guard let text = server else {
|
||||
throw ValidationError("Need to specify either a server name or an account.")
|
||||
}
|
||||
do {
|
||||
return try IMAPConnection.Configuration(
|
||||
serverText: text,
|
||||
logging: connectionLogging
|
||||
)
|
||||
} catch {
|
||||
throw ValidationError("\(error)")
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a ``IMAPCredential`` from the parsed authentication arguments.
|
||||
func makeCredential() throws -> IMAPCredential {
|
||||
if let resolved = try resolveAccount() {
|
||||
return resolved.credential
|
||||
}
|
||||
return try IMAPCredential(url: self.server, sasl: self.sasl, username: self.username)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import ArgumentParser
|
||||
import IMAPCommands
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
import NIO
|
||||
import NIOIMAP
|
||||
import SystemPackage
|
||||
|
||||
struct DeleteMessagesCommand: AsyncParsableCommand {
|
||||
static let configuration = CommandConfiguration(
|
||||
commandName: "delete-messages",
|
||||
abstract: "Delete messages."
|
||||
)
|
||||
|
||||
@OptionGroup()
|
||||
var connectionInfo: ConnectionInfo
|
||||
|
||||
@Option(help: "How to format the result.")
|
||||
var outputFormat: ResultFormat = .text
|
||||
|
||||
@Option(
|
||||
name: .customLong("mailbox"),
|
||||
help: """
|
||||
The mailbox to delete messages from.
|
||||
"""
|
||||
)
|
||||
var mailboxName: MailboxName = .inbox
|
||||
|
||||
@ArgumentParser.Flag(
|
||||
name: .customLong("all"),
|
||||
help: ArgumentHelp(
|
||||
"Delete all messages in the mailbox",
|
||||
discussion: #"""
|
||||
This will (permanently) delete all messages in the given mailbox.
|
||||
Since this can lead to permanent data loss, this will either (a)
|
||||
query the user to confirm this choice (if running in an interactive
|
||||
shell), or (b) check for the existence of a file named
|
||||
.imap-tool-allow-delete-all
|
||||
in the current user’s home directory.
|
||||
"""#
|
||||
)
|
||||
)
|
||||
var deleteAllMessages = false
|
||||
|
||||
@Option(
|
||||
help: #"""
|
||||
A file to read message info from. This should be JSON as output by the \
|
||||
'append' command. The JSON needs to be an array where each element has a \
|
||||
'uid' value or an 'id' value, the latter being the message-id header of \
|
||||
the messages to be deleted.
|
||||
"""#,
|
||||
completion: .file(extensions: ["json"])
|
||||
)
|
||||
var messages: String?
|
||||
|
||||
func run() async throws {
|
||||
switch action {
|
||||
case .deleteSpecific(filePath: let path):
|
||||
let ids = try UIDsAndMessageIDs.parse(filePath: path)
|
||||
guard !ids.isEmpty else {
|
||||
writeStatus("No UIDs / Message-IDs found.")
|
||||
return
|
||||
}
|
||||
try await deleteSpecificMessages(ids: ids)
|
||||
case .deleteAll:
|
||||
try await deleteAllMessages()
|
||||
case .fail(let text):
|
||||
exitWithErrorMessage(text)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension DeleteMessagesCommand {
|
||||
enum Action: Equatable {
|
||||
case deleteAll
|
||||
case deleteSpecific(filePath: String)
|
||||
case fail(Output)
|
||||
}
|
||||
|
||||
var action: Action {
|
||||
switch (deleteAllMessages, messages) {
|
||||
case (false, let messages?):
|
||||
return .deleteSpecific(filePath: messages)
|
||||
case (true, nil):
|
||||
return .deleteAll
|
||||
case (true, .some):
|
||||
return .fail("Can not specify both --all and a file to read message info from.")
|
||||
case (false, nil):
|
||||
return .fail("Need to specify a file to read message info from.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Delete All Messages
|
||||
|
||||
extension DeleteMessagesCommand {
|
||||
func deleteAllMessages() async throws {
|
||||
struct Result: Encodable {
|
||||
var count: Int
|
||||
}
|
||||
|
||||
let result: Result = try await IMAPConnection.withAuthenticatedConnection(info: connectionInfo) {
|
||||
id,
|
||||
connection in
|
||||
let info = try await connection.select(
|
||||
mailbox: mailboxName,
|
||||
createMailbox: .fail
|
||||
)
|
||||
|
||||
writeStatus("Mailbox has \(info.messageCount) messages.")
|
||||
|
||||
guard
|
||||
0 < info.messageCount
|
||||
else { return Result(count: 0) }
|
||||
|
||||
await checkDeleteAllSafeguards(
|
||||
mailbox: mailboxName,
|
||||
messageCount: info.messageCount
|
||||
)
|
||||
|
||||
try await connection.deleteAllMessages()
|
||||
|
||||
return Result(
|
||||
count: info.messageCount
|
||||
)
|
||||
}
|
||||
|
||||
writeResult(
|
||||
result: result,
|
||||
format: outputFormat
|
||||
)
|
||||
|
||||
}
|
||||
|
||||
func checkDeleteAllSafeguards(
|
||||
mailbox: MailboxName,
|
||||
messageCount: Int
|
||||
) async {
|
||||
if standardInputIsTTY {
|
||||
writeStatus(
|
||||
"You are about to delete \(messageCount) messages in mailbox '\(mailbox)'. Please type the exact message count to confirm.",
|
||||
terminator: ""
|
||||
)
|
||||
guard
|
||||
let input = readLine()
|
||||
else { exitWithErrorMessage("EOF") }
|
||||
guard
|
||||
input == "\(messageCount)"
|
||||
else { exitWithErrorMessage("'\(input)' != '\(messageCount)'") }
|
||||
} else {
|
||||
guard
|
||||
let home = ProcessInfo.processInfo.environment["HOME"]
|
||||
else { exitWithErrorMessage("HOME not set") }
|
||||
let path = FilePath(home).appending(".imap-tool-allow-delete-all")
|
||||
do {
|
||||
_ = try await Data(
|
||||
asyncContentsOf: path,
|
||||
length: 1
|
||||
)
|
||||
} catch {
|
||||
exitWithErrorMessage("Safeguard file '\(path)' does not exist.")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Delete Specific Messages
|
||||
|
||||
extension DeleteMessagesCommand {
|
||||
func deleteSpecificMessages(
|
||||
ids: UIDsAndMessageIDs
|
||||
) async throws {
|
||||
struct Result: Encodable {
|
||||
var uids: [UID]
|
||||
}
|
||||
|
||||
let result: Result = try await IMAPConnection.withAuthenticatedConnection(info: connectionInfo) {
|
||||
id,
|
||||
connection in
|
||||
|
||||
let info = try await connection.select(
|
||||
mailbox: mailboxName,
|
||||
createMailbox: .fail
|
||||
)
|
||||
|
||||
let allUIDs = try await connection.findMessageIDs(
|
||||
selectInfo: info,
|
||||
capabilities: id.capabilities,
|
||||
ids: ids
|
||||
)
|
||||
|
||||
try await connection.deleteMessages(
|
||||
uids: allUIDs
|
||||
)
|
||||
|
||||
return Result(
|
||||
uids: Array(allUIDs)
|
||||
)
|
||||
}
|
||||
|
||||
writeResult(
|
||||
result: result,
|
||||
format: outputFormat
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import IMAPCommands
|
||||
import ArgumentParser
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
import NIOIMAP
|
||||
import SystemPackage
|
||||
|
||||
struct DownloadCommand: AsyncParsableCommand {
|
||||
static let configuration = CommandConfiguration(
|
||||
commandName: "download",
|
||||
abstract: "Download raw messages.",
|
||||
discussion: #"""
|
||||
This downloads the raw message data for messages in the specified mailbox on the server into a local directory.
|
||||
|
||||
Previously downloaded messages already in the directory are skipped, allowing downloads to be resumed.
|
||||
|
||||
Passing --delete-unknown deletes any local message files that no longer exist on the server.
|
||||
"""#
|
||||
)
|
||||
|
||||
@OptionGroup()
|
||||
var connectionInfo: ConnectionInfo
|
||||
|
||||
@Option(
|
||||
name: .customLong("mailbox"),
|
||||
help: """
|
||||
The mailbox to get messages from.
|
||||
"""
|
||||
)
|
||||
var mailbox: MailboxName = .inbox
|
||||
|
||||
@OptionGroup()
|
||||
var fetchQueryGroup: FetchQueryGroup
|
||||
|
||||
@ArgumentParser.Flag(
|
||||
name: .customLong("delete-unknown"),
|
||||
inversion: .prefixedNo,
|
||||
help: "Delete downloaded messages that do not exist on the server."
|
||||
)
|
||||
var deleteUnknown: Bool = false
|
||||
|
||||
@Option(
|
||||
help: ArgumentHelp(
|
||||
#"The directory to download into."#,
|
||||
valueName: "directory"
|
||||
),
|
||||
completion: .directory
|
||||
)
|
||||
var destination: FilePath
|
||||
|
||||
@Option(help: "How to format the result.")
|
||||
var outputFormat: ResultFormat = .text
|
||||
|
||||
func run() async throws {
|
||||
let query = try fetchQueryGroup.makeFetchQuery()
|
||||
|
||||
try await IMAPConnection.withAuthenticatedConnection(info: connectionInfo) { id, connection -> Void in
|
||||
let info = try await connection.select(
|
||||
mailbox: mailbox,
|
||||
createMailbox: .fail
|
||||
)
|
||||
_ = try await connection.download(
|
||||
mailboxMessageCount: info.messageCount,
|
||||
capabilities: id.capabilities,
|
||||
uidValidity: info.uidValidity,
|
||||
query: query,
|
||||
into: destination,
|
||||
deleteUnknown: deleteUnknown
|
||||
)
|
||||
}
|
||||
|
||||
// Write an empty result. Allows for future expansion.
|
||||
struct Result: Encodable {}
|
||||
writeResult(result: Result(), format: outputFormat)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import ArgumentParser
|
||||
import NIOIMAP
|
||||
import SystemPackage
|
||||
|
||||
extension NIOIMAP.MailboxName: ArgumentParser.ExpressibleByArgument {
|
||||
public init?(argument: String) {
|
||||
do {
|
||||
let path = try MailboxPath.makeRootMailbox(displayName: argument)
|
||||
self = path.name
|
||||
} catch {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
public var defaultValueDescription: String { "INBOX" }
|
||||
}
|
||||
|
||||
extension FilePath: ArgumentParser.ExpressibleByArgument {
|
||||
public init?(argument: String) {
|
||||
self.init(argument)
|
||||
}
|
||||
|
||||
public var defaultValueDescription: String { "path" }
|
||||
}
|
||||
|
||||
extension UID: ArgumentParser.ExpressibleByArgument {
|
||||
public init?(argument: String) {
|
||||
guard
|
||||
let v = UInt32(argument),
|
||||
let uid = UID(exactly: v)
|
||||
else { return nil }
|
||||
self = uid
|
||||
}
|
||||
|
||||
public var defaultValueDescription: String { "uid" }
|
||||
}
|
||||
|
||||
extension NIOIMAP.MessageID: ArgumentParser.ExpressibleByArgument {
|
||||
public init?(argument: String) {
|
||||
// Reject empty / whitespace-only input rather than producing an empty "<>" id.
|
||||
guard argument.contains(where: { !$0.isWhitespace }) else { return nil }
|
||||
// MessageID should be in the format <id@domain> with angle brackets
|
||||
// If the user provides it without brackets, add them
|
||||
let normalized: String
|
||||
switch (argument.hasPrefix("<"), argument.hasSuffix(">")) {
|
||||
case (true, true): normalized = argument
|
||||
case (false, false): normalized = "<\(argument)>"
|
||||
case (false, true), (true, false): return nil
|
||||
}
|
||||
// Reject a bracketed-but-empty id such as "<>".
|
||||
guard normalized.count > 2 else { return nil }
|
||||
self.init(normalized)
|
||||
}
|
||||
|
||||
public var defaultValueDescription: String { "<message-id>" }
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import ArgumentParser
|
||||
import IMAPCommands
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
|
||||
struct IdentifyCommand: AsyncParsableCommand, Sendable {
|
||||
static let configuration = CommandConfiguration(
|
||||
commandName: "id",
|
||||
abstract: "Identify the server"
|
||||
)
|
||||
|
||||
@OptionGroup()
|
||||
var connectionInfo: ConnectionInfo
|
||||
|
||||
@Option(help: "How to format the result.")
|
||||
var outputFormat: ResultFormat = .text
|
||||
|
||||
func run() async throws {
|
||||
let config = try connectionInfo.makeConfiguration()
|
||||
|
||||
let result = try await IMAPConnection.withConnection(configuration: config) { greeting, connection in
|
||||
writeStatus("Server greeting: \(greeting.status)")
|
||||
let r = try await connection.authenticate(
|
||||
greeting: greeting,
|
||||
connectionInfo: connectionInfo
|
||||
)
|
||||
return try await connection.identify(
|
||||
capabilities: r.capabilities
|
||||
)
|
||||
}
|
||||
|
||||
writeResult(result: result, format: outputFormat)
|
||||
}
|
||||
}
|
||||
|
||||
extension IMAPConnection {
|
||||
/// Authenticates the connection using the credentials from `connectionInfo`.
|
||||
func authenticate(
|
||||
greeting: IMAPConnection.Greeting,
|
||||
connectionInfo: ConnectionInfo
|
||||
) async throws -> AuthenticationResult {
|
||||
try await authenticate(
|
||||
greeting: greeting,
|
||||
credential: try connectionInfo.makeCredential(),
|
||||
disableSASLIR: connectionInfo.disableSASLIR,
|
||||
method: connectionInfo.authenticationMethod
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
extension IMAPConnection {
|
||||
/// Runs the given closure with an authenticated IMAP connection.
|
||||
static func withAuthenticatedConnection<Result: Sendable>(
|
||||
info connectionInfo: ConnectionInfo,
|
||||
_ body: @Sendable @escaping (Identity, IMAPConnection) async throws -> Result
|
||||
) async throws -> Result {
|
||||
let config = try connectionInfo.makeConfiguration()
|
||||
|
||||
return try await IMAPConnection.withConnection(configuration: config) { greeting, connection in
|
||||
writeStatus("Connected to \(config.endpoint.hostname ?? ""), received greeting: '\(greeting.status)'")
|
||||
let r = try await connection.authenticate(
|
||||
greeting: greeting,
|
||||
connectionInfo: connectionInfo
|
||||
)
|
||||
let identity = try await connection.identify(
|
||||
capabilities: r.capabilities
|
||||
)
|
||||
|
||||
defer {
|
||||
writeStatus("Closing connection to server.")
|
||||
}
|
||||
return try await body(identity, connection)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import ArgumentParser
|
||||
import IMAPCommands
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
import NIO
|
||||
import NIOIMAP
|
||||
|
||||
struct IdleCommand: AsyncParsableCommand {
|
||||
static let configuration = CommandConfiguration(
|
||||
commandName: "idle",
|
||||
abstract: "Listen for IDLE (RFC 2177) updates.",
|
||||
discussion: #"""
|
||||
This writes each received event to standard output.
|
||||
"""#
|
||||
)
|
||||
|
||||
@OptionGroup()
|
||||
var connectionInfo: ConnectionInfo
|
||||
|
||||
@Option(help: "How to format the result.")
|
||||
var outputFormat: ResultFormat = .text
|
||||
|
||||
@Option(help: "Which delimiter to use to separate events in JSON output. Uses json-seq (RFC 7464) by default.")
|
||||
var recordSeparator: RecordSeparator = .recordSeparator
|
||||
|
||||
@Option(
|
||||
name: .customLong("mailbox"),
|
||||
help: """
|
||||
The mailbox to listen for updates on.
|
||||
"""
|
||||
)
|
||||
var mailboxName: MailboxName = .inbox
|
||||
|
||||
func run() async throws {
|
||||
try await IMAPConnection.withAuthenticatedConnection(info: connectionInfo) { id, connection in
|
||||
_ = try await connection.select(
|
||||
mailbox: mailboxName,
|
||||
createMailbox: .fail
|
||||
)
|
||||
|
||||
let terminator: Data = {
|
||||
switch outputFormat {
|
||||
case .text: return Data("\n".utf8)
|
||||
case .json: return Data(recordSeparator.separatorBytes)
|
||||
}
|
||||
}()
|
||||
|
||||
try await connection.runIdle { _, events in
|
||||
for try await event in events {
|
||||
writeResult(
|
||||
result: event,
|
||||
format: outputFormat,
|
||||
terminator: terminator
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum RecordSeparator: Equatable, Sendable {
|
||||
/// 0x1e
|
||||
case recordSeparator
|
||||
/// 0x0a
|
||||
case lineFeed
|
||||
/// 0x0d
|
||||
case carriageReturn
|
||||
}
|
||||
|
||||
extension RecordSeparator: ExpressibleByArgument {
|
||||
init?(argument: String) {
|
||||
switch argument.lowercased() {
|
||||
case "1e", "rs", "recordseparator", "json-seq":
|
||||
self = .recordSeparator
|
||||
case "0a", "lf", "linefeed":
|
||||
self = .lineFeed
|
||||
case "0d", "cr", "carriagereturn":
|
||||
self = .carriageReturn
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension RecordSeparator {
|
||||
var separatorBytes: [UInt8] {
|
||||
switch self {
|
||||
case .recordSeparator: [0x1e]
|
||||
case .lineFeed: [0x0a]
|
||||
case .carriageReturn: [0x0d]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,362 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import ArgumentParser
|
||||
import IMAPCommands
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
import NIOIMAP
|
||||
|
||||
struct MailboxCommand: AsyncParsableCommand, Sendable {
|
||||
static let configuration = CommandConfiguration(
|
||||
commandName: "mailbox",
|
||||
abstract: "Operations on mailboxes / maildirs",
|
||||
subcommands: [
|
||||
List.self,
|
||||
Create.self,
|
||||
Delete.self,
|
||||
Rename.self,
|
||||
],
|
||||
defaultSubcommand: List.self,
|
||||
aliases: ["maildir", "mailboxes", "maildirs"]
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: List
|
||||
|
||||
extension MailboxCommand {
|
||||
struct List: AsyncParsableCommand, Sendable {
|
||||
static let configuration = CommandConfiguration(
|
||||
commandName: "list",
|
||||
abstract: "List all mailboxes / maildirs"
|
||||
)
|
||||
|
||||
@OptionGroup()
|
||||
var connectionInfo: ConnectionInfo
|
||||
|
||||
@Option(help: "How to format the result.")
|
||||
var outputFormat: ResultFormat = .text
|
||||
|
||||
func run() async throws {
|
||||
let result = try await IMAPConnection.withAuthenticatedConnection(info: connectionInfo) {
|
||||
info,
|
||||
connection in
|
||||
try await connection.listMailboxes(
|
||||
capabilities: info.capabilities
|
||||
)
|
||||
}
|
||||
|
||||
writeResult(
|
||||
result: result.map { MailboxInfoAndStatus.EncodableInfo($0) },
|
||||
format: outputFormat
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Create
|
||||
|
||||
extension MailboxCommand {
|
||||
struct Create: AsyncParsableCommand, Sendable {
|
||||
static let configuration = CommandConfiguration(
|
||||
commandName: "create",
|
||||
abstract: "Create mailbox(es)",
|
||||
discussion: #"""
|
||||
This creates one or multiple mailboxes.
|
||||
|
||||
Note that servers that support CREATE-SPECIAL-USE will let the user specify the so-called “special-use” attributes on the mailbox upon creation.
|
||||
"""#
|
||||
)
|
||||
|
||||
@OptionGroup()
|
||||
var connectionInfo: ConnectionInfo
|
||||
|
||||
@Option(help: "How to format the result.")
|
||||
var outputFormat: ResultFormat = .text
|
||||
|
||||
@Option(
|
||||
name: .customLong("name")
|
||||
)
|
||||
var names: [String] = []
|
||||
|
||||
@Option(
|
||||
name: .customLong("name-json"),
|
||||
help: .init(
|
||||
"Mailbox path as a JSON",
|
||||
discussion: #"""
|
||||
Specify the mailbox with JSON. Using the 'path' key allows specifying a nested mailbox. Using the 'name' key, allow specifying a top-level mailbox. The 'specialUse' key can be used for CREATE-SPECIAL-USE. For example: `{path: ["foo", "bar"], specialUse: "trash"}`.
|
||||
"""#,
|
||||
)
|
||||
)
|
||||
var paths: [MailboxNameWithSpecialUse] = []
|
||||
|
||||
func run() async throws {
|
||||
let result = try await IMAPConnection.withAuthenticatedConnection(info: connectionInfo) {
|
||||
info,
|
||||
connection in
|
||||
let list = try await connection.listMailboxes(
|
||||
capabilities: info.capabilities
|
||||
)
|
||||
|
||||
let existing = ExistingMailboxHierarchy(mailboxPaths: list.map { $0.path })
|
||||
let mailboxes = try existing.makeMailboxNamesForCreation(mailboxDisplayNamesWithSpecialUse)
|
||||
|
||||
var result: [MailboxInfoAndStatus] = []
|
||||
for m in mailboxes {
|
||||
result.append(
|
||||
try await connection.createIfNeededAndList(
|
||||
capabilities: info.capabilities,
|
||||
mailbox: m
|
||||
)
|
||||
)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
writeResult(
|
||||
result: result.map { MailboxInfoAndStatus.EncodableInfo($0) },
|
||||
format: outputFormat
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: -
|
||||
|
||||
extension MailboxCommand.Create {
|
||||
var mailboxDisplayNamesWithSpecialUse: [MailboxDisplayNameWithSpecialUse] {
|
||||
names.map {
|
||||
MailboxDisplayNameWithSpecialUse(namePath: [$0], parameters: [])
|
||||
}
|
||||
+ paths.map {
|
||||
MailboxDisplayNameWithSpecialUse($0)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension MailboxCommand.Create {
|
||||
struct MailboxNameWithSpecialUse: Hashable, Sendable {
|
||||
var namePath: [String]
|
||||
var specialUse: SpecialUse?
|
||||
|
||||
enum SpecialUse: String, Hashable, Sendable {
|
||||
case archive
|
||||
case drafts
|
||||
case junk
|
||||
case sent
|
||||
case trash
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension MailboxDisplayNameWithSpecialUse {
|
||||
init(
|
||||
_ other: MailboxCommand.Create.MailboxNameWithSpecialUse
|
||||
) {
|
||||
self.init(
|
||||
namePath: other.namePath,
|
||||
parameters: other.specialUse.map { [CreateParameter($0)] } ?? []
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
extension CreateParameter {
|
||||
init(
|
||||
_ other: MailboxCommand.Create.MailboxNameWithSpecialUse.SpecialUse
|
||||
) {
|
||||
let attr: UseAttribute
|
||||
switch other {
|
||||
case .archive: attr = .archive
|
||||
case .drafts: attr = .drafts
|
||||
case .junk: attr = .junk
|
||||
case .sent: attr = .sent
|
||||
case .trash: attr = .trash
|
||||
}
|
||||
self = .attributes([attr])
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: -
|
||||
|
||||
extension MailboxCommand.Create.MailboxNameWithSpecialUse: ExpressibleByArgument {
|
||||
fileprivate struct Raw: Decodable {
|
||||
var name: String?
|
||||
var path: [String]?
|
||||
var specialUse: String?
|
||||
}
|
||||
|
||||
init?(argument: String) {
|
||||
let decoder = JSONDecoder()
|
||||
decoder.allowsJSON5 = true
|
||||
decoder.assumesTopLevelDictionary = true
|
||||
guard
|
||||
let raw = try? decoder.decode(Raw.self, from: Data(argument.utf8))
|
||||
else { return nil }
|
||||
// Path
|
||||
let namePath: [String]
|
||||
switch (raw.name, raw.path) {
|
||||
case (let name?, nil):
|
||||
namePath = [name]
|
||||
case (nil, let path?):
|
||||
namePath = path
|
||||
case (.some, .some), (nil, nil):
|
||||
return nil
|
||||
}
|
||||
// Special Use:
|
||||
let specialUse: SpecialUse?
|
||||
if let s = raw.specialUse {
|
||||
guard
|
||||
let ss = SpecialUse(rawValue: s)
|
||||
else { return nil }
|
||||
specialUse = ss
|
||||
} else {
|
||||
specialUse = nil
|
||||
}
|
||||
self.init(
|
||||
namePath: namePath,
|
||||
specialUse: specialUse
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Delete
|
||||
|
||||
extension MailboxCommand {
|
||||
struct Delete: AsyncParsableCommand, Sendable {
|
||||
static let configuration = CommandConfiguration(
|
||||
commandName: "delete",
|
||||
abstract: "Delete mailbox(es)",
|
||||
discussion: #"""
|
||||
This deletes one or multiple mailboxes and all their contents.
|
||||
|
||||
WARNING: This operation is irreversible and will permanently delete all messages in the specified mailboxes.
|
||||
"""#
|
||||
)
|
||||
|
||||
@OptionGroup()
|
||||
var connectionInfo: ConnectionInfo
|
||||
|
||||
@Option(help: "How to format the result.")
|
||||
var outputFormat: ResultFormat = .text
|
||||
|
||||
@Argument(
|
||||
help: .init(
|
||||
"Mailbox name to be deleted",
|
||||
valueName: "mailbox-name"
|
||||
)
|
||||
)
|
||||
var names: [MailboxName] = []
|
||||
|
||||
func run() async throws {
|
||||
guard !names.isEmpty else {
|
||||
throw ValidationError("At least one mailbox name must be specified")
|
||||
}
|
||||
|
||||
let result = try await IMAPConnection.withAuthenticatedConnection(info: connectionInfo) {
|
||||
info,
|
||||
connection in
|
||||
// Delete each mailbox:
|
||||
for mailboxName in names {
|
||||
try await connection.deleteMailbox(
|
||||
capabilities: info.capabilities,
|
||||
mailbox: mailboxName
|
||||
)
|
||||
}
|
||||
// List the mailboxes after the deletion:
|
||||
return try await connection.listMailboxes(
|
||||
capabilities: info.capabilities
|
||||
)
|
||||
}
|
||||
|
||||
writeResult(
|
||||
result: result.map { MailboxInfoAndStatus.EncodableInfo($0) },
|
||||
format: outputFormat
|
||||
)
|
||||
}
|
||||
|
||||
mutating func validate() throws {
|
||||
guard
|
||||
!names.isEmpty
|
||||
else {
|
||||
throw ValidationError("Must specify at least one mailbox")
|
||||
}
|
||||
var previous = Set<MailboxName>()
|
||||
for name in names {
|
||||
defer { previous.insert(name) }
|
||||
guard
|
||||
!previous.contains(name)
|
||||
else {
|
||||
let n = (try? MailboxPath(name: name))?.displayStringComponents().first ?? ""
|
||||
throw ValidationError("Duplicate mailbox name '\(n)'")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Rename
|
||||
|
||||
extension MailboxCommand {
|
||||
struct Rename: AsyncParsableCommand, Sendable {
|
||||
static let configuration = CommandConfiguration(
|
||||
commandName: "rename",
|
||||
abstract: "Rename a mailbox",
|
||||
discussion: #"""
|
||||
This renames a mailbox on the server.
|
||||
"""#
|
||||
)
|
||||
|
||||
@OptionGroup()
|
||||
var connectionInfo: ConnectionInfo
|
||||
|
||||
@Option(help: "How to format the result.")
|
||||
var outputFormat: ResultFormat = .text
|
||||
|
||||
@Option(
|
||||
name: .long,
|
||||
help: "Current (old) name of the mailbox"
|
||||
)
|
||||
var oldName: MailboxName
|
||||
|
||||
@Option(
|
||||
name: .long,
|
||||
help: "New name for the mailbox"
|
||||
)
|
||||
var newName: MailboxName
|
||||
|
||||
func run() async throws {
|
||||
let result = try await IMAPConnection.withAuthenticatedConnection(info: connectionInfo) {
|
||||
info,
|
||||
connection in
|
||||
try await connection.renameMailbox(
|
||||
capabilities: info.capabilities,
|
||||
old: oldName,
|
||||
new: newName
|
||||
)
|
||||
|
||||
return try await connection.listMailboxes(
|
||||
capabilities: info.capabilities
|
||||
)
|
||||
}
|
||||
|
||||
writeResult(
|
||||
result: result.map { MailboxInfoAndStatus.EncodableInfo($0) },
|
||||
format: outputFormat
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import ArgumentParser
|
||||
import IMAPCommands
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
import NIO
|
||||
import NIOIMAP
|
||||
import SystemPackage
|
||||
|
||||
struct MessageFlagCommand: AsyncParsableCommand {
|
||||
static let configuration = CommandConfiguration(
|
||||
commandName: "flag",
|
||||
abstract: "Set / unset IMAP flags on messages.",
|
||||
aliases: ["flags"]
|
||||
)
|
||||
|
||||
@OptionGroup()
|
||||
var connectionInfo: ConnectionInfo
|
||||
|
||||
@Option(help: "The mailbox containing the message(s).")
|
||||
var mailbox: MailboxName = .inbox
|
||||
|
||||
@Option(help: "How to format the result.")
|
||||
var outputFormat: ResultFormat = .text
|
||||
|
||||
@Option(
|
||||
name: [.customLong("flag"), .customLong("set")],
|
||||
help: .init(
|
||||
"IMAP flag to set on the message(s).",
|
||||
discussion: #"""
|
||||
Allows specifying flags to be set on messages.
|
||||
|
||||
This can be repeated multiple times to set multiple flags.
|
||||
|
||||
Valid values: \#(MessageFlag.allCases.map { $0.rawValue }.joined(separator: ", "))
|
||||
"""#
|
||||
)
|
||||
)
|
||||
var setFlags: [MessageFlag] = []
|
||||
|
||||
@Option(
|
||||
name: [.customLong("unset"), .customLong("remove")],
|
||||
help: .init(
|
||||
"IMAP flag to unset on the message(s).",
|
||||
discussion: #"""
|
||||
Allows specifying flags to be unset on messages.
|
||||
|
||||
This can be repeated multiple times to unset multiple flags.
|
||||
|
||||
Valid values: \#(MessageFlag.allCases.map { $0.rawValue }.joined(separator: ", "))
|
||||
"""#
|
||||
)
|
||||
)
|
||||
var unsetFlags: [MessageFlag] = []
|
||||
|
||||
@Option(
|
||||
name: .customLong("uid"),
|
||||
help: "UIDs of messages to modify (can be specified multiple times)"
|
||||
)
|
||||
var uids: [UID] = []
|
||||
@Option(
|
||||
name: .customLong("message-id"),
|
||||
help: "Message-ID of message to modify (can be specified multiple times)"
|
||||
)
|
||||
var messageIDs: [MessageID] = []
|
||||
|
||||
@Option(
|
||||
help: #"""
|
||||
A file to read message info from. This should be JSON as output by the \
|
||||
'append' command. The JSON needs to be an array where each element has a \
|
||||
'uid' value or an 'id' value, the latter being the message-id header of \
|
||||
the messages to be deleted.
|
||||
"""#,
|
||||
completion: .file(extensions: ["json"])
|
||||
)
|
||||
var messages: String?
|
||||
|
||||
func validate() throws {
|
||||
guard
|
||||
!uids.isEmpty || !messageIDs.isEmpty || (messages != nil)
|
||||
else {
|
||||
throw ValidationError(
|
||||
"Must specify at least one UID (--uid) or a file to read UIDs and/or message-id from (--messages)."
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func run() async throws {
|
||||
let ids = try UIDsAndMessageIDs(
|
||||
filePath: messages,
|
||||
uids: uids,
|
||||
messageIDs: messageIDs
|
||||
)
|
||||
guard
|
||||
!ids.isEmpty
|
||||
else {
|
||||
writeStatus("No messages to update,")
|
||||
return
|
||||
}
|
||||
|
||||
try await run(
|
||||
ids: ids,
|
||||
changes: imapFlags
|
||||
)
|
||||
}
|
||||
|
||||
func run(
|
||||
ids: UIDsAndMessageIDs,
|
||||
changes: IMAPToolLib.FlagChanges
|
||||
) async throws {
|
||||
try await IMAPConnection.withAuthenticatedConnection(info: connectionInfo) { id, connection in
|
||||
let info = try await connection.select(
|
||||
mailbox: mailbox,
|
||||
createMailbox: .fail
|
||||
)
|
||||
|
||||
let allUIDs = try await connection.findMessageIDs(
|
||||
selectInfo: info,
|
||||
capabilities: id.capabilities,
|
||||
ids: ids
|
||||
)
|
||||
|
||||
guard
|
||||
!allUIDs.isEmpty
|
||||
else { return }
|
||||
|
||||
try await connection.updateFlags(
|
||||
uids: allUIDs,
|
||||
changes: changes
|
||||
)
|
||||
}
|
||||
|
||||
struct EmptyResult: Encodable {}
|
||||
|
||||
writeResult(result: EmptyResult(), format: outputFormat)
|
||||
}
|
||||
}
|
||||
|
||||
extension MessageFlagCommand {
|
||||
var imapFlags: IMAPToolLib.FlagChanges {
|
||||
IMAPToolLib.FlagChanges(
|
||||
setFlags: setFlags,
|
||||
unsetFlags: unsetFlags
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
extension IMAPToolLib.FlagChanges {
|
||||
init(
|
||||
setFlags: [MessageFlag],
|
||||
unsetFlags: [MessageFlag]
|
||||
) {
|
||||
let a =
|
||||
setFlags
|
||||
.reduce(into: Set<NIOIMAP.Flag>()) {
|
||||
$0.formUnion($1.flagsToSet)
|
||||
}
|
||||
let b =
|
||||
unsetFlags
|
||||
.reduce(into: Set<NIOIMAP.Flag>()) {
|
||||
$0.formUnion($1.flagsToUnset)
|
||||
}
|
||||
self.init(set: [], unset: [])
|
||||
self.set = a.subtracting(b)
|
||||
.sorted(by: { "\($0)" < "\($1)" })
|
||||
self.unset = b.subtracting(a)
|
||||
.sorted(by: { "\($0)" < "\($1)" })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import IMAPCommands
|
||||
import ArgumentParser
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
import NIOIMAP
|
||||
|
||||
struct MessageInfoCommand: AsyncParsableCommand {
|
||||
static let configuration = CommandConfiguration(
|
||||
commandName: "message-info",
|
||||
abstract: "Get information about messages."
|
||||
)
|
||||
|
||||
@OptionGroup()
|
||||
var connectionInfo: ConnectionInfo
|
||||
|
||||
@Option(
|
||||
name: .customLong("mailbox"),
|
||||
help: """
|
||||
The mailbox to get messages from.
|
||||
"""
|
||||
)
|
||||
var mailbox: MailboxName = .inbox
|
||||
|
||||
@OptionGroup()
|
||||
var fetchQueryGroup: FetchQueryGroup
|
||||
|
||||
@Option(help: "How to format the result.")
|
||||
var outputFormat: ResultFormat = .text
|
||||
|
||||
func run() async throws {
|
||||
let query = try fetchQueryGroup.makeFetchQuery()
|
||||
|
||||
let result: [MessageInfo] = try await IMAPConnection.withAuthenticatedConnection(info: connectionInfo) {
|
||||
id,
|
||||
connection in
|
||||
let info = try await connection.select(
|
||||
mailbox: mailbox,
|
||||
createMailbox: .fail
|
||||
)
|
||||
return try await connection.fetchMessageInfo(
|
||||
mailboxMessageCount: info.messageCount,
|
||||
capabilities: id.capabilities,
|
||||
query: query
|
||||
)
|
||||
}
|
||||
|
||||
writeResult(result: result, format: outputFormat)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import ArgumentParser
|
||||
import IMAPCommands
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
import NIOIMAP
|
||||
|
||||
struct MoveMessageCommand: AsyncParsableCommand, Sendable {
|
||||
static let configuration = CommandConfiguration(
|
||||
commandName: "move-message",
|
||||
abstract: "Move messages between mailboxes",
|
||||
discussion: #"""
|
||||
This command moves messages from one mailbox to another.
|
||||
|
||||
If the server supports the MOVE extension (RFC 6851), it will use the UID MOVE command. Otherwise, it will fall back to UID COPY and then delete the source.
|
||||
"""#
|
||||
)
|
||||
|
||||
@OptionGroup()
|
||||
var connectionInfo: ConnectionInfo
|
||||
|
||||
@Option(help: "How to format the result.")
|
||||
var outputFormat: ResultFormat = .text
|
||||
|
||||
@Option(
|
||||
name: [.customLong("source"), .customLong("from")],
|
||||
help: "Source mailbox containing the message(s)"
|
||||
)
|
||||
var sourceMailbox: MailboxName
|
||||
|
||||
@Option(
|
||||
name: [.customLong("destination"), .customLong("to")],
|
||||
help: "Destination mailbox for the message(s)"
|
||||
)
|
||||
var destinationMailbox: MailboxName
|
||||
|
||||
@Option(
|
||||
name: .customLong("uid"),
|
||||
help: "UID of message to move (can be specified multiple times)"
|
||||
)
|
||||
var uids: [UID] = []
|
||||
|
||||
@Option(
|
||||
name: .customLong("message-id"),
|
||||
help: "Message-ID of message to move (can be specified multiple times)"
|
||||
)
|
||||
var messageIDs: [MessageID] = []
|
||||
|
||||
@Option(
|
||||
help: #"""
|
||||
A file to read message info from. This should be JSON as output by the \
|
||||
'append' command. The JSON needs to be an array where each element has a \
|
||||
'uid' value or an 'id' value, the latter being the message-id header of \
|
||||
the messages to be moved.
|
||||
"""#,
|
||||
completion: .file(extensions: ["json"])
|
||||
)
|
||||
var messages: String?
|
||||
|
||||
func validate() throws {
|
||||
guard
|
||||
!uids.isEmpty || !messageIDs.isEmpty || (messages != nil)
|
||||
else {
|
||||
throw ValidationError(
|
||||
"Must specify at least one UID (--uid), Message-ID (--message-id), or a file to read from (--messages)."
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func run() async throws {
|
||||
let ids = try UIDsAndMessageIDs(
|
||||
filePath: messages,
|
||||
uids: uids,
|
||||
messageIDs: messageIDs
|
||||
)
|
||||
guard !ids.isEmpty else {
|
||||
writeStatus("No messages to move.")
|
||||
return
|
||||
}
|
||||
|
||||
struct Result: Encodable {
|
||||
var uids: [UID]
|
||||
}
|
||||
|
||||
let result = try await IMAPConnection.withAuthenticatedConnection(info: connectionInfo) { info, connection in
|
||||
// Select the source mailbox
|
||||
let selectInfo = try await connection.select(
|
||||
mailbox: sourceMailbox,
|
||||
createMailbox: .fail
|
||||
)
|
||||
|
||||
let allUIDs = try await connection.findMessageIDs(
|
||||
selectInfo: selectInfo,
|
||||
capabilities: info.capabilities,
|
||||
ids: ids
|
||||
)
|
||||
|
||||
guard !allUIDs.isEmpty else {
|
||||
writeStatus("No messages found to move.")
|
||||
return Result(uids: [])
|
||||
}
|
||||
|
||||
try await connection.moveMessages(
|
||||
selectInfo: selectInfo,
|
||||
capabilities: info.capabilities,
|
||||
uids: allUIDs,
|
||||
to: destinationMailbox
|
||||
)
|
||||
|
||||
return Result(uids: Array(allUIDs))
|
||||
}
|
||||
|
||||
writeResult(result: result, format: outputFormat)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import ArgumentParser
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
|
||||
/// The subcommands provided by `IMAPToolLib`.
|
||||
///
|
||||
/// This is exposed so that an embedding tool can build its own root command
|
||||
/// that combines these built-in subcommands with additional ones.
|
||||
public let builtinSubcommands: [any ParsableCommand.Type] = [
|
||||
AppendCommand.self,
|
||||
DeleteMessagesCommand.self,
|
||||
DownloadCommand.self,
|
||||
IdentifyCommand.self,
|
||||
IdleCommand.self,
|
||||
MailboxCommand.self,
|
||||
MessageInfoCommand.self,
|
||||
MessageFlagCommand.self,
|
||||
MoveMessageCommand.self,
|
||||
SearchMessagesCommand.self,
|
||||
]
|
||||
|
||||
struct RootCommand: AsyncParsableCommand {
|
||||
static let configuration = CommandConfiguration(
|
||||
commandName: "imap-tool",
|
||||
subcommands: builtinSubcommands
|
||||
)
|
||||
}
|
||||
|
||||
/// Describes how the CLI should terminate for an error thrown while parsing or
|
||||
/// running a command.
|
||||
///
|
||||
/// ArgumentParser signals `--help`, `--version`, and other "clean" exits by
|
||||
/// throwing. Those must be written to standard output with a `0` exit code,
|
||||
/// whereas genuine parsing/validation errors belong on standard error with a
|
||||
/// non-zero exit code (e.g. `EX_USAGE`).
|
||||
struct TerminationInfo: Equatable {
|
||||
var message: String
|
||||
/// A clean exit (help/version) — print to standard output and exit `0`.
|
||||
var isCleanExit: Bool
|
||||
var code: Int32
|
||||
}
|
||||
|
||||
func terminationInfo(for error: any Swift.Error) -> TerminationInfo {
|
||||
let exitCode = RootCommand.exitCode(for: error)
|
||||
return TerminationInfo(
|
||||
message: RootCommand.fullMessage(for: error),
|
||||
isCleanExit: exitCode == .success,
|
||||
code: exitCode.rawValue
|
||||
)
|
||||
}
|
||||
|
||||
/// Parses command-line arguments and runs the specified IMAP tool subcommand.
|
||||
public func main() async {
|
||||
do {
|
||||
var command = try RootCommand.parseAsRoot()
|
||||
if var asyncCommand = command as? AsyncParsableCommand {
|
||||
try await asyncCommand.run()
|
||||
} else {
|
||||
try command.run()
|
||||
}
|
||||
} catch {
|
||||
let info = terminationInfo(for: error)
|
||||
if info.isCleanExit {
|
||||
// Help / version / other clean exits belong on standard output.
|
||||
if !info.message.isEmpty {
|
||||
writeStandardOutput(info.message + "\n")
|
||||
}
|
||||
} else if !info.message.isEmpty {
|
||||
writeStatus("\(info.message)")
|
||||
flushStatus()
|
||||
}
|
||||
_exit(info.code)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import ArgumentParser
|
||||
import IMAPCommands
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
import NIO
|
||||
import NIOIMAP
|
||||
|
||||
struct SearchMessagesCommand: AsyncParsableCommand, Sendable {
|
||||
static let configuration = CommandConfiguration(
|
||||
commandName: "search",
|
||||
abstract: "Search for messages",
|
||||
discussion: #"""
|
||||
This command searches for messages in a mailbox based on various criteria such as date ranges, flags, and subjects.
|
||||
"""#,
|
||||
aliases: [
|
||||
"search-messages",
|
||||
"search-message",
|
||||
]
|
||||
)
|
||||
|
||||
@OptionGroup()
|
||||
var connectionInfo: ConnectionInfo
|
||||
|
||||
@Option(help: "How to format the result.")
|
||||
var outputFormat: ResultFormat = .text
|
||||
|
||||
@Option(
|
||||
name: .customLong("mailbox"),
|
||||
help: "The mailbox to search in"
|
||||
)
|
||||
var mailbox: MailboxName = .inbox
|
||||
|
||||
@OptionGroup()
|
||||
var predicate: Predicate
|
||||
|
||||
@ArgumentParser.Flag(
|
||||
name: .customLong("fetch-message-info"),
|
||||
help: "Fetch message info for the found UIDs"
|
||||
)
|
||||
var shouldFetchMessageInfo: Bool = false
|
||||
|
||||
func run() async throws {
|
||||
// Get the search criteria:
|
||||
let searchKey = try SearchKey(predicate)
|
||||
writeStatus("Searching for messages with \(searchKey)")
|
||||
|
||||
struct Result: Encodable {
|
||||
var imapQuery: String
|
||||
var uids: [UID]
|
||||
var messageInfo: [MessageInfo]?
|
||||
}
|
||||
|
||||
let result: Result = try await IMAPConnection.withAuthenticatedConnection(
|
||||
info: connectionInfo
|
||||
) { info, connection -> Result in
|
||||
let mailboxInfo = try await connection.select(
|
||||
mailbox: mailbox,
|
||||
createMailbox: .fail
|
||||
)
|
||||
|
||||
let uids = try await connection.search(
|
||||
capabilities: info.capabilities,
|
||||
key: searchKey
|
||||
)
|
||||
|
||||
let messageInfo: [MessageInfo]?
|
||||
if shouldFetchMessageInfo {
|
||||
messageInfo = try await connection.fetchMessageInfo(
|
||||
mailboxMessageCount: mailboxInfo.messageCount,
|
||||
capabilities: info.capabilities,
|
||||
query: .uids(uids)
|
||||
)
|
||||
} else {
|
||||
messageInfo = nil
|
||||
}
|
||||
|
||||
return Result(
|
||||
imapQuery: String(reflecting: searchKey),
|
||||
uids: uids.map { $0 },
|
||||
messageInfo: messageInfo
|
||||
)
|
||||
}
|
||||
|
||||
writeResult(
|
||||
result: result,
|
||||
format: outputFormat
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import ArgumentParser
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
import NIOIMAP
|
||||
|
||||
extension SearchMessagesCommand {
|
||||
/// Command-line arguments that specify the search predicate.
|
||||
struct Predicate: ParsableArguments, Sendable {
|
||||
init() {}
|
||||
|
||||
init(
|
||||
olderThanDays: Int? = nil,
|
||||
newerThanDays: Int? = nil,
|
||||
subject: String? = nil,
|
||||
fromAddress: String? = nil,
|
||||
toAddress: String? = nil,
|
||||
ccAddress: String? = nil,
|
||||
text: String? = nil,
|
||||
messageSizeSmallerThan: Int? = nil,
|
||||
messageSizeLargerThan: Int? = nil,
|
||||
messageID: String? = nil,
|
||||
emailID: String? = nil,
|
||||
threadID: String? = nil,
|
||||
flags: [MessageFlag] = []
|
||||
) {
|
||||
self.olderThanDays = olderThanDays
|
||||
self.newerThanDays = newerThanDays
|
||||
self.subject = subject
|
||||
self.fromAddress = fromAddress
|
||||
self.toAddress = toAddress
|
||||
self.ccAddress = ccAddress
|
||||
self.text = text
|
||||
self.messageSizeSmallerThan = messageSizeSmallerThan
|
||||
self.messageSizeLargerThan = messageSizeLargerThan
|
||||
self.messageID = messageID
|
||||
self.emailID = emailID
|
||||
self.threadID = threadID
|
||||
self.flags = flags
|
||||
}
|
||||
|
||||
@Option(
|
||||
name: .customLong("older-than-days"),
|
||||
help: "Match messages older than N days"
|
||||
)
|
||||
var olderThanDays: Int?
|
||||
|
||||
@Option(
|
||||
name: .customLong("newer-than-days"),
|
||||
help: "Match messages newer than N days"
|
||||
)
|
||||
var newerThanDays: Int?
|
||||
|
||||
@Option(
|
||||
name: .customLong("subject"),
|
||||
help: "Match messages with this subject"
|
||||
)
|
||||
var subject: String?
|
||||
|
||||
@Option(
|
||||
name: .customLong("from"),
|
||||
help: "Match messages from this sender"
|
||||
)
|
||||
var fromAddress: String?
|
||||
|
||||
@Option(
|
||||
name: .customLong("to"),
|
||||
help: "Match messages to this recipient"
|
||||
)
|
||||
var toAddress: String?
|
||||
|
||||
@Option(
|
||||
name: .customLong("cc"),
|
||||
help: "Match messages with this CC recipient"
|
||||
)
|
||||
var ccAddress: String?
|
||||
|
||||
@Option(
|
||||
name: .customLong("text"),
|
||||
help: "Match messages containing this text"
|
||||
)
|
||||
var text: String?
|
||||
|
||||
@Option(
|
||||
name: .customLong("message-size-smaller-than"),
|
||||
help: "Match messages smaller than N bytes"
|
||||
)
|
||||
var messageSizeSmallerThan: Int?
|
||||
|
||||
@Option(
|
||||
name: .customLong("message-size-larger-than"),
|
||||
help: "Match messages larger than N bytes"
|
||||
)
|
||||
var messageSizeLargerThan: Int?
|
||||
|
||||
@Option(
|
||||
name: .customLong("message-id"),
|
||||
help: "Match message by IMAP Message-ID"
|
||||
)
|
||||
var messageID: String?
|
||||
|
||||
@Option(
|
||||
name: .customLong("email-id"),
|
||||
help: "Match message by RFC 8474 Email ID"
|
||||
)
|
||||
var emailID: String?
|
||||
|
||||
@Option(
|
||||
name: .customLong("thread-id"),
|
||||
help: "Match messages by RFC 8474 Thread ID"
|
||||
)
|
||||
var threadID: String?
|
||||
|
||||
@Option(
|
||||
name: .customLong("flag"),
|
||||
help: .init(
|
||||
"Match messages with this flag.",
|
||||
discussion: #"""
|
||||
Match messages with this flag set.
|
||||
|
||||
This can be repeated multiple times.
|
||||
|
||||
Valid values: \#(MessageFlag.allCases.map { $0.rawValue }.joined(separator: ", "))
|
||||
"""#
|
||||
)
|
||||
)
|
||||
var flags: [MessageFlag] = []
|
||||
}
|
||||
}
|
||||
|
||||
extension SearchKey {
|
||||
/// Create a ``SearchKey`` from command line arguments.
|
||||
init(
|
||||
_ other: SearchMessagesCommand.Predicate
|
||||
) throws {
|
||||
try self.init(SearchKey.Predicate(other))
|
||||
}
|
||||
}
|
||||
|
||||
extension SearchKey.Predicate {
|
||||
/// Convert to a `SearchKey.Predicate`.
|
||||
init(
|
||||
_ other: SearchMessagesCommand.Predicate
|
||||
) throws {
|
||||
// Combine all flags
|
||||
var flagsSet: Set<NIOIMAP.Flag> = []
|
||||
var flagsNotSet: Set<NIOIMAP.Flag> = []
|
||||
for flag in other.flags {
|
||||
let toSearch = flag.flagsToSearch
|
||||
flagsSet.formUnion(toSearch.set)
|
||||
flagsNotSet.formUnion(toSearch.notSet)
|
||||
}
|
||||
guard
|
||||
flagsSet.isDisjoint(with: flagsNotSet)
|
||||
else {
|
||||
let a = flagsSet.intersection(flagsNotSet)
|
||||
let invalid = other
|
||||
.flags
|
||||
.filter { flag in
|
||||
!flag.flagsToSearch.set.isDisjoint(with: a) || !flag.flagsToSearch.notSet.isDisjoint(with: a)
|
||||
}
|
||||
guard
|
||||
!invalid.isEmpty
|
||||
else { throw ValidationError("Invalid flag combination") }
|
||||
throw ValidationError("Invalid combination of flags {\(invalid.map { "\($0)" }.joined(separator: ", "))}")
|
||||
}
|
||||
|
||||
// Parse string IDs to typed IDs
|
||||
let emailID: EmailID?
|
||||
if let emailIDString = other.emailID {
|
||||
guard let parsed = EmailID(emailIDString) else {
|
||||
throw ValidationError("Invalid email-id: \(emailIDString)")
|
||||
}
|
||||
emailID = parsed
|
||||
} else {
|
||||
emailID = nil
|
||||
}
|
||||
|
||||
let threadID: ThreadID?
|
||||
if let threadIDString = other.threadID {
|
||||
guard let parsed = ThreadID(threadIDString) else {
|
||||
throw ValidationError("Invalid thread-id: \(threadIDString)")
|
||||
}
|
||||
threadID = parsed
|
||||
} else {
|
||||
threadID = nil
|
||||
}
|
||||
|
||||
if let o = other.olderThanDays, let n = other.newerThanDays {
|
||||
guard
|
||||
o < n
|
||||
else { throw ValidationError("Messages can not be older than \(o) and newer than \(n) at the same time.") }
|
||||
}
|
||||
|
||||
self.init(
|
||||
olderThanDays: other.olderThanDays,
|
||||
newerThanDays: other.newerThanDays,
|
||||
subject: other.subject,
|
||||
from: other.fromAddress,
|
||||
to: other.toAddress,
|
||||
cc: other.ccAddress,
|
||||
text: other.text,
|
||||
messageSizeSmallerThan: other.messageSizeSmallerThan,
|
||||
messageSizeLargerThan: other.messageSizeLargerThan,
|
||||
messageID: other.messageID.map { MessageID($0) },
|
||||
emailID: emailID,
|
||||
threadID: threadID,
|
||||
flagsSet: flagsSet,
|
||||
flagsNotSet: flagsNotSet
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import NIOCore
|
||||
import NIOFileSystem
|
||||
import SystemPackage
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
|
||||
private let tokenBucket = TokenBucket(tokens: 20)
|
||||
|
||||
extension Data {
|
||||
/// Reads the contents of the file at the given path asynchronously.
|
||||
init(
|
||||
asyncContentsOf filePath: FilePath,
|
||||
length: Int = .max
|
||||
) async throws {
|
||||
let buffer = try await read(
|
||||
filePath: filePath,
|
||||
length: length
|
||||
)
|
||||
self.init(buffer.readableBytesView)
|
||||
}
|
||||
}
|
||||
|
||||
extension ByteBuffer {
|
||||
/// Reads the contents of the file at the given path asynchronously.
|
||||
init(
|
||||
asyncContentsOf filePath: FilePath,
|
||||
length: Int = .max
|
||||
) async throws {
|
||||
self = try await read(
|
||||
filePath: filePath,
|
||||
length: length
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private func read(
|
||||
filePath: FilePath,
|
||||
length: Int
|
||||
) async throws -> ByteBuffer {
|
||||
// Use the TokenBucket to limit concurrency.
|
||||
try await tokenBucket.withToken {
|
||||
try await readWithToken(
|
||||
filePath: filePath,
|
||||
length: length
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private func readWithToken(
|
||||
filePath: FilePath,
|
||||
length: Int
|
||||
) async throws -> ByteBuffer {
|
||||
try await FileSystem.shared.withFileHandle(forReadingAt: filePath) { handle in
|
||||
guard length != .max else {
|
||||
return try await handle.readToEnd(maximumSizeAllowed: .unlimited)
|
||||
}
|
||||
// `length` is an upper bound, not the exact size to read: callers use it to
|
||||
// look at just the start of a message. Reading in chunks lets us stop early
|
||||
// rather than pulling a whole (potentially huge) file into memory.
|
||||
var result = ByteBuffer()
|
||||
for try await var chunk in handle.readChunks() {
|
||||
let remaining = length - result.readableBytes
|
||||
guard chunk.readableBytes < remaining else {
|
||||
result.writeImmutableBuffer(chunk.readSlice(length: remaining)!)
|
||||
break
|
||||
}
|
||||
result.writeImmutableBuffer(chunk)
|
||||
}
|
||||
return result
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
import NIOIMAP
|
||||
import SystemPackage
|
||||
|
||||
/// An RFC 5322 email message stored as raw data.
|
||||
public struct EmailMessage: Hashable, Sendable {
|
||||
var data: Data
|
||||
}
|
||||
|
||||
extension EmailMessage {
|
||||
init(filePath: FilePath) async throws {
|
||||
let input = try await Data(
|
||||
asyncContentsOf: filePath
|
||||
)
|
||||
// This is not entirely clean, but we want to avoid uploading
|
||||
// messages with Unix file endings to an IMAP server.
|
||||
guard
|
||||
EmailMessage.headerIsCRLFClean(input)
|
||||
else {
|
||||
self = EmailMessage.convertingLineEndings(input)
|
||||
return
|
||||
}
|
||||
self.init(data: input)
|
||||
}
|
||||
}
|
||||
|
||||
extension EmailMessage {
|
||||
/// Checks whether the message header uses CRLF line endings.
|
||||
static func headerIsCRLFClean(_ input: Data) -> Bool {
|
||||
let bytes = input.span
|
||||
// Only the first four line breaks are inspected, and only near the start.
|
||||
let limit = min(bytes.count, 10_000)
|
||||
var position = 0
|
||||
var lineBreakCount = 0
|
||||
while lineBreakCount < 4, position < limit {
|
||||
guard let index = bytes.firstIndexOfLineBreak(in: position..<limit) else { break }
|
||||
// Every line break in the header has to be a CRLF pair.
|
||||
guard
|
||||
bytes[index] == 0x0D,
|
||||
index + 1 < limit,
|
||||
bytes[index + 1] == 0x0A
|
||||
else { return false }
|
||||
lineBreakCount += 1
|
||||
position = index + 2
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/// Creates an email message by converting all line endings to CRLF.
|
||||
static func convertingLineEndings(_ input: Data) -> EmailMessage {
|
||||
// Convert to CRLF:
|
||||
var output = Data(capacity: input.count)
|
||||
let bytes = input.span
|
||||
var position = 0
|
||||
while let ending = bytes.locateLineEnding(from: position) {
|
||||
output.append(bytes.extracting(position..<ending.lowerBound))
|
||||
output.append(contentsOf: [0xD, 0xA])
|
||||
position = ending.upperBound
|
||||
}
|
||||
if position < bytes.count {
|
||||
output.append(bytes.extracting(position..<bytes.count))
|
||||
}
|
||||
return EmailMessage(data: output)
|
||||
}
|
||||
}
|
||||
|
||||
extension EmailMessage {
|
||||
public struct HeadersOfInterest: Hashable, Sendable {
|
||||
public var messageID: MessageID
|
||||
public var date: InternetMessageDate
|
||||
/// The message subject, for display purposes. Not populated by the
|
||||
/// default ``MiniMIMEHeaderParser``.
|
||||
public var subject: String?
|
||||
|
||||
public init(messageID: MessageID, date: InternetMessageDate, subject: String? = nil) {
|
||||
self.messageID = messageID
|
||||
self.date = date
|
||||
self.subject = subject
|
||||
}
|
||||
}
|
||||
|
||||
var headersOfInterest: HeadersOfInterest? {
|
||||
MessageHeaderParser.current.headersOfInterest(data)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: -
|
||||
|
||||
extension Span<UInt8> {
|
||||
/// Returns the index of the first CR or LF within `range`, or `nil` if there is none.
|
||||
func firstIndexOfLineBreak(in range: Range<Int>) -> Int? {
|
||||
for index in range where self[index] == 0x0D || self[index] == 0x0A {
|
||||
return index
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
/// Locates the next line ending at or after `start`, returning the range it
|
||||
/// occupies. A CRLF pair is reported as a single two-byte ending.
|
||||
func locateLineEnding(from start: Int) -> Range<Int>? {
|
||||
guard let lf = firstIndexOfLineEnding(from: start) else { return nil }
|
||||
// Include a preceding CR, so that CRLF is treated as one ending.
|
||||
if start < lf, self[lf - 1] == 0x0D {
|
||||
return (lf - 1)..<(lf + 1)
|
||||
}
|
||||
return lf..<(lf + 1)
|
||||
}
|
||||
|
||||
private func firstIndexOfLineEnding(from start: Int) -> Int? {
|
||||
for index in start..<count where self[index] == 0x0A {
|
||||
return index
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
extension Data {
|
||||
/// Appends the bytes of `span`.
|
||||
fileprivate mutating func append(_ span: Span<UInt8>) {
|
||||
span.withUnsafeBufferPointer { append(contentsOf: $0) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,382 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import Foundation
|
||||
import NIOIMAP
|
||||
#if canImport(Darwin)
|
||||
import locale_h
|
||||
import time_h
|
||||
import xlocale
|
||||
#endif
|
||||
|
||||
extension InternetMessageDate {
|
||||
/// Parses the date string.
|
||||
///
|
||||
/// Performs a lenient parse as needed. It is better to return a slightly wrong date than no date at all.
|
||||
func parse() -> Foundation.Date? {
|
||||
return parseWithoutFoundation() ?? parseWithFoundation()
|
||||
}
|
||||
|
||||
/// Creates an RFC 822 formatted `DateString` from the given `Date` and `Calendar`.
|
||||
///
|
||||
/// Uses the calendar’s `timeZone` to format the time zone output.
|
||||
init(from date: Foundation.Date, calendar: Calendar) {
|
||||
self.init(date.formatAsRFC822(calendar: calendar))
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Internal Formatting
|
||||
|
||||
#if canImport(Darwin)
|
||||
extension Foundation.Date {
|
||||
private func makeDarwinTM(calendar: Calendar) -> tm {
|
||||
let components = calendar.dateComponents(
|
||||
[.second, .minute, .hour, .day, .month, .year, .weekday, .timeZone],
|
||||
from: self
|
||||
)
|
||||
var t = tm()
|
||||
t.tm_sec = Int32(components.second ?? 0) // seconds after the minute [0-60]
|
||||
t.tm_min = Int32(components.minute ?? 0) // minutes after the hour [0-59]
|
||||
t.tm_hour = Int32(components.hour ?? 0) // hours since midnight [0-23]
|
||||
t.tm_mday = Int32(components.day ?? 1) // day of the month [1-31]
|
||||
t.tm_mon = Int32(components.month ?? 1) - 1 // months since January [0-11]
|
||||
t.tm_year = Int32(components.year ?? 100) - 1900 // years since 1900
|
||||
t.tm_wday = Int32(components.weekday ?? 1) - 1 // days since Sunday [0-6]
|
||||
t.tm_isdst = -1 // Disables `%z` output -- because we can’t use it.
|
||||
if let zone = components.timeZone {
|
||||
t.tm_gmtoff = zone.secondsFromGMT(for: self) // offset from UTC in seconds
|
||||
}
|
||||
return t
|
||||
}
|
||||
|
||||
func formatAsRFC822(calendar: Calendar) -> String {
|
||||
var output = [UInt8](repeating: 0, count: 80)
|
||||
let byteCount = output.withUnsafeMutableBufferPointer { outputBuffer -> Int in
|
||||
var t = makeDarwinTM(calendar: calendar)
|
||||
return outputBuffer.withMemoryRebound(to: Int8.self) { outputBuffer -> Int in
|
||||
let byteCount = strftime_l(
|
||||
outputBuffer.baseAddress!,
|
||||
outputBuffer.count,
|
||||
"%a, %d %b %Y %H:%M:%S %z",
|
||||
&t,
|
||||
posixLocale
|
||||
)
|
||||
guard byteCount != 0 else { return 0 }
|
||||
// Print the GMT offset:
|
||||
let offsetInMinutes = t.tm_gmtoff / 60
|
||||
let offsetValue = (offsetInMinutes / 60) * 100 + (offsetInMinutes % 60)
|
||||
let byteCount2 = snprintf(
|
||||
ptr: outputBuffer.baseAddress! + byteCount,
|
||||
outputBuffer.count - byteCount,
|
||||
"%+05d",
|
||||
CInt(offsetValue)
|
||||
)
|
||||
return byteCount + Int(byteCount2)
|
||||
}
|
||||
}
|
||||
guard byteCount != 0, byteCount <= output.count else { fatalError() }
|
||||
return output.withUnsafeBufferPointer { outputBuffer -> String in
|
||||
String(cString: outputBuffer.baseAddress!)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
nonisolated(unsafe) let posixLocale: locale_t = newlocale(0x3f, nil, nil)
|
||||
#else
|
||||
extension Foundation.Date {
|
||||
/// Formats the date as an RFC 822 date-time using `Foundation.DateFormatter`.
|
||||
///
|
||||
/// This mirrors the Darwin `strftime`-based implementation. `DateFormatter`
|
||||
/// is backed by ICU on non-Darwin platforms, and its `en_US_POSIX` locale is
|
||||
/// independent of the process's C locale, so the output is stable regardless
|
||||
/// of the environment's `LANG`/`LC_*` settings. The single `Z` produces the
|
||||
/// numeric `±HHMM` offset RFC 822 requires.
|
||||
func formatAsRFC822(calendar: Calendar) -> String {
|
||||
let formatter = DateFormatter()
|
||||
formatter.locale = Locale(identifier: "en_US_POSIX")
|
||||
formatter.calendar = calendar
|
||||
formatter.timeZone = calendar.timeZone
|
||||
formatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss Z"
|
||||
return formatter.string(from: self)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
// MARK: - Internal Parsing
|
||||
|
||||
extension InternetMessageDate {
|
||||
/// Parsing without bridging into Foundation is much more performant because:
|
||||
/// 1. we avoid bridging the bytes into a String and then NSString.
|
||||
/// 2. we can parse almost entirely without doing allocations.
|
||||
func parseWithoutFoundation() -> Foundation.Date? {
|
||||
#if canImport(Darwin)
|
||||
String(self).withCString { input -> Foundation.Date? in
|
||||
for format in strptimeDateFormats {
|
||||
if let date = scan(zeroTerminated: input, format: format) {
|
||||
// Don’t return for dates before 1972. Those happen when
|
||||
// a year without century is parsed as a 72 BC instead of 1972 BC.
|
||||
if -900_000_000 < date.timeIntervalSinceReferenceDate {
|
||||
return date
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
#else
|
||||
// The `strptime_l`-based fast path is Darwin-only (glibc doesn't provide
|
||||
// `strptime_l`). On other platforms the Foundation path handles parsing.
|
||||
return nil
|
||||
#endif
|
||||
}
|
||||
|
||||
func parseWithFoundation() -> Foundation.Date? {
|
||||
let string = String(self).strippingTrailingTimeZoneName()
|
||||
// Strict:
|
||||
for formatter in FoundationFormatters() {
|
||||
formatter.isLenient = false
|
||||
if let date = formatter.date(from: string) {
|
||||
return date
|
||||
}
|
||||
}
|
||||
// Lenient:
|
||||
for formatter in FoundationFormatters() {
|
||||
formatter.isLenient = true
|
||||
if let date = formatter.date(from: string) {
|
||||
return date
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
extension String {
|
||||
/// Drops a trailing parenthesised time-zone name, e.g. the `(GMT)` in
|
||||
/// `"Sat, 5 Sep 2020 02:25:49 +0000 (GMT)"`.
|
||||
///
|
||||
/// Such a name is redundant next to the numeric offset that precedes it, but
|
||||
/// `DateFormatter` has no pattern for it and fails the whole parse. The
|
||||
/// Darwin `strptime` path tolerates it via `zeroTerminatedRemainderIsTimeZoneName`;
|
||||
/// stripping it here gives the Foundation path the same tolerance on every platform.
|
||||
fileprivate func strippingTrailingTimeZoneName() -> String {
|
||||
let trimmed = self.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
guard trimmed.hasSuffix(")"), let open = trimmed.lastIndex(of: "(") else { return self }
|
||||
let name = trimmed[trimmed.index(after: open)..<trimmed.index(before: trimmed.endIndex)]
|
||||
// Only an all-uppercase abbreviation counts, matching the Darwin path.
|
||||
guard !name.isEmpty, name.allSatisfy({ $0.isUppercase }) else { return self }
|
||||
return String(trimmed[trimmed.startIndex..<open]).trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
}
|
||||
}
|
||||
|
||||
/// Create all our formatters / scanners.
|
||||
///
|
||||
/// - Note: See https://developer.apple.com/library/archive/qa/qa1480/_index.html
|
||||
#if canImport(Darwin)
|
||||
private func scan(zeroTerminated inputBuffer: UnsafePointer<Int8>, format: String) -> Foundation.Date? {
|
||||
return format.withCString { formatBuffer -> Foundation.Date? in
|
||||
var t = tm()
|
||||
guard let r = strptime_l(inputBuffer, formatBuffer, &t, nil) else { return nil }
|
||||
if !format.contains("%z") {
|
||||
// Without an offset in the input the date is a local wall-clock time, and
|
||||
// `strptime` leaves `tm_isdst` at 0 — asserting "standard time". `mktime`
|
||||
// then reads a summer date such as "19 Aug 2003 14:49" as CET rather than
|
||||
// CEST, an hour off. -1 tells `mktime` to work out DST from the date itself.
|
||||
t.tm_isdst = -1
|
||||
}
|
||||
let time = mktime(&t)
|
||||
let date = Date(timeIntervalSince1970: TimeInterval(time))
|
||||
if r.pointee == 0 {
|
||||
return date
|
||||
}
|
||||
// We still have more that we can parse.
|
||||
// If we have already parsed a “time zone offset from UTC”, skip
|
||||
// any remaining “time zone name”:
|
||||
guard format.contains("%z") && zeroTerminatedRemainderIsTimeZoneName(remainder: r) else {
|
||||
return nil
|
||||
}
|
||||
return date
|
||||
}
|
||||
}
|
||||
|
||||
private func zeroTerminatedRemainderIsTimeZoneName(remainder: UnsafeMutablePointer<CChar>) -> Bool {
|
||||
let s = Scanner(string: String(cString: remainder))
|
||||
_ = s.scanUpToString("(")
|
||||
guard
|
||||
s.scanString("(") != nil,
|
||||
s.scanCharacters(from: .uppercaseLetters) != nil,
|
||||
s.scanString(")") != nil
|
||||
else { return false }
|
||||
_ = s.scanCharacters(from: .whitespacesAndNewlines)
|
||||
guard s.isAtEnd else { return false }
|
||||
return true
|
||||
}
|
||||
#endif
|
||||
|
||||
/// Returns the same formatter repeatedly, each time configured with a different format.
|
||||
private struct FoundationFormatters: Sequence {
|
||||
func makeIterator() -> Iterator {
|
||||
return Iterator()
|
||||
}
|
||||
|
||||
struct Iterator: IteratorProtocol {
|
||||
var formats = foundationDateFormats.makeIterator()
|
||||
|
||||
mutating func next() -> DateFormatter? {
|
||||
guard let format = formats.next() else { return nil }
|
||||
let formatter = makeFormatter()
|
||||
formatter.dateFormat = format
|
||||
return formatter
|
||||
}
|
||||
|
||||
/// Creates a `DateFormatter` and caches it in the current thread’s thread dictionary.
|
||||
func makeFormatter() -> DateFormatter {
|
||||
let key = "IMAP.protocol.dateFormatter" as NSString
|
||||
if let f = Thread.current.threadDictionary[key] as? DateFormatter {
|
||||
return f
|
||||
}
|
||||
// See also:
|
||||
// https://developer.apple.com/library/archive/qa/qa1480/_index.html
|
||||
let f = DateFormatter()
|
||||
f.locale = Locale(identifier: "en_US_POSIX")
|
||||
f.timeZone = TimeZone(secondsFromGMT: 0)
|
||||
Thread.current.threadDictionary[key] = f
|
||||
return f
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// From RFC 2822, section 3.3
|
||||
// https://tools.ietf.org/html/rfc2822#section-3.3
|
||||
//
|
||||
// 3.3. Date and Time Specification
|
||||
//
|
||||
// Date and time occur in several header fields. This section specifies
|
||||
// the syntax for a full date and time specification. Though folding
|
||||
// white space is permitted throughout the date-time specification, it
|
||||
// is RECOMMENDED that a single space be used in each place that FWS
|
||||
// appears (whether it is required or optional); some older
|
||||
// implementations may not interpret other occurrences of folding white
|
||||
// space correctly.
|
||||
//
|
||||
// date-time = [ day-of-week "," ] date FWS time [CFWS]
|
||||
//
|
||||
// day-of-week = ([FWS] day-name) / obs-day-of-week
|
||||
//
|
||||
// day-name = "Mon" / "Tue" / "Wed" / "Thu" /
|
||||
// "Fri" / "Sat" / "Sun"
|
||||
//
|
||||
// date = day month year
|
||||
//
|
||||
// year = 4*DIGIT / obs-year
|
||||
//
|
||||
// month = (FWS month-name FWS) / obs-month
|
||||
//
|
||||
// month-name = "Jan" / "Feb" / "Mar" / "Apr" /
|
||||
// "May" / "Jun" / "Jul" / "Aug" /
|
||||
// "Sep" / "Oct" / "Nov" / "Dec"
|
||||
//
|
||||
// day = ([FWS] 1*2DIGIT) / obs-day
|
||||
//
|
||||
// time = time-of-day FWS zone
|
||||
//
|
||||
// time-of-day = hour ":" minute [ ":" second ]
|
||||
//
|
||||
// hour = 2DIGIT / obs-hour
|
||||
//
|
||||
// minute = 2DIGIT / obs-minute
|
||||
//
|
||||
// second = 2DIGIT / obs-second
|
||||
//
|
||||
// zone = (( "+" / "-" ) 4DIGIT) / obs-zone
|
||||
|
||||
private let foundationDateFormats: [String] = [
|
||||
// Ordered by empirical frequency in real-world mailboxes; the uncommon formats
|
||||
// are here because they show up in practice despite being illegal per RFC 5322.
|
||||
|
||||
// date-time with the optional day-of-week and seconds
|
||||
// Note that in all the following format strings the year is specified with a single
|
||||
// y instead of 4. That's because yyyy will interpret "13" as 0013 instead of 2013.
|
||||
// While 2 digit dates are illegal, we're trying to be lenient here.
|
||||
"EEE',' d MMM y HH':'mm':'ss ZZZ",
|
||||
|
||||
// date-time with the optional day-of-week and seconds, and obs-zone
|
||||
// This doesn't really work; obs-zone is the "specific non-location format" but only
|
||||
// for UTC and the United States. All other zones are covered by the military format,
|
||||
// but NSDateFormatter doesn't appear to support that.
|
||||
"EEE',' d MMM y HH':'mm':'ss zzz",
|
||||
|
||||
// this one's just plain illegal, but appeared in ~5% of a real-world sample
|
||||
"EEE MMM d HH':'mm':'ss zzz y",
|
||||
|
||||
// date-time without the optional day-of-week and with seconds
|
||||
"d MMM y HH':'mm':'ss ZZZ",
|
||||
|
||||
// date-time without the optional day-of-week, and with seconds and obs-zone
|
||||
"d MMM y HH':'mm':'ss zzz",
|
||||
|
||||
// date-time with the optional day-of-week and without seconds
|
||||
"EEE',' d MMM y HH':'mm ZZZ",
|
||||
|
||||
// date-time with the optional day-of-week and obs-zone, and without seconds
|
||||
"EEE',' d MMM y HH':'mm zzz",
|
||||
|
||||
// date-time without the optional day-of-week or seconds
|
||||
"d MMM y HH':'mm ZZZ",
|
||||
|
||||
// date-time without the optional day-of-week or seconds, and with obs-zone
|
||||
"d MMM y HH':'mm zzz",
|
||||
|
||||
// Illegal formats:
|
||||
|
||||
"'\"'dd'-'MMM'-'y HH':'mm':'ss ZZZ'\"'",
|
||||
"EEE MMM d HH':'mm':'ss y",
|
||||
"y'-'MM'-'d HH':'mm':'ss ZZZ",
|
||||
"EEE',' d MMM y HH':'mm':'ss",
|
||||
"d MMM y HH':'mm':'ss",
|
||||
"MM'/'d HH':'mm a",
|
||||
"MM'/'d'/'y HH':'mm a",
|
||||
"MMM d',' y HH':'mm':'ss a vvvv",
|
||||
"EEE',' MMM d y HH':'mm':'ss ZZZ",
|
||||
"EEE',' MMM d',' y HH':'mm zzz",
|
||||
"EEE MMM d',' y HH':'mm':'ss vvvv",
|
||||
"MMMM d',' y HH':'mm':'ss zzz",
|
||||
// Uses `h` (1-12) rather than `HH` (0-23) because of the trailing AM/PM
|
||||
// marker: ICU ignores `a` when it's paired with a 24-hour field, which made
|
||||
// "3:22 PM" parse as 03:22. Darwin's `strptime` applies the marker either
|
||||
// way, so this only ever misparsed on non-Darwin platforms.
|
||||
"EEE',' MMM d',' y 'at' h':'mm a",
|
||||
]
|
||||
|
||||
#if canImport(Darwin)
|
||||
private let strptimeDateFormats: [String] = [
|
||||
// These are the same ones from above, with those using "zzz" removed.
|
||||
// "zzz" corresponds to time zone specifiers like "EST", but
|
||||
// these abbreviations are not unique, and as such strptime_l()
|
||||
// refuses to parse these. "EST" might be "Eastern Standard Time",
|
||||
// "Australian Eastern Standard Time", or "European Summer Time".
|
||||
|
||||
" %a, %d %b %Y %H:%M:%S %z ",
|
||||
" %d %b %Y %H:%M:%S %z ",
|
||||
" %a, %d %b %Y %H:%M %z ",
|
||||
" %d %b %Y %H:%M %z ",
|
||||
" \"%d-%b-%Y %H:%M:%S %z\" ",
|
||||
" %a %b %d %H:%M:%S %Y ",
|
||||
" %Y-%m-%d %H:%M:%S %z ",
|
||||
" %a, %d %b %Y %H:%M:%S ",
|
||||
" %d %b %Y %H:%M:%S ",
|
||||
" %m/%d %H:%M %p ",
|
||||
" %m/%d/%Y %H:%M %p ",
|
||||
" %a, %b %d %Y %H:%M:%S %z ",
|
||||
" %a, %b %d, %Y at %H:%M %p ",
|
||||
]
|
||||
#endif
|
||||
@@ -0,0 +1,33 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import ArgumentParser
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
|
||||
/// Options that control message generation for testing and seeding.
|
||||
struct MessageCreationOptions: ParsableArguments {
|
||||
init() {}
|
||||
|
||||
/// The number of messages to create or use.
|
||||
@Option(help: "Number of messages to create or use.")
|
||||
var messageCount: Int = 43
|
||||
|
||||
/// The seed for deterministic message generation.
|
||||
@Option(help: "A seed for message generation.")
|
||||
var messageSeed: SeededRandomNumberGenerator.Seed = .default
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import ArgumentParser
|
||||
import NIOIMAP
|
||||
|
||||
enum MessageFlag: String, Hashable, CaseIterable, ExpressibleByArgument {
|
||||
/// `\Answered`
|
||||
case answered
|
||||
/// `\Flagged`
|
||||
case flagged
|
||||
/// `\Deleted`
|
||||
case deleted
|
||||
/// `\Seen`
|
||||
case seen
|
||||
/// `\Draft`
|
||||
case draft
|
||||
|
||||
case red
|
||||
case orange
|
||||
case yellow
|
||||
case green
|
||||
case blue
|
||||
case purple
|
||||
case gray
|
||||
}
|
||||
|
||||
extension MessageFlag {
|
||||
var flagsToSearch: FlagsToSearch {
|
||||
switch self {
|
||||
case .answered, .flagged, .deleted, .seen, .draft:
|
||||
return FlagsToSearch(
|
||||
set: flagsToSet,
|
||||
notSet: []
|
||||
)
|
||||
case .red, .orange, .yellow, .green, .blue, .purple, .gray:
|
||||
let allColorBits: Set<NIOIMAP.Flag> = [.mailFlagBit0, .mailFlagBit1, .mailFlagBit2]
|
||||
return FlagsToSearch(
|
||||
set: flagsToSet,
|
||||
notSet: allColorBits.subtracting(flagsToSet)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
struct FlagsToSearch: Sendable, Hashable {
|
||||
var set: Set<NIOIMAP.Flag>
|
||||
var notSet: Set<NIOIMAP.Flag>
|
||||
}
|
||||
}
|
||||
|
||||
extension MessageFlag {
|
||||
var flagsToSet: Set<NIOIMAP.Flag> {
|
||||
switch self {
|
||||
case .answered: [.answered]
|
||||
case .flagged: [.flagged]
|
||||
case .deleted: [.deleted]
|
||||
case .seen: [.seen]
|
||||
case .draft: [.draft]
|
||||
case .red: [.flagged]
|
||||
case .orange: [.flagged, .mailFlagBit0]
|
||||
case .yellow: [.flagged, .mailFlagBit1]
|
||||
case .green: [.flagged, .mailFlagBit0, .mailFlagBit1, .mailFlagBit2]
|
||||
case .blue: [.flagged, .mailFlagBit2]
|
||||
case .purple: [.flagged, .mailFlagBit0, .mailFlagBit2]
|
||||
case .gray: [.flagged, .mailFlagBit1, .mailFlagBit2]
|
||||
}
|
||||
}
|
||||
|
||||
var flagsToUnset: Set<NIOIMAP.Flag> {
|
||||
switch self {
|
||||
case .answered: [.answered]
|
||||
case .flagged: [.flagged]
|
||||
case .deleted: [.deleted]
|
||||
case .seen: [.seen]
|
||||
case .draft: [.draft]
|
||||
case .red,
|
||||
.orange,
|
||||
.yellow,
|
||||
.green,
|
||||
.blue,
|
||||
.purple,
|
||||
.gray:
|
||||
[.flagged, .mailFlagBit0, .mailFlagBit1, .mailFlagBit2]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension NIOIMAP.Flag {
|
||||
static var mailFlagBit0: NIOIMAP.Flag { NIOIMAP.Flag("$MailFlagBit0") }
|
||||
static var mailFlagBit1: NIOIMAP.Flag { NIOIMAP.Flag("$MailFlagBit1") }
|
||||
static var mailFlagBit2: NIOIMAP.Flag { NIOIMAP.Flag("$MailFlagBit2") }
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import Synchronization
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
import NIOIMAP
|
||||
|
||||
/// Parses the small set of message headers that `IMAPToolLib` needs when
|
||||
/// appending messages to a mailbox.
|
||||
///
|
||||
/// `IMAPToolLib` ships with a minimal, dependency-free implementation
|
||||
/// (``MiniMIMEHeaderParser``). An embedding tool can install a richer parser
|
||||
/// (for example, one backed by a full MIME parser) via
|
||||
/// ``MessageHeaderParser/current``.
|
||||
public protocol MessageHeaderParsing: Sendable {
|
||||
/// Parses just the `Date` header from the given message data.
|
||||
func dateHeader(_ data: Data) -> InternetMessageDate?
|
||||
|
||||
/// Parses the headers needed to append the given message.
|
||||
func headersOfInterest(_ data: Data) -> EmailMessage.HeadersOfInterest?
|
||||
}
|
||||
|
||||
/// The minimal header parser used by default. It does not handle header folding
|
||||
/// (continuation lines) and only understands `Date` and `Message-ID`.
|
||||
struct MiniMIMEHeaderParser: MessageHeaderParsing {
|
||||
init() {}
|
||||
|
||||
func dateHeader(_ data: Data) -> InternetMessageDate? {
|
||||
MIMEMessage.data(data).dateHeader()
|
||||
}
|
||||
|
||||
func headersOfInterest(_ data: Data) -> EmailMessage.HeadersOfInterest? {
|
||||
MIMEMessage.data(data).headersOfInterest()
|
||||
}
|
||||
}
|
||||
|
||||
/// The message header parser used throughout `IMAPToolLib`.
|
||||
///
|
||||
/// Defaults to ``MiniMIMEHeaderParser``. Embedders can replace it before running
|
||||
/// any command.
|
||||
public enum MessageHeaderParser {
|
||||
private static let _current = Mutex<any MessageHeaderParsing>(MiniMIMEHeaderParser())
|
||||
|
||||
public static var current: any MessageHeaderParsing {
|
||||
get { _current.withLock { $0 } }
|
||||
set { _current.withLock { $0 = newValue } }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import NIOIMAP
|
||||
|
||||
/// A summary of a fetched message, including its envelope and flags.
|
||||
struct MessageInfo: Sendable, Hashable, Encodable {
|
||||
/// The UID of the message.
|
||||
var uid: UID
|
||||
/// The RFC 2822 date string from the envelope.
|
||||
var date: String?
|
||||
/// The date as seconds since the Unix epoch.
|
||||
var dateSeconds: Double?
|
||||
/// The subject line of the message.
|
||||
var subject: String?
|
||||
/// The sender of the message.
|
||||
var from: String?
|
||||
/// The primary recipients of the message.
|
||||
var to: String?
|
||||
/// The carbon-copy recipients of the message.
|
||||
var cc: String?
|
||||
/// The `Message-ID` header value.
|
||||
var messageID: String?
|
||||
/// The `In-Reply-To` header value.
|
||||
var inReplyTo: String?
|
||||
/// The flags set on the message.
|
||||
var flags: [String]
|
||||
|
||||
func encode(to encoder: Encoder) throws {
|
||||
var c = encoder.container(keyedBy: CodingKeys.self)
|
||||
try c.encode(UInt32(uid), forKey: .uid)
|
||||
try c.encodeIfPresent(date, forKey: .date)
|
||||
try c.encodeIfPresent(dateSeconds, forKey: .dateSeconds)
|
||||
try c.encodeIfPresent(subject, forKey: .subject)
|
||||
try c.encodeIfPresent(from, forKey: .from)
|
||||
try c.encodeIfPresent(to, forKey: .to)
|
||||
try c.encodeIfPresent(cc, forKey: .cc)
|
||||
try c.encodeIfPresent(messageID, forKey: .messageID)
|
||||
try c.encodeIfPresent(inReplyTo, forKey: .inReplyTo)
|
||||
try c.encode(flags, forKey: .flags)
|
||||
}
|
||||
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case uid
|
||||
case date
|
||||
case dateSeconds
|
||||
case subject
|
||||
case from
|
||||
case to
|
||||
case cc
|
||||
case messageID
|
||||
case inReplyTo
|
||||
case flags
|
||||
}
|
||||
}
|
||||
|
||||
extension MessageInfo {
|
||||
init?(
|
||||
uid: UID,
|
||||
attributes: [MessageAttribute]
|
||||
) {
|
||||
var uid: UID = uid
|
||||
var envelope: Envelope?
|
||||
var flags: [Flag]?
|
||||
|
||||
for attribute in attributes {
|
||||
switch attribute {
|
||||
case .uid(let u):
|
||||
uid = u
|
||||
case .envelope(let e):
|
||||
envelope = e
|
||||
case .flags(let f):
|
||||
flags = f
|
||||
default:
|
||||
break
|
||||
}
|
||||
}
|
||||
guard
|
||||
let envelope,
|
||||
let flags
|
||||
else { return nil }
|
||||
self.init(uid: uid, envelope: envelope, flags: flags)
|
||||
}
|
||||
|
||||
init(uid: UID, envelope: Envelope, flags: [Flag]) {
|
||||
self.uid = uid
|
||||
let date = envelope.date.map { String($0) }
|
||||
self.date = date
|
||||
if let date, let seconds = InternetMessageDate(date).parse() {
|
||||
self.dateSeconds = seconds.timeIntervalSince1970
|
||||
}
|
||||
self.subject = envelope.subject.map { String(buffer: $0) }
|
||||
self.from = envelope.from.isEmpty ? nil : String(envelope.from)
|
||||
self.to = envelope.to.isEmpty ? nil : String(envelope.to)
|
||||
self.cc = envelope.cc.isEmpty ? nil : String(envelope.cc)
|
||||
self.messageID = envelope.messageID.map { String($0) }
|
||||
self.inReplyTo = envelope.inReplyTo.map { String($0) }
|
||||
self.flags = flags.map { String($0) }
|
||||
}
|
||||
}
|
||||
|
||||
extension String {
|
||||
fileprivate init(_ list: [EmailAddressListElement]) {
|
||||
self =
|
||||
list
|
||||
.map {
|
||||
String($0)
|
||||
}
|
||||
.joined(separator: ", ")
|
||||
}
|
||||
|
||||
fileprivate init(_ listElement: EmailAddressListElement) {
|
||||
switch listElement {
|
||||
case .singleAddress(let address):
|
||||
switch (address.personName, address.mailbox, address.host) {
|
||||
case (let name?, let mailbox?, let host?):
|
||||
self = "\"\(String(buffer: name))\" <\(String(buffer: mailbox))@\(String(buffer: host))>"
|
||||
case (_, let mailbox?, let host?):
|
||||
self = "\(String(buffer: mailbox))@\(String(buffer: host))"
|
||||
default:
|
||||
self = "<>"
|
||||
}
|
||||
case .group(let group):
|
||||
let groupName = String(buffer: group.groupName)
|
||||
self = "\"\(groupName)\": {\(String(group.children))}"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
import NIOCore
|
||||
import NIOIMAP
|
||||
|
||||
// Does not handle header folding (continuation lines).
|
||||
enum MIMEMessage {
|
||||
case data(Data)
|
||||
case byteBuffer(ByteBuffer)
|
||||
|
||||
func dateHeader() -> InternetMessageDate? {
|
||||
withContiguousBytes { buffer in
|
||||
var result: InternetMessageDate?
|
||||
enumerateHeaderLines(in: buffer) { name, value in
|
||||
if caseInsensitiveEqual(name, "date") {
|
||||
result = InternetMessageDate(trimmedString(value))
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
func messageIDHeader() -> MessageID? {
|
||||
withContiguousBytes { buffer in
|
||||
var result: MessageID?
|
||||
enumerateHeaderLines(in: buffer) { name, value in
|
||||
if caseInsensitiveEqual(name, "message-id") {
|
||||
result = MessageID(trimmedString(value))
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
func headersOfInterest() -> EmailMessage.HeadersOfInterest? {
|
||||
withContiguousBytes { buffer in
|
||||
var date: InternetMessageDate?
|
||||
var messageID: MessageID?
|
||||
enumerateHeaderLines(in: buffer) { name, value in
|
||||
if caseInsensitiveEqual(name, "date") {
|
||||
date = InternetMessageDate(trimmedString(value))
|
||||
} else if caseInsensitiveEqual(name, "message-id") {
|
||||
messageID = MessageID(trimmedString(value))
|
||||
}
|
||||
return date == nil || messageID == nil
|
||||
}
|
||||
guard let date, let messageID else { return nil }
|
||||
return EmailMessage.HeadersOfInterest(messageID: messageID, date: date)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Internal
|
||||
|
||||
extension MIMEMessage {
|
||||
func withContiguousBytes<R>(_ body: (Span<UInt8>) -> R) -> R {
|
||||
switch self {
|
||||
case .data(let data):
|
||||
return body(data.span)
|
||||
case .byteBuffer(let buffer):
|
||||
return buffer.withUnsafeReadableBytes { body($0.bindMemory(to: UInt8.self).span) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Iterates header lines, calling `body` with the header name and value
|
||||
/// portions of each line. Stops at the first empty line (end of headers)
|
||||
/// or when `body` returns `false`.
|
||||
func enumerateHeaderLines(
|
||||
in buffer: Span<UInt8>,
|
||||
body: (_ name: Span<UInt8>, _ value: Span<UInt8>) -> Bool
|
||||
) {
|
||||
var position = 0
|
||||
let count = buffer.count
|
||||
|
||||
while position < count {
|
||||
let lineStart = position
|
||||
while position < count && buffer[position] != UInt8(ascii: "\n") {
|
||||
position += 1
|
||||
}
|
||||
var lineEnd = position
|
||||
if lineEnd > lineStart && buffer[lineEnd - 1] == UInt8(ascii: "\r") {
|
||||
lineEnd -= 1
|
||||
}
|
||||
if position < count {
|
||||
position += 1
|
||||
}
|
||||
|
||||
if lineEnd == lineStart { return }
|
||||
|
||||
// Find the colon separating name from value.
|
||||
var colonIndex = lineStart
|
||||
while colonIndex < lineEnd && buffer[colonIndex] != UInt8(ascii: ":") {
|
||||
colonIndex += 1
|
||||
}
|
||||
guard colonIndex < lineEnd else { continue }
|
||||
|
||||
let name = buffer.extracting(lineStart..<colonIndex)
|
||||
let value = buffer.extracting((colonIndex + 1)..<lineEnd)
|
||||
if !body(name, value) { return }
|
||||
}
|
||||
}
|
||||
|
||||
private func caseInsensitiveEqual(
|
||||
_ buffer: Span<UInt8>,
|
||||
_ expected: StaticString
|
||||
) -> Bool {
|
||||
guard buffer.count == expected.utf8CodeUnitCount else { return false }
|
||||
return expected.withUTF8Buffer { expectedBytes in
|
||||
for i in 0..<expectedBytes.count {
|
||||
let b = buffer[i]
|
||||
let lower = (b >= 0x41 && b <= 0x5A) ? b | 0x20 : b
|
||||
if lower != expectedBytes[i] { return false }
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
private func trimmedString(_ buffer: Span<UInt8>) -> String {
|
||||
var start = 0
|
||||
var end = buffer.count
|
||||
while start < end && (buffer[start] == UInt8(ascii: " ") || buffer[start] == UInt8(ascii: "\t")) {
|
||||
start += 1
|
||||
}
|
||||
while end > start && (buffer[end - 1] == UInt8(ascii: " ") || buffer[end - 1] == UInt8(ascii: "\t")) {
|
||||
end -= 1
|
||||
}
|
||||
return buffer.extracting(start..<end).utf8String
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
import NIOIMAP
|
||||
|
||||
struct UIDsAndMessageIDs: Equatable, Sendable {
|
||||
var uids: UIDSet
|
||||
var messageIDs: Set<MessageID>
|
||||
|
||||
var isEmpty: Bool {
|
||||
uids.isEmpty && messageIDs.isEmpty
|
||||
}
|
||||
}
|
||||
|
||||
extension UIDsAndMessageIDs {
|
||||
init(
|
||||
filePath: String?,
|
||||
uids: [UID],
|
||||
messageIDs: [MessageID]
|
||||
) throws {
|
||||
if let filePath {
|
||||
self = try Self.parse(filePath: filePath)
|
||||
} else {
|
||||
self.init(uids: [], messageIDs: [])
|
||||
}
|
||||
self.uids.formUnion(UIDSet(uids))
|
||||
self.messageIDs.formUnion(messageIDs)
|
||||
}
|
||||
}
|
||||
|
||||
extension UIDsAndMessageIDs {
|
||||
static func parse(
|
||||
filePath: String
|
||||
) throws -> UIDsAndMessageIDs {
|
||||
let json = try Data(contentsOf: URL(filePath: filePath, directoryHint: .notDirectory))
|
||||
return try Self.parse(input: json)
|
||||
}
|
||||
|
||||
static func parse(
|
||||
input: Data
|
||||
) throws -> UIDsAndMessageIDs {
|
||||
var uids = UIDSet()
|
||||
var ids = Set<MessageID>()
|
||||
for m in try parseMessages(input: input) {
|
||||
switch m {
|
||||
case .uid(let uid): uids.insert(uid)
|
||||
case .messageID(let id): ids.insert(id)
|
||||
}
|
||||
}
|
||||
return UIDsAndMessageIDs(
|
||||
uids: uids,
|
||||
messageIDs: ids
|
||||
)
|
||||
}
|
||||
|
||||
enum MessageInfo {
|
||||
case uid(UID)
|
||||
case messageID(MessageID)
|
||||
}
|
||||
|
||||
static func parseMessages(input: Data) throws -> [MessageInfo] {
|
||||
struct Messages: Decodable {
|
||||
var messages: [Message]
|
||||
|
||||
struct Message: Decodable {
|
||||
var uid: UInt32?
|
||||
var id: String?
|
||||
}
|
||||
}
|
||||
|
||||
let decoder = JSONDecoder()
|
||||
decoder.allowsJSON5 = true
|
||||
let m = try decoder.decode(Messages.self, from: input)
|
||||
return m.messages.compactMap { raw -> MessageInfo? in
|
||||
if let u = raw.uid, let uid = UID(exactly: u) {
|
||||
return .uid(uid)
|
||||
} else if let id = raw.id {
|
||||
guard
|
||||
id.first == "<",
|
||||
id.last == ">"
|
||||
else { return nil }
|
||||
return .messageID(MessageID(id))
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension ConnectionProtocol {
|
||||
func findMessageIDs(
|
||||
selectInfo: SelectInfo,
|
||||
capabilities: [Capability],
|
||||
ids: UIDsAndMessageIDs
|
||||
) async throws -> UIDSet {
|
||||
guard
|
||||
let key = SearchKey.messageID(ids.messageIDs)
|
||||
else { return ids.uids }
|
||||
|
||||
let new = try await search(
|
||||
capabilities: capabilities,
|
||||
key: key
|
||||
)
|
||||
return ids.uids.union(new)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import IMAPCommands
|
||||
import NIO
|
||||
import NIOIMAP
|
||||
|
||||
/// A protocol for sending commands and receiving responses, enabling testability.
|
||||
///
|
||||
/// In production, this is always an ``IMAPConnection``. In tests, a mock can send
|
||||
/// simple commands without requiring `AUTHENTICATE` or `APPEND` support.
|
||||
///
|
||||
/// ## Where the operations live
|
||||
///
|
||||
/// The operations in `IMAPToolLib/Operations` are methods on the connection, so they read
|
||||
/// as `connection.listMailboxes(capabilities:)`. Most are declared in an
|
||||
/// `extension ConnectionProtocol`, and that is what keeps them testable: they reach the
|
||||
/// server only through `send(_:_:)`, the single protocol requirement, so a mock that
|
||||
/// implements `send` gets all of them for free.
|
||||
///
|
||||
/// A few — `append`, `authenticate`, `runIdle` — are declared in an `extension IMAPConnection`
|
||||
/// instead, because they use methods (`append`, `sendAuthenticate`, `sendIdle`) that are not
|
||||
/// part of this protocol. Those methods deal with continuation-driven flows (literals, SASL
|
||||
/// challenges, IDLE) that don't fit the simple "send a `Command`, consume the
|
||||
/// `IMAPConnection.ResponseStream`" shape, so adding them here would complicate the mock
|
||||
/// surface used by tests.
|
||||
///
|
||||
/// ## Closure isolation
|
||||
///
|
||||
/// The requirement mirrors `IMAPConnection.send(_:_:)`: the handler is
|
||||
/// `nonisolated(nonsending)`, so it needs to be neither `@Sendable` nor `@escaping` and runs in
|
||||
/// the caller's isolation domain. Unlike an `isolated (any Actor)?` parameter — which a protocol
|
||||
/// requirement cannot give a default argument — this needs nothing at the call site.
|
||||
protocol ConnectionProtocol: Sendable {
|
||||
func send<Result>(
|
||||
_ command: Command,
|
||||
_ handler: nonisolated(nonsending) (IMAPConnection.Tag, IMAPConnection.ResponseStream) async throws -> Result
|
||||
) async throws -> Result
|
||||
}
|
||||
|
||||
extension IMAPConnection: ConnectionProtocol {}
|
||||
@@ -0,0 +1,39 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
import NIO
|
||||
|
||||
extension ByteBuffer {
|
||||
init(_ other: Data) {
|
||||
self.init()
|
||||
// `Data` is a `Collection` of `UInt8`, so this needs no pointer access.
|
||||
writeBytes(other)
|
||||
}
|
||||
|
||||
init(_ other: String) {
|
||||
self.init(other.data(using: .utf8)!)
|
||||
}
|
||||
}
|
||||
|
||||
extension Data {
|
||||
init(_ other: ByteBuffer) {
|
||||
// `readableBytesView` is a `Collection` of the buffer's readable bytes.
|
||||
self.init(other.readableBytesView)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import SystemPackage
|
||||
#if canImport(Glibc)
|
||||
import Glibc
|
||||
#elseif canImport(Darwin)
|
||||
import Darwin
|
||||
#endif
|
||||
|
||||
// MARK: - Directory walk helpers
|
||||
//
|
||||
// Both `DownloadDirectory` (`*.message` parsing) and `Append_Files`
|
||||
// (regular-file enumeration) need to walk a directory and inspect each
|
||||
// `dirent` entry. The pointer gymnastics around `d_name` (POSIX gives us a
|
||||
// fixed-size C array; we want a Swift buffer) and the `opendir`/`readdir`
|
||||
// iteration live here so the call sites can stay focused on their own logic.
|
||||
|
||||
/// Calls `closure` once for each entry in `directory`.
|
||||
///
|
||||
/// Iterates the directory with `opendir(3)` / `readdir(3)` / `closedir(3)`,
|
||||
/// which are available on both Darwin and Glibc. Entries are returned in
|
||||
/// directory order (unsorted).
|
||||
///
|
||||
/// Throws `UnableToScanDirectory` if the directory can't be opened or if
|
||||
/// reading an entry fails.
|
||||
func scan(
|
||||
directory: FilePath,
|
||||
closure: (UnsafePointer<dirent>) -> Void
|
||||
) throws {
|
||||
guard let dir = directory.withPlatformString({ opendir($0) }) else {
|
||||
throw UnableToScanDirectory()
|
||||
}
|
||||
defer { closedir(dir) }
|
||||
while true {
|
||||
// `readdir` returns `nil` both at end-of-directory and on error. It
|
||||
// leaves `errno` untouched at end-of-directory, so reset it first and
|
||||
// check afterwards to tell the two apart.
|
||||
errno = 0
|
||||
guard let entry = readdir(dir) else {
|
||||
guard errno == 0 else { throw UnableToScanDirectory() }
|
||||
break
|
||||
}
|
||||
closure(UnsafePointer(entry))
|
||||
}
|
||||
}
|
||||
|
||||
struct UnableToScanDirectory: Swift.Error {}
|
||||
|
||||
/// If `entry` describes a regular file, invokes `body` with the file name as a
|
||||
/// UTF-8 span (no NUL terminator) and returns its result. Returns `nil` if the
|
||||
/// entry is not a regular file or if `body` itself returns `nil`.
|
||||
///
|
||||
/// The span is only valid for the duration of `body` — copy out anything you
|
||||
/// need to keep.
|
||||
///
|
||||
/// - Note: On filesystems that don't report a `d_type` (returning `DT_UNKNOWN`),
|
||||
/// entries are skipped. That doesn't occur on the local filesystems this tool
|
||||
/// targets, but a fully general implementation would `stat` such entries.
|
||||
func withRegularFileName<R>(
|
||||
dirent entry: UnsafePointer<dirent>,
|
||||
_ body: (Span<Unicode.UTF8.CodeUnit>) -> R?
|
||||
) -> R? {
|
||||
guard entry.pointee.d_type == DT_REG else { return nil }
|
||||
// `d_name` is a fixed-size C array. Darwin also carries the exact length in
|
||||
// `d_namlen`, but Glibc's `dirent` has no such field, so on other platforms
|
||||
// we find the NUL terminator within the array ourselves.
|
||||
let capacity = MemoryLayout.size(ofValue: entry.pointee.d_name)
|
||||
return withUnsafePointer(to: entry.pointee.d_name) { pointer in
|
||||
pointer.withMemoryRebound(
|
||||
to: Unicode.UTF8.CodeUnit.self,
|
||||
capacity: capacity
|
||||
) { rebound in
|
||||
#if canImport(Darwin)
|
||||
let count = Int(entry.pointee.d_namlen)
|
||||
#else
|
||||
var count = 0
|
||||
while count < capacity, rebound[count] != 0 {
|
||||
count += 1
|
||||
}
|
||||
#endif
|
||||
return body(UnsafeBufferPointer(start: rebound, count: count).span)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import ArgumentParser
|
||||
// `Scanner`/`CharacterSet` are not part of `FoundationEssentials`.
|
||||
import Foundation
|
||||
|
||||
/// Generates deterministic pseudo-random numbers from a fixed seed.
|
||||
struct SeededRandomNumberGenerator: RandomNumberGenerator {
|
||||
fileprivate struct State {
|
||||
var state: UInt64
|
||||
var inc: UInt64
|
||||
}
|
||||
|
||||
fileprivate var state: State
|
||||
|
||||
/// Creates a generator with the given seed.
|
||||
init(_ seed: Seed) {
|
||||
self.state = State(state: seed.a, inc: seed.b)
|
||||
}
|
||||
|
||||
/// Creates a generator with two raw state values.
|
||||
init(_ a: UInt64, _ b: UInt64) {
|
||||
self.state = State(state: a, inc: b)
|
||||
}
|
||||
|
||||
/// Returns the next random `UInt64` value.
|
||||
mutating func next() -> UInt64 {
|
||||
UInt64(self.state.next()) << 32 | UInt64(self.state.next())
|
||||
}
|
||||
|
||||
/// Returns the next random `UInt32` value.
|
||||
mutating func next() -> UInt32 {
|
||||
self.state.next()
|
||||
}
|
||||
}
|
||||
|
||||
extension SeededRandomNumberGenerator.State {
|
||||
/// Advances the state and returns the next random `UInt32` value.
|
||||
mutating func next() -> UInt32 {
|
||||
let oldstate = self.state
|
||||
self.state = oldstate &* 6_364_136_223_846_793_005 &+ (inc | 1)
|
||||
let xorshifted: UInt64 = ((oldstate >> 18) ^ oldstate) >> 27
|
||||
let rot: UInt64 = oldstate >> 59
|
||||
let irot = UInt64(bitPattern: -Int64(bitPattern: rot))
|
||||
let result: UInt64 = (xorshifted >> rot) | (xorshifted << (irot & 31))
|
||||
return UInt32(result & UInt64(UInt32.max))
|
||||
}
|
||||
}
|
||||
|
||||
extension SeededRandomNumberGenerator {
|
||||
/// A pair of values that initializes the random number generator state.
|
||||
struct Seed: Equatable {
|
||||
/// The first state component.
|
||||
var a: UInt64
|
||||
/// The second state component.
|
||||
var b: UInt64
|
||||
|
||||
/// Creates a seed with the given state components.
|
||||
init(a: UInt64, b: UInt64) {
|
||||
self.a = a
|
||||
self.b = b
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension SeededRandomNumberGenerator.Seed: ExpressibleByArgument {
|
||||
/// The default seed value.
|
||||
static var `default`: SeededRandomNumberGenerator.Seed {
|
||||
SeededRandomNumberGenerator.Seed(a: 0x3501_404A_0218_5150, b: 0xF23C_78DA_2C09_7E04)
|
||||
}
|
||||
|
||||
/// Creates a seed by parsing a hex-prefixed string argument.
|
||||
init?(argument: String) {
|
||||
guard
|
||||
let a = SeededRandomNumberGenerator.Seed(hexPrefixed: argument)
|
||||
else { return nil }
|
||||
self = a
|
||||
}
|
||||
|
||||
init?(hexPrefixed string: String) {
|
||||
let scanner = Scanner(string: string)
|
||||
guard scanner.scanString("hex:") != nil else { return nil }
|
||||
scanner.charactersToBeSkipped = CharacterSet(charactersIn: " _")
|
||||
var values: [UInt8] = []
|
||||
while !scanner.isAtEnd {
|
||||
guard
|
||||
let a = scanner.scanCharacter(),
|
||||
let b = scanner.scanCharacter(),
|
||||
let c = UInt8(String([a, b]), radix: 16)
|
||||
else { return nil }
|
||||
values.append(c)
|
||||
}
|
||||
guard values.count == 16 else { return nil }
|
||||
|
||||
var remaining = values[...]
|
||||
func pop() -> UInt64 {
|
||||
var r = 0 as UInt64
|
||||
for _ in 0..<8 {
|
||||
r *= 256
|
||||
r += UInt64(remaining.popFirst()!)
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
self.init(a: pop(), b: pop())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension Span<UInt8> {
|
||||
/// Decodes the bytes as UTF-8, repairing any ill-formed sequences.
|
||||
///
|
||||
/// `Span` is not a `Collection`, so `String(decoding:as:)` can’t take it
|
||||
/// directly. This borrows the underlying buffer for the length of the call.
|
||||
var utf8String: String {
|
||||
withUnsafeBufferPointer { String(decoding: $0, as: UTF8.self) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import NIOIMAP
|
||||
|
||||
func stableCompare(
|
||||
_ lhs: MailboxName,
|
||||
_ rhs: MailboxName
|
||||
) -> Bool {
|
||||
switch (lhs.isInbox, rhs.isInbox) {
|
||||
case (true, false): return true
|
||||
case (true, true): return false
|
||||
case (false, true): return false
|
||||
case (false, false): break
|
||||
}
|
||||
// Byte-wise ordering, with a shorter name sorting before a longer one that
|
||||
// shares its prefix — the same ordering `memcmp` plus a length tie-break gives.
|
||||
return lhs.bytes.lexicographicallyPrecedes(rhs.bytes)
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import DequeModule
|
||||
|
||||
/// Lets us limit concurrency.
|
||||
actor TokenBucket {
|
||||
private var tokens: Int
|
||||
private var waiters: Deque<Waiter>
|
||||
private var nextWaiterID = 0
|
||||
|
||||
private struct Waiter {
|
||||
var id: Int
|
||||
var continuation: CheckedContinuation<Void, any Swift.Error>
|
||||
}
|
||||
|
||||
init(tokens: Int) {
|
||||
self.tokens = tokens
|
||||
self.waiters = Deque()
|
||||
}
|
||||
|
||||
func withToken<ReturnType: Sendable>(
|
||||
_ body: () async throws -> ReturnType
|
||||
) async throws -> ReturnType {
|
||||
try await self.getToken()
|
||||
defer {
|
||||
self.returnToken()
|
||||
}
|
||||
|
||||
return try await body()
|
||||
}
|
||||
|
||||
private func getToken() async throws {
|
||||
if self.tokens > 0 {
|
||||
self.tokens -= 1
|
||||
return
|
||||
}
|
||||
|
||||
let id = self.nextWaiterID
|
||||
self.nextWaiterID += 1
|
||||
|
||||
// Park until a token is returned to us — but honor cancellation, so a
|
||||
// cancelled task doesn't stay parked forever (and doesn't consume a
|
||||
// token it never received).
|
||||
try await withTaskCancellationHandler {
|
||||
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, any Swift.Error>) in
|
||||
// If we were cancelled before parking, don't park at all.
|
||||
if Task.isCancelled {
|
||||
continuation.resume(throwing: CancellationError())
|
||||
return
|
||||
}
|
||||
self.waiters.append(Waiter(id: id, continuation: continuation))
|
||||
}
|
||||
} onCancel: {
|
||||
Task { await self.cancelWaiter(id: id) }
|
||||
}
|
||||
}
|
||||
|
||||
private func cancelWaiter(id: Int) {
|
||||
guard let index = self.waiters.firstIndex(where: { $0.id == id }) else {
|
||||
// The waiter was already granted a token by `returnToken`; that
|
||||
// path stays balanced via the holder's `defer returnToken()`.
|
||||
return
|
||||
}
|
||||
let waiter = self.waiters.remove(at: index)
|
||||
waiter.continuation.resume(throwing: CancellationError())
|
||||
}
|
||||
|
||||
private func returnToken() {
|
||||
if let nextWaiter = self.waiters.popFirst() {
|
||||
nextWaiter.continuation.resume()
|
||||
} else {
|
||||
self.tokens += 1
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,323 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import IMAPCommands
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
import NIOIMAP
|
||||
import NIO
|
||||
import Synchronization
|
||||
import SystemPackage
|
||||
|
||||
extension IMAPConnection {
|
||||
/// Uploads (`APPEND`s) the given messages into the given mailbox.
|
||||
///
|
||||
/// Selects the target mailbox first to receive any updates to it.
|
||||
func append<ID: Sendable>(
|
||||
messages: some AsyncSequence<MessageToAppend<ID>, any Swift.Error>,
|
||||
into mailbox: MailboxName,
|
||||
createMailbox: SelectCreateOption
|
||||
) async throws -> [AppendedMessageInfo<ID>] {
|
||||
let info = try await select(
|
||||
mailbox: mailbox,
|
||||
createMailbox: createMailbox
|
||||
)
|
||||
|
||||
var result: [AppendedMessageInfo<ID>] = []
|
||||
|
||||
var messageCount = 0
|
||||
for try await message in messages {
|
||||
messageCount += 1
|
||||
|
||||
let uidAppend = try await append(
|
||||
message: message,
|
||||
into: mailbox
|
||||
)
|
||||
let uid = singleAppendUIDFromResponse(
|
||||
uidAppend: uidAppend,
|
||||
uidValidity: info.uidValidity,
|
||||
messageCount: messageCount
|
||||
)
|
||||
result.append(AppendedMessageInfo(messageID: message.messageID, uid: uid, id: message.id))
|
||||
}
|
||||
|
||||
writeStatus("Did append \(result.count) message(s)")
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
/// Metadata about a message that was successfully appended via `APPEND`.
|
||||
struct AppendedMessageInfo<ID: Sendable>: Sendable {
|
||||
/// The RFC 2822 `Message-ID` header value of the appended message.
|
||||
var messageID: MessageID
|
||||
/// The server-assigned `UID` from the `APPENDUID` response code, or `nil`
|
||||
/// if the server did not return one (e.g. no `UIDPLUS` support).
|
||||
var uid: UID?
|
||||
/// The caller-supplied identifier originally passed in via ``MessageToAppend/id``.
|
||||
var id: ID
|
||||
}
|
||||
|
||||
/// Extracts the ``UID`` from the ``ResponseCodeAppend`` (`APPENDUID`, part of `UIDPLUS`).
|
||||
///
|
||||
/// This helper assumes a single-message `APPEND`, and returns `nil` if the
|
||||
/// `APPENDUID` response code contains anything other than exactly one UID.
|
||||
/// It is therefore not suitable for `MULTIAPPEND` (RFC 3502) responses.
|
||||
private func singleAppendUIDFromResponse(
|
||||
uidAppend: ResponseCodeAppend?,
|
||||
uidValidity: UIDValidity,
|
||||
messageCount: Int
|
||||
) -> UID? {
|
||||
guard
|
||||
let uidAppend
|
||||
else {
|
||||
writeStatus("[\(messageCount)] Server did not send APPENDUID for message")
|
||||
return nil
|
||||
}
|
||||
guard
|
||||
uidAppend.uidValidity == uidValidity
|
||||
else {
|
||||
writeStatus("[\(messageCount)] UIDVALIDITY in APPENDUID differs from mailbox UIDVALIDITY")
|
||||
return nil
|
||||
}
|
||||
guard
|
||||
uidAppend.uids.set.count == 1
|
||||
else {
|
||||
writeStatus("[\(messageCount)] APPENDUID has \(uidAppend.uids.set.count) UIDs, only expected 1")
|
||||
return nil
|
||||
}
|
||||
let uid = uidAppend.uids.min()
|
||||
writeStatus("[\(messageCount)] New message has UID \(uid)")
|
||||
return uid
|
||||
}
|
||||
|
||||
extension IMAPConnection {
|
||||
/// Sends an `APPEND` for the given message.
|
||||
func append<ID: Sendable>(
|
||||
message: MessageToAppend<ID>,
|
||||
into mailbox: MailboxName
|
||||
) async throws -> ResponseCodeAppend? {
|
||||
let options = AppendOptions(
|
||||
flagList: message.flags ?? [],
|
||||
internalDate: message.serverMessageDate
|
||||
)
|
||||
|
||||
let tagged: TaggedResponse = try await append(
|
||||
to: mailbox,
|
||||
writing: { tag, writer in
|
||||
writeStatus("Appending message \(message.messageID) with tag \(tag)")
|
||||
try await writer.write(
|
||||
message: AppendMessage(
|
||||
options: options,
|
||||
data: AppendData(
|
||||
byteCount: message.byteCount
|
||||
)
|
||||
)
|
||||
) { writer in
|
||||
for await bytes in message.data {
|
||||
writeStatus("Sending \(bytes.readableBytes) message bytes")
|
||||
try await writer.write(messageBytes: bytes)
|
||||
}
|
||||
}
|
||||
},
|
||||
reading: { _, responses in
|
||||
try await responses.waitForCompletion()
|
||||
}
|
||||
)
|
||||
guard
|
||||
case .ok(let text) = tagged.state
|
||||
else {
|
||||
writeStatus("error: failed to append (\(tagged.state))")
|
||||
throw FailedToAppendMessage(state: tagged.state)
|
||||
}
|
||||
guard
|
||||
case .uidAppend(let c) = text.code
|
||||
else { return nil }
|
||||
return c
|
||||
}
|
||||
}
|
||||
|
||||
struct FailedToAppendMessage: Equatable, Swift.Error {
|
||||
var state: TaggedResponse.State
|
||||
}
|
||||
|
||||
extension AppendedMessageInfo where ID == FilePath {
|
||||
/// The file path the message was loaded from.
|
||||
var filePath: FilePath { id }
|
||||
}
|
||||
|
||||
// MARK: MessageToAppend
|
||||
|
||||
/// A message to upload via `APPEND`, including its metadata and byte stream.
|
||||
struct MessageToAppend<ID: Sendable>: Sendable {
|
||||
/// The total number of bytes in the message.
|
||||
var byteCount: Int
|
||||
/// A generic ID for this message, such as a file path or a counter.
|
||||
var id: ID
|
||||
/// The RFC 2822 `Message-ID` header value.
|
||||
var messageID: MessageID
|
||||
/// A sequence of bytes that make up the message. The total byte count must match `byteCount`.
|
||||
var data: AsyncStream<ByteBuffer>
|
||||
/// The flags to set on the message, or `nil` to use defaults.
|
||||
var flags: [Flag]?
|
||||
/// The internal date to assign to the message on the server.
|
||||
var serverMessageDate: ServerMessageDate?
|
||||
/// The subject of the message, for display purposes.
|
||||
var subject: String?
|
||||
}
|
||||
|
||||
struct UnableToParseMessageID<ID: Sendable>: Swift.Error {
|
||||
var id: ID
|
||||
}
|
||||
|
||||
extension MessageToAppend {
|
||||
/// Creates a message to append from an already-parsed email message.
|
||||
init(
|
||||
message other: EmailMessage,
|
||||
id: ID
|
||||
) throws {
|
||||
guard
|
||||
let headers = other.headersOfInterest
|
||||
else { throw UnableToParseMessageID(id: id) }
|
||||
let dataStream = AsyncStream(
|
||||
ByteBuffer.self,
|
||||
{ continuation in
|
||||
continuation.yield(with: .success(ByteBuffer(bytes: other.data)))
|
||||
continuation.finish()
|
||||
}
|
||||
)
|
||||
self.init(
|
||||
byteCount: other.data.count,
|
||||
id: id,
|
||||
messageID: headers.messageID,
|
||||
data: dataStream,
|
||||
flags: nil,
|
||||
serverMessageDate: ServerMessageDate(headers.date),
|
||||
subject: headers.subject
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
extension ServerMessageDate {
|
||||
init?(
|
||||
_ other: InternetMessageDate,
|
||||
) {
|
||||
guard
|
||||
let date = other.parse()
|
||||
else { return nil }
|
||||
|
||||
var calendar = Calendar(identifier: .gregorian)
|
||||
calendar.timeZone = .gmt
|
||||
|
||||
let c = calendar.dateComponents(
|
||||
[
|
||||
.year,
|
||||
.month,
|
||||
.day,
|
||||
.hour,
|
||||
.minute,
|
||||
.second,
|
||||
.timeZone,
|
||||
],
|
||||
from: date
|
||||
)
|
||||
guard
|
||||
let year = c.year,
|
||||
let month = c.month,
|
||||
let day = c.day,
|
||||
let hour = c.hour,
|
||||
let minute = c.minute,
|
||||
let second = c.second,
|
||||
let timeZone = c.timeZone,
|
||||
let cc = ServerMessageDate.Components(
|
||||
year: year,
|
||||
month: month,
|
||||
day: day,
|
||||
hour: hour,
|
||||
minute: minute,
|
||||
second: second,
|
||||
timeZoneMinutes: timeZone.secondsFromGMT() / 60
|
||||
)
|
||||
else { return nil }
|
||||
self.init(cc)
|
||||
}
|
||||
}
|
||||
|
||||
extension MessageToAppend: AsyncSequence {
|
||||
struct AsyncIterator: AsyncIteratorProtocol {
|
||||
typealias Element = NIOIMAP.AppendCommand
|
||||
|
||||
var state: State
|
||||
|
||||
enum State {
|
||||
case beginMessage(MessageToAppend)
|
||||
case messageBytes(AsyncStream<ByteBuffer>.Iterator)
|
||||
case endMessage
|
||||
}
|
||||
|
||||
mutating func next() async throws -> NIOIMAP.AppendCommand? {
|
||||
try await next(isolation: #isolation)
|
||||
}
|
||||
|
||||
/// Both `next` overloads are implemented, and the isolation is forwarded to the wrapped
|
||||
/// `AsyncStream` iterator, because neither iterator is `Sendable`: falling back to
|
||||
/// `AsyncIteratorProtocol`'s default implementation of `next(isolation:)` — which calls
|
||||
/// the `@concurrent` `next()` — would send them out of the caller's isolation domain.
|
||||
mutating func next(
|
||||
isolation actor: isolated (any Actor)?
|
||||
) async throws -> NIOIMAP.AppendCommand? {
|
||||
switch state {
|
||||
case .beginMessage(let message):
|
||||
state = .messageBytes(message.data.makeAsyncIterator())
|
||||
return .beginMessage(message: AppendMessage(message))
|
||||
case .messageBytes(var data):
|
||||
guard
|
||||
let bytes = await data.next(isolation: actor)
|
||||
else {
|
||||
state = .endMessage
|
||||
return .endMessage
|
||||
}
|
||||
state = .messageBytes(data)
|
||||
return .messageBytes(bytes)
|
||||
case .endMessage:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
init(
|
||||
message: MessageToAppend
|
||||
) {
|
||||
self.state = .beginMessage(message)
|
||||
}
|
||||
}
|
||||
|
||||
func makeAsyncIterator() -> AsyncIterator {
|
||||
AsyncIterator(message: self)
|
||||
}
|
||||
}
|
||||
|
||||
extension AppendMessage {
|
||||
init<ID: Sendable>(_ message: MessageToAppend<ID>) {
|
||||
self.init(
|
||||
options: AppendOptions(
|
||||
flagList: message.flags ?? [],
|
||||
internalDate: message.serverMessageDate,
|
||||
extensions: [:]
|
||||
),
|
||||
data: AppendData(byteCount: message.byteCount)
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,422 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import IMAPCommands
|
||||
import NIO
|
||||
import NIOIMAP
|
||||
import SystemPackage
|
||||
#if canImport(Glibc)
|
||||
import Glibc
|
||||
#elseif canImport(Darwin)
|
||||
import Darwin
|
||||
#endif
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
|
||||
extension IMAPConnection {
|
||||
/// Uploads (`APPEND`s) the given messages into the given mailbox.
|
||||
///
|
||||
/// Selects the target mailbox first to receive any updates to it.
|
||||
func append(
|
||||
messages: [FilePath],
|
||||
options: Set<AppendOption>,
|
||||
into mailbox: MailboxName
|
||||
) async throws -> [AppendedMessageInfo<FilePath>] {
|
||||
try await append(
|
||||
messages: FileBasedMessageToAppendSequence(
|
||||
paths: messages,
|
||||
options: options
|
||||
),
|
||||
into: mailbox,
|
||||
createMailbox: SelectCreateOption(options)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Options that control the behavior of an `APPEND` operation.
|
||||
enum AppendOption: Hashable, Sendable {
|
||||
/// Skips files that fail to parse instead of aborting.
|
||||
case skipErrors
|
||||
/// Sorts messages by date before uploading.
|
||||
case sort
|
||||
/// Creates the target mailbox with the given parameters if it does not exist.
|
||||
case createMailbox([CreateParameter])
|
||||
/// Sets these flags on all appended messages.
|
||||
case flags([NIOIMAP.Flag])
|
||||
}
|
||||
|
||||
extension SelectCreateOption {
|
||||
init(
|
||||
_ other: Set<AppendOption>
|
||||
) {
|
||||
for option in other {
|
||||
if case .createMailbox(let parameters) = option {
|
||||
self = .create(parameters)
|
||||
return
|
||||
}
|
||||
}
|
||||
self = .fail
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: -
|
||||
|
||||
/// An async sequence that reads email message files from disk and yields them as `MessageToAppend` values.
|
||||
struct FileBasedMessageToAppendSequence: AsyncSequence, Sendable {
|
||||
typealias Element = MessageToAppend<FilePath>
|
||||
typealias Failure = any Swift.Error
|
||||
|
||||
/// The file paths to read messages from.
|
||||
let paths: [FilePath]
|
||||
/// The options controlling how messages are read and processed.
|
||||
let options: Set<AppendOption>
|
||||
|
||||
/// Creates a new sequence from the given file paths and options.
|
||||
init(
|
||||
paths: [FilePath],
|
||||
options: Set<AppendOption>
|
||||
) {
|
||||
self.paths = paths
|
||||
self.options = options
|
||||
}
|
||||
|
||||
struct AsyncIterator: AsyncIteratorProtocol {
|
||||
typealias Failure = any Swift.Error
|
||||
|
||||
fileprivate let paths: [FilePath]
|
||||
fileprivate let options: Set<AppendOption>
|
||||
var remainingPaths: ArraySlice<FilePathWithDate>?
|
||||
private var sorted: Sorted = .initial
|
||||
|
||||
fileprivate init(
|
||||
paths: [FilePath],
|
||||
options: Set<AppendOption>
|
||||
) {
|
||||
self.paths = paths
|
||||
self.options = options
|
||||
}
|
||||
|
||||
private enum Sorted {
|
||||
case initial
|
||||
case isReading
|
||||
case sorted([FilePathWithDate])
|
||||
}
|
||||
|
||||
mutating func next() async throws -> MessageToAppend<FilePath>? {
|
||||
let flags = extractFlags(from: options)
|
||||
while true {
|
||||
guard
|
||||
let pathWithDate = try await nextPath()
|
||||
else { return nil }
|
||||
do {
|
||||
var message = try await MessageToAppend(
|
||||
message: EmailMessage(filePath: pathWithDate.filePath),
|
||||
id: pathWithDate.filePath
|
||||
)
|
||||
if !flags.isEmpty {
|
||||
message.flags = flags
|
||||
}
|
||||
return message
|
||||
} catch {
|
||||
writeStatus("error: failed to read message \(pathWithDate.filePath)")
|
||||
guard options.contains(.skipErrors) else { throw error }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func extractFlags(from options: Set<AppendOption>) -> [NIOIMAP.Flag] {
|
||||
for option in options {
|
||||
if case .flags(let flags) = option {
|
||||
return flags
|
||||
}
|
||||
}
|
||||
return []
|
||||
}
|
||||
|
||||
private mutating func nextPath() async throws -> FilePathWithDate? {
|
||||
var remaining: ArraySlice<FilePathWithDate>
|
||||
if let r = remainingPaths {
|
||||
remaining = r
|
||||
} else {
|
||||
remaining = try await sortedPaths()[...]
|
||||
}
|
||||
guard let next = remaining.popFirst() else { return nil }
|
||||
remainingPaths = remaining
|
||||
return next
|
||||
}
|
||||
|
||||
private mutating func sortedPaths() async throws -> [FilePathWithDate] {
|
||||
switch sorted {
|
||||
case .initial:
|
||||
sorted = .isReading
|
||||
let paths = try await FileBasedMessageToAppendSequence.readAndSort(
|
||||
paths: paths,
|
||||
options: options
|
||||
)
|
||||
sorted = .sorted(paths)
|
||||
return paths
|
||||
case .isReading:
|
||||
fatalError("Recursively calling next() ?!?")
|
||||
case .sorted(let array):
|
||||
return array
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func makeAsyncIterator() -> AsyncIterator {
|
||||
AsyncIterator(
|
||||
paths: paths,
|
||||
options: options
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
extension FileBasedMessageToAppendSequence {
|
||||
struct IndexedFilePath: Hashable, Sendable {
|
||||
/// The index of the input argument (the order in which files were passed to the imap-tool).
|
||||
var originalIndex: UInt32
|
||||
/// If the input was a directory, this is the (relatively random) index within that directory.
|
||||
var nestedIndex: UInt32
|
||||
var path: FilePathWithDate
|
||||
|
||||
var sortIndex: UInt64 {
|
||||
(UInt64(originalIndex) << 32) + UInt64(nestedIndex)
|
||||
}
|
||||
}
|
||||
|
||||
/// The path of an email message file combined with its parsed `Date` header.
|
||||
///
|
||||
/// This lets us sort input files based on their date.
|
||||
struct FilePathWithDate: Hashable, Sendable, Comparable {
|
||||
var filePath: FilePath
|
||||
var date: Date
|
||||
|
||||
static func < (
|
||||
lhs: FileBasedMessageToAppendSequence.FilePathWithDate,
|
||||
rhs: FileBasedMessageToAppendSequence.FilePathWithDate
|
||||
) -> Bool {
|
||||
lhs.date < rhs.date
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension FileBasedMessageToAppendSequence {
|
||||
/// Read an email message file, or all files inside a given directory.
|
||||
///
|
||||
/// If `path` is a regular file, parse that file as a directory. If `path` is a directory,
|
||||
/// parse the files inside it.
|
||||
///
|
||||
/// We attempt to read `path` as a single message first; only if that fails do we fall back
|
||||
/// to treating it as a directory. This skips an up-front `stat(2)` on the common case where
|
||||
/// the argument is a regular email file — the read itself tells us whether `path` is a file
|
||||
/// or directory, at the cost of a slightly less informative error when both interpretations
|
||||
/// fail.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - originalIndex: Used for (later) sorting messages according to their
|
||||
/// original input order.
|
||||
static func readMessage(
|
||||
path: FilePath,
|
||||
originalIndex: Int
|
||||
) async -> [Result<IndexedFilePath, UnableToParseFile>] {
|
||||
do {
|
||||
let result = try await readSingleMessage(
|
||||
path: path,
|
||||
originalIndex: originalIndex
|
||||
)
|
||||
return [.success(result)]
|
||||
} catch {
|
||||
// Try to see if this is a directory:
|
||||
guard let r = try? await readDirectory(directoryPath: path, originalIndex: originalIndex) else {
|
||||
return [.failure(error)]
|
||||
}
|
||||
return r
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an array with one entry for each file in the directory at the given path.
|
||||
///
|
||||
/// Throws an error if the directory can not be scanned, for example because it does not exist.
|
||||
static func readDirectory(
|
||||
directoryPath: FilePath,
|
||||
originalIndex: Int
|
||||
) async throws -> [Result<IndexedFilePath, UnableToParseFile>] {
|
||||
let paths = try allRegularFiles(in: directoryPath)
|
||||
writeStatus("Did find \(paths.count) file(s) inside '\(directoryPath)'")
|
||||
|
||||
var result: [Result<IndexedFilePath, UnableToParseFile>] = []
|
||||
for (subIndex, path) in paths.enumerated() {
|
||||
do {
|
||||
var r = try await readSingleMessage(
|
||||
path: path,
|
||||
originalIndex: originalIndex
|
||||
)
|
||||
r.nestedIndex = UInt32(subIndex)
|
||||
result.append(.success(r))
|
||||
} catch {
|
||||
result.append(.failure(error))
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
/// Returns the paths of all regular files inside the directory.
|
||||
///
|
||||
/// This does _not_ recurse into sub-directories.
|
||||
static func allRegularFiles(
|
||||
in directoryPath: FilePath,
|
||||
) throws -> [FilePath] {
|
||||
var paths: [FilePath] = []
|
||||
|
||||
func add(dirent entry: UnsafePointer<dirent>) {
|
||||
let name = withRegularFileName(dirent: entry) { buffer -> FilePath.Component? in
|
||||
// `FilePath.Component(platformString:)` requires a NUL-terminated buffer;
|
||||
// `d_name` from `readdir` is not, so copy into a temp NUL-terminated buffer.
|
||||
withUnsafeTemporaryAllocation(
|
||||
of: CInterop.PlatformChar.self,
|
||||
capacity: buffer.count + 1
|
||||
) { temp in
|
||||
for i in buffer.indices {
|
||||
temp[i] = CInterop.PlatformChar(bitPattern: buffer[i])
|
||||
}
|
||||
temp[buffer.count] = 0
|
||||
return temp.baseAddress.flatMap { FilePath.Component(platformString: $0) }
|
||||
}
|
||||
}
|
||||
guard let name else { return }
|
||||
paths.append(directoryPath.appending(name))
|
||||
}
|
||||
|
||||
try scan(
|
||||
directory: directoryPath,
|
||||
closure: add(dirent:)
|
||||
)
|
||||
|
||||
return paths
|
||||
}
|
||||
|
||||
static func readSingleMessage(
|
||||
path: FilePath,
|
||||
originalIndex: Int
|
||||
) async throws(UnableToParseFile) -> IndexedFilePath {
|
||||
do {
|
||||
// Read the first 100,000 bytes:
|
||||
let data = try await Data(
|
||||
asyncContentsOf: path,
|
||||
length: 100_000
|
||||
)
|
||||
// Parse the date from it:
|
||||
guard
|
||||
let date = MessageHeaderParser.current.dateHeader(data)
|
||||
else {
|
||||
throw NoMessageDateInFile()
|
||||
}
|
||||
guard
|
||||
let date = date.parse()
|
||||
else {
|
||||
throw UnableToParseDate(date: String(date))
|
||||
}
|
||||
return IndexedFilePath(
|
||||
originalIndex: UInt32(originalIndex),
|
||||
nestedIndex: 0,
|
||||
path: FilePathWithDate(
|
||||
filePath: path,
|
||||
date: date
|
||||
)
|
||||
)
|
||||
} catch {
|
||||
throw UnableToParseFile(
|
||||
filePath: path,
|
||||
underlying: error
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension FileBasedMessageToAppendSequence {
|
||||
static func readAndSort(
|
||||
paths: [FilePath],
|
||||
options: Set<AppendOption>
|
||||
) async throws -> [FilePathWithDate] {
|
||||
try await withThrowingTaskGroup { group in
|
||||
writeStatus("Reading and sorting \(paths.count) input path(s) by message date")
|
||||
for (index, path) in paths.enumerated() {
|
||||
group.addTask {
|
||||
await readMessage(
|
||||
path: path,
|
||||
originalIndex: index
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Bin results by `originalIndex` so input order is preserved without sorting.
|
||||
// Within each bin `nestedIndex` is in ascending order because `readDirectory`
|
||||
// assigns it from `enumerated()`.
|
||||
var bins: [[FilePathWithDate]] = Array(repeating: [], count: paths.count)
|
||||
while true {
|
||||
do {
|
||||
guard
|
||||
let nextBatch = try await group.next()
|
||||
else { break }
|
||||
for next in nextBatch {
|
||||
switch next {
|
||||
case .success(let s):
|
||||
bins[Int(s.originalIndex)].append(s.path)
|
||||
case .failure(let error):
|
||||
writeErrorStatus(error: error)
|
||||
guard options.contains(.skipErrors) else { throw error }
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
writeStatus("error: \(error)")
|
||||
guard options.contains(.skipErrors) else { throw error }
|
||||
}
|
||||
}
|
||||
let inOrder = bins.flatMap { $0 }
|
||||
guard options.contains(.sort) else { return inOrder }
|
||||
return inOrder.sorted()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension FileBasedMessageToAppendSequence {
|
||||
static func writeErrorStatus(
|
||||
error: UnableToParseFile
|
||||
) {
|
||||
switch error.underlying {
|
||||
case is NoMessageDateInFile:
|
||||
writeStatus("error: message is missing 'date' header ('\(error.filePath)')")
|
||||
case let u as UnableToParseDate:
|
||||
writeStatus(
|
||||
"error: message 'date' header '\(u.date)' is not a valid RFC 5322 'date-time' ('\(error.filePath)')"
|
||||
)
|
||||
default:
|
||||
writeStatus("error: unable to parse file: \(error.underlying) ('\(error.filePath)')")
|
||||
}
|
||||
}
|
||||
|
||||
struct NoMessageDateInFile: Swift.Error, Hashable {}
|
||||
|
||||
struct UnableToParseDate: Swift.Error, Hashable {
|
||||
var date: String
|
||||
}
|
||||
|
||||
struct UnableToParseFile: Swift.Error {
|
||||
var filePath: FilePath
|
||||
var underlying: any Swift.Error
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import IMAPCommands
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
import NIO
|
||||
import NIOIMAP
|
||||
|
||||
/// The result of a successful IMAP authentication.
|
||||
struct AuthenticationResult: Hashable, Sendable {
|
||||
var responseText: String
|
||||
var capabilities: [Capability]
|
||||
}
|
||||
|
||||
/// Which command to use to authenticate.
|
||||
enum AuthenticationMethod: Hashable, Sendable {
|
||||
/// Use `AUTHENTICATE` when the server advertises the credential’s SASL
|
||||
/// mechanism, and fall back to `LOGIN` when it does not.
|
||||
case automatic
|
||||
/// Always try `LOGIN`, even when the server advertises the mechanism. Fails without
|
||||
/// sending anything if the credential has no password, or if the server prohibits `LOGIN`.
|
||||
case login
|
||||
}
|
||||
|
||||
extension IMAPConnection {
|
||||
/// Authenticates the connection using the given credential.
|
||||
func authenticate(
|
||||
greeting: IMAPConnection.Greeting,
|
||||
credential: IMAPCredential,
|
||||
disableSASLIR: Bool,
|
||||
method: AuthenticationMethod
|
||||
) async throws -> AuthenticationResult {
|
||||
let preAuthCapabilities = try await capabilitiesFromCodeOrSendCommand(
|
||||
text: try greeting.status.getOK()
|
||||
)
|
||||
writeStatus("Pre-auth capabilities: \(preAuthCapabilities.map { String($0) }.sorted().joined(separator: " "))")
|
||||
|
||||
// Authenticate. `AUTHENTICATE` requires the server to advertise the
|
||||
// credential’s mechanism; `.login` overrides that and uses `LOGIN`.
|
||||
let (mechanism, ir) = credential.makeAuthenticateCommand()
|
||||
let useAuthenticate =
|
||||
switch method {
|
||||
case .automatic: preAuthCapabilities.contains(.authenticate(mechanism))
|
||||
case .login: false
|
||||
}
|
||||
|
||||
let authResult: TaggedResponse
|
||||
if useAuthenticate {
|
||||
authResult = try await authenticate(
|
||||
saslMechanism: mechanism,
|
||||
initialResponse: ir,
|
||||
useSASL_IR: !disableSASLIR && preAuthCapabilities.contains(.saslIR)
|
||||
)
|
||||
} else {
|
||||
authResult = try await login(
|
||||
credential: credential,
|
||||
capabilities: preAuthCapabilities,
|
||||
method: method
|
||||
)
|
||||
}
|
||||
|
||||
let text = try authResult.getOK()
|
||||
writeStatus("Did authenticate: \(text.text)")
|
||||
|
||||
let postAuthCapabilities = try await capabilitiesFromCodeOrSendCommand(
|
||||
text: text
|
||||
)
|
||||
writeStatus(
|
||||
"Post-auth capabilities: \(postAuthCapabilities.map { String($0) }.sorted().joined(separator: " "))"
|
||||
)
|
||||
|
||||
return AuthenticationResult(
|
||||
responseText: text.text,
|
||||
capabilities: postAuthCapabilities
|
||||
)
|
||||
}
|
||||
|
||||
private func capabilitiesFromCodeOrSendCommand(
|
||||
text: ResponseText
|
||||
) async throws -> [Capability] {
|
||||
if case .capability(let c) = text.code {
|
||||
return c
|
||||
}
|
||||
// Get them from the server:
|
||||
return try await getCapabilities()
|
||||
}
|
||||
|
||||
private func getCapabilities() async throws -> [Capability] {
|
||||
try await send(.capability) { tag, responses in
|
||||
var result: [Capability]? = nil
|
||||
for try await r in responses {
|
||||
switch r {
|
||||
case .tagged(let r):
|
||||
try r.checkOK()
|
||||
case .untagged(.capabilityData(let c)):
|
||||
result = c
|
||||
default:
|
||||
break
|
||||
}
|
||||
}
|
||||
guard
|
||||
let result
|
||||
else {
|
||||
throw AuthenticationError(message: "Server did not return Capabilities")
|
||||
}
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
/// Sends `LOGIN`, or throws if either the credential or the server rules it out.
|
||||
///
|
||||
/// The credential is checked first: when it can’t produce a `LOGIN` at all, saying so is
|
||||
/// more useful than pointing at `LOGINDISABLED` for a command the user never asked for.
|
||||
private func login(
|
||||
credential: IMAPCredential,
|
||||
capabilities: [Capability],
|
||||
method: AuthenticationMethod
|
||||
) async throws -> TaggedResponse {
|
||||
guard let loginCommand = credential.makeLoginCommand() else {
|
||||
switch method {
|
||||
case .login:
|
||||
throw AuthenticationError(
|
||||
message: "The given credential can only be used with AUTHENTICATE, not LOGIN."
|
||||
)
|
||||
case .automatic:
|
||||
throw AuthenticationError(
|
||||
message:
|
||||
"Server capabilities do not support the available credentials. Capabilities: \(capabilities.map { String($0) }.sorted().joined(separator: " "))"
|
||||
)
|
||||
}
|
||||
}
|
||||
guard !capabilities.contains(.loginDisabled) else {
|
||||
throw AuthenticationError(
|
||||
message: "The server advertises LOGINDISABLED, which prohibits the LOGIN command."
|
||||
)
|
||||
}
|
||||
return try await send(loginCommand) { tag, responses in
|
||||
writeStatus("Did send LOGIN command \(tag)")
|
||||
return try await responses.waitForCompletion()
|
||||
}
|
||||
}
|
||||
|
||||
private func authenticate(
|
||||
saslMechanism mechanism: AuthenticationMechanism,
|
||||
initialResponse ir: InitialResponse,
|
||||
useSASL_IR supportsIR: Bool
|
||||
) async throws -> TaggedResponse {
|
||||
try await sendAuthenticate(
|
||||
mechanism: mechanism,
|
||||
initialResponse: supportsIR ? ir : nil
|
||||
) { tag, responses, writer in
|
||||
writeStatus(
|
||||
"Did send AUTHENTICATE \(String(mechanism)) command \(tag) \(supportsIR ? "with" : "without") IR"
|
||||
)
|
||||
return try await responses.forEach { response in
|
||||
switch response {
|
||||
case .authenticationChallenge:
|
||||
guard !supportsIR else {
|
||||
throw AuthenticationError(message: "Unexpected challenge.")
|
||||
}
|
||||
try await writer.writeContinuation(ir.data)
|
||||
default:
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct AuthenticationError: Equatable, Swift.Error {
|
||||
var message: String
|
||||
}
|
||||
|
||||
// MARK: -
|
||||
|
||||
extension ResponsePayload {
|
||||
var capabilities: [Capability]? {
|
||||
if case .conditionalState(.ok(let s)) = self, case .capability(let c)? = s.code {
|
||||
return c
|
||||
} else if case .capabilityData(let c) = self {
|
||||
return c
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
extension IMAPCredential {
|
||||
func makeAuthenticateCommand() -> (AuthenticationMechanism, InitialResponse) {
|
||||
let mechanism: AuthenticationMechanism
|
||||
let data: Data
|
||||
switch self {
|
||||
case .username(let u, password: let p):
|
||||
mechanism = .plain
|
||||
data = Data([0]) + Data(u.utf8) + Data([0]) + Data(p.utf8)
|
||||
case .sasl(mechanism: let m, response: let response):
|
||||
mechanism = m
|
||||
data = response
|
||||
}
|
||||
return (mechanism, InitialResponse(ByteBuffer(data)))
|
||||
}
|
||||
|
||||
func makeLoginCommand() -> Command? {
|
||||
guard case .username(let u, password: let p) = self else { return nil }
|
||||
return .login(username: u, password: p)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import NIOIMAP
|
||||
|
||||
/// Number of messages per batch when partitioning `FETCH` / `SEARCH` requests.
|
||||
struct BatchSize: Hashable, Sendable {
|
||||
/// Always positive.
|
||||
let count: Int
|
||||
|
||||
init?(_ count: Int) {
|
||||
guard 0 < count else { return nil }
|
||||
self.count = count
|
||||
}
|
||||
}
|
||||
|
||||
extension BatchSize {
|
||||
/// Floor for the batch size.
|
||||
///
|
||||
/// When a server advertises a smaller `MESSAGELIMIT`, we still use this floor as
|
||||
/// the batch size — the server's `MESSAGELIMIT` caps how many results may be
|
||||
/// returned in a single response, not how many UIDs we may include in a request.
|
||||
static let minimum: BatchSize = 1_000
|
||||
|
||||
/// `max(minimum, serverMessageLimit)`.
|
||||
///
|
||||
/// Falls back to `minimum` if the server does not advertise `MESSAGELIMIT` (RFC 9738).
|
||||
init(capabilities: [Capability]) {
|
||||
guard
|
||||
let value = capabilities.first(where: { $0.name == "MESSAGELIMIT" })?.value,
|
||||
let parsed = UInt32(value),
|
||||
let limit = Int(exactly: parsed).flatMap(BatchSize.init)
|
||||
else {
|
||||
self = .minimum
|
||||
return
|
||||
}
|
||||
self = max(.minimum, limit)
|
||||
}
|
||||
}
|
||||
|
||||
extension BatchSize {
|
||||
/// Sequence numbers covered by the batch at `index`, for RFC 9394 `PARTIAL` ranges.
|
||||
///
|
||||
/// Counted from the end of the mailbox (1 = newest).
|
||||
/// E.g. for a size of 1,000: index 0 → `1...1000`, index 1 → `1001...2000`.
|
||||
/// The end is clamped to `SequenceNumber.max`.
|
||||
func partialRange(batch index: Int) -> ClosedRange<SequenceNumber> {
|
||||
let startOffset = Int64(index) * Int64(count)
|
||||
let endOffset = Swift.min(
|
||||
startOffset + Int64(count) - 1,
|
||||
SequenceNumber.min.distance(to: .max)
|
||||
)
|
||||
return SequenceNumber.min.advanced(by: startOffset)...SequenceNumber.min.advanced(by: endOffset)
|
||||
}
|
||||
}
|
||||
|
||||
extension BatchSize: Comparable {
|
||||
static func < (lhs: BatchSize, rhs: BatchSize) -> Bool {
|
||||
lhs.count < rhs.count
|
||||
}
|
||||
}
|
||||
|
||||
extension BatchSize: ExpressibleByIntegerLiteral {
|
||||
init(integerLiteral value: Int) {
|
||||
guard let size = BatchSize(value) else { preconditionFailure("BatchSize must be positive: \(value)") }
|
||||
self = size
|
||||
}
|
||||
}
|
||||
|
||||
extension BatchSize: CustomStringConvertible {
|
||||
var description: String { "\(count)" }
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import IMAPCommands
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
import NIO
|
||||
import NIOIMAP
|
||||
|
||||
extension ConnectionProtocol {
|
||||
/// Creates the mailbox unless it already exists, then runs `LIST` and `STATUS` on it.
|
||||
func createIfNeededAndList(
|
||||
capabilities: [Capability],
|
||||
mailbox: NewMailboxAction
|
||||
) async throws -> MailboxInfoAndStatus {
|
||||
switch mailbox {
|
||||
case .alreadyExists(let name):
|
||||
return try await listAlreadyExisting(
|
||||
capabilities: capabilities,
|
||||
mailbox: name
|
||||
)
|
||||
case .create(let name, let parameters):
|
||||
return try await createAndList(
|
||||
capabilities: capabilities,
|
||||
mailbox: name,
|
||||
parameters: parameters
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates the mailbox and then runs `LIST` and `STATUS` on it.
|
||||
func createAndList(
|
||||
capabilities: [Capability],
|
||||
mailbox: MailboxName,
|
||||
parameters _parameters: [CreateParameter]
|
||||
) async throws -> MailboxInfoAndStatus {
|
||||
let parameters: [CreateParameter]
|
||||
if capabilities.contains(.createSpecialUse) {
|
||||
parameters = _parameters
|
||||
} else {
|
||||
if !_parameters.isEmpty {
|
||||
writeStatus("Server does not support CREATE-SPECIAL-USE")
|
||||
}
|
||||
parameters = []
|
||||
}
|
||||
|
||||
let createText = try await send(.create(mailbox, parameters)) { tag, responses in
|
||||
writeStatus("Did send CREATE mailbox '\(mailbox)' with tag \(tag)")
|
||||
return try await responses.waitForCompletion()
|
||||
}.getOK()
|
||||
writeStatus("Did CREATE mailbox '\(mailbox)': \(createText)")
|
||||
|
||||
guard
|
||||
let info = try await listMailbox(
|
||||
capabilities: capabilities,
|
||||
mailbox: mailbox
|
||||
)
|
||||
else { throw NoListResponseAfterCreate(mailbox: mailbox) }
|
||||
return info
|
||||
}
|
||||
}
|
||||
|
||||
struct NoListResponseAfterCreate: Swift.Error {
|
||||
var mailbox: MailboxName
|
||||
}
|
||||
|
||||
extension ConnectionProtocol {
|
||||
private func listAlreadyExisting(
|
||||
capabilities: [Capability],
|
||||
mailbox: MailboxName,
|
||||
) async throws -> MailboxInfoAndStatus {
|
||||
guard
|
||||
let info = try await listMailbox(
|
||||
capabilities: capabilities,
|
||||
mailbox: mailbox
|
||||
)
|
||||
else { throw NoListResponseForExistingMailbox(mailbox: mailbox) }
|
||||
return info
|
||||
}
|
||||
}
|
||||
|
||||
struct NoListResponseForExistingMailbox: Swift.Error {
|
||||
var mailbox: MailboxName
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import IMAPCommands
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
import NIO
|
||||
import NIOIMAP
|
||||
|
||||
extension ConnectionProtocol {
|
||||
/// Deletes a mailbox from the server.
|
||||
func deleteMailbox(
|
||||
capabilities _: [Capability],
|
||||
mailbox: MailboxName
|
||||
) async throws {
|
||||
let text = try await send(.delete(mailbox)) { tag, responses in
|
||||
writeStatus("Did send DELETE mailbox '\(mailbox)' with tag \(tag)")
|
||||
return try await responses.waitForCompletion()
|
||||
}.getOK()
|
||||
writeStatus("Did DELETE mailbox '\(mailbox)': \(text)")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import IMAPCommands
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
import NIO
|
||||
import NIOIMAP
|
||||
|
||||
extension ConnectionProtocol {
|
||||
/// Marks the specified messages as deleted and expunges them.
|
||||
func deleteMessages(
|
||||
uids: UIDSet
|
||||
) async throws {
|
||||
guard !uids.isEmpty else { return }
|
||||
guard
|
||||
let command = Command.uidStore(
|
||||
messages: uids,
|
||||
modifiers: [],
|
||||
data: StoreData.flags(StoreFlags.add(silent: true, list: [.deleted]))
|
||||
)
|
||||
else { return }
|
||||
try await send(command) { tag, responses in
|
||||
return try await responses.waitForCompletion()
|
||||
}.checkOK()
|
||||
writeStatus("Did mark \(uids.count) UIDs as \\Deleted")
|
||||
try await send(.expunge) { tag, responses in
|
||||
return try await responses.waitForCompletion()
|
||||
}.checkOK()
|
||||
writeStatus("Did EXPUNGE")
|
||||
}
|
||||
|
||||
/// Marks all messages in the selected mailbox as deleted and expunges them.
|
||||
func deleteAllMessages() async throws {
|
||||
guard
|
||||
let command = Command.uidStore(
|
||||
messages: .all,
|
||||
modifiers: [],
|
||||
data: StoreData.flags(StoreFlags.add(silent: true, list: [.deleted]))
|
||||
)
|
||||
else { return }
|
||||
try await send(command) { tag, responses in
|
||||
return try await responses.waitForCompletion()
|
||||
}.checkOK()
|
||||
writeStatus("Did mark as \\Deleted")
|
||||
try await send(.expunge) { tag, responses in
|
||||
return try await responses.waitForCompletion()
|
||||
}.checkOK()
|
||||
writeStatus("Did EXPUNGE")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,301 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import IMAPCommands
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
import NIO
|
||||
import NIOIMAP
|
||||
import SystemPackage
|
||||
|
||||
extension ConnectionProtocol {
|
||||
/// Downloads messages specified by `query` into the directory at `root`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - deleteUnknown: Whether to delete local message files that no longer exist on the server.
|
||||
/// - Returns: All UIDs in the directory, including previously downloaded UIDs.
|
||||
func download(
|
||||
mailboxMessageCount: Int,
|
||||
capabilities: [Capability],
|
||||
uidValidity: UIDValidity,
|
||||
query: FetchQuery,
|
||||
into root: FilePath,
|
||||
deleteUnknown: Bool
|
||||
) async throws -> UIDSet {
|
||||
// Get all UIDs on the server:
|
||||
let uids = try await allUIDs(
|
||||
query: query,
|
||||
mailboxMessageCount: mailboxMessageCount,
|
||||
capabilities: capabilities
|
||||
)
|
||||
writeStatus("Did find \(uids.count) UID(s) in mailbox")
|
||||
|
||||
var directory = try DownloadDirectory.openDeletingInvalidFiles(
|
||||
directory: root,
|
||||
uidValidity: uidValidity,
|
||||
deleteUnknown: deleteUnknown
|
||||
)
|
||||
|
||||
// Delete local files no longer on the server:
|
||||
if deleteUnknown {
|
||||
directory.unlinkFiles(notIncludedIn: uids)
|
||||
}
|
||||
|
||||
try await download(
|
||||
uids: uids,
|
||||
into: &directory
|
||||
)
|
||||
|
||||
return directory.downloadedUIDs
|
||||
}
|
||||
|
||||
/// Downloads a batch of UIDs with a concurrency limit.
|
||||
func download(
|
||||
uids allUIDs: UIDSet,
|
||||
concurrencyLimit: Int = 11,
|
||||
into _directory: inout DownloadDirectory,
|
||||
) async throws {
|
||||
let directory = DownloadDirectory.Helper(
|
||||
connection: self,
|
||||
directory: _directory
|
||||
)
|
||||
|
||||
// Loop over all UIDs and download them.
|
||||
try await withThrowingTaskGroup(
|
||||
of: Void.self,
|
||||
returning: Void.self
|
||||
) { group in
|
||||
let previouslyDownloadedUIDs = await directory.directory.downloadedUIDs
|
||||
var remainingUIDs = allUIDs.subtracting(previouslyDownloadedUIDs)
|
||||
if remainingUIDs.count != allUIDs.count {
|
||||
writeStatus(
|
||||
"Downloading \(remainingUIDs.count) remaining message(s) out of \(allUIDs.count) total message(s) — \(previouslyDownloadedUIDs.count) already downloaded"
|
||||
)
|
||||
} else {
|
||||
writeStatus("Downloading \(remainingUIDs.count) message(s)")
|
||||
}
|
||||
|
||||
func popNextUID() -> UID? {
|
||||
guard
|
||||
let uid = remainingUIDs.last
|
||||
else { return nil }
|
||||
remainingUIDs.remove(uid)
|
||||
return uid
|
||||
}
|
||||
|
||||
func addTask() {
|
||||
guard let uid = popNextUID() else { return }
|
||||
group.addTask {
|
||||
try await directory.download(uid: uid)
|
||||
}
|
||||
}
|
||||
|
||||
for _ in 0..<concurrencyLimit {
|
||||
addTask()
|
||||
}
|
||||
|
||||
var throughputEstimator = ThroughputEstimator()
|
||||
|
||||
for try await _ in group {
|
||||
// Every time a task completes, start another one
|
||||
addTask()
|
||||
if let throughput = throughputEstimator.didComplete() {
|
||||
let remainingCount = remainingUIDs.count + concurrencyLimit
|
||||
if let remainingTime = throughput.formattedTimeRemaining(
|
||||
remainingCount: remainingCount,
|
||||
remainingCountCutOff: max(20 + concurrencyLimit, 4 * concurrencyLimit)
|
||||
) {
|
||||
writeStatus(
|
||||
"Downloading at \(throughput.formattedTasksPerSecond()) messages per second — \(remainingTime) remaining"
|
||||
)
|
||||
} else {
|
||||
writeStatus("Downloading at \(throughput.formattedTasksPerSecond()) messages per second")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Get the updated value out of the Mutex
|
||||
_directory = await directory.directory
|
||||
}
|
||||
}
|
||||
|
||||
extension DownloadDirectory {
|
||||
/// Provides concurrent access to a `DownloadDirectory` during downloads.
|
||||
actor Helper<C: ConnectionProtocol> {
|
||||
let connection: C
|
||||
var directory: DownloadDirectory
|
||||
|
||||
init(
|
||||
connection: C,
|
||||
directory: DownloadDirectory
|
||||
) {
|
||||
self.connection = connection
|
||||
self.directory = directory
|
||||
}
|
||||
|
||||
func makeWriter(
|
||||
uid: UID
|
||||
) throws -> DownloadDirectory.Writer {
|
||||
try directory.makeWriter(uid: uid)
|
||||
}
|
||||
|
||||
func didDownload(uid: UID) {
|
||||
directory.didDownload(uid: uid)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension DownloadDirectory.Helper {
|
||||
func download(uid: UID) async throws {
|
||||
let section = SectionSpecifier(part: [], kind: .complete)
|
||||
let command = Command.uidFetch(
|
||||
.set(UIDSetNonEmpty(range: uid...uid)),
|
||||
[.uid, .bodySection(peek: true, section, nil)],
|
||||
[]
|
||||
)
|
||||
|
||||
let writer = try makeWriter(uid: uid)
|
||||
let byteCount = try await connection.send(command) { tag, responses -> Int? in
|
||||
writeStatus("Did send \(tag) UID FETCH \(uid) for complete message")
|
||||
|
||||
var state = FetchState.waiting
|
||||
|
||||
for try await response in responses {
|
||||
let action = state.update(
|
||||
uid: uid,
|
||||
section: section,
|
||||
response: response
|
||||
)
|
||||
switch action {
|
||||
case .none:
|
||||
break
|
||||
case .writeData(let data):
|
||||
writer.write(data)
|
||||
case .closeAndFail:
|
||||
writer.closeAndFail()
|
||||
case .closeAndSucceed:
|
||||
writer.closeAndSucceed()
|
||||
}
|
||||
}
|
||||
|
||||
// Wait for the writer to have completed.
|
||||
await writer.waitForCompletion()
|
||||
return state.byteCount
|
||||
}
|
||||
|
||||
guard
|
||||
let byteCount
|
||||
else {
|
||||
writeStatus("Did not receive any data for UID \(uid) — message might have been deleted")
|
||||
return
|
||||
}
|
||||
writeStatus("Did write \(byteCount) bytes for UID \(uid)")
|
||||
directory.didDownload(uid: uid)
|
||||
}
|
||||
}
|
||||
|
||||
/// Keeps track of where we are wrt. receiving `FetchResponse` for a particular message.
|
||||
///
|
||||
/// State transitions, driven by `update(uid:section:response:)`:
|
||||
///
|
||||
/// ```
|
||||
/// .fetch(.start)
|
||||
/// waiting ─────────────────────────────────► didStart
|
||||
///
|
||||
/// .simpleAttribute(.uid(matching))
|
||||
/// didStart ───────────────────────────────────────────► didMatchUID
|
||||
///
|
||||
/// .streamingBegin(.body(section, nil))
|
||||
/// didMatchUID ──────────────────────────────────────────► didBeginStream
|
||||
///
|
||||
/// .streamingBytes (→ writeData)
|
||||
/// didBeginStream ◄─────self loop──────────
|
||||
/// │
|
||||
/// │ .streamingEnd
|
||||
/// └──────────────────────► didEndStream
|
||||
///
|
||||
/// .finish (→ closeAndSucceed)
|
||||
/// didEndStream ─────────────────────────► done
|
||||
/// │
|
||||
/// │ anything else (→ closeAndFail)
|
||||
/// └──────────────────────► failed
|
||||
/// ```
|
||||
///
|
||||
/// Any unmatched `(state, response)` pair returns `.none` and leaves the state
|
||||
/// untouched — the iterator simply waits for the next response.
|
||||
private enum FetchState: Equatable, Sendable {
|
||||
case waiting
|
||||
case didStart
|
||||
case didMatchUID
|
||||
case didBeginStream(byteCount: Int)
|
||||
case didEndStream(byteCount: Int)
|
||||
case done(byteCount: Int)
|
||||
case failed
|
||||
}
|
||||
|
||||
extension FetchState {
|
||||
/// If writing completed (successfully), return the written byte count.
|
||||
var byteCount: Int? {
|
||||
guard
|
||||
case .done(let c) = self
|
||||
else { return nil }
|
||||
return c
|
||||
}
|
||||
|
||||
enum UpdateAction: Sendable {
|
||||
case none
|
||||
case writeData(ByteBuffer)
|
||||
case closeAndFail
|
||||
case closeAndSucceed
|
||||
}
|
||||
|
||||
mutating func update(
|
||||
uid: UID,
|
||||
section: SectionSpecifier,
|
||||
response: Response
|
||||
) -> UpdateAction {
|
||||
guard case .fetch(let fetch) = response else { return .none }
|
||||
switch (self, fetch) {
|
||||
case (.waiting, .start):
|
||||
self = .didStart
|
||||
return .none
|
||||
case (.didStart, .simpleAttribute(.uid(uid))):
|
||||
self = .didMatchUID
|
||||
return .none
|
||||
case (
|
||||
.didMatchUID,
|
||||
.streamingBegin(kind: StreamingKind.body(section: section, offset: nil), byteCount: let byteCount)
|
||||
):
|
||||
self = .didBeginStream(byteCount: byteCount)
|
||||
return .none
|
||||
case (.didBeginStream, .streamingBytes(let bytes)):
|
||||
return .writeData(bytes)
|
||||
case (.didBeginStream(byteCount: let byteCount), .streamingEnd):
|
||||
self = .didEndStream(byteCount: byteCount)
|
||||
return .none
|
||||
case (.didEndStream(byteCount: let byteCount), .finish):
|
||||
self = .done(byteCount: byteCount)
|
||||
return .closeAndSucceed
|
||||
case (.didEndStream, _):
|
||||
self = .failed
|
||||
return .closeAndFail
|
||||
default:
|
||||
return .none
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,438 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import SystemPackage
|
||||
#if canImport(Glibc)
|
||||
import Glibc
|
||||
#elseif canImport(Darwin)
|
||||
import Darwin
|
||||
#endif
|
||||
import NIOCore
|
||||
import NIOFileSystem
|
||||
import NIOIMAP
|
||||
|
||||
/// Tracks which message files exist in a download directory and determines file names for new downloads.
|
||||
struct DownloadDirectory: Sendable {
|
||||
let root: FilePath
|
||||
let uidValidity: UIDValidity
|
||||
private(set) var downloadedUIDs: UIDSet
|
||||
private var tempFilePrefix = Int.random(in: 1_000...9_999)
|
||||
}
|
||||
|
||||
extension DownloadDirectory {
|
||||
/// Opens the directory, deleting temporary files and files with a different UID validity.
|
||||
///
|
||||
/// - Parameter directory: The path to an existing directory for downloading messages.
|
||||
/// - Parameter uidValidity: The current UID validity of the mailbox on the server.
|
||||
static func openDeletingInvalidFiles(
|
||||
directory root: FilePath,
|
||||
uidValidity: UIDValidity,
|
||||
deleteUnknown: Bool
|
||||
) throws -> DownloadDirectory {
|
||||
var dir = DownloadDirectory(
|
||||
root: root,
|
||||
uidValidity: uidValidity,
|
||||
downloadedUIDs: UIDSet()
|
||||
)
|
||||
try Self.withFilenames(in: root) { filename in
|
||||
switch filename {
|
||||
case .message(let uid, uidValidity):
|
||||
dir.downloadedUIDs.insert(uid)
|
||||
case .message(let uid, let other):
|
||||
guard deleteUnknown else { break }
|
||||
writeStatus("Deleting message with wrong UID validity \(other), UID \(uid)")
|
||||
dir.unlink(file: filename)
|
||||
case .temporary:
|
||||
guard deleteUnknown else { break }
|
||||
writeStatus("Deleting temporary message")
|
||||
dir.unlink(file: filename)
|
||||
}
|
||||
}
|
||||
if dir.downloadedUIDs.isEmpty {
|
||||
writeStatus("Did find no previously downloaded messages")
|
||||
} else {
|
||||
writeStatus("Did find \(dir.downloadedUIDs.count) previously downloaded message(s)")
|
||||
}
|
||||
return dir
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: -
|
||||
|
||||
extension DownloadDirectory {
|
||||
/// Delete the given file in the directory.
|
||||
func unlink(file: Filename) {
|
||||
do {
|
||||
try root.appending(file).unlink()
|
||||
} catch {
|
||||
writeStatus("error: failed to delete '\(String(decoding: FilePath.Component(file)))' (\(error))")
|
||||
}
|
||||
}
|
||||
|
||||
mutating func unlinkFiles(notIncludedIn uids: UIDSet) {
|
||||
let toDelete = downloadedUIDs.subtracting(uids)
|
||||
guard !toDelete.isEmpty else { return }
|
||||
writeStatus("Deleting \(toDelete.count) downloaded message(s) that no longer exist on the server")
|
||||
for uid in toDelete {
|
||||
unlink(file: .message(uid, uidValidity))
|
||||
}
|
||||
downloadedUIDs.subtract(toDelete)
|
||||
}
|
||||
}
|
||||
|
||||
extension FilePath {
|
||||
func appending(_ filename: DownloadDirectory.Filename) -> FilePath {
|
||||
appending(FilePath.Component(filename))
|
||||
}
|
||||
|
||||
func unlink() throws {
|
||||
try withPlatformString { path in
|
||||
// Qualified because an unqualified `unlink` would resolve to this method.
|
||||
#if canImport(Glibc)
|
||||
let result = Glibc.unlink(path)
|
||||
#elseif canImport(Darwin)
|
||||
let result = Darwin.unlink(path)
|
||||
#endif
|
||||
guard
|
||||
result == 0
|
||||
else {
|
||||
let error = Errno(rawValue: errno)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: -
|
||||
|
||||
extension DownloadDirectory {
|
||||
/// Writes a downloaded message to a temporary file, then moves it into place.
|
||||
///
|
||||
/// Writing to `NIOFileSystem` is `async`, but callers hand over chunks synchronously as
|
||||
/// they arrive off the connection. The chunks therefore go into a stream that a
|
||||
/// detached task drains, and the file is opened, written, closed, and renamed entirely
|
||||
/// inside that task. `waitForCompletion()` awaits it.
|
||||
struct Writer: ~Copyable {
|
||||
let uid: UID
|
||||
private let continuation: AsyncStream<Chunk>.Continuation
|
||||
private let task: Task<Void, Never>
|
||||
|
||||
/// A unit of work handed to the writing task.
|
||||
fileprivate enum Chunk: Sendable {
|
||||
case write(ByteBuffer)
|
||||
/// Stop writing and discard the file.
|
||||
case fail
|
||||
}
|
||||
|
||||
init(
|
||||
uid: UID,
|
||||
path: FilePath,
|
||||
finalPath: FilePath
|
||||
) throws {
|
||||
self.uid = uid
|
||||
guard
|
||||
let finalFilename = finalPath.lastComponent
|
||||
else { throw InvalidFilePath(path: finalPath) }
|
||||
let name = String(decoding: finalFilename)
|
||||
|
||||
let (stream, continuation) = AsyncStream.makeStream(of: Chunk.self)
|
||||
self.continuation = continuation
|
||||
self.task = Task {
|
||||
await Writer.run(
|
||||
stream: stream,
|
||||
path: path,
|
||||
finalPath: finalPath,
|
||||
name: name
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Consumes `stream`, writing each chunk to the file at `path`.
|
||||
///
|
||||
/// The file is renamed to `finalPath` only if the stream completes without a
|
||||
/// `.fail` chunk and every write succeeds.
|
||||
private static func run(
|
||||
stream: AsyncStream<Chunk>,
|
||||
path: FilePath,
|
||||
finalPath: FilePath,
|
||||
name: String
|
||||
) async {
|
||||
do {
|
||||
let didSucceed = try await FileSystem.shared.withFileHandle(
|
||||
forWritingAt: path,
|
||||
options: .newFile(replaceExisting: true)
|
||||
) { handle -> Bool in
|
||||
var offset: Int64 = 0
|
||||
for await chunk in stream {
|
||||
switch chunk {
|
||||
case .write(let buffer):
|
||||
offset += try await handle.write(
|
||||
contentsOf: buffer.readableBytesView,
|
||||
toAbsoluteOffset: offset
|
||||
)
|
||||
case .fail:
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
guard didSucceed else {
|
||||
await Writer.removeTemporaryFile(at: path)
|
||||
return
|
||||
}
|
||||
try await FileSystem.shared.moveItem(at: path, to: finalPath)
|
||||
} catch {
|
||||
writeStatus("error: failed to write file '\(name)' (\(error))")
|
||||
await Writer.removeTemporaryFile(at: path)
|
||||
}
|
||||
}
|
||||
|
||||
/// Removes the partially written file, ignoring the case where it was never created.
|
||||
private static func removeTemporaryFile(at path: FilePath) async {
|
||||
do {
|
||||
_ = try await FileSystem.shared.removeItem(at: path)
|
||||
} catch {
|
||||
writeStatus("error: failed to remove temporary file '\(path)' (\(error))")
|
||||
}
|
||||
}
|
||||
|
||||
func write(_ buffer: ByteBuffer) {
|
||||
continuation.yield(.write(buffer))
|
||||
}
|
||||
|
||||
func closeAndFail() {
|
||||
continuation.yield(.fail)
|
||||
continuation.finish()
|
||||
}
|
||||
|
||||
func closeAndSucceed() {
|
||||
continuation.finish()
|
||||
}
|
||||
|
||||
func close() {
|
||||
continuation.finish()
|
||||
}
|
||||
|
||||
/// Waits for the file to be written, closed, and moved into place.
|
||||
func waitForCompletion() async {
|
||||
// Finishing is a no-op if the stream is already finished, but it makes sure
|
||||
// the writing task can run to completion rather than waiting for more chunks.
|
||||
continuation.finish()
|
||||
await task.value
|
||||
}
|
||||
|
||||
deinit {
|
||||
continuation.finish()
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a `Writer` to write data for the given message.
|
||||
func makeWriter(
|
||||
uid: UID
|
||||
) throws -> Writer {
|
||||
try Writer(
|
||||
uid: uid,
|
||||
path: root.appending(.temporary("\(tempFilePrefix).\(uid)")),
|
||||
finalPath: root.appending(.message(uid, uidValidity))
|
||||
)
|
||||
}
|
||||
|
||||
mutating func didDownload(uid: UID) {
|
||||
downloadedUIDs.insert(uid)
|
||||
}
|
||||
}
|
||||
|
||||
private struct InvalidFilePath: Swift.Error {
|
||||
var path: String
|
||||
init(path: FilePath) {
|
||||
self.path = String(decoding: path)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Enumerating (Existing) Files
|
||||
|
||||
extension DownloadDirectory {
|
||||
static func withFilenames(
|
||||
in directory: FilePath,
|
||||
closure: (Filename) -> Void
|
||||
) throws {
|
||||
try scan(directory: directory) { entry in
|
||||
guard let f = Filename(dirent: entry) else { return }
|
||||
closure(f)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension FilePath.Component {
|
||||
init(_ other: DownloadDirectory.Filename) {
|
||||
switch other {
|
||||
case .message(let uid, let validity):
|
||||
// UIDVALIDITY is encoded as hex padded to an even number of digits.
|
||||
// The parser (`scanUIDValidity`) consumes the hex two digits at a time,
|
||||
// so writer and reader must agree on this padding.
|
||||
let b = String(UInt32(validity), radix: 16)
|
||||
self.init("\(UInt32(uid)).\(((b.count % 2) == 0) ? "" : "0")\(b).message")!
|
||||
case .temporary(let id):
|
||||
self.init(".\(id).message")!
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension DownloadDirectory.Filename {
|
||||
init?(dirent entry: UnsafePointer<dirent>) {
|
||||
guard
|
||||
let parsed = withRegularFileName(
|
||||
dirent: entry,
|
||||
{ buffer in
|
||||
DownloadDirectory.Filename(regularFilename: buffer)
|
||||
}
|
||||
)
|
||||
else { return nil }
|
||||
self = parsed
|
||||
}
|
||||
|
||||
init?(
|
||||
regularFilename filename: Span<Unicode.UTF8.CodeUnit>
|
||||
) {
|
||||
// Filenames are short, so copying out of the span costs nothing and lets
|
||||
// the scanning below stay in ordinary, consuming `Collection` code —
|
||||
// `Span` is non-escapable and so cannot have `mutating` methods.
|
||||
var remainder = filename.withUnsafeBufferPointer { Array($0) }[...]
|
||||
if remainder.popDot() {
|
||||
guard
|
||||
remainder.dropMessageSuffix(),
|
||||
let s = String(validating: remainder, as: UTF8.self)
|
||||
else { return nil }
|
||||
self = .temporary(s)
|
||||
} else {
|
||||
guard
|
||||
remainder.dropMessageSuffix(),
|
||||
let uid = remainder.scanUID(),
|
||||
remainder.popDot(),
|
||||
let validity = remainder.scanUIDValidity(),
|
||||
remainder.isEmpty
|
||||
else { return nil }
|
||||
self = .message(uid, validity)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - File Names
|
||||
|
||||
extension DownloadDirectory {
|
||||
enum Filename: Hashable, Sendable {
|
||||
case message(UID, UIDValidity)
|
||||
case temporary(String)
|
||||
}
|
||||
}
|
||||
|
||||
private let fileExtension: StaticString = ".message"
|
||||
|
||||
extension ArraySlice<Unicode.UTF8.CodeUnit> {
|
||||
/// If the buffer has a ".message" suffix remove it and return `true`,
|
||||
/// return `false` otherwise.
|
||||
fileprivate mutating func dropMessageSuffix() -> Bool {
|
||||
guard
|
||||
fileExtension.utf8CodeUnitCount < self.count
|
||||
else { return false }
|
||||
// Check for ".message" file extension
|
||||
let start = self.index(self.endIndex, offsetBy: -fileExtension.utf8CodeUnitCount)
|
||||
guard
|
||||
fileExtension.withUTF8Buffer({ self[start...].elementsEqual($0) })
|
||||
else { return false }
|
||||
|
||||
self = self[..<start]
|
||||
return true
|
||||
}
|
||||
|
||||
fileprivate mutating func scanUID() -> UID? {
|
||||
guard
|
||||
var result = popNumber().map({ UInt32($0) })
|
||||
else { return nil }
|
||||
while true {
|
||||
guard
|
||||
let next = popNumber()
|
||||
else { return UID(exactly: result) }
|
||||
// Widen to `UInt64` _before_ multiplying so an overflowing filename
|
||||
// (e.g. `9999999999.0001.message`) makes the guard below skip the
|
||||
// file rather than trapping on `UInt32` overflow.
|
||||
let a = UInt64(result) * 10 + UInt64(next)
|
||||
guard
|
||||
let b = UInt32(exactly: a)
|
||||
else { return nil }
|
||||
result = b
|
||||
}
|
||||
}
|
||||
|
||||
fileprivate mutating func scanUIDValidity() -> UIDValidity? {
|
||||
guard
|
||||
var result = popDoubleHex().map({ UInt32($0) })
|
||||
else { return nil }
|
||||
while true {
|
||||
guard
|
||||
let next = popDoubleHex()
|
||||
else { return UIDValidity(exactly: result) }
|
||||
// Widen to `UInt64` _before_ multiplying so an overflowing validity
|
||||
// segment makes the guard below skip the file rather than trapping.
|
||||
let a = UInt64(result) * 256 + UInt64(next)
|
||||
guard
|
||||
let b = UInt32(exactly: a)
|
||||
else { return nil }
|
||||
result = b
|
||||
}
|
||||
}
|
||||
|
||||
fileprivate mutating func popDot() -> Bool {
|
||||
guard first == UTF8.CodeUnit(ascii: ".") else { return false }
|
||||
self = dropFirst()
|
||||
return true
|
||||
}
|
||||
|
||||
fileprivate mutating func popNumber() -> UInt8? {
|
||||
guard
|
||||
let f = first,
|
||||
UTF8.CodeUnit(ascii: "0") <= f,
|
||||
f <= UTF8.CodeUnit(ascii: "9")
|
||||
else { return nil }
|
||||
self = dropFirst()
|
||||
return f - UTF8.CodeUnit(ascii: "0")
|
||||
}
|
||||
|
||||
fileprivate mutating func popDoubleHex() -> UInt8? {
|
||||
guard
|
||||
2 <= count
|
||||
else { return nil }
|
||||
guard
|
||||
let a = self[self.startIndex].hexValue,
|
||||
let b = self[self.index(after: self.startIndex)].hexValue
|
||||
else { return nil }
|
||||
self = dropFirst(2)
|
||||
return a << 4 + b
|
||||
}
|
||||
}
|
||||
|
||||
extension UTF8.CodeUnit {
|
||||
fileprivate var hexValue: UInt8? {
|
||||
switch self {
|
||||
case UTF8.CodeUnit(ascii: "0")...UTF8.CodeUnit(ascii: "9"):
|
||||
self - UTF8.CodeUnit(ascii: "0")
|
||||
case UTF8.CodeUnit(ascii: "a")...UTF8.CodeUnit(ascii: "f"):
|
||||
self - UTF8.CodeUnit(ascii: "a") + 10
|
||||
case UTF8.CodeUnit(ascii: "A")...UTF8.CodeUnit(ascii: "F"):
|
||||
self - UTF8.CodeUnit(ascii: "A") + 10
|
||||
default:
|
||||
nil
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import NIOIMAP
|
||||
|
||||
/// Represents the existing mailbox hierarchy on the server.
|
||||
struct ExistingMailboxHierarchy: Sendable {
|
||||
var paths: [Path]
|
||||
|
||||
struct Path: Sendable {
|
||||
var mailboxPath: MailboxPath
|
||||
var displayStringComponents: [String]
|
||||
}
|
||||
}
|
||||
|
||||
/// A mailbox display name with its associated special-use parameters.
|
||||
struct MailboxDisplayNameWithSpecialUse: Hashable, Sendable {
|
||||
/// The path components of the mailbox display name.
|
||||
var namePath: [String]
|
||||
/// The `CREATE` parameters including special-use attributes.
|
||||
var parameters: [CreateParameter]
|
||||
|
||||
/// Creates a display name with the given path and parameters.
|
||||
init(
|
||||
namePath: [String],
|
||||
parameters: [CreateParameter]
|
||||
) {
|
||||
self.namePath = namePath
|
||||
self.parameters = parameters
|
||||
}
|
||||
}
|
||||
|
||||
/// Describes whether a mailbox already exists or needs creation.
|
||||
enum NewMailboxAction: Hashable, Sendable {
|
||||
/// The mailbox already exists with the given name.
|
||||
case alreadyExists(MailboxName)
|
||||
/// The mailbox needs creation with the given name and parameters.
|
||||
case create(MailboxName, [CreateParameter])
|
||||
}
|
||||
|
||||
extension ExistingMailboxHierarchy {
|
||||
/// Returns the mailbox actions needed to create the given display paths.
|
||||
///
|
||||
/// The returned array orders parent mailboxes before their nested children.
|
||||
func makeMailboxNamesForCreation(
|
||||
_ displayNames: [MailboxDisplayNameWithSpecialUse]
|
||||
) throws -> [NewMailboxAction] {
|
||||
var existing = self
|
||||
let sortedNames =
|
||||
displayNames
|
||||
.sorted(by: {
|
||||
// We sort primarily so that shorter paths come before longer ones; this
|
||||
// guarantees parents are created before their children. For two paths of
|
||||
// equal length we still need a deterministic tiebreaker (so tests are
|
||||
// stable), but we can't sort by lexicographic `String` order — IMAP
|
||||
// mailbox names are byte sequences (RFC 3501 §5.1) and a Unicode-aware
|
||||
// compare can re-order names that differ only in normalization. XOR of
|
||||
// `hashValue`s gives a tiebreaker that doesn't pretend names are strings.
|
||||
let lhs = $0.namePath.count
|
||||
let rhs = $1.namePath.count
|
||||
if lhs < rhs {
|
||||
return true
|
||||
} else if rhs < lhs {
|
||||
return false
|
||||
}
|
||||
return $0.namePath.reduce(into: 0, { $0 = $0 ^ $1.hashValue })
|
||||
< $1.namePath.reduce(into: 0, { $0 = $0 ^ $1.hashValue })
|
||||
})
|
||||
return try sortedNames.map { name in
|
||||
let path = try existing.makeMailboxPath(displayStrings: name.namePath)
|
||||
guard
|
||||
!existing.paths.contains(where: { $0.mailboxPath.name == path.name })
|
||||
else { return .alreadyExists(path.name) }
|
||||
existing.insert(mailboxPath: path)
|
||||
return .create(path.name, name.parameters)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: -
|
||||
|
||||
extension ExistingMailboxHierarchy {
|
||||
/// Creates a new hierarchy from the given mailbox paths.
|
||||
init(
|
||||
mailboxPaths: some Sequence<MailboxPath>
|
||||
) {
|
||||
self.paths = []
|
||||
for p in mailboxPaths {
|
||||
insert(mailboxPath: p)
|
||||
}
|
||||
}
|
||||
|
||||
mutating func insert(
|
||||
mailboxPath new: MailboxPath
|
||||
) {
|
||||
guard
|
||||
!paths.contains(where: { $0.mailboxPath.name == new.name })
|
||||
else { return }
|
||||
paths.append(
|
||||
Path(
|
||||
mailboxPath: new,
|
||||
displayStringComponents: new.displayStringComponents(omittingEmptySubsequences: false)
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
var inbox: Path? {
|
||||
paths.first(where: { $0.mailboxPath.name.isInbox })
|
||||
}
|
||||
|
||||
func bestParent(
|
||||
displayStrings _displayStrings: [String]
|
||||
) -> Path? {
|
||||
let displayStrings =
|
||||
_displayStrings
|
||||
.map { $0.precomposedStringWithCanonicalMapping }
|
||||
guard
|
||||
!displayStrings.isEmpty
|
||||
else { return nil }
|
||||
guard
|
||||
2 <= displayStrings.count
|
||||
else {
|
||||
return nil
|
||||
}
|
||||
return
|
||||
paths
|
||||
.filter { path in
|
||||
guard
|
||||
path.displayStringComponents.count < displayStrings.count
|
||||
else { return false }
|
||||
return Array(displayStrings.prefix(path.displayStringComponents.count)) == path.displayStringComponents
|
||||
}
|
||||
.sorted(by: { $0.displayStringComponents.count > $1.displayStringComponents.count })
|
||||
.first
|
||||
}
|
||||
|
||||
/// Constructs a `MailboxPath` from the given display-name path components.
|
||||
func makeMailboxPath(
|
||||
displayStrings _displayStrings: [String]
|
||||
) throws -> MailboxPath {
|
||||
let displayStrings =
|
||||
_displayStrings
|
||||
.map { $0.precomposedStringWithCanonicalMapping }
|
||||
guard
|
||||
let firstName = displayStrings.first
|
||||
else { throw Error.emptyMailboxPath }
|
||||
guard
|
||||
1 < displayStrings.count
|
||||
else {
|
||||
return try MailboxPath.makeRootMailbox(
|
||||
displayName: firstName,
|
||||
pathSeparator: self.inbox?.mailboxPath.pathSeparator
|
||||
)
|
||||
}
|
||||
|
||||
guard
|
||||
let parent = bestParent(
|
||||
displayStrings: displayStrings
|
||||
)
|
||||
else {
|
||||
guard
|
||||
let pathSeparator = self.inbox?.mailboxPath.pathSeparator
|
||||
else { throw Error.noExistingInbox }
|
||||
|
||||
var result = try MailboxPath.makeRootMailbox(
|
||||
displayName: firstName,
|
||||
pathSeparator: pathSeparator
|
||||
)
|
||||
for name in displayStrings.suffix(from: 1) {
|
||||
result = try result.makeSubMailbox(displayName: name)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
var result = parent.mailboxPath
|
||||
for name in displayStrings.suffix(from: parent.displayStringComponents.count) {
|
||||
result = try result.makeSubMailbox(displayName: name)
|
||||
}
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
extension ExistingMailboxHierarchy {
|
||||
enum Error: Swift.Error {
|
||||
case emptyMailboxPath
|
||||
case noExistingInbox
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import IMAPCommands
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
import NIO
|
||||
import NIOIMAP
|
||||
|
||||
// MARK: - Message Info
|
||||
|
||||
extension ConnectionProtocol {
|
||||
/// Get ``MessageInfo`` for all messages specified by `query`.
|
||||
func fetchMessageInfo(
|
||||
mailboxMessageCount: Int,
|
||||
capabilities: [Capability],
|
||||
query: FetchQuery
|
||||
) async throws -> [MessageInfo] {
|
||||
// Store into a dictionary to make sure the values
|
||||
// are unique per UID -- in case the server returns multiple
|
||||
// replies (commands running in parallel).
|
||||
let all: [UID: MessageInfo]
|
||||
all = try await batchedFetchSimpleAttributes(
|
||||
mailboxMessageCount: mailboxMessageCount,
|
||||
capabilities: capabilities,
|
||||
query: query,
|
||||
attributes: [.uid, .flags, .envelope],
|
||||
into: [:],
|
||||
update: { result, batchResult in
|
||||
for (uid, attr) in batchResult {
|
||||
guard
|
||||
let info = MessageInfo(
|
||||
uid: uid,
|
||||
attributes: attr
|
||||
)
|
||||
else { continue }
|
||||
result[info.uid] = info
|
||||
}
|
||||
}
|
||||
)
|
||||
return all
|
||||
.values
|
||||
.sorted(by: { $0.uid < $1.uid })
|
||||
}
|
||||
|
||||
/// Fetches the given `attributes` for messages specified by `query`, in batches.
|
||||
///
|
||||
/// The `update` closure merges one batch's results into `result`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - mailboxMessageCount: The number of messages in the mailbox.
|
||||
/// - capabilities: The server capabilities.
|
||||
func batchedFetchSimpleAttributes<Result: Sendable>(
|
||||
mailboxMessageCount: Int,
|
||||
capabilities: [Capability],
|
||||
query: FetchQuery,
|
||||
attributes: [FetchAttribute],
|
||||
into result: Result,
|
||||
update: @Sendable (inout Result, [UID: [MessageAttribute]]) throws -> Void
|
||||
) async throws -> Result {
|
||||
return try await batched(
|
||||
query: query,
|
||||
mailboxMessageCount: mailboxMessageCount,
|
||||
capabilities: capabilities,
|
||||
fetch: { batch in
|
||||
let r: [UID: [MessageAttribute]] = try await self.fetchSimpleAttributes(
|
||||
capabilities: capabilities,
|
||||
uids: batch.makeUIDs(query),
|
||||
attributes: attributes,
|
||||
modifiers: batch.fetchModifiers,
|
||||
into: [:]
|
||||
) { all, uid, _, attributes in
|
||||
all[uid] = attributes
|
||||
}
|
||||
return r
|
||||
},
|
||||
into: result,
|
||||
update: update
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Simple Attributes
|
||||
|
||||
extension ConnectionProtocol {
|
||||
/// Sends a `UID FETCH` command for non-streaming message attributes.
|
||||
///
|
||||
/// The `update` closure runs for each `* FETCH` response received.
|
||||
/// Due to command pipelining, responses for other commands may also arrive.
|
||||
func fetchSimpleAttributes<Result: Sendable>(
|
||||
capabilities: [Capability],
|
||||
uids: UIDSet,
|
||||
attributes _attributes: [FetchAttribute],
|
||||
modifiers: [FetchModifier],
|
||||
into result: Result,
|
||||
update: @Sendable (inout Result, UID, SequenceNumber?, [MessageAttribute]) throws -> Void
|
||||
) async throws -> Result {
|
||||
guard
|
||||
_attributes.allSatisfy({ $0.isSimpleAttribute })
|
||||
else {
|
||||
throw FetchAttributeIsNotSimpleAttribute(
|
||||
attributes: _attributes.filter { !$0.isSimpleAttribute }
|
||||
)
|
||||
}
|
||||
|
||||
// Make sure we’re requesting the UID:
|
||||
let attributes: [FetchAttribute] = (_attributes.contains(.uid) ? _attributes : [.uid] + _attributes)
|
||||
|
||||
return try await fetch(
|
||||
capabilities: capabilities,
|
||||
uids: uids,
|
||||
attributes: attributes,
|
||||
modifiers: modifiers,
|
||||
into: ResultWithState(
|
||||
state: .noMessage,
|
||||
result: result
|
||||
)
|
||||
) { result, response in
|
||||
switch (result.state, response) {
|
||||
case (.noMessage, .start(let seq)):
|
||||
result.state = .message(seq, [])
|
||||
case (.noMessage, .startUID(let uid)):
|
||||
result.state = .message(nil, [.uid(uid)])
|
||||
case (_, .start), (_, .startUID):
|
||||
break
|
||||
case (.message(let seq, var attributes), .simpleAttribute(let new)):
|
||||
attributes.append(new)
|
||||
result.state = .message(seq, attributes)
|
||||
case (.noMessage, .simpleAttribute):
|
||||
break
|
||||
case (_, .streamingBegin), (_, .streamingBytes), (_, .streamingEnd):
|
||||
break
|
||||
case (.noMessage, .finish):
|
||||
break
|
||||
case (.message(let seq, let attributes), .finish):
|
||||
defer {
|
||||
result.state = .noMessage
|
||||
}
|
||||
let uid: UID? = attributes
|
||||
.lazy
|
||||
.compactMap {
|
||||
guard case .uid(let uid) = $0 else { return nil }
|
||||
return uid
|
||||
}
|
||||
.first
|
||||
guard
|
||||
let uid,
|
||||
uids.contains(uid)
|
||||
else { break }
|
||||
try update(&result.result, uid, seq, attributes)
|
||||
}
|
||||
}.result
|
||||
}
|
||||
}
|
||||
|
||||
private struct ResultWithState<Result: Sendable>: Sendable {
|
||||
var state: State
|
||||
var result: Result
|
||||
|
||||
enum State: Sendable {
|
||||
case noMessage
|
||||
case message(SequenceNumber?, [MessageAttribute])
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Returns Data
|
||||
|
||||
struct FetchAttributeIsNotSimpleAttribute: Swift.Error {
|
||||
var attributes: [FetchAttribute]
|
||||
}
|
||||
|
||||
extension FetchAttribute {
|
||||
var isSimpleAttribute: Bool {
|
||||
switch self {
|
||||
case .binarySize,
|
||||
.bodyStructure,
|
||||
.emailID,
|
||||
.envelope,
|
||||
.flags,
|
||||
.gmailLabels,
|
||||
.gmailMessageID,
|
||||
.gmailThreadID,
|
||||
.internalDate,
|
||||
.modificationSequence,
|
||||
.modificationSequenceValue,
|
||||
.preview,
|
||||
.rfc822Size,
|
||||
.threadID,
|
||||
.uid:
|
||||
true
|
||||
case .binary,
|
||||
.bodySection,
|
||||
.rfc822,
|
||||
.rfc822Header,
|
||||
.rfc822Text:
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Generic
|
||||
|
||||
extension ConnectionProtocol {
|
||||
/// Sends a `UID FETCH` command.
|
||||
///
|
||||
/// The `update` closure runs for each ``FetchResponse`` received.
|
||||
/// Due to command pipelining, responses for other commands may also arrive.
|
||||
func fetch<Result: Sendable>(
|
||||
capabilities: [Capability],
|
||||
uids _uids: UIDSet,
|
||||
attributes: [FetchAttribute],
|
||||
modifiers: [FetchModifier],
|
||||
into _result: Result,
|
||||
update: @Sendable (inout Result, FetchResponse) throws -> Void
|
||||
) async throws -> Result {
|
||||
guard
|
||||
let uids = UIDSetNonEmpty(set: _uids)
|
||||
else { return _result }
|
||||
|
||||
let command = Command.uidFetch(
|
||||
.set(uids),
|
||||
attributes,
|
||||
modifiers
|
||||
)
|
||||
return try await send(command) { tag, responses -> Result in
|
||||
writeStatus("Did send \(tag) \(command)")
|
||||
var result = _result
|
||||
for try await response in responses {
|
||||
guard
|
||||
case .fetch(let fetch) = response
|
||||
else { continue }
|
||||
try update(&result, fetch)
|
||||
}
|
||||
return result
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import NIOIMAP
|
||||
|
||||
// MARK: - Fixed `[UIDRange]` strategy
|
||||
//
|
||||
// Used when the caller passes `FetchQuery.uids(_)` to `makeBatches(...)` on a server
|
||||
// without RFC 9394 `PARTIAL` support. The requested UIDs are split into ranges of
|
||||
// at most `batchSize` UIDs each, preserving the UID ordering.
|
||||
|
||||
/// Splits the given UIDs into `UIDRange`s with at most `batchSize` UIDs each.
|
||||
func splitUIDsIntoRanges(
|
||||
uids: UIDSet,
|
||||
batchSize: BatchSize
|
||||
) -> [UIDRange] {
|
||||
var ranges: [UIDRange] = []
|
||||
var remaining = uids
|
||||
while !remaining.isEmpty {
|
||||
guard
|
||||
let next = UIDSetNonEmpty(set: remaining.suffix(batchSize.count))
|
||||
else { break }
|
||||
ranges.append(next.min()...next.max())
|
||||
remaining.subtract(UIDSet(next.min()...UID.max))
|
||||
}
|
||||
return ranges
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import NIOIMAP
|
||||
|
||||
// MARK: - `UIDBatchFromBoundaries` strategy
|
||||
//
|
||||
// Used on servers without RFC 9394 `PARTIAL` support for `.all` and `.last(n)`
|
||||
// queries. Because UIDs are not contiguous, we first issue a `SEARCH` on sequence
|
||||
// numbers at batch boundaries (e.g. every 1,000th message) to learn the actual
|
||||
// boundary UIDs, then emit one `.uidRange(low...high)` batch per gap.
|
||||
//
|
||||
// Striding is anchored at the *max* sequence number so the newest batch is full —
|
||||
// callers may use that property to restrict follow-up tasks to the latest batch.
|
||||
|
||||
extension ConnectionProtocol {
|
||||
/// Returns batches by first asking the server for boundary UIDs.
|
||||
///
|
||||
/// Used for `.all` / `.last(n)` queries on servers without RFC 9394 `PARTIAL`.
|
||||
func makeBoundaryFetchBatch(
|
||||
query: FetchQuery,
|
||||
mailboxMessageCount: Int,
|
||||
batchSize: BatchSize,
|
||||
capabilities: [Capability],
|
||||
) async throws -> FetchBatches {
|
||||
func make(count: Int) async throws -> FetchBatches {
|
||||
guard
|
||||
batchSize.count / 2 < count
|
||||
else {
|
||||
writeStatus("Requesting list of latest \(count) UIDs from server")
|
||||
// Run a search to get the UIDs:
|
||||
let uids = try await search(
|
||||
capabilities: capabilities,
|
||||
key: .lastMessages(
|
||||
count: count,
|
||||
mailboxMessageCount: mailboxMessageCount
|
||||
)
|
||||
)
|
||||
guard
|
||||
let a = uids.min(),
|
||||
let b = uids.max()
|
||||
else {
|
||||
writeStatus("No UIDs — mailbox is empty?")
|
||||
return .empty
|
||||
}
|
||||
return .singleBatch(a...b)
|
||||
}
|
||||
// Split up into batches.
|
||||
guard
|
||||
let boundarySequenceNumbers = sequenceNumbersForMessageBatches(
|
||||
mailboxMessageCount: mailboxMessageCount,
|
||||
maximumCount: count,
|
||||
batchSize: batchSize
|
||||
)
|
||||
else {
|
||||
writeStatus("No UIDs — mailbox is empty?")
|
||||
return .empty
|
||||
}
|
||||
writeStatus("Searching for message batches UID boundaries")
|
||||
let boundaryUIDs = try await search(
|
||||
capabilities: capabilities,
|
||||
key: .sequenceNumbers(.set(boundarySequenceNumbers))
|
||||
)
|
||||
writeStatus("Message batch UID boundaries (for \(count) messages): \(boundaryUIDs)")
|
||||
return .fromBoundaries(UIDBatchFromBoundaries(boundaries: boundaryUIDs))
|
||||
}
|
||||
|
||||
switch query {
|
||||
case .last(count: let count):
|
||||
// Honor `count` even on a small mailbox: fetching the whole mailbox to satisfy
|
||||
// a `.last(n)` request would over-fetch. `make(count:)` issues a bounded SEARCH
|
||||
// for (at most) the last `count` messages.
|
||||
return try await make(count: min(count, mailboxMessageCount))
|
||||
case .all:
|
||||
// The whole mailbox is wanted. If it is small enough, fetch it in a single batch
|
||||
// without a boundary SEARCH.
|
||||
guard
|
||||
batchSize.count / 2 < mailboxMessageCount
|
||||
else {
|
||||
writeStatus("Mailbox has very few messages — using a single batch")
|
||||
return .fixed([UID.min...UID.max])
|
||||
}
|
||||
return try await make(count: mailboxMessageCount)
|
||||
case .uids(let uids):
|
||||
let ranges = splitUIDsIntoRanges(
|
||||
uids: uids,
|
||||
batchSize: batchSize
|
||||
)
|
||||
writeStatus("Did split FETCH for \(uids.count) UIDs into \(ranges.count) batch(es) / range(s)")
|
||||
return .fixed(ranges)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Calculate the sequence numbers that should be queried for UIDs, based on the message count.
|
||||
/// - Parameters:
|
||||
/// - mailboxMessageCount: The total number of messages in the mailbox.
|
||||
/// - maximumCount: The number of messages of interest, that is, the number of messages that
|
||||
/// the returned UIDs should span.
|
||||
/// - batchSize: The number of messages in each batch.
|
||||
func sequenceNumbersForMessageBatches(
|
||||
mailboxMessageCount: Int,
|
||||
maximumCount: Int?,
|
||||
batchSize: BatchSize
|
||||
) -> MessageIdentifierSetNonEmpty<SequenceNumber>? {
|
||||
let min: SequenceNumber
|
||||
if let maximumCount, let m = SequenceNumber(exactly: mailboxMessageCount - maximumCount + 1) {
|
||||
min = m
|
||||
} else {
|
||||
min = SequenceNumber.min
|
||||
}
|
||||
guard
|
||||
let max = SequenceNumber(exactly: mailboxMessageCount)
|
||||
else { return nil }
|
||||
|
||||
// We stride starting from max. That way the last (newest) batch
|
||||
// will be (close to) the desired batch size, and we can then
|
||||
// subsequently use that when we want to limit tasks to only operate
|
||||
// on messages in that last batch.
|
||||
var next: SequenceNumber? = max
|
||||
let step = Int64(batchSize.count)
|
||||
let boundaries = AnyIterator {
|
||||
defer {
|
||||
if let n = next, step <= min.distance(to: n) {
|
||||
next = n.advanced(by: -step)
|
||||
} else {
|
||||
next = nil
|
||||
}
|
||||
}
|
||||
return next
|
||||
}
|
||||
var result = SequenceSet(boundaries)
|
||||
result.insert(min)
|
||||
return MessageIdentifierSetNonEmpty(set: result)
|
||||
}
|
||||
|
||||
/// A sequence of `FetchBatch` based on boundary UIDs.
|
||||
///
|
||||
/// The boundary UIDs should be the result of `sequenceNumbersForMessageBatches()`.
|
||||
struct UIDBatchFromBoundaries: Hashable, Sendable {
|
||||
let boundaries: UIDSet
|
||||
}
|
||||
|
||||
extension UIDBatchFromBoundaries: Sequence {
|
||||
typealias Element = FetchBatch
|
||||
|
||||
struct Iterator: IteratorProtocol {
|
||||
let start: UID?
|
||||
var boundaries: ReversedCollection<UIDSet>.Iterator
|
||||
var last: UID?
|
||||
|
||||
mutating func next() -> FetchBatch? {
|
||||
while true {
|
||||
guard
|
||||
let uid = boundaries.next()
|
||||
else { return nil }
|
||||
guard
|
||||
let last
|
||||
else {
|
||||
last = uid
|
||||
continue
|
||||
}
|
||||
self.last = uid
|
||||
guard uid == start else {
|
||||
return .uidRange(uid.advanced(by: 1)...last)
|
||||
}
|
||||
// The last range has to include the last UID
|
||||
return .uidRange(uid...last)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func makeIterator() -> Iterator {
|
||||
Iterator(
|
||||
start: boundaries.first,
|
||||
boundaries: boundaries.reversed().makeIterator()
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import NIOIMAP
|
||||
|
||||
// MARK: - `PartialFetchBatches` strategy (RFC 9394 “Partial”)
|
||||
//
|
||||
// Used when the server supports RFC 9394 `PARTIAL`. Each batch is a
|
||||
// `.partialLast(start...end)` referring to a window counted from the *end* of the
|
||||
// mailbox (so `1` is the newest message). This avoids any preliminary SEARCH —
|
||||
// the server resolves the window itself.
|
||||
//
|
||||
// `PartialFetchBatches` is the `Sequence` that walks from the newest message
|
||||
// back to `last`, emitting one `.partialLast` batch per step of `batchSize`.
|
||||
|
||||
/// Returns batches based on RFC 9394 “Partial” ranges.
|
||||
///
|
||||
/// No preliminary `SEARCH` is needed — each batch resolves on the server.
|
||||
func makePartialFetchBatch(
|
||||
query: FetchQuery,
|
||||
mailboxMessageCount: Int,
|
||||
batchSize: BatchSize
|
||||
) -> FetchBatches {
|
||||
guard
|
||||
let batches = PartialFetchBatches(
|
||||
query: query,
|
||||
mailboxMessageCount: mailboxMessageCount,
|
||||
batchSize: batchSize
|
||||
)
|
||||
else { return .empty }
|
||||
return .partial(batches)
|
||||
}
|
||||
|
||||
/// A sequence of `FetchBatch` for a server that supports RFC 9394 “Partial”.
|
||||
struct PartialFetchBatches: Hashable, Sendable {
|
||||
/// The last message to include in the sequence.
|
||||
///
|
||||
/// Note that 1 (`.min`) refers to the last message in the mailbox, whereas e.g
|
||||
/// 1,000 would refer to the 1,000th message _from the end_ of the mailbox.
|
||||
let last: SequenceNumber
|
||||
let batchSize: BatchSize
|
||||
}
|
||||
|
||||
extension PartialFetchBatches {
|
||||
init?(
|
||||
query: FetchQuery,
|
||||
mailboxMessageCount: Int,
|
||||
batchSize: BatchSize
|
||||
) {
|
||||
guard
|
||||
0 < mailboxMessageCount
|
||||
else { return nil }
|
||||
switch query {
|
||||
case .last(count: let c):
|
||||
guard
|
||||
let l = SequenceNumber(exactly: Swift.min(c, mailboxMessageCount))
|
||||
else { return nil }
|
||||
self.last = l
|
||||
case .uids(let uids):
|
||||
guard
|
||||
let l = SequenceNumber(exactly: Swift.min(uids.count, mailboxMessageCount))
|
||||
else { return nil }
|
||||
self.last = l
|
||||
case .all:
|
||||
self.last = SequenceNumber.min.advanced(by: Int64(mailboxMessageCount - 1))
|
||||
}
|
||||
self.batchSize = batchSize
|
||||
}
|
||||
}
|
||||
|
||||
extension PartialFetchBatches: Sequence {
|
||||
typealias Element = FetchBatch
|
||||
|
||||
struct Iterator: IteratorProtocol {
|
||||
let last: SequenceNumber
|
||||
let batchSize: BatchSize
|
||||
var index = 0
|
||||
|
||||
mutating func next() -> FetchBatch? {
|
||||
let range = batchSize.partialRange(batch: index)
|
||||
guard
|
||||
range.lowerBound <= last
|
||||
else { return nil }
|
||||
let end = Swift.min(last, range.upperBound)
|
||||
index += 1
|
||||
return .partialLast(NIOIMAP.PartialRange.last(range.lowerBound...end))
|
||||
}
|
||||
|
||||
typealias Element = FetchBatch
|
||||
}
|
||||
|
||||
func makeIterator() -> Iterator {
|
||||
Iterator(
|
||||
last: last,
|
||||
batchSize: batchSize
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import NIOIMAP
|
||||
|
||||
// MARK: - How batching works
|
||||
//
|
||||
// IMAP `UID FETCH` and `UID SEARCH` operate on potentially huge mailboxes. To stay
|
||||
// within server limits (`MESSAGELIMIT`, RFC 9738) and to keep memory bounded, we
|
||||
// partition the messages of interest into a sequence of `FetchBatch` values and
|
||||
// issue one server round-trip per batch.
|
||||
//
|
||||
// `makeBatches(...)` picks one of three strategies based on the server capabilities
|
||||
// and the shape of the request:
|
||||
//
|
||||
// ┌──────────────────────────────────────────────────────────────────────┐
|
||||
// │ Server supports RFC 9394 `PARTIAL` ? │
|
||||
// │ │
|
||||
// │ yes ──► `PartialFetchBatches` ── see `FetchBatch+Partial.swift` │
|
||||
// │ (`.partialLast(range)`, no extra SEARCH needed) │
|
||||
// │ │
|
||||
// │ no ──► one of two `UID range` strategies: │
|
||||
// │ │
|
||||
// │ query = .uids(_) ──► fixed `[UIDRange]` from the requested UIDs │
|
||||
// │ ── see `FetchBatch+Fixed.swift` │
|
||||
// │ │
|
||||
// │ query = .all / .last(n) ──► `UIDBatchFromBoundaries` │
|
||||
// │ ── see `FetchBatch+FromBoundaries` │
|
||||
// │ (one SEARCH for boundary UIDs first) │
|
||||
// └──────────────────────────────────────────────────────────────────────┘
|
||||
//
|
||||
// Each strategy is implemented as its own `Sequence` of `FetchBatch` in a sibling
|
||||
// file. `FetchBatches` is the enum that unifies them so callers can iterate without
|
||||
// caring which strategy was chosen.
|
||||
|
||||
/// Describes a batch of messages to fetch or search with `UID FETCH` or `UID SEARCH`.
|
||||
///
|
||||
/// Supports RFC 9394 partial ranges or regular UID ranges.
|
||||
/// Create batches using the `makeBatches()` function, which selects the best strategy
|
||||
/// based on server capabilities.
|
||||
enum FetchBatch: Hashable, Sendable {
|
||||
/// A range of UIDs.
|
||||
case uidRange(UIDRange)
|
||||
/// A range using RFC 9394 “Partial”
|
||||
case partialLast(NIOIMAP.PartialRange)
|
||||
}
|
||||
|
||||
extension FetchBatch {
|
||||
func makeUIDs(_ query: FetchQuery) -> UIDSet {
|
||||
switch (self, query) {
|
||||
case (.uidRange(let range), .last),
|
||||
(.uidRange(let range), .all):
|
||||
return UIDSet(range)
|
||||
case (.uidRange(let range), .uids(let allUIDs)):
|
||||
return allUIDs.intersection(UIDSet(range))
|
||||
case (.partialLast, .last),
|
||||
(.partialLast, .all):
|
||||
return .all
|
||||
case (.partialLast, .uids(let allUIDs)):
|
||||
return allUIDs
|
||||
}
|
||||
}
|
||||
|
||||
var fetchModifiers: [FetchModifier] {
|
||||
switch self {
|
||||
case .uidRange: []
|
||||
case .partialLast(let range): [FetchModifier.partial(range)]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Make Sequence
|
||||
|
||||
extension ConnectionProtocol {
|
||||
/// Returns a `FetchBatches` (that is, a `Sequence` of `FetchBatch`) based on the server capabilities.
|
||||
///
|
||||
/// This spans the messages based on `query` and `mailboxMessageCount`.
|
||||
func makeBatches(
|
||||
query: FetchQuery,
|
||||
mailboxMessageCount: Int,
|
||||
capabilities: [Capability]
|
||||
) async throws -> FetchBatches {
|
||||
let batchSize = BatchSize(capabilities: capabilities)
|
||||
guard capabilities.contains(.partial) else {
|
||||
return try await makeBoundaryFetchBatch(
|
||||
query: query,
|
||||
mailboxMessageCount: mailboxMessageCount,
|
||||
batchSize: batchSize,
|
||||
capabilities: capabilities
|
||||
)
|
||||
}
|
||||
return makePartialFetchBatch(
|
||||
query: query,
|
||||
mailboxMessageCount: mailboxMessageCount,
|
||||
batchSize: batchSize
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Sequence(s)
|
||||
|
||||
/// Describes the batches that we split the `FETCH` into.
|
||||
enum FetchBatches {
|
||||
case fixed([UIDRange])
|
||||
case partial(PartialFetchBatches)
|
||||
case fromBoundaries(UIDBatchFromBoundaries)
|
||||
|
||||
static var empty: FetchBatches {
|
||||
FetchBatches.fixed([])
|
||||
}
|
||||
|
||||
static func singleBatch(_ r: UIDRange) -> FetchBatches {
|
||||
FetchBatches.fixed([r])
|
||||
}
|
||||
}
|
||||
|
||||
extension FetchBatches: Sequence {
|
||||
func makeIterator() -> Iterator {
|
||||
switch self {
|
||||
case .fixed(let u):
|
||||
Iterator(underlying: u.map { FetchBatch.uidRange($0) }.makeIterator())
|
||||
case .partial(let u):
|
||||
Iterator(underlying: u.makeIterator())
|
||||
case .fromBoundaries(let u):
|
||||
Iterator(underlying: u.makeIterator())
|
||||
}
|
||||
}
|
||||
|
||||
struct Iterator: IteratorProtocol {
|
||||
var underlying: any IteratorProtocol<FetchBatch>
|
||||
typealias Element = FetchBatch
|
||||
mutating func next() -> FetchBatch? {
|
||||
underlying.next()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import ArgumentParser
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
import NIO
|
||||
import NIOIMAP
|
||||
|
||||
/// Which messages to operate on.
|
||||
enum FetchQuery: Hashable, Sendable {
|
||||
/// Fetches the specific UIDs.
|
||||
case uids(UIDSet)
|
||||
/// Fetches the last `count` messages in a mailbox.
|
||||
case last(count: Int)
|
||||
/// Fetches all messages.
|
||||
case all
|
||||
}
|
||||
|
||||
extension ConnectionProtocol {
|
||||
/// Determines the best combination of `UIDSet` and `[FetchModifier]` to operate on messages in the mailbox.
|
||||
///
|
||||
/// Use this for `UID FETCH`, `UID SEARCH`, and similar commands. This helper checks which capabilities
|
||||
/// the server supports, and picks the best approach to split the work into multiple ranges or multiple
|
||||
/// `UID FETCH` commands.
|
||||
///
|
||||
/// It does not perform the `UID FETCH` itself, but repeatedly calls the `fetch` closure to do any fetching,
|
||||
/// and the `update` closure to collect results.
|
||||
func batched<InnerResult: Sendable, Result: Sendable>(
|
||||
query: FetchQuery,
|
||||
mailboxMessageCount: Int,
|
||||
capabilities: [Capability],
|
||||
fetch: @Sendable @escaping (FetchBatch) async throws -> InnerResult,
|
||||
into _result: Result,
|
||||
update: @Sendable (inout Result, InnerResult) throws -> Void
|
||||
) async throws -> Result {
|
||||
let batches = try await makeBatches(
|
||||
query: query,
|
||||
mailboxMessageCount: mailboxMessageCount,
|
||||
capabilities: capabilities
|
||||
)
|
||||
// Run multiple concurrently:
|
||||
let maxConcurrentTasks = 11
|
||||
return try await withThrowingTaskGroup(
|
||||
of: InnerResult.self,
|
||||
returning: Result.self
|
||||
) { group in
|
||||
var batchIterator = batches.makeIterator()
|
||||
|
||||
// A helper that does the actual work:
|
||||
func addTask() {
|
||||
guard let batch = batchIterator.next() else { return }
|
||||
group.addTask {
|
||||
try await fetch(batch)
|
||||
}
|
||||
}
|
||||
|
||||
// Start the first set of tasks:
|
||||
for _ in 0..<maxConcurrentTasks {
|
||||
addTask()
|
||||
}
|
||||
|
||||
var result = _result
|
||||
while let innerResult = try await group.next() {
|
||||
try update(&result, innerResult)
|
||||
// Start the next task:
|
||||
addTask()
|
||||
}
|
||||
return result
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: -
|
||||
|
||||
/// A helper that provides flexible `FetchQuery` parsing as an `@OptionGroup` for `ArgumentParser`.
|
||||
struct FetchQueryGroup: ParsableArguments, Sendable {
|
||||
init() {}
|
||||
|
||||
@Option(
|
||||
help: """
|
||||
The number of messages to get.
|
||||
"""
|
||||
)
|
||||
/// The number of messages to fetch, or `nil` to use the default.
|
||||
var count: Int?
|
||||
|
||||
@ArgumentParser.Flag(
|
||||
help: "Get all messages."
|
||||
)
|
||||
var all: Bool = false
|
||||
|
||||
mutating func validate() throws {
|
||||
// Validation logic lives in `makeFetchQuery()`; building and discarding
|
||||
// the result is the simplest way to surface any thrown error here.
|
||||
_ = try self.makeFetchQuery()
|
||||
}
|
||||
|
||||
/// Creates a `FetchQuery` from the parsed arguments.
|
||||
func makeFetchQuery() throws -> FetchQuery {
|
||||
switch (count, all) {
|
||||
case (nil, false):
|
||||
// Default to “last 20”:
|
||||
return .last(count: 20)
|
||||
case (let c?, false):
|
||||
return .last(count: c)
|
||||
case (nil, true):
|
||||
return .all
|
||||
case (.some, true):
|
||||
throw ValidationError("Must not specify both --count and --all.")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import IMAPCommands
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
import NIO
|
||||
import NIOIMAP
|
||||
import OrderedCollections
|
||||
|
||||
extension ConnectionProtocol {
|
||||
/// Sends an `ID` command and returns the server's identity information.
|
||||
func identify(
|
||||
capabilities: [Capability]
|
||||
) async throws -> Identity {
|
||||
guard
|
||||
capabilities.contains(.id)
|
||||
else { return Identity(capabilities: capabilities) }
|
||||
|
||||
return try await send(.id(clientID)) { _, responses -> Identity in
|
||||
var result = Identity(
|
||||
capabilities: capabilities
|
||||
)
|
||||
_ = try await responses.forEach { response in
|
||||
guard
|
||||
case .untagged(.id(let id)) = response
|
||||
else { return }
|
||||
result.serverID = Dictionary(uniqueKeysWithValues: id.map { ($0.key, $0.value) })
|
||||
}.getOK()
|
||||
return result
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private let clientID: OrderedDictionary<String, String?> = [
|
||||
"name": "imap-tool",
|
||||
"os": Identity.operatingSystemName,
|
||||
"os-version": Identity.operatingSystemVersion,
|
||||
]
|
||||
@@ -0,0 +1,108 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import IMAPCommands
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
import NIO
|
||||
import NIOIMAP
|
||||
#if canImport(Darwin)
|
||||
import Darwin
|
||||
#else
|
||||
import Glibc
|
||||
import SystemPackage
|
||||
#endif
|
||||
|
||||
/// The identity of a server, including its `ID` response and capabilities.
|
||||
struct Identity: Hashable, Sendable {
|
||||
/// The key-value pairs from the server’s `ID` response.
|
||||
var serverID: [String: String?]
|
||||
/// The capabilities advertised by the server.
|
||||
var capabilities: [Capability]
|
||||
|
||||
/// Creates a new identity with the given server ID and capabilities.
|
||||
init(
|
||||
serverID: [String: String?] = [:],
|
||||
capabilities: [Capability]
|
||||
) {
|
||||
self.serverID = serverID
|
||||
self.capabilities = capabilities
|
||||
}
|
||||
}
|
||||
|
||||
#if canImport(Darwin)
|
||||
|
||||
extension Identity {
|
||||
static var operatingSystemName: String? {
|
||||
systemInformation(name: "kern.ostype")
|
||||
}
|
||||
|
||||
static var operatingSystemVersion: String? {
|
||||
systemInformation(name: "kern.osproductversion")
|
||||
}
|
||||
}
|
||||
|
||||
/// Retrieves system information by name. Wraps `sysctlbyname(3)`.
|
||||
private func systemInformation(name: String) -> String? {
|
||||
name.withCString { _name -> String? in
|
||||
withUnsafeTemporaryAllocation(of: UInt8.self, capacity: 200) { buffer -> String? in
|
||||
var count = buffer.count
|
||||
guard sysctlbyname(_name, buffer.baseAddress, &count, nil, 0) == 0
|
||||
else { return nil }
|
||||
guard 0 < count else { return nil }
|
||||
// sysctlbyname includes a trailing NUL in the byte count.
|
||||
return String(decoding: buffer.prefix(count - 1), as: UTF8.self)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#else
|
||||
|
||||
extension Identity {
|
||||
static var operatingSystemName: String? {
|
||||
systemInformation(name: "ostype")
|
||||
}
|
||||
|
||||
static var operatingSystemVersion: String? {
|
||||
systemInformation(name: "osrelease")
|
||||
}
|
||||
}
|
||||
|
||||
/// Retrieves system information by name. Reads from `/proc/sys/kernel/`.
|
||||
private func systemInformation(name: String) -> String? {
|
||||
let url = URL(fileURLWithPath: "/proc/sys/kernel/\(name)")
|
||||
guard
|
||||
let data = try? Data(contentsOf: url),
|
||||
let text = String(data: data, encoding: .utf8)
|
||||
else { return nil }
|
||||
return text.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
extension Identity: Encodable {
|
||||
func encode(to encoder: Encoder) throws {
|
||||
var c = encoder.container(keyedBy: CodingKeys.self)
|
||||
try c.encode(self.serverID, forKey: .id)
|
||||
try c.encode(self.capabilities.map { String($0) }, forKey: .capabilities)
|
||||
}
|
||||
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case id
|
||||
case capabilities
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import IMAPCommands
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
import NIO
|
||||
import NIOIMAP
|
||||
|
||||
extension IMAPConnection {
|
||||
/// Runs an `IDLE` command and passes the event stream to the given closure.
|
||||
func runIdle<Result: Sendable>(
|
||||
_ closure: (IMAPConnection.Tag, IdleEventStream) async throws -> Result
|
||||
) async throws -> Result {
|
||||
try await sendIdle { tag, responses in
|
||||
writeStatus("Running IDLE as \(tag)")
|
||||
let r = try await closure(tag, IdleEventStream(underlying: responses))
|
||||
writeStatus("Did run IDLE")
|
||||
return r
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Event
|
||||
|
||||
/// An event received during an `IDLE` session.
|
||||
enum IdleEvent: Equatable, Sendable {
|
||||
/// The mailbox now contains this many messages.
|
||||
case exists(Int)
|
||||
/// The message at this sequence number was expunged.
|
||||
case expunge(SequenceNumber)
|
||||
/// The given UIDs were removed (via `VANISHED`).
|
||||
case vanished(UIDSet)
|
||||
/// A `FETCH` response with the given attributes.
|
||||
case fetch(SequenceNumber?, [MessageAttribute])
|
||||
}
|
||||
|
||||
extension IdleEvent: Encodable {
|
||||
/// Encodes the event into a format that is straightforward to read and parse.
|
||||
func encode(to encoder: any Encoder) throws {
|
||||
var container = encoder.container(keyedBy: CodingKeys.self)
|
||||
try container.encode(kind, forKey: .kind)
|
||||
switch self {
|
||||
case .exists(let count):
|
||||
try container.encode(count, forKey: .count)
|
||||
case .expunge(let seq):
|
||||
try container.encode(UInt32(seq), forKey: .sequenceNumber)
|
||||
case .vanished(let uids):
|
||||
// Two encodings:
|
||||
// - `uids` — the canonical IMAP wire form (e.g. `"1:5,7,9:12"`),
|
||||
// for clients that prefer the compact range syntax.
|
||||
// - `uidsList` — a fully-expanded JSON array of UIDs, for clients
|
||||
// that don't want to parse the IMAP grammar.
|
||||
//
|
||||
// `debugDescription` on `MessageIdentifierSet` produces the wire
|
||||
// form by running its IMAP encoder, so this is stable across runs.
|
||||
try container.encode(uids.debugDescription, forKey: .uids)
|
||||
try container.encode(uids.map { UInt32($0) }, forKey: .uidsList)
|
||||
case .fetch(let seq, let attributes):
|
||||
try container.encodeIfPresent(seq.map { UInt32($0) }, forKey: .sequenceNumber)
|
||||
// We need to keep track of what (which keys) we’ve already added.
|
||||
// We might receive the same key multiple times, but we can only encode it once.
|
||||
var allKeys = Set<CodingKeys>()
|
||||
|
||||
func check(key: CodingKeys) -> Bool {
|
||||
guard !allKeys.contains(key) else { return false }
|
||||
allKeys.insert(key)
|
||||
return true
|
||||
}
|
||||
|
||||
for attr in attributes {
|
||||
switch attr {
|
||||
case .flags(let flags):
|
||||
guard check(key: .flags) else { continue }
|
||||
try container.encode(flags.map { String($0) }, forKey: .flags)
|
||||
case .uid(let uid):
|
||||
guard check(key: .uid) else { continue }
|
||||
try container.encode(UInt32(uid), forKey: .uid)
|
||||
case .rfc822Size(let count):
|
||||
guard check(key: .rfc822Size) else { continue }
|
||||
try container.encode(count, forKey: .rfc822Size)
|
||||
case .fetchModificationSequence(let modSeq):
|
||||
guard check(key: .fetchModificationResponse) else { continue }
|
||||
try container.encode(UInt64(modSeq), forKey: .fetchModificationResponse)
|
||||
case .gmailMessageID(let id):
|
||||
guard check(key: .gmailMessageID) else { continue }
|
||||
try container.encode(id, forKey: .gmailMessageID)
|
||||
case .gmailThreadID(let id):
|
||||
guard check(key: .gmailThreadID) else { continue }
|
||||
try container.encode(id, forKey: .gmailThreadID)
|
||||
case .gmailLabels(let labels):
|
||||
guard check(key: .gmailLabels) else { continue }
|
||||
try container.encode(labels.map { $0.makeDisplayString() }, forKey: .gmailLabels)
|
||||
case .preview(let preview):
|
||||
guard check(key: .preview) else { continue }
|
||||
try container.encode(preview.map { String($0) }, forKey: .preview)
|
||||
case .emailID(let id):
|
||||
guard check(key: .emailID) else { continue }
|
||||
try container.encode(String(id), forKey: .emailID)
|
||||
case .threadID(let id):
|
||||
guard check(key: .threadID) else { continue }
|
||||
try container.encode(id.map { String($0) }, forKey: .threadID)
|
||||
default:
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var kind: String {
|
||||
switch self {
|
||||
case .exists: "exists"
|
||||
case .expunge: "expunge"
|
||||
case .vanished: "vanished"
|
||||
case .fetch: "fetch"
|
||||
}
|
||||
}
|
||||
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case kind
|
||||
case count
|
||||
case sequenceNumber
|
||||
case uids
|
||||
case uidsList
|
||||
|
||||
case flags
|
||||
case uid
|
||||
case rfc822Size
|
||||
case fetchModificationResponse
|
||||
case gmailMessageID
|
||||
case gmailThreadID
|
||||
case gmailLabels
|
||||
case preview
|
||||
case emailID
|
||||
case threadID
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Event Decoder
|
||||
|
||||
enum IdleEventDecoder: Sendable {
|
||||
case normal
|
||||
case fetch(SequenceNumber?, [MessageAttribute])
|
||||
}
|
||||
|
||||
extension IdleEventDecoder {
|
||||
mutating func update(
|
||||
_ response: Response
|
||||
) -> IdleEvent? {
|
||||
switch (self, response) {
|
||||
case (.normal, .fetch(.start(let seq))):
|
||||
self = .fetch(seq, [])
|
||||
return nil
|
||||
case (.normal, .fetch(.startUID(let uid))):
|
||||
self = .fetch(nil, [.uid(uid)])
|
||||
return nil
|
||||
case (.fetch(let seq, var attr), .fetch(.simpleAttribute(let new))):
|
||||
attr.append(new)
|
||||
self = .fetch(seq, attr)
|
||||
return nil
|
||||
case (.fetch(let seq, let attr), .fetch(.finish)):
|
||||
self = .normal
|
||||
return .fetch(seq, attr)
|
||||
case (.fetch, .fetch(.streamingBegin)),
|
||||
(.fetch, .fetch(.streamingBytes)),
|
||||
(.fetch, .fetch(.streamingEnd)):
|
||||
// Ignore bytes being streamed
|
||||
return nil
|
||||
case (.fetch, _):
|
||||
// We received something that’s not part of FETCH. Should not happen, but ignore.
|
||||
return nil
|
||||
case (.normal, .fetch):
|
||||
// Should not happen, but ignore.
|
||||
return nil
|
||||
case (.normal, .untagged(.mailboxData(.exists(let count)))):
|
||||
return .exists(count)
|
||||
case (.normal, .untagged(.messageData(.expunge(let seq)))):
|
||||
return .expunge(seq)
|
||||
case (.normal, .untagged(.messageData(.vanished(let uids)))):
|
||||
return .vanished(uids)
|
||||
case (.normal, _):
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Idle Stream
|
||||
|
||||
/// An async sequence that transforms raw IMAP responses into `IdleEvent` values.
|
||||
struct IdleEventStream: AsyncSequence, Sendable {
|
||||
/// The iterator that decodes responses into idle events.
|
||||
struct AsyncIterator: AsyncIteratorProtocol {
|
||||
typealias Element = IdleEvent
|
||||
|
||||
var underlying: IMAPConnection.ResponseStream.AsyncIterator
|
||||
var decoder = IdleEventDecoder.normal
|
||||
|
||||
mutating func next() async throws -> IdleEvent? {
|
||||
while let response = try await underlying.next() {
|
||||
guard
|
||||
let event = decoder.update(response)
|
||||
else { continue }
|
||||
writeStatus("Did receive '\(event.kind)' during IDLE")
|
||||
return event
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
typealias Element = IdleEvent
|
||||
|
||||
let underlying: IMAPConnection.ResponseStream
|
||||
|
||||
func makeAsyncIterator() -> AsyncIterator {
|
||||
AsyncIterator(underlying: underlying.makeAsyncIterator())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,390 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import IMAPCommands
|
||||
import AsyncAlgorithms
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
import NIO
|
||||
import NIOIMAP
|
||||
|
||||
extension ConnectionProtocol {
|
||||
/// Runs `LIST` and `STATUS` on all mailboxes for the account.
|
||||
///
|
||||
/// Uses `LIST-STATUS` (RFC 5819) if available, or falls back to separate `LIST` and `STATUS` commands
|
||||
/// based on the capabilities of the server.
|
||||
func listMailboxes(
|
||||
capabilities: [Capability]
|
||||
) async throws -> [MailboxInfoAndStatus] {
|
||||
try await list(
|
||||
capabilities: capabilities,
|
||||
target: .allMailboxes
|
||||
)
|
||||
}
|
||||
|
||||
func listMailbox(
|
||||
capabilities: [Capability],
|
||||
mailbox: MailboxName
|
||||
) async throws -> MailboxInfoAndStatus? {
|
||||
let allInfo = try await list(
|
||||
capabilities: capabilities,
|
||||
target: .specific(mailbox)
|
||||
)
|
||||
return allInfo.first(where: { $0.path.name == mailbox })
|
||||
}
|
||||
}
|
||||
|
||||
enum ListTarget: Hashable, Sendable {
|
||||
case allMailboxes
|
||||
case specific(MailboxName)
|
||||
}
|
||||
|
||||
extension ConnectionProtocol {
|
||||
func list(
|
||||
capabilities: [Capability],
|
||||
target: ListTarget
|
||||
) async throws -> [MailboxInfoAndStatus] {
|
||||
let strategy = ListStatusStrategy(
|
||||
capabilities: capabilities
|
||||
)
|
||||
|
||||
switch strategy.kind {
|
||||
case .listThenStatus:
|
||||
let listInfo = try await list(
|
||||
target: target,
|
||||
listReturnOptions: strategy.listReturnOptions
|
||||
)
|
||||
let statusInfo = try await status(
|
||||
mailboxes: listInfo.keys.lazy.map { $0.name },
|
||||
statusAttributes: strategy.statusAttributes
|
||||
)
|
||||
return combineListAndStatus(
|
||||
listInfo: listInfo,
|
||||
statusInfo: statusInfo
|
||||
)
|
||||
case .listStatus:
|
||||
return try await listStatus(
|
||||
target: target,
|
||||
listReturnOptions: strategy.listReturnOptions,
|
||||
statusAttributes: strategy.statusAttributes
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Strategy
|
||||
|
||||
struct ListStatusStrategy: Hashable, Sendable {
|
||||
var listReturnOptions: [ReturnOption]
|
||||
var statusAttributes: [MailboxAttribute]
|
||||
var kind: Kind
|
||||
|
||||
enum Kind: Hashable, Sendable {
|
||||
/// Run LIST followed by STATUS for each mailbox
|
||||
case listThenStatus
|
||||
/// Run LIST-STATUS
|
||||
case listStatus
|
||||
}
|
||||
}
|
||||
|
||||
extension ListStatusStrategy {
|
||||
init(
|
||||
capabilities: [Capability]
|
||||
) {
|
||||
self.init(
|
||||
listReturnOptions: [],
|
||||
statusAttributes: [
|
||||
.messageCount,
|
||||
.uidNext,
|
||||
.uidValidity,
|
||||
.unseenCount,
|
||||
],
|
||||
kind: .listThenStatus
|
||||
)
|
||||
|
||||
// RFC 5162
|
||||
if capabilities.contains(.condStore) {
|
||||
statusAttributes.append(.highestModificationSequence)
|
||||
}
|
||||
// RFC 6154
|
||||
if capabilities.contains(.specialUse) {
|
||||
listReturnOptions.append(.specialUse)
|
||||
}
|
||||
// RFC 7889
|
||||
// Disabled for now. Many servers fail on this.
|
||||
if false && capabilities.contains(where: { $0.name == "APPENDLIMIT" }) {
|
||||
statusAttributes.append(.appendLimit)
|
||||
}
|
||||
// RFC 8438 "STATUS=SIZE"
|
||||
if capabilities.contains(Capability("STATUS=SIZE")) {
|
||||
statusAttributes.append(.size)
|
||||
}
|
||||
// RFC 5819 “LIST-STATUS”
|
||||
kind = capabilities.contains(.listStatus) ? .listStatus : .listThenStatus
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - List then Status
|
||||
|
||||
private func combineListAndStatus(
|
||||
listInfo: [MailboxPath: [MailboxInfo.Attribute]],
|
||||
statusInfo: [MailboxName: MailboxStatus]
|
||||
) -> [MailboxInfoAndStatus] {
|
||||
return
|
||||
listInfo
|
||||
.reduce(into: []) { all, list in
|
||||
all.append(
|
||||
MailboxInfoAndStatus(
|
||||
path: list.key,
|
||||
attributes: Set(list.value),
|
||||
status: statusInfo[list.key.name]
|
||||
)
|
||||
)
|
||||
}
|
||||
.sorted {
|
||||
stableCompare($0.path.name, $1.path.name)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: -
|
||||
|
||||
/// The combined result of `LIST` and `STATUS` for a single mailbox.
|
||||
struct MailboxInfoAndStatus: Hashable, Sendable {
|
||||
/// The mailbox path including its separator.
|
||||
var path: MailboxPath
|
||||
/// The mailbox attributes from `LIST`.
|
||||
var attributes: Set<MailboxInfo.Attribute>
|
||||
/// The mailbox status from `STATUS`, if available.
|
||||
var status: MailboxStatus?
|
||||
}
|
||||
|
||||
extension MailboxInfoAndStatus {
|
||||
/// An encodable representation of mailbox information and status.
|
||||
struct EncodableInfo: Encodable, Sendable {
|
||||
/// The raw mailbox name as a string.
|
||||
var name: String?
|
||||
/// The path separator character.
|
||||
var pathSeparator: String?
|
||||
/// The display name split into path components.
|
||||
var displayName: [String]
|
||||
/// The mailbox attributes as strings.
|
||||
var attributes: [String]
|
||||
|
||||
/// The total number of messages in the mailbox.
|
||||
var messageCount: Int?
|
||||
/// The predicted next UID value.
|
||||
var nextUID: UInt32?
|
||||
/// The UID validity value for the mailbox.
|
||||
var uidValidity: UInt32?
|
||||
/// The number of unseen messages.
|
||||
var unseenCount: Int?
|
||||
/// The highest modification sequence value.
|
||||
var highestModificationSequence: UInt64?
|
||||
/// The per-message append size limit, if the server reports one.
|
||||
var appendLimit: Int?
|
||||
}
|
||||
}
|
||||
|
||||
extension MailboxInfoAndStatus.EncodableInfo {
|
||||
/// Creates an encodable representation from a `MailboxInfoAndStatus`.
|
||||
init(_ other: MailboxInfoAndStatus) {
|
||||
self.init(
|
||||
name: String(validating: other.path.name.bytes, as: UTF8.self),
|
||||
pathSeparator: other.path.pathSeparator.map { String($0) },
|
||||
displayName: other.path.displayStringComponents(omittingEmptySubsequences: false),
|
||||
attributes: other.attributes.map { String($0) }.sorted(),
|
||||
messageCount: other.status?.messageCount,
|
||||
nextUID: (other.status?.nextUID).map { UInt32($0) },
|
||||
uidValidity: (other.status?.uidValidity).map { UInt32($0) },
|
||||
unseenCount: other.status?.unseenCount,
|
||||
highestModificationSequence: (other.status?.highestModificationSequence).map { UInt64($0) },
|
||||
appendLimit: other.status?.appendLimit
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: -
|
||||
|
||||
extension Command {
|
||||
fileprivate static func list(
|
||||
target: ListTarget,
|
||||
returnOptions: [ReturnOption]
|
||||
) -> Command {
|
||||
switch target {
|
||||
case .allMailboxes: .listAllMailboxes(returnOptions: returnOptions)
|
||||
case .specific(let name): .listMailbox(mailbox: name, returnOptions: returnOptions)
|
||||
}
|
||||
}
|
||||
|
||||
fileprivate static func listAllMailboxes(
|
||||
returnOptions: [ReturnOption]
|
||||
) -> Command {
|
||||
Command.listIndependent(
|
||||
[],
|
||||
reference: MailboxName([]),
|
||||
.mailbox(ByteBuffer(string: "*")),
|
||||
returnOptions
|
||||
)
|
||||
}
|
||||
|
||||
fileprivate static func listMailbox(
|
||||
mailbox: MailboxName,
|
||||
returnOptions: [ReturnOption]
|
||||
) -> Command {
|
||||
Command.listIndependent(
|
||||
[],
|
||||
reference: MailboxName([]),
|
||||
.mailbox(ByteBuffer(bytes: mailbox.bytes)),
|
||||
returnOptions
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
extension ConnectionProtocol {
|
||||
private func list(
|
||||
target: ListTarget,
|
||||
listReturnOptions: [ReturnOption]
|
||||
) async throws -> [MailboxPath: [MailboxInfo.Attribute]] {
|
||||
let command = Command.list(
|
||||
target: target,
|
||||
returnOptions: listReturnOptions
|
||||
)
|
||||
return try await send(command) { tag, responses in
|
||||
var all: [MailboxPath: [MailboxInfo.Attribute]] = [:]
|
||||
for try await response in responses {
|
||||
switch response {
|
||||
case .untagged(.mailboxData(.list(let info))):
|
||||
all[info.path] = info.attributes
|
||||
case .tagged(let r):
|
||||
try r.checkOK()
|
||||
default:
|
||||
break
|
||||
}
|
||||
}
|
||||
return all
|
||||
}
|
||||
}
|
||||
|
||||
private func status(
|
||||
mailboxes: some Sequence<MailboxName>,
|
||||
statusAttributes: [MailboxAttribute]
|
||||
) async throws -> [MailboxName: MailboxStatus] {
|
||||
// Loop over all mailboxes
|
||||
// Pipeline a few STATUS at the time:
|
||||
let concurrencyLimit = 5
|
||||
|
||||
return try await withThrowingTaskGroup { group in
|
||||
var remaining = mailboxes.makeIterator()
|
||||
var submittedCount = 0
|
||||
|
||||
func popNextMailbox() -> MailboxName? {
|
||||
guard
|
||||
submittedCount < concurrencyLimit,
|
||||
let result = remaining.next()
|
||||
else { return nil }
|
||||
submittedCount += 1
|
||||
return result
|
||||
}
|
||||
|
||||
while let mailbox = popNextMailbox() {
|
||||
group.addTask {
|
||||
let s = try await self.status(
|
||||
mailbox: mailbox,
|
||||
statusAttributes: statusAttributes
|
||||
)
|
||||
return (mailbox, s)
|
||||
}
|
||||
}
|
||||
|
||||
var all: [MailboxName: MailboxStatus] = [:]
|
||||
for try await result in group {
|
||||
if let s = result.1 {
|
||||
all[result.0] = s
|
||||
}
|
||||
|
||||
submittedCount -= 1
|
||||
// Every time we get a result back, check if there's more work we should submit and do so
|
||||
if let mailbox = popNextMailbox() {
|
||||
group.addTask {
|
||||
let s = try await self.status(
|
||||
mailbox: mailbox,
|
||||
statusAttributes: statusAttributes
|
||||
)
|
||||
return (mailbox, s)
|
||||
}
|
||||
}
|
||||
}
|
||||
return all
|
||||
}
|
||||
}
|
||||
|
||||
private func status(
|
||||
mailbox: MailboxName,
|
||||
statusAttributes: [MailboxAttribute]
|
||||
) async throws -> MailboxStatus? {
|
||||
try await send(.status(mailbox, statusAttributes)) { tag, responses in
|
||||
var result: MailboxStatus?
|
||||
for try await response in responses {
|
||||
switch response {
|
||||
case .untagged(.mailboxData(.status(mailbox, let status))):
|
||||
result = status
|
||||
case .tagged(let r):
|
||||
try r.checkOK()
|
||||
default:
|
||||
break
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - List-Status
|
||||
|
||||
extension ConnectionProtocol {
|
||||
/// Use RFC 5819 “LIST-STATUS” to get LIST and STATUS with a single command.
|
||||
private func listStatus(
|
||||
target: ListTarget,
|
||||
listReturnOptions: [ReturnOption],
|
||||
statusAttributes: [MailboxAttribute]
|
||||
) async throws -> [MailboxInfoAndStatus] {
|
||||
let command = Command.list(
|
||||
target: target,
|
||||
returnOptions: listReturnOptions + [.statusOption(statusAttributes)]
|
||||
)
|
||||
return try await send(command) { tag, responses in
|
||||
var list: [MailboxPath: [MailboxInfo.Attribute]] = [:]
|
||||
var status: [MailboxName: MailboxStatus] = [:]
|
||||
for try await response in responses {
|
||||
switch response {
|
||||
case .untagged(.mailboxData(.list(let info))):
|
||||
list[info.path] = info.attributes
|
||||
case .untagged(.mailboxData(.status(let mailbox, let s))):
|
||||
status[mailbox] = s
|
||||
case .tagged(let r):
|
||||
try r.checkOK()
|
||||
default:
|
||||
break
|
||||
}
|
||||
}
|
||||
return combineListAndStatus(
|
||||
listInfo: list,
|
||||
statusInfo: status
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import IMAPCommands
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
import NIO
|
||||
import NIOIMAP
|
||||
|
||||
extension ConnectionProtocol {
|
||||
/// Moves messages from the currently selected mailbox to another mailbox.
|
||||
///
|
||||
/// The source mailbox must already be selected before calling this function.
|
||||
/// Requiring a ``SelectInfo`` argument makes that prerequisite visible in the
|
||||
/// type signature, even though the value itself is not read.
|
||||
func moveMessages(
|
||||
selectInfo _: SelectInfo,
|
||||
capabilities: [Capability],
|
||||
uids _uids: UIDSet,
|
||||
to destinationMailbox: MailboxName
|
||||
) async throws {
|
||||
guard
|
||||
let uids = MessageIdentifierSetNonEmpty(set: _uids)
|
||||
else { return }
|
||||
|
||||
// Check if server supports MOVE command (RFC 6851)
|
||||
if capabilities.contains(.move) {
|
||||
try await moveMessagesUsingMoveCommand(
|
||||
uids: uids,
|
||||
to: destinationMailbox
|
||||
)
|
||||
} else {
|
||||
try await moveMessagesUsingCopyCommand(
|
||||
uids: uids,
|
||||
to: destinationMailbox
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Moves messages using `UID MOVE`.
|
||||
private func moveMessagesUsingMoveCommand(
|
||||
uids: MessageIdentifierSetNonEmpty<UID>,
|
||||
to destinationMailbox: MailboxName
|
||||
) async throws {
|
||||
let text = try await send(
|
||||
.uidMove(.set(uids), destinationMailbox)
|
||||
) { tag, responses in
|
||||
writeStatus("Did send UID MOVE \(uids.set.count) message(s) to '\(destinationMailbox)' with tag \(tag)")
|
||||
return try await responses.waitForCompletion()
|
||||
}.getOK()
|
||||
|
||||
writeStatus("Did UID MOVE message(s): \(text)")
|
||||
}
|
||||
|
||||
/// Moves messages using `UID COPY` followed by `UID STORE` and `EXPUNGE`.
|
||||
///
|
||||
/// Used when the server does not advertise the `MOVE` capability (RFC 6851).
|
||||
///
|
||||
/// - Note: The final `EXPUNGE` is a plain, mailbox-wide expunge (RFC 3501): it
|
||||
/// permanently removes *every* message flagged `\Deleted` in the selected
|
||||
/// mailbox, not only the ones copied here. This is intentional. A mailbox is
|
||||
/// commonly accessed from several devices at once, any of which may expunge at
|
||||
/// any time, so relying on `\Deleted` messages lingering is unsafe — the modern
|
||||
/// best practice is to expunge right after flagging.
|
||||
private func moveMessagesUsingCopyCommand(
|
||||
uids: MessageIdentifierSetNonEmpty<UID>,
|
||||
to destinationMailbox: MailboxName
|
||||
) async throws {
|
||||
// UID COPY
|
||||
let copyText = try await send(
|
||||
.uidCopy(.set(uids), destinationMailbox)
|
||||
) { tag, responses in
|
||||
writeStatus("Did send UID COPY \(uids.set.count) message(s) to '\(destinationMailbox)' with tag \(tag)")
|
||||
return try await responses.waitForCompletion()
|
||||
}.getOK()
|
||||
writeStatus("Did UID COPY message(s): \(copyText)")
|
||||
|
||||
// UID STORE
|
||||
let storeText = try await send(
|
||||
.uidStore(.set(uids), [], .flags(.add(silent: true, list: [.deleted])))
|
||||
) { tag, responses in
|
||||
writeStatus("Did send UID STORE \\Deleted with tag \(tag)")
|
||||
return try await responses.waitForCompletion()
|
||||
}.getOK()
|
||||
writeStatus("Did mark message(s) as deleted: \(storeText)")
|
||||
|
||||
// EXPUNGE
|
||||
let expungeText = try await send(.expunge) { tag, responses in
|
||||
writeStatus("Did send EXPUNGE with tag \(tag)")
|
||||
return try await responses.waitForCompletion()
|
||||
}.getOK()
|
||||
writeStatus("Did EXPUNGE: \(expungeText)")
|
||||
|
||||
writeStatus("Did move \(uids.set.count) message(s) using UID COPY")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import IMAPCommands
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
import NIO
|
||||
import NIOIMAP
|
||||
|
||||
extension ConnectionProtocol {
|
||||
/// Renames a mailbox on the server.
|
||||
func renameMailbox(
|
||||
capabilities: [Capability],
|
||||
old oldName: MailboxName,
|
||||
new newName: MailboxName
|
||||
) async throws {
|
||||
let text = try await send(
|
||||
.rename(from: oldName, to: newName, parameters: [:])
|
||||
) { tag, responses in
|
||||
writeStatus("Did send RENAME mailbox '\(oldName)' to '\(newName)' with tag \(tag)")
|
||||
return try await responses.waitForCompletion()
|
||||
}.getOK()
|
||||
writeStatus("Did RENAME mailbox '\(oldName)' to '\(newName)': \(text)")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,270 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import IMAPCommands
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
import NIO
|
||||
import NIOIMAP
|
||||
|
||||
extension ConnectionProtocol {
|
||||
/// Returns all UIDs matching the given fetch query.
|
||||
func allUIDs(
|
||||
query: FetchQuery,
|
||||
mailboxMessageCount: Int,
|
||||
capabilities: [Capability]
|
||||
) async throws -> UIDSet {
|
||||
try await batchedSearch(
|
||||
key: .all,
|
||||
query: query,
|
||||
mailboxMessageCount: mailboxMessageCount,
|
||||
capabilities: capabilities
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
extension SearchKey {
|
||||
static func messageID(_ id: MessageID) -> SearchKey {
|
||||
.header("message-id", ByteBuffer(string: String(id)))
|
||||
}
|
||||
|
||||
static func messageID(_ ids: some Sequence<MessageID>) -> SearchKey? {
|
||||
ids.reduce(
|
||||
into: SearchKey?.none,
|
||||
{ all, id in
|
||||
let new = SearchKey.messageID(id)
|
||||
if let a = all {
|
||||
all = SearchKey.or(a, new)
|
||||
} else {
|
||||
all = new
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
/// Will match the last `count` messages in a mailbox with `mailboxMessageCount` messages.
|
||||
static func lastMessages(
|
||||
count: Int,
|
||||
mailboxMessageCount: Int
|
||||
) -> SearchKey {
|
||||
guard
|
||||
count < mailboxMessageCount
|
||||
else { return .all }
|
||||
let end = SequenceNumber
|
||||
.min
|
||||
.advanced(by: Int64(mailboxMessageCount))
|
||||
.advanced(by: -Int64(count))
|
||||
let range = MessageIdentifierSetNonEmpty<SequenceNumber>(range: end...SequenceNumber.max)
|
||||
return .sequenceNumbers(.set(range))
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: -
|
||||
|
||||
extension ConnectionProtocol {
|
||||
/// Performs a search for the given `SearchKey`, but splits the messages into batches
|
||||
/// and runs multiple searches, one on each batch.
|
||||
func batchedSearch(
|
||||
key searchKey: SearchKey,
|
||||
query: FetchQuery,
|
||||
mailboxMessageCount: Int,
|
||||
capabilities: [Capability]
|
||||
) async throws -> UIDSet {
|
||||
try await batched(
|
||||
query: query,
|
||||
mailboxMessageCount: mailboxMessageCount,
|
||||
capabilities: capabilities,
|
||||
fetch: { batch in
|
||||
try await self.searchBatch(
|
||||
capabilities: capabilities,
|
||||
key: searchKey,
|
||||
query: query,
|
||||
batch: batch
|
||||
) ?? UIDSet()
|
||||
},
|
||||
into: UIDSet(),
|
||||
update: {
|
||||
$0.formUnion($1)
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
extension SearchKey {
|
||||
/// Combine the given `SearchKey` with a predicate that limits the UIDs to the ones in the given `FetchBatch`.
|
||||
static func combine(
|
||||
key searchKey: SearchKey,
|
||||
query: FetchQuery,
|
||||
batch: FetchBatch
|
||||
) -> Self {
|
||||
let uids = batch.makeUIDs(query)
|
||||
guard uids != .all else { return searchKey }
|
||||
guard let set = UIDSetNonEmpty(set: uids) else { return .not(.all) }
|
||||
let uidKey = SearchKey.uid(.set(set))
|
||||
guard searchKey != .all else { return uidKey }
|
||||
return SearchKey.and([uidKey, searchKey])
|
||||
}
|
||||
}
|
||||
|
||||
extension ConnectionProtocol {
|
||||
/// Sends a `UID SEARCH` command.
|
||||
///
|
||||
/// Depending on the server capabilities, a normal (RFC 3501), an extended, or a partial
|
||||
/// search command may be used.
|
||||
func searchBatch(
|
||||
capabilities: [Capability],
|
||||
key searchKey: SearchKey,
|
||||
query: FetchQuery,
|
||||
batch: FetchBatch
|
||||
) async throws -> UIDSet? {
|
||||
let combined = SearchKey.combine(
|
||||
key: searchKey,
|
||||
query: query,
|
||||
batch: batch
|
||||
)
|
||||
|
||||
switch batch {
|
||||
case .uidRange:
|
||||
return try await search(
|
||||
capabilities: capabilities,
|
||||
kind: .nonPartial(combined)
|
||||
)
|
||||
case .partialLast(let partialRange):
|
||||
return try await search(
|
||||
capabilities: capabilities,
|
||||
kind: .partial(partialRange, combined)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: -
|
||||
|
||||
extension ConnectionProtocol {
|
||||
/// Sends a `UID SEARCH` command.
|
||||
///
|
||||
/// Depending on the server capabilities, a normal (RFC 3501), an extended, or a partial
|
||||
/// search command may be used.
|
||||
func search(
|
||||
capabilities: [Capability],
|
||||
key searchKey: SearchKey
|
||||
) async throws -> UIDSet {
|
||||
guard capabilities.contains(.partial) else {
|
||||
return try await search(
|
||||
capabilities: capabilities,
|
||||
kind: .nonPartial(searchKey)
|
||||
) ?? UIDSet()
|
||||
}
|
||||
let batchSize = BatchSize(capabilities: capabilities)
|
||||
|
||||
var uids = UIDSet()
|
||||
for batch in 0... {
|
||||
let range = NIOIMAP.PartialRange.last(SequenceRange(batchSize.partialRange(batch: batch)))
|
||||
writeStatus("[PARTIAL SEARCH] searching range \(range)")
|
||||
let newUIDs = try await search(
|
||||
capabilities: capabilities,
|
||||
kind: .partial(range, searchKey)
|
||||
)
|
||||
guard let newUIDs, !newUIDs.isEmpty else { break }
|
||||
writeStatus("[PARTIAL SEARCH] Batch \(batch + 1) returned \(newUIDs.count) UIDs")
|
||||
uids.formUnion(newUIDs)
|
||||
}
|
||||
writeStatus("Did find \(uids.count) UIDs using PARTIAL SEARCH")
|
||||
return uids
|
||||
}
|
||||
}
|
||||
|
||||
struct NoUntaggedSearchResponse: Swift.Error {}
|
||||
|
||||
// MARK: -
|
||||
|
||||
enum SearchKind: Hashable, Sendable {
|
||||
case nonPartial(SearchKey)
|
||||
case partial(NIOIMAP.PartialRange, SearchKey)
|
||||
}
|
||||
|
||||
extension ConnectionProtocol {
|
||||
func search(
|
||||
capabilities: [Capability],
|
||||
kind: SearchKind,
|
||||
) async throws -> UIDSet? {
|
||||
let searchKey: SearchKey
|
||||
let returnOptions: [SearchReturnOption]
|
||||
switch kind {
|
||||
case .partial(let range, let key):
|
||||
searchKey = key
|
||||
returnOptions = [.partial(range)]
|
||||
case .nonPartial(let key):
|
||||
searchKey = key
|
||||
returnOptions = capabilities.contains(.extendedSearch) ? [.all] : []
|
||||
}
|
||||
|
||||
guard returnOptions.isEmpty else {
|
||||
let uids = try await sendUIDSearch(
|
||||
key: searchKey,
|
||||
returnOptions: returnOptions
|
||||
) { tag, response in
|
||||
guard
|
||||
case .untagged(.mailboxData(.extendedSearch(let result))) = response,
|
||||
let c = result.correlator,
|
||||
c.tag == "\(tag)"
|
||||
else { return nil }
|
||||
return result.matchedUIDs ?? UIDSet()
|
||||
}
|
||||
writeStatus("Did find \(uids?.count ?? 0) UIDs using extended UID SEARCH")
|
||||
return uids
|
||||
}
|
||||
let uids = try await sendUIDSearch(
|
||||
key: searchKey,
|
||||
returnOptions: []
|
||||
) { _, response in
|
||||
guard
|
||||
case .untagged(.mailboxData(.search(let ids, _))) = response
|
||||
else { return nil }
|
||||
return UIDSet(MessageIdentifierSet(ids))
|
||||
}
|
||||
writeStatus("Did find \(uids?.count ?? 0) UIDs using UID SEARCH")
|
||||
return uids
|
||||
}
|
||||
|
||||
/// Sends a `UID SEARCH` command and extracts matching UIDs from untagged responses
|
||||
/// using `extract`. Throws `NoUntaggedSearchResponse` if no matching untagged response
|
||||
/// arrived before the tagged completion.
|
||||
private func sendUIDSearch(
|
||||
key searchKey: SearchKey,
|
||||
returnOptions: [SearchReturnOption],
|
||||
extract: @Sendable @escaping (IMAPConnection.Tag, Response) -> UIDSet?
|
||||
) async throws -> UIDSet? {
|
||||
try await send(
|
||||
.uidSearch(
|
||||
key: searchKey,
|
||||
charset: nil,
|
||||
returnOptions: returnOptions
|
||||
)
|
||||
) { tag, responses in
|
||||
var didFind = false
|
||||
var uids: UIDSet?
|
||||
try await responses.forEach { response in
|
||||
guard let extracted = extract(tag, response) else { return }
|
||||
didFind = true
|
||||
uids = extracted
|
||||
}.checkOK()
|
||||
guard didFind else { throw NoUntaggedSearchResponse() }
|
||||
return uids
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,281 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import ArgumentParser
|
||||
import IMAPCommands
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
import NIO
|
||||
import NIOIMAP
|
||||
|
||||
extension SearchKey {
|
||||
/// A combination of search criteria for filtering messages.
|
||||
struct Predicate: Hashable, Sendable {
|
||||
var olderThanDays: Int?
|
||||
var newerThanDays: Int?
|
||||
var subject: String?
|
||||
var from: String?
|
||||
var to: String?
|
||||
var cc: String?
|
||||
var text: String?
|
||||
var messageSizeSmallerThan: Int?
|
||||
var messageSizeLargerThan: Int?
|
||||
var messageID: MessageID?
|
||||
var emailID: EmailID?
|
||||
var threadID: ThreadID?
|
||||
var flagsSet: Set<NIOIMAP.Flag>
|
||||
var flagsNotSet: Set<NIOIMAP.Flag>
|
||||
|
||||
init(
|
||||
olderThanDays: Int? = nil,
|
||||
newerThanDays: Int? = nil,
|
||||
subject: String? = nil,
|
||||
from: String? = nil,
|
||||
to: String? = nil,
|
||||
cc: String? = nil,
|
||||
text: String? = nil,
|
||||
messageSizeSmallerThan: Int? = nil,
|
||||
messageSizeLargerThan: Int? = nil,
|
||||
messageID: MessageID? = nil,
|
||||
emailID: EmailID? = nil,
|
||||
threadID: ThreadID? = nil,
|
||||
flagsSet: Set<NIOIMAP.Flag> = [],
|
||||
flagsNotSet: Set<NIOIMAP.Flag> = []
|
||||
) {
|
||||
self.olderThanDays = olderThanDays
|
||||
self.newerThanDays = newerThanDays
|
||||
self.subject = subject
|
||||
self.from = from
|
||||
self.to = to
|
||||
self.cc = cc
|
||||
self.text = text
|
||||
self.messageSizeSmallerThan = messageSizeSmallerThan
|
||||
self.messageSizeLargerThan = messageSizeLargerThan
|
||||
self.messageID = messageID
|
||||
self.emailID = emailID
|
||||
self.threadID = threadID
|
||||
self.flagsSet = flagsSet
|
||||
self.flagsNotSet = flagsNotSet
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension SearchKey.Predicate: CustomStringConvertible {
|
||||
var description: String {
|
||||
var components: [String] = []
|
||||
if let olderThanDays {
|
||||
components.append("olderThanDays: \(olderThanDays)")
|
||||
}
|
||||
if let newerThanDays {
|
||||
components.append("newerThanDays: \(newerThanDays)")
|
||||
}
|
||||
if let subject {
|
||||
components.append("subject: \"\(subject)\"")
|
||||
}
|
||||
if let from {
|
||||
components.append("from: \"\(from)\"")
|
||||
}
|
||||
if let to {
|
||||
components.append("to: \"\(to)\"")
|
||||
}
|
||||
if let cc {
|
||||
components.append("cc: \"\(cc)\"")
|
||||
}
|
||||
if let text {
|
||||
components.append("text: \"\(text)\"")
|
||||
}
|
||||
if let messageSizeSmallerThan {
|
||||
components.append("messageSizeSmallerThan: \(messageSizeSmallerThan)")
|
||||
}
|
||||
if let messageSizeLargerThan {
|
||||
components.append("messageSizeLargerThan: \(messageSizeLargerThan)")
|
||||
}
|
||||
if let messageID {
|
||||
components.append("messageID: \(messageID)")
|
||||
}
|
||||
if let emailID {
|
||||
components.append("emailID: \(emailID)")
|
||||
}
|
||||
if let threadID {
|
||||
components.append("threadID: \(threadID)")
|
||||
}
|
||||
if !flagsSet.isEmpty {
|
||||
components.append("flagsSet: [\(flagsSet.map { String($0) }.joined(separator: ", "))]")
|
||||
}
|
||||
if !flagsNotSet.isEmpty {
|
||||
components.append("flagsNotSet: [\(flagsNotSet.map { String($0) }.joined(separator: ", "))]")
|
||||
}
|
||||
return components.joined(separator: ", ")
|
||||
}
|
||||
}
|
||||
|
||||
extension IMAPCalendarDay {
|
||||
init(
|
||||
days: Int,
|
||||
since now: Date,
|
||||
timeZone: TimeZone
|
||||
) throws {
|
||||
var calendar = Calendar(identifier: .gregorian)
|
||||
calendar.timeZone = timeZone
|
||||
|
||||
guard
|
||||
let date = calendar.date(
|
||||
byAdding: .day,
|
||||
value: -days,
|
||||
to: now
|
||||
)
|
||||
else { throw ValidationError("Can not construct date with \(days) day(s) before now.") }
|
||||
let components = calendar.dateComponents([.year, .month, .day], from: date)
|
||||
guard
|
||||
let result = IMAPCalendarDay(
|
||||
year: components.year!,
|
||||
month: components.month!,
|
||||
day: components.day!
|
||||
)
|
||||
else { throw ValidationError("Can not construct date with \(days) day(s) since now.") }
|
||||
self = result
|
||||
}
|
||||
}
|
||||
|
||||
extension SearchKey {
|
||||
/// Builds search criteria from common parameters.
|
||||
init(
|
||||
_ predicate: Predicate,
|
||||
now: Date = Date(),
|
||||
timeZone: TimeZone = TimeZone.current
|
||||
) throws {
|
||||
var keys: [SearchKey] = []
|
||||
|
||||
// Date based searches:
|
||||
if let days = predicate.olderThanDays {
|
||||
try keys.append(
|
||||
.sentBefore(
|
||||
IMAPCalendarDay(
|
||||
days: days,
|
||||
since: now,
|
||||
timeZone: timeZone
|
||||
)
|
||||
)
|
||||
)
|
||||
}
|
||||
if let days = predicate.newerThanDays {
|
||||
try keys.append(
|
||||
.sentSince(
|
||||
IMAPCalendarDay(
|
||||
days: days,
|
||||
since: now,
|
||||
timeZone: timeZone
|
||||
)
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
// Text-based searches
|
||||
if let subject = predicate.subject {
|
||||
keys.append(.subject(ByteBuffer(string: subject)))
|
||||
}
|
||||
if let from = predicate.from {
|
||||
keys.append(.from(ByteBuffer(string: from)))
|
||||
}
|
||||
if let to = predicate.to {
|
||||
keys.append(.to(ByteBuffer(string: to)))
|
||||
}
|
||||
if let cc = predicate.cc {
|
||||
keys.append(.cc(ByteBuffer(string: cc)))
|
||||
}
|
||||
if let text = predicate.text {
|
||||
keys.append(.text(ByteBuffer(string: text)))
|
||||
}
|
||||
|
||||
// Size-based searches
|
||||
if let size = predicate.messageSizeSmallerThan {
|
||||
keys.append(.messageSizeSmaller(size))
|
||||
}
|
||||
if let size = predicate.messageSizeLargerThan {
|
||||
keys.append(.messageSizeLarger(size))
|
||||
}
|
||||
|
||||
// ID-based searches
|
||||
if let messageID = predicate.messageID {
|
||||
keys.append(.messageID(messageID))
|
||||
}
|
||||
if let emailID = predicate.emailID {
|
||||
keys.append(.emailID(emailID))
|
||||
}
|
||||
if let threadID = predicate.threadID {
|
||||
keys.append(.threadID(threadID))
|
||||
}
|
||||
|
||||
// Flag-based searches
|
||||
for flag in predicate.flagsSet.sorted(by: { String($0) < String($1) }) {
|
||||
try keys.append(.init(flag: flag))
|
||||
}
|
||||
|
||||
for flag in predicate.flagsNotSet.sorted(by: { String($0) < String($1) }) {
|
||||
try keys.append(.init(notFlag: flag))
|
||||
}
|
||||
|
||||
// Combine all keys
|
||||
if keys.isEmpty {
|
||||
self = .all
|
||||
} else if keys.count == 1 {
|
||||
self = keys[0]
|
||||
} else {
|
||||
self = .and(keys)
|
||||
}
|
||||
}
|
||||
|
||||
init(
|
||||
flag: NIOIMAP.Flag
|
||||
) throws {
|
||||
if flag == .answered {
|
||||
self = .answered
|
||||
} else if flag == .flagged {
|
||||
self = .flagged
|
||||
} else if flag == .deleted {
|
||||
self = .deleted
|
||||
} else if flag == .seen {
|
||||
self = .seen
|
||||
} else if flag == .draft {
|
||||
self = .draft
|
||||
} else if let keyword = NIOIMAP.Flag.Keyword(String(flag)) {
|
||||
self = .keyword(keyword)
|
||||
} else {
|
||||
throw ValidationError("Invalid flag: \(String(flag))")
|
||||
}
|
||||
}
|
||||
|
||||
init(
|
||||
notFlag flag: NIOIMAP.Flag
|
||||
) throws {
|
||||
if flag == .answered {
|
||||
self = .unanswered
|
||||
} else if flag == .flagged {
|
||||
self = .unflagged
|
||||
} else if flag == .deleted {
|
||||
self = .undeleted
|
||||
} else if flag == .seen {
|
||||
self = .unseen
|
||||
} else if flag == .draft {
|
||||
self = .undraft
|
||||
} else if let keyword = NIOIMAP.Flag.Keyword(String(flag)) {
|
||||
self = .not(.keyword(keyword))
|
||||
} else {
|
||||
throw ValidationError("Invalid flag: \(String(flag))")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import IMAPCommands
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
import NIO
|
||||
import NIOIMAP
|
||||
|
||||
/// The result of selecting a mailbox, containing its metadata.
|
||||
struct SelectInfo: Hashable, Sendable {
|
||||
/// The name of the selected mailbox.
|
||||
var mailbox: MailboxName
|
||||
/// The text from the `OK` command completion.
|
||||
var responseText: ResponseText
|
||||
/// The flags defined for this mailbox.
|
||||
var flags: [Flag]
|
||||
/// The permanent flags that can be modified in this mailbox.
|
||||
var permanentFlags: [PermanentFlag]
|
||||
/// The total number of messages from the `EXISTS` response.
|
||||
var messageCount: Int
|
||||
/// The next UID the server assigns to a new message.
|
||||
var uidNext: UID
|
||||
/// The UID validity value for this mailbox.
|
||||
var uidValidity: UIDValidity
|
||||
|
||||
/// Creates a `SelectInfo` with all required fields.
|
||||
init(
|
||||
mailbox: MailboxName,
|
||||
responseText: ResponseText,
|
||||
flags: [Flag],
|
||||
permanentFlags: [PermanentFlag],
|
||||
messageCount: Int,
|
||||
uidNext: UID,
|
||||
uidValidity: UIDValidity
|
||||
) {
|
||||
self.mailbox = mailbox
|
||||
self.responseText = responseText
|
||||
self.flags = flags
|
||||
self.permanentFlags = permanentFlags
|
||||
self.messageCount = messageCount
|
||||
self.uidNext = uidNext
|
||||
self.uidValidity = uidValidity
|
||||
}
|
||||
}
|
||||
|
||||
extension SelectInfo {
|
||||
init(
|
||||
temp: Temporary,
|
||||
response: TaggedResponse
|
||||
) throws {
|
||||
let responseText = try response.getOK()
|
||||
guard
|
||||
let flags = temp.flags
|
||||
else { throw Error.missingSelectField("flags") }
|
||||
guard
|
||||
let permanentFlags = temp.permanentFlags
|
||||
else { throw Error.missingSelectField("permanent flags") }
|
||||
guard
|
||||
let messageCount = temp.messageCount
|
||||
else { throw Error.missingSelectField("message count") }
|
||||
guard
|
||||
let uidNext = temp.uidNext
|
||||
else { throw Error.missingSelectField("UIDNEXT") }
|
||||
guard
|
||||
let uidValidity = temp.uidValidity
|
||||
else { throw Error.missingSelectField("UIDVALIDITY") }
|
||||
self.init(
|
||||
mailbox: temp.mailbox,
|
||||
responseText: responseText,
|
||||
flags: flags,
|
||||
permanentFlags: permanentFlags,
|
||||
messageCount: messageCount,
|
||||
uidNext: uidNext,
|
||||
uidValidity: uidValidity
|
||||
)
|
||||
}
|
||||
|
||||
/// The in-progress version that gets updated while `SELECT` runs.
|
||||
struct Temporary: Hashable, Sendable {
|
||||
var mailbox: MailboxName
|
||||
var flags: [Flag]?
|
||||
var permanentFlags: [PermanentFlag]?
|
||||
/// From `<n> EXISTS`
|
||||
var messageCount: Int?
|
||||
var uidNext: UID?
|
||||
var uidValidity: UIDValidity?
|
||||
}
|
||||
|
||||
enum Error: Swift.Error {
|
||||
/// The `SELECT` response was missing a required untagged field. The associated
|
||||
/// value names the field (e.g. `"UIDNEXT"`).
|
||||
case missingSelectField(String)
|
||||
}
|
||||
}
|
||||
|
||||
/// Controls behavior when the mailbox does not exist during selection.
|
||||
enum SelectCreateOption: Hashable, Sendable {
|
||||
/// Fails selection if the mailbox does not exist.
|
||||
case fail
|
||||
/// Creates the mailbox with the given parameters if it does not exist.
|
||||
case create([CreateParameter])
|
||||
}
|
||||
|
||||
private enum FirstResult {
|
||||
case success(SelectInfo)
|
||||
case create([CreateParameter])
|
||||
}
|
||||
|
||||
extension ConnectionProtocol {
|
||||
/// Selects the given mailbox.
|
||||
func select(
|
||||
createMailbox: SelectCreateOption,
|
||||
mailbox: MailboxPath
|
||||
) async throws -> SelectInfo {
|
||||
try await select(
|
||||
mailbox: mailbox.name,
|
||||
createMailbox: createMailbox
|
||||
)
|
||||
}
|
||||
|
||||
/// Selects the given mailbox, optionally creating it first.
|
||||
func select(
|
||||
mailbox: MailboxName,
|
||||
createMailbox: SelectCreateOption
|
||||
) async throws -> SelectInfo {
|
||||
let info = try await selectOrCreate(
|
||||
createMailbox: createMailbox,
|
||||
mailbox: mailbox
|
||||
)
|
||||
writeStatus(
|
||||
"Did select mailbox '\(mailbox)'. Message count: \(info.messageCount), UIDNEXT: \(info.uidNext), UIDVALIDITY: \(info.uidValidity)"
|
||||
)
|
||||
return info
|
||||
}
|
||||
|
||||
private func selectOrCreate(
|
||||
createMailbox: SelectCreateOption,
|
||||
mailbox: MailboxName
|
||||
) async throws -> SelectInfo {
|
||||
let parameters: [CreateParameter]
|
||||
switch try await trySelect(
|
||||
createMailbox: createMailbox,
|
||||
mailbox: mailbox
|
||||
) {
|
||||
case .success(let info):
|
||||
return info
|
||||
case .create(let p):
|
||||
parameters = p
|
||||
}
|
||||
|
||||
// Try to create:
|
||||
let createText = try await send(.create(mailbox, parameters)) { tag, responses in
|
||||
writeStatus("Did send CREATE with tag \(tag)")
|
||||
return try await responses.waitForCompletion()
|
||||
}.getOK()
|
||||
writeStatus("Did CREATE: \(createText)")
|
||||
// Re-try SELECT:
|
||||
let (info, response) = try await sendSelect(
|
||||
mailbox: mailbox
|
||||
)
|
||||
return try SelectInfo(
|
||||
temp: info,
|
||||
response: response
|
||||
)
|
||||
}
|
||||
|
||||
/// Attempts a `SELECT` and either returns the result, or — if the mailbox does not
|
||||
/// exist and the caller opted in to creation — returns the parameters needed to create it.
|
||||
private func trySelect(
|
||||
createMailbox: SelectCreateOption,
|
||||
mailbox: MailboxName
|
||||
) async throws -> FirstResult {
|
||||
let (info, response) = try await sendSelect(
|
||||
mailbox: mailbox
|
||||
)
|
||||
// The only branch that diverts from the normal "construct SelectInfo" path is
|
||||
// a `NO` response when the caller opted in to creating the mailbox.
|
||||
// Every other state — `.ok`, `.bad`, or `.no` with `.fail` — goes through
|
||||
// `SelectInfo.init`, which surfaces success or throws the underlying error.
|
||||
if case .create(let parameters) = createMailbox,
|
||||
case .no(let text) = response.state
|
||||
{
|
||||
writeStatus("Unable to SELECT mailbox — will try to create (\(text))")
|
||||
return .create(parameters)
|
||||
}
|
||||
return try .success(
|
||||
SelectInfo(
|
||||
temp: info,
|
||||
response: response
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
private func sendSelect(
|
||||
mailbox: MailboxName
|
||||
) async throws -> (SelectInfo.Temporary, TaggedResponse) {
|
||||
try await send(.select(mailbox)) { _, responses in
|
||||
var info = SelectInfo.Temporary(mailbox: mailbox)
|
||||
let response = try await responses.forEach { response in
|
||||
switch response {
|
||||
case .untagged(let untagged):
|
||||
info.update(untagged)
|
||||
default:
|
||||
break
|
||||
}
|
||||
}
|
||||
return (info, response)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension SelectInfo.Temporary {
|
||||
mutating func update(_ untagged: ResponsePayload) {
|
||||
switch untagged {
|
||||
case .mailboxData(.flags(let f)):
|
||||
flags = f
|
||||
case .mailboxData(.exists(let count)):
|
||||
messageCount = count
|
||||
case .conditionalState(.ok(let text)):
|
||||
switch text.code {
|
||||
case .permanentFlags(let f):
|
||||
permanentFlags = f
|
||||
case .uidNext(let uid):
|
||||
uidNext = uid
|
||||
case .uidValidity(let v):
|
||||
uidValidity = v
|
||||
default:
|
||||
break
|
||||
}
|
||||
default:
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import IMAPCommands
|
||||
import NIOIMAP
|
||||
|
||||
/// Describes flags to add and remove from messages.
|
||||
struct FlagChanges: Hashable, Sendable {
|
||||
/// The flags to add to the messages.
|
||||
var set: [NIOIMAP.Flag]
|
||||
/// The flags to remove from the messages.
|
||||
var unset: [NIOIMAP.Flag]
|
||||
|
||||
/// Creates a new flag change set with the given flags to add and remove.
|
||||
init(
|
||||
set: [NIOIMAP.Flag],
|
||||
unset: [NIOIMAP.Flag]
|
||||
) {
|
||||
self.set = set
|
||||
self.unset = unset
|
||||
}
|
||||
|
||||
var isEmpty: Bool {
|
||||
self.set.isEmpty && self.unset.isEmpty
|
||||
}
|
||||
}
|
||||
|
||||
extension ConnectionProtocol {
|
||||
/// Updates flags on the messages specified by UIDs.
|
||||
func updateFlags(
|
||||
uids: UIDSet,
|
||||
changes: FlagChanges
|
||||
) async throws {
|
||||
try await sendStore(
|
||||
uids: uids,
|
||||
flags: changes.set,
|
||||
operatorLabel: "+FLAGS",
|
||||
makeStoreFlags: { StoreFlags.add(silent: false, list: $0) }
|
||||
)
|
||||
try await sendStore(
|
||||
uids: uids,
|
||||
flags: changes.unset,
|
||||
operatorLabel: "-FLAGS",
|
||||
makeStoreFlags: { StoreFlags.remove(silent: false, list: $0) }
|
||||
)
|
||||
}
|
||||
|
||||
private func sendStore(
|
||||
uids: UIDSet,
|
||||
flags: [NIOIMAP.Flag],
|
||||
operatorLabel: String,
|
||||
makeStoreFlags: ([NIOIMAP.Flag]) -> StoreFlags
|
||||
) async throws {
|
||||
guard
|
||||
!flags.isEmpty,
|
||||
let command = Command.uidStore(
|
||||
messages: uids,
|
||||
modifiers: [],
|
||||
data: StoreData.flags(makeStoreFlags(flags))
|
||||
)
|
||||
else { return }
|
||||
try await send(command) { tag, responses in
|
||||
writeStatus(
|
||||
"Did send UID STORE \(operatorLabel) \(flags.map { String($0) }.joined(separator: ", ")) with tag \(tag)"
|
||||
)
|
||||
return try await responses.waitForCompletion()
|
||||
}.checkOK()
|
||||
writeStatus("Did UID STORE \(operatorLabel) on \(uids.count) UID(s)")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
// `NumberFormatter` is not part of `FoundationEssentials`.
|
||||
import Foundation
|
||||
|
||||
extension String {
|
||||
/// Creates a Unicode bar that’s `width` wide, and `fraction` of it filled in.
|
||||
static func barWithLabel(fraction: Double, width: Int) -> String {
|
||||
let basic = self.bar(fraction: fraction, width: width)
|
||||
let label = formatFraction(fraction)
|
||||
// We need room for the label plus at least one bar character. If the
|
||||
// bar is too narrow (or empty), fall back to the plain bar.
|
||||
guard 11 <= width, label.count + 1 <= basic.count else { return basic }
|
||||
guard fraction < 0.5 else {
|
||||
return String(basic.prefix(1)) + label
|
||||
+ String(basic.suffix(from: basic.index(basic.startIndex, offsetBy: 1 + label.count)))
|
||||
}
|
||||
return basic.prefix(basic.count - label.count) + label
|
||||
}
|
||||
|
||||
/// Creates a Unicode bar that’s `width` wide, and `fraction` of it filled in.
|
||||
static func bar(fraction: Double, width: Int) -> String {
|
||||
// Clamp so a non-positive width (e.g. from a very long label) yields an
|
||||
// empty bar rather than trapping on an invalid `Range`.
|
||||
let width = Swift.max(0, width)
|
||||
let chars = (0..<width).map { index -> Character in
|
||||
let lower = Double(index) / Double(width)
|
||||
let blockWidth = 1.0 / Double(width)
|
||||
let fill = (fraction - lower) / blockWidth
|
||||
let index = Swift.max(0, Swift.min(8, Int(round(fill * 8))))
|
||||
return blocks[index]
|
||||
}
|
||||
return String(chars)
|
||||
}
|
||||
}
|
||||
|
||||
private let blocks: [Character] = [
|
||||
" ",
|
||||
"▏",
|
||||
"▎",
|
||||
"▍",
|
||||
"▌",
|
||||
"▋",
|
||||
"▊",
|
||||
"▉",
|
||||
"█",
|
||||
]
|
||||
|
||||
// MARK: -
|
||||
|
||||
extension Locale {
|
||||
static let posix = Locale(identifier: "en_US_POSIX")
|
||||
}
|
||||
|
||||
private func formatFraction(_ fraction: Double) -> String {
|
||||
formatter.string(for: fraction)!
|
||||
}
|
||||
|
||||
private let formatter: NumberFormatter = {
|
||||
var f = NumberFormatter()
|
||||
f.numberStyle = .percent
|
||||
f.minimumSignificantDigits = 1
|
||||
f.maximumSignificantDigits = 3
|
||||
f.locale = .posix
|
||||
return f
|
||||
}()
|
||||
@@ -0,0 +1,95 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
// `round`/`floor`/`log10`/`pow` are not part of `FoundationEssentials`.
|
||||
import Foundation
|
||||
|
||||
struct Histogram: Equatable, Encodable {
|
||||
var bins: [Bin]
|
||||
var totalCount: Int
|
||||
|
||||
struct Bin: Equatable, Encodable {
|
||||
var range: Range<Double>
|
||||
var count: Int
|
||||
}
|
||||
}
|
||||
|
||||
extension Histogram {
|
||||
init?(data: [Double]) {
|
||||
guard let h = Histogram.withEmptyBins(data: data) else { return nil }
|
||||
self = h
|
||||
data.forEach { value in
|
||||
guard let index = bins.firstIndex(where: { $0.range.contains(value) }) else { return }
|
||||
bins[index].count += 1
|
||||
}
|
||||
}
|
||||
|
||||
static func withEmptyBins(data: [Double]) -> Histogram? {
|
||||
guard let ranges = binRanges(data: data) else { return nil }
|
||||
return Histogram(
|
||||
bins: ranges.map {
|
||||
Histogram.Bin(range: $0, count: 0)
|
||||
},
|
||||
totalCount: data.count
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: -
|
||||
|
||||
func binRanges(data: [Double]) -> [Range<Double>]? {
|
||||
guard
|
||||
let mean = data.mean(),
|
||||
let standardDeviation = data.standardDeviation()
|
||||
else { return nil }
|
||||
// We want to span approx. ±2σ
|
||||
// -- but less if the data doesn’t span that interval:
|
||||
let lower = max(
|
||||
data.reduce(into: Double.infinity) {
|
||||
$0 = min($0, $1)
|
||||
},
|
||||
mean - 2 * standardDeviation
|
||||
)
|
||||
let upper = min(
|
||||
data.reduce(into: -Double.infinity) {
|
||||
$0 = max($0, $1)
|
||||
},
|
||||
mean + 2 * standardDeviation
|
||||
)
|
||||
guard lower < upper else { return nil }
|
||||
// Calculate the bins with “rounded” sizes:
|
||||
let bins = -3..<3
|
||||
let binSpan = roundedBinSpan((upper - lower) / Double(bins.count))
|
||||
let middle = roundedBinSpan(lower + 0.5 * (upper - lower))
|
||||
return bins.map {
|
||||
let lower = middle + Double($0) * binSpan
|
||||
let upper = lower + binSpan
|
||||
return lower..<upper
|
||||
}
|
||||
}
|
||||
|
||||
/// Finds a “nice” value that’s relatively close to `input`.
|
||||
func roundedBinSpan(_ input: Double) -> Double {
|
||||
// `log10`/`pow` are only meaningful for a positive magnitude. Guard against zero
|
||||
// and non-finite input (which would otherwise yield NaN), and round the magnitude
|
||||
// for negative input so the result keeps `input`’s sign.
|
||||
guard input.isFinite, input != 0 else { return 0 }
|
||||
let magnitude = abs(input)
|
||||
let scale = pow(10, floor(log10(magnitude)))
|
||||
let a = magnitude / scale
|
||||
let x: Double = 5
|
||||
let b = round(a * x) / x
|
||||
let rounded = b * scale
|
||||
return input < 0 ? -rounded : rounded
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
// `NumberFormatter` is not part of `FoundationEssentials`.
|
||||
import Foundation
|
||||
|
||||
/// A text-based histogram suitable for terminal output.
|
||||
struct TextHistogram: Equatable, Encodable, TextOutputEncodable {
|
||||
let underlying: Histogram
|
||||
let lines: [String]
|
||||
|
||||
/// Encodes the underlying histogram data.
|
||||
func encode(to encoder: Encoder) throws {
|
||||
try self.underlying.encode(to: encoder)
|
||||
}
|
||||
|
||||
/// The single-line text representation.
|
||||
var textOutput: String { "" }
|
||||
/// The multi-line text representation.
|
||||
var textOutputLines: [String] { self.lines }
|
||||
}
|
||||
|
||||
extension TextHistogram {
|
||||
/// Creates a histogram from duration values, or returns `nil` if the data is insufficient.
|
||||
init?(durations: [TimeInterval], width: Int = 78) {
|
||||
guard let histogram = Histogram(data: durations) else { return nil }
|
||||
let lines = histogram.makeDurationLines(width: width)
|
||||
self.init(underlying: histogram, lines: lines)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: -
|
||||
|
||||
extension Histogram {
|
||||
func makeDurationLines(width: Int) -> [String] {
|
||||
let binsAndLabels: [(Histogram.Bin, String)] = bins.map { bin -> (Histogram.Bin, String) in
|
||||
let label = formatDuration(bin.range.lowerBound) + "-" + formatDuration(bin.range.upperBound)
|
||||
return (bin, label)
|
||||
}
|
||||
let maxLabelWidth = binsAndLabels.reduce(into: 0) { $0 = max($0, $1.1.count) }
|
||||
|
||||
let lines: [String] = binsAndLabels.map { bin, label -> String in
|
||||
let fraction = Double(bin.count) / Double(totalCount)
|
||||
// Guard against very long labels driving the bar width non-positive.
|
||||
let barWidth = max(1, width - maxLabelWidth - 2)
|
||||
let bar = String.barWithLabel(fraction: fraction, width: barWidth)
|
||||
return label + String(repeating: " ", count: maxLabelWidth - label.count) + ": " + bar
|
||||
}
|
||||
return lines
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: -
|
||||
|
||||
func formatDuration(_ value: TimeInterval) -> String {
|
||||
guard value >= 10 else {
|
||||
return numberFormatter.string(for: value * 1000)! + "ms"
|
||||
}
|
||||
return numberFormatter.string(for: value)! + "s"
|
||||
}
|
||||
|
||||
private let numberFormatter: NumberFormatter = {
|
||||
var f = NumberFormatter()
|
||||
f.numberStyle = .decimal
|
||||
f.minimumSignificantDigits = 1
|
||||
f.maximumSignificantDigits = 3
|
||||
f.usesGroupingSeparator = true
|
||||
f.groupingSeparator = ","
|
||||
f.groupingSize = 3
|
||||
f.locale = .posix
|
||||
return f
|
||||
}()
|
||||
|
||||
private let calendar: Calendar = {
|
||||
var c = Calendar(identifier: .gregorian)
|
||||
c.locale = .posix
|
||||
return c
|
||||
}()
|
||||
@@ -0,0 +1,202 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
// `NumberFormatter` is not part of `FoundationEssentials`.
|
||||
import Foundation
|
||||
import NIOIMAP
|
||||
import IMAPCommands
|
||||
import SystemPackage
|
||||
|
||||
/// A formatted output value that supports custom string interpolations.
|
||||
public struct Output: Equatable {
|
||||
var text: String
|
||||
}
|
||||
|
||||
/// Using `Output`, the tool can use different string interpolations than the default
|
||||
/// `String` interpolations.
|
||||
extension Output: ExpressibleByStringLiteral {
|
||||
public init(stringLiteral value: String) {
|
||||
self.init(text: value)
|
||||
}
|
||||
}
|
||||
|
||||
extension Output: ExpressibleByStringInterpolation {
|
||||
public init(stringInterpolation: StringInterpolation) {
|
||||
self.text = stringInterpolation.text
|
||||
}
|
||||
|
||||
public struct StringInterpolation: StringInterpolationProtocol {
|
||||
var text: String
|
||||
|
||||
public init(literalCapacity: Int, interpolationCount: Int) {
|
||||
self.text = ""
|
||||
self.text.reserveCapacity(literalCapacity + interpolationCount * 10)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Output.StringInterpolation {
|
||||
public mutating func appendLiteral(_ literal: String) {
|
||||
self.text.append(literal)
|
||||
}
|
||||
|
||||
public mutating func appendInterpolation(_ value: String) {
|
||||
self.text.append(value)
|
||||
}
|
||||
|
||||
public mutating func appendInterpolation(_ value: Command) {
|
||||
self.text.append(String(reflecting: value))
|
||||
}
|
||||
|
||||
public mutating func appendInterpolation(_ duration: TimeInterval) {
|
||||
let ms = duration * 1000
|
||||
self.text.append(integerFormatter.string(for: ms)! + " ms")
|
||||
}
|
||||
|
||||
public mutating func appendInterpolation(_ duration: Duration) {
|
||||
self.appendInterpolation(TimeInterval(duration))
|
||||
}
|
||||
|
||||
public mutating func appendInterpolation(_ path: MailboxPath) {
|
||||
let text =
|
||||
path
|
||||
.displayStringComponents(omittingEmptySubsequences: false)
|
||||
.joined(separator: path.pathSeparator.map { String($0) } ?? "/")
|
||||
self.text.append(text)
|
||||
}
|
||||
|
||||
public mutating func appendInterpolation(_ name: MailboxName) {
|
||||
guard let path = try? MailboxPath(name: name, pathSeparator: nil) else { return }
|
||||
self.appendInterpolation(path)
|
||||
}
|
||||
|
||||
public mutating func appendInterpolation(_ value: UID) {
|
||||
self.text.append("\(UInt32(value))")
|
||||
}
|
||||
|
||||
public mutating func appendInterpolation(_ value: SearchKey) {
|
||||
self.text.append("\(String(reflecting: value))")
|
||||
}
|
||||
|
||||
public mutating func appendInterpolation(_ value: MessageID) {
|
||||
self.text.append("\(String(value))")
|
||||
}
|
||||
|
||||
public mutating func appendInterpolation(_ value: UIDSet) {
|
||||
self.text.append(String(reflecting: value))
|
||||
}
|
||||
|
||||
public mutating func appendInterpolation(_ value: UIDValidity) {
|
||||
self.text.append("\(UInt32(value))")
|
||||
}
|
||||
|
||||
public mutating func appendInterpolation(_ value: UIDSetNonEmpty) {
|
||||
self.text.append("\(String(reflecting: value.set))")
|
||||
}
|
||||
|
||||
public mutating func appendInterpolation(_ value: IMAPConnection.Tag) {
|
||||
self.text.append(String(value))
|
||||
}
|
||||
|
||||
public mutating func appendInterpolation(_ value: ResponseText) {
|
||||
if let code = value.code {
|
||||
self.appendInterpolation(code)
|
||||
self.appendLiteral(" ")
|
||||
}
|
||||
self.text.append(value.text)
|
||||
}
|
||||
|
||||
public mutating func appendInterpolation(_ range: NIOIMAP.PartialRange) {
|
||||
switch range {
|
||||
case .first(let r):
|
||||
self.appendLiteral("first-")
|
||||
self.appendInterpolation(r)
|
||||
case .last(let r):
|
||||
self.appendLiteral("last-")
|
||||
self.appendInterpolation(r)
|
||||
}
|
||||
}
|
||||
|
||||
public mutating func appendInterpolation<ID: MessageIdentifier>(_ range: MessageIdentifierRange<ID>) {
|
||||
self.text.append(String(reflecting: range))
|
||||
}
|
||||
|
||||
public mutating func appendInterpolation(_ code: ResponseTextCode) {
|
||||
self.text.append(String(reflecting: code))
|
||||
}
|
||||
|
||||
public mutating func appendInterpolation(_ state: TaggedResponse.State) {
|
||||
self.text.append(String(reflecting: state))
|
||||
}
|
||||
|
||||
public mutating func appendInterpolation(_ status: UntaggedStatus) {
|
||||
self.text.append(String(reflecting: Response.untagged(.conditionalState(status))))
|
||||
}
|
||||
|
||||
public mutating func appendInterpolation(_ status: Bool) {
|
||||
self.text.append(status ? "true" : "false")
|
||||
}
|
||||
|
||||
public mutating func appendInterpolation(_ value: Int) {
|
||||
self.text.append(integerFormatter.string(for: value)!)
|
||||
}
|
||||
|
||||
public mutating func appendInterpolation(_ value: CInt) {
|
||||
self.text.append(integerFormatter.string(for: value)!)
|
||||
}
|
||||
|
||||
public mutating func appendInterpolation(_ value: FilePath) {
|
||||
self.text.append(String(decoding: value))
|
||||
}
|
||||
|
||||
public mutating func appendInterpolation(_ value: FilePath.Component) {
|
||||
self.text.append(String(decoding: value))
|
||||
}
|
||||
|
||||
public mutating func appendInterpolation(_ error: some Swift.Error) {
|
||||
switch error {
|
||||
case let e as LocalizedError:
|
||||
self.text.append(e.errorDescription ?? "\(e)")
|
||||
default:
|
||||
self.text.append("\(error)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension TimeInterval {
|
||||
/// The duration expressed as a number of seconds.
|
||||
fileprivate init(_ duration: Duration) {
|
||||
let components = duration.components
|
||||
self = Double(components.seconds) + Double(components.attoseconds) * 1e-18
|
||||
}
|
||||
}
|
||||
|
||||
private let integerFormatter: NumberFormatter = {
|
||||
var f = NumberFormatter()
|
||||
f.locale = Locale(identifier: "en_US_POSIX")
|
||||
f.numberStyle = .decimal
|
||||
f.groupingSeparator = ","
|
||||
f.usesGroupingSeparator = true
|
||||
f.groupingSize = 3
|
||||
f.maximumFractionDigits = 0
|
||||
f.roundingMode = .halfUp
|
||||
return f
|
||||
}()
|
||||
|
||||
extension IMAPConnection.Tag: TextOutputEncodable {
|
||||
/// The text representation of the tag.
|
||||
public var textOutput: String { String(self) }
|
||||
/// Additional output lines (always empty for tags).
|
||||
public var textOutputLines: [String] { [] }
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
// `FileHandle` is not part of `FoundationEssentials`.
|
||||
import Foundation
|
||||
|
||||
#if canImport(Glibc)
|
||||
import Glibc
|
||||
nonisolated(unsafe) let _exit: (Int32) -> Never = Glibc.exit
|
||||
#elseif canImport(Darwin)
|
||||
import Darwin
|
||||
nonisolated(unsafe) let _exit: (Int32) -> Never = Darwin.exit
|
||||
#elseif canImport(MSVCRT)
|
||||
import MSVCRT
|
||||
nonisolated(unsafe) let _exit: (Int32) -> Never = ucrt._exit
|
||||
#endif
|
||||
|
||||
/// Writes to standard error (`stderr`).
|
||||
///
|
||||
/// This is for informational messages. It does not interfere with command output (such as JSON).
|
||||
public func writeStatus(_ output: Output, terminator: String = "\n") {
|
||||
let text = output.text + terminator
|
||||
FileHandle.standardError.write(text.data(using: .utf8)!)
|
||||
}
|
||||
|
||||
/// Writes to standard output (`stdout`).
|
||||
///
|
||||
/// Used for "clean" terminations such as `--help` and `--version`, whose text
|
||||
/// belongs on standard output rather than standard error.
|
||||
func writeStandardOutput(_ text: String) {
|
||||
FileHandle.standardOutput.write(Data(text.utf8))
|
||||
_ = fsync(FileHandle.standardOutput.fileDescriptor)
|
||||
}
|
||||
|
||||
func flushStatus() {
|
||||
// We use fsync(2) and intentionally ignore the result. This can fail depending on what kind of output (terminal vs. pipe vs. file) standard output is going to.
|
||||
_ = fsync(FileHandle.standardError.fileDescriptor)
|
||||
}
|
||||
|
||||
/// Writes the output message to standard error and terminates the process.
|
||||
public func exitWithErrorMessage(_ output: Output, code: Int32 = -1) -> Never {
|
||||
writeStatus(output)
|
||||
flushStatus()
|
||||
_exit(code)
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import ArgumentParser
|
||||
// `FileHandle` is not part of `FoundationEssentials`.
|
||||
import Foundation
|
||||
#if canImport(Glibc)
|
||||
import Glibc
|
||||
#elseif canImport(Darwin)
|
||||
import Darwin
|
||||
#endif
|
||||
|
||||
/// The output format for command results.
|
||||
public enum ResultFormat: String, Sendable {
|
||||
/// Plain text output.
|
||||
case text
|
||||
/// JSON output.
|
||||
case json
|
||||
}
|
||||
|
||||
extension ResultFormat: ExpressibleByArgument {
|
||||
public init?(argument: String) {
|
||||
self.init(rawValue: argument)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: -
|
||||
|
||||
/// Write the execution result to standard output.
|
||||
///
|
||||
/// This uses the given `format` and writes either plain text or JSON.
|
||||
/// Note that all other output should use `writeStatus()` and go to standard error to allow
|
||||
/// piping the result to another tool.
|
||||
public func writeResult<R>(
|
||||
result: R,
|
||||
format: ResultFormat,
|
||||
terminator: Data? = nil
|
||||
) where R: Encodable {
|
||||
let data: Data
|
||||
do {
|
||||
data = try makeResultData(
|
||||
result: result,
|
||||
format: format
|
||||
)
|
||||
} catch {
|
||||
exitWithErrorMessage("Failed to encode result '\(String(describing: result))'.")
|
||||
}
|
||||
|
||||
// Flush the status -- if we’re running in the terminal, both will
|
||||
// go to the tty.
|
||||
flushStatus()
|
||||
// Write to stdout:
|
||||
FileHandle.standardOutput.write(data)
|
||||
if let terminator {
|
||||
FileHandle.standardOutput.write(terminator)
|
||||
}
|
||||
// We use fsync(2) and intentionally ignore the result. This can fail depending on what kind of output (terminal vs. pipe vs. file) standard output is going to.
|
||||
_ = fsync(FileHandle.standardOutput.fileDescriptor)
|
||||
}
|
||||
|
||||
private func makeResultData<R>(
|
||||
result: R,
|
||||
format: ResultFormat
|
||||
) throws -> Data where R: Encodable {
|
||||
try makeResultData(result, format: format)
|
||||
}
|
||||
|
||||
func makeResultData<R>(_ result: R, format: ResultFormat) throws -> Data where R: Encodable {
|
||||
switch format {
|
||||
case .text:
|
||||
let encoder = TextEncoder()
|
||||
return try encoder.encode(result).data(using: .utf8)!
|
||||
case .json:
|
||||
let encoder = JSONEncoder()
|
||||
encoder.outputFormatting = [.sortedKeys, .prettyPrinted]
|
||||
return try encoder.encode(result)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension Array where Element: FloatingPoint {
|
||||
func mean() -> Element? {
|
||||
guard !isEmpty else { return nil }
|
||||
return self.sum() / Element(count)
|
||||
}
|
||||
|
||||
func sum() -> Element {
|
||||
reduce(0, +)
|
||||
}
|
||||
|
||||
func standardDeviation() -> Element? {
|
||||
guard let meanValue = mean() else { return nil }
|
||||
let variance = (reduce(into: 0 as Element) { $0 += (meanValue - $1) * (meanValue - $1) }) / Element(count)
|
||||
return variance.squareRoot()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
#if canImport(Glibc)
|
||||
import Glibc
|
||||
#elseif canImport(Darwin)
|
||||
import Darwin
|
||||
#endif
|
||||
// `FileHandle` is not part of `FoundationEssentials`.
|
||||
import Foundation
|
||||
|
||||
/// Returns `true` if standard input connects to an interactive terminal session.
|
||||
var standardInputIsTTY: Bool {
|
||||
isatty(FileHandle.standardInput.fileDescriptor) == 1
|
||||
}
|
||||
@@ -0,0 +1,494 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import Synchronization
|
||||
|
||||
final class TextEncoder: Encoder {
|
||||
init() {
|
||||
self.values = Values()
|
||||
}
|
||||
|
||||
fileprivate init(values: Values) {
|
||||
self.values = values
|
||||
}
|
||||
|
||||
func encode<T>(_ value: T) throws -> String where T: Encodable {
|
||||
let e = self.copy()
|
||||
try value.encode(to: e)
|
||||
return e.output
|
||||
}
|
||||
|
||||
fileprivate func copy() -> TextEncoder {
|
||||
TextEncoder(values: Values(values: self.values.values))
|
||||
}
|
||||
|
||||
var codingPath: [CodingKey] = []
|
||||
|
||||
var userInfo: [CodingUserInfoKey: Any] = [:]
|
||||
|
||||
fileprivate let values: Values
|
||||
|
||||
func container<Key>(keyedBy _: Key.Type) -> KeyedEncodingContainer<Key> where Key: CodingKey {
|
||||
let c = TextKeyedEncodingContainer<Key>(codingPath: codingPath, values: values)
|
||||
return KeyedEncodingContainer(c)
|
||||
}
|
||||
|
||||
func unkeyedContainer() -> UnkeyedEncodingContainer {
|
||||
TextUnkeyedEncodingContainer(codingPath: self.codingPath, values: self.values)
|
||||
}
|
||||
|
||||
func singleValueContainer() -> SingleValueEncodingContainer {
|
||||
TextSingleValueEncodingContainer(codingPath: self.codingPath, values: self.values)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Stored Values
|
||||
|
||||
private struct KeyedValue {
|
||||
var keyName: String
|
||||
var value: Value
|
||||
}
|
||||
|
||||
private indirect enum Value {
|
||||
case text(String)
|
||||
case sub(Values)
|
||||
case keyed(String, Value)
|
||||
}
|
||||
|
||||
private final class Values {
|
||||
var values: [Value]
|
||||
init(values: [Value] = []) {
|
||||
self.values = values
|
||||
}
|
||||
}
|
||||
|
||||
extension Values {
|
||||
func addNestedValues() -> Values {
|
||||
let nestedValues = Values()
|
||||
self.values.append(.sub(nestedValues))
|
||||
return nestedValues
|
||||
}
|
||||
|
||||
func addNestedValues<Key: CodingKey>(for key: Key) -> Values {
|
||||
let nestedValues = Values()
|
||||
self.values.append(.keyed(key.textOutputKey, .sub(nestedValues)))
|
||||
return nestedValues
|
||||
}
|
||||
|
||||
func add(text: String) {
|
||||
self.values.append(.text(text))
|
||||
}
|
||||
|
||||
func add<Key: CodingKey>(text: String, for key: Key) {
|
||||
self.values.append(.keyed(key.textOutputKey, .text(text)))
|
||||
}
|
||||
}
|
||||
|
||||
extension CodingKey {
|
||||
fileprivate var textOutputKey: String {
|
||||
// Split words by "_". Uppercase the 1st word.
|
||||
stringValue
|
||||
.camelCaseComponents
|
||||
.filter { !$0.isEmpty }
|
||||
.enumerated()
|
||||
.map { ($0.0 == 0) ? $0.1.titlecased() : $0.1.lowercased() }
|
||||
.joined(separator: " ")
|
||||
}
|
||||
}
|
||||
|
||||
extension String {
|
||||
fileprivate var camelCaseComponents: [Substring] {
|
||||
var result: [Substring] = []
|
||||
var idx = startIndex
|
||||
var lastStart: Index?
|
||||
while idx < endIndex {
|
||||
if self[idx].isLetter, self[idx].isUppercase {
|
||||
if let s = lastStart {
|
||||
result.append(self[s..<idx])
|
||||
}
|
||||
lastStart = idx
|
||||
} else if lastStart == nil {
|
||||
lastStart = idx
|
||||
}
|
||||
idx = index(after: idx)
|
||||
}
|
||||
if let s = lastStart, s < idx {
|
||||
result.append(self[s..<idx])
|
||||
}
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
extension StringProtocol {
|
||||
fileprivate func titlecased() -> String {
|
||||
let idx = index(after: startIndex)
|
||||
guard idx <= endIndex else { return String(self) }
|
||||
return String(self[startIndex..<idx]).uppercased() + String(self[idx..<endIndex])
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Generate Output String
|
||||
|
||||
extension TextEncoder {
|
||||
private var output: String {
|
||||
var result = ""
|
||||
self.values.appendOutput(to: &result, indent: 0)
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
extension Values {
|
||||
func appendOutput(to result: inout String, indent: Int) {
|
||||
// If some values have more than 1 line, separate them with a newline:
|
||||
let needsSeparation = self.values.reduce(false) { $0 || ($1.count > 1) }
|
||||
if needsSeparation {
|
||||
self.appendSeparatedOutput(to: &result, indent: indent)
|
||||
} else {
|
||||
self.values.forEach {
|
||||
$0.appendOutput(to: &result, indent: indent)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func appendSeparatedOutput(to result: inout String, indent: Int) {
|
||||
var isFirst = true
|
||||
self.values.forEach {
|
||||
if isFirst {
|
||||
isFirst = false
|
||||
} else {
|
||||
result.append(String.indentation(indent) + .newline)
|
||||
}
|
||||
$0.appendOutput(to: &result, indent: indent)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Value {
|
||||
var count: Int {
|
||||
switch self {
|
||||
case .text:
|
||||
return 1
|
||||
case .sub(let sub):
|
||||
return sub.values.count
|
||||
case .keyed: return 1
|
||||
}
|
||||
}
|
||||
|
||||
func appendOutput(to result: inout String, indent: Int) {
|
||||
switch self {
|
||||
case .text(let text):
|
||||
result.append(String.indentation(indent) + text + .newline)
|
||||
case .sub(let sub):
|
||||
sub.appendOutput(to: &result, indent: indent) // Don't indent here.
|
||||
case .keyed(let key, .text(let text)):
|
||||
result.append(String.indentation(indent) + key + ": " + text + .newline)
|
||||
case .keyed(let key, .sub(let sub)):
|
||||
if sub.values.isEmpty {
|
||||
result.append(String.indentation(indent) + key + ":" + .newline)
|
||||
} else if sub.values.count == 1, case .some(.text(let text)) = sub.values.first {
|
||||
result.append(String.indentation(indent) + key + ": " + text + .newline)
|
||||
} else if sub.values.count == 1, case .some(.sub(let subsub)) = sub.values.first {
|
||||
result.append(String.indentation(indent) + key + ":" + .newline)
|
||||
subsub.appendOutput(to: &result, indent: indent + 1)
|
||||
} else {
|
||||
result.append(String.indentation(indent) + key + ":" + .newline)
|
||||
sub.appendOutput(to: &result, indent: indent + 1)
|
||||
}
|
||||
case .keyed(_, .keyed):
|
||||
fatalError("Value.keyed must not contain sub-key.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private let indentationMemo = Mutex<[String]>([])
|
||||
|
||||
extension String {
|
||||
fileprivate static func indentation(_ indent: Int) -> String {
|
||||
indentationMemo.withLock { memo in
|
||||
while memo.count <= indent {
|
||||
memo.append(String(repeating: " ", count: memo.count * 4))
|
||||
}
|
||||
return memo[indent]
|
||||
}
|
||||
}
|
||||
|
||||
fileprivate static let newline: String = "\n"
|
||||
}
|
||||
|
||||
// MARK: Encoding Containers
|
||||
|
||||
private struct TextKeyedEncodingContainer<Key: CodingKey>: KeyedEncodingContainerProtocol {
|
||||
init(codingPath: [CodingKey], values: Values) {
|
||||
self.codingPath = codingPath
|
||||
self.values = values
|
||||
}
|
||||
|
||||
var codingPath: [CodingKey]
|
||||
fileprivate var values: Values
|
||||
|
||||
mutating func encodeNil(forKey key: Key) throws {
|
||||
self.values.add(text: "", for: key)
|
||||
}
|
||||
|
||||
mutating func encode<T>(_ value: T, forKey key: Key) throws where T: Encodable {
|
||||
switch value {
|
||||
case let v as TextOutputEncodable:
|
||||
self.values.add(text: v.textOutput, for: key)
|
||||
v.textOutputLines.forEach {
|
||||
self.values.add(text: $0)
|
||||
}
|
||||
case let text as String:
|
||||
self.values.add(text: text, for: key)
|
||||
case let b as Bool:
|
||||
self.values.add(text: b ? "true" : "false", for: key)
|
||||
case let i as Double:
|
||||
self.values.add(text: i.description, for: key)
|
||||
case let i as Float:
|
||||
self.values.add(text: i.description, for: key)
|
||||
|
||||
case let i as UInt:
|
||||
self.values.add(text: i.description, for: key)
|
||||
case let i as Int:
|
||||
self.values.add(text: i.description, for: key)
|
||||
case let i as UInt8:
|
||||
self.values.add(text: i.description, for: key)
|
||||
case let i as Int8:
|
||||
self.values.add(text: i.description, for: key)
|
||||
case let i as UInt16:
|
||||
self.values.add(text: i.description, for: key)
|
||||
case let i as Int16:
|
||||
self.values.add(text: i.description, for: key)
|
||||
case let i as UInt32:
|
||||
self.values.add(text: i.description, for: key)
|
||||
case let i as Int32:
|
||||
self.values.add(text: i.description, for: key)
|
||||
case let i as UInt64:
|
||||
self.values.add(text: i.description, for: key)
|
||||
case let i as Int64:
|
||||
self.values.add(text: i.description, for: key)
|
||||
|
||||
case let i as [Double]:
|
||||
self.values.add(text: i.description, for: key)
|
||||
case let i as [Float]:
|
||||
self.values.add(text: i.description, for: key)
|
||||
|
||||
case let i as [UInt]:
|
||||
self.values.add(text: i.description, for: key)
|
||||
case let i as [Int]:
|
||||
self.values.add(text: i.description, for: key)
|
||||
case let i as [UInt8]:
|
||||
self.values.add(text: i.description, for: key)
|
||||
case let i as [Int8]:
|
||||
self.values.add(text: i.description, for: key)
|
||||
case let i as [UInt16]:
|
||||
self.values.add(text: i.description, for: key)
|
||||
case let i as [Int16]:
|
||||
self.values.add(text: i.description, for: key)
|
||||
case let i as [UInt32]:
|
||||
self.values.add(text: i.description, for: key)
|
||||
case let i as [Int32]:
|
||||
self.values.add(text: i.description, for: key)
|
||||
case let i as [UInt64]:
|
||||
self.values.add(text: i.description, for: key)
|
||||
case let i as [Int64]:
|
||||
self.values.add(text: i.description, for: key)
|
||||
|
||||
default:
|
||||
let nested = self.values.addNestedValues(for: key)
|
||||
let e = TextEncoder(values: nested)
|
||||
e.codingPath = self.codingPath + [key]
|
||||
try value.encode(to: e)
|
||||
}
|
||||
}
|
||||
|
||||
mutating func nestedContainer<NestedKey>(
|
||||
keyedBy _: NestedKey.Type,
|
||||
forKey key: Key
|
||||
) -> KeyedEncodingContainer<NestedKey> where NestedKey: CodingKey {
|
||||
let nestedPath = self.codingPath + [key]
|
||||
let nestedValues = self.values.addNestedValues(for: key)
|
||||
let c = TextKeyedEncodingContainer<NestedKey>(codingPath: nestedPath, values: nestedValues)
|
||||
return KeyedEncodingContainer(c)
|
||||
}
|
||||
|
||||
mutating func nestedUnkeyedContainer(forKey key: Key) -> UnkeyedEncodingContainer {
|
||||
let nestedPath = self.codingPath + [key]
|
||||
let nestedValues = self.values.addNestedValues(for: key)
|
||||
return TextUnkeyedEncodingContainer(codingPath: nestedPath, values: nestedValues)
|
||||
}
|
||||
|
||||
mutating func superEncoder() -> Encoder {
|
||||
fatalError()
|
||||
}
|
||||
|
||||
mutating func superEncoder(forKey _: Key) -> Encoder {
|
||||
fatalError()
|
||||
}
|
||||
}
|
||||
|
||||
/// A type that provides custom text encoding for the ``TextEncoder``.
|
||||
protocol TextOutputEncodable {
|
||||
/// The single-line text representation.
|
||||
var textOutput: String { get }
|
||||
/// Additional output lines beyond the primary text representation.
|
||||
var textOutputLines: [String] { get }
|
||||
}
|
||||
|
||||
private struct TextUnkeyedEncodingContainer: UnkeyedEncodingContainer {
|
||||
init(codingPath: [CodingKey], values: Values) {
|
||||
self.codingPath = codingPath
|
||||
self.values = values
|
||||
}
|
||||
|
||||
var codingPath: [CodingKey]
|
||||
fileprivate var values: Values
|
||||
|
||||
var count: Int {
|
||||
values.values.count
|
||||
}
|
||||
|
||||
mutating func encodeNil() throws {
|
||||
self.values.add(text: "")
|
||||
}
|
||||
|
||||
mutating func encode<T>(_ value: T) throws where T: Encodable {
|
||||
switch value {
|
||||
case let v as TextOutputEncodable:
|
||||
if !v.textOutput.isEmpty {
|
||||
self.values.add(text: v.textOutput)
|
||||
}
|
||||
v.textOutputLines.forEach {
|
||||
self.values.add(text: $0)
|
||||
}
|
||||
case let text as String:
|
||||
self.values.add(text: text)
|
||||
case let b as Bool:
|
||||
self.values.add(text: b ? "true" : "false")
|
||||
case let i as Double:
|
||||
self.values.add(text: i.description)
|
||||
case let i as Float:
|
||||
self.values.add(text: i.description)
|
||||
case let i as UInt:
|
||||
self.values.add(text: i.description)
|
||||
case let i as Int:
|
||||
self.values.add(text: i.description)
|
||||
case let i as UInt8:
|
||||
self.values.add(text: i.description)
|
||||
case let i as Int8:
|
||||
self.values.add(text: i.description)
|
||||
case let i as UInt16:
|
||||
self.values.add(text: i.description)
|
||||
case let i as Int16:
|
||||
self.values.add(text: i.description)
|
||||
case let i as UInt32:
|
||||
self.values.add(text: i.description)
|
||||
case let i as Int32:
|
||||
self.values.add(text: i.description)
|
||||
case let i as UInt64:
|
||||
self.values.add(text: i.description)
|
||||
case let i as Int64:
|
||||
self.values.add(text: i.description)
|
||||
default:
|
||||
let e = TextEncoder(values: values.addNestedValues())
|
||||
e.codingPath = self.codingPath
|
||||
try value.encode(to: e)
|
||||
}
|
||||
}
|
||||
|
||||
mutating func encodeConditional<T>(_ object: T) throws where T: AnyObject, T: Encodable {
|
||||
try self.encode(object)
|
||||
}
|
||||
|
||||
mutating func encode<T>(contentsOf sequence: T) throws where T: Sequence, T.Element: Encodable {
|
||||
let e = TextEncoder(values: values)
|
||||
e.codingPath = self.codingPath
|
||||
for value in sequence {
|
||||
try value.encode(to: e)
|
||||
}
|
||||
}
|
||||
|
||||
mutating func nestedContainer<NestedKey>(keyedBy _: NestedKey.Type) -> KeyedEncodingContainer<NestedKey>
|
||||
where NestedKey: CodingKey {
|
||||
let nestedValues = self.values.addNestedValues()
|
||||
let c = TextKeyedEncodingContainer<NestedKey>(codingPath: codingPath, values: nestedValues)
|
||||
return KeyedEncodingContainer(c)
|
||||
}
|
||||
|
||||
mutating func nestedUnkeyedContainer() -> UnkeyedEncodingContainer {
|
||||
let nestedValues = self.values.addNestedValues()
|
||||
return TextUnkeyedEncodingContainer(codingPath: self.codingPath, values: nestedValues)
|
||||
}
|
||||
|
||||
mutating func superEncoder() -> Encoder {
|
||||
fatalError()
|
||||
}
|
||||
}
|
||||
|
||||
private struct TextSingleValueEncodingContainer: SingleValueEncodingContainer {
|
||||
init(codingPath: [CodingKey], values: Values) {
|
||||
self.codingPath = codingPath
|
||||
self.values = values
|
||||
}
|
||||
|
||||
var codingPath: [CodingKey]
|
||||
fileprivate var values: Values
|
||||
|
||||
mutating func encodeNil() throws {
|
||||
self.values.add(text: "")
|
||||
}
|
||||
|
||||
mutating func encode<T>(_ value: T) throws where T: Encodable {
|
||||
switch value {
|
||||
case let v as TextOutputEncodable:
|
||||
if !v.textOutput.isEmpty {
|
||||
self.values.add(text: v.textOutput)
|
||||
}
|
||||
v.textOutputLines.forEach {
|
||||
self.values.add(text: $0)
|
||||
}
|
||||
case let text as String:
|
||||
self.values.add(text: text)
|
||||
case let b as Bool:
|
||||
self.values.add(text: b ? "true" : "false")
|
||||
case let i as Double:
|
||||
self.values.add(text: i.description)
|
||||
case let i as Float:
|
||||
self.values.add(text: i.description)
|
||||
case let i as UInt:
|
||||
self.values.add(text: i.description)
|
||||
case let i as Int:
|
||||
self.values.add(text: i.description)
|
||||
case let i as UInt8:
|
||||
self.values.add(text: i.description)
|
||||
case let i as Int8:
|
||||
self.values.add(text: i.description)
|
||||
case let i as UInt16:
|
||||
self.values.add(text: i.description)
|
||||
case let i as Int16:
|
||||
self.values.add(text: i.description)
|
||||
case let i as UInt32:
|
||||
self.values.add(text: i.description)
|
||||
case let i as Int32:
|
||||
self.values.add(text: i.description)
|
||||
case let i as UInt64:
|
||||
self.values.add(text: i.description)
|
||||
case let i as Int64:
|
||||
self.values.add(text: i.description)
|
||||
default:
|
||||
let e = TextEncoder(values: values)
|
||||
e.codingPath = self.codingPath
|
||||
try value.encode(to: e)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
|
||||
struct ThroughputEstimator {
|
||||
var start: Date
|
||||
var count = 0
|
||||
|
||||
init(
|
||||
now: Date = Date()
|
||||
) {
|
||||
self.start = now
|
||||
}
|
||||
|
||||
mutating func didComplete(
|
||||
now: Date = Date()
|
||||
) -> Throughput? {
|
||||
count += 1
|
||||
let duration = now.timeIntervalSince(start)
|
||||
guard
|
||||
2 <= count,
|
||||
0 < duration,
|
||||
(30 < duration) || (60 < count)
|
||||
else { return nil }
|
||||
let throughput = Double(count) / Double(duration)
|
||||
count = 0
|
||||
start = now
|
||||
return Throughput(tasksPerSecond: throughput)
|
||||
}
|
||||
}
|
||||
|
||||
extension ThroughputEstimator {
|
||||
struct Throughput {
|
||||
var tasksPerSecond: Double
|
||||
}
|
||||
}
|
||||
|
||||
extension ThroughputEstimator.Throughput {
|
||||
func formattedTasksPerSecond(
|
||||
fractionLength: Int = 1
|
||||
) -> String {
|
||||
tasksPerSecond.formatted(
|
||||
.number.precision(.fractionLength(fractionLength))
|
||||
.locale(Locale(identifier: "en_US.posix"))
|
||||
)
|
||||
}
|
||||
|
||||
func formattedTimeRemaining(
|
||||
remainingCount: Int,
|
||||
remainingCountCutOff: Int = 0
|
||||
) -> String? {
|
||||
// Don’t create this when things are super slow.
|
||||
guard
|
||||
remainingCountCutOff < remainingCount,
|
||||
0.001 < tasksPerSecond
|
||||
else { return nil }
|
||||
|
||||
let secondsRemaining = Double(remainingCount) / tasksPerSecond
|
||||
return formatCondensedDuration(seconds: secondsRemaining)
|
||||
}
|
||||
}
|
||||
|
||||
/// Formats a duration as `1hr 2min 3s`, omitting zero components.
|
||||
///
|
||||
/// `Date`’s `.components(style:fields:)` format style is Darwin-only, and this is
|
||||
/// user-visible output, so it is spelled out by hand.
|
||||
func formatCondensedDuration(seconds: Double) -> String {
|
||||
// Anything non-finite (or negative) has no sensible representation.
|
||||
guard seconds.isFinite, 0 < seconds else { return "0sec" }
|
||||
// Clamp rather than trap when converting to an integer.
|
||||
guard seconds < Double(Int.max) else { return "0sec" }
|
||||
// Truncate towards zero, matching the format style this replaces.
|
||||
let total = Int(seconds)
|
||||
let components = [
|
||||
(total / 3600, "hr"),
|
||||
((total % 3600) / 60, "min"),
|
||||
(total % 60, "sec"),
|
||||
]
|
||||
let parts =
|
||||
components
|
||||
.filter { value, _ in value != 0 }
|
||||
.map { value, unit in "\(value)\(unit)" }
|
||||
guard !parts.isEmpty else { return "0sec" }
|
||||
return parts.joined(separator: " ")
|
||||
}
|
||||
@@ -0,0 +1,396 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import ArgumentParser
|
||||
@testable import IMAPToolLib
|
||||
@testable import IMAPCommands
|
||||
import Foundation
|
||||
import NIO
|
||||
import NIOIMAP
|
||||
import Testing
|
||||
|
||||
@Suite("Argument Parsing")
|
||||
enum ArgumentParsingTests {
|
||||
static func parse<A>(
|
||||
_: A.Type,
|
||||
_ arguments: [String],
|
||||
sourceLocation: SourceLocation = #_sourceLocation
|
||||
) throws -> A where A: ParsableCommand {
|
||||
let root = try RootCommand.parseAsRoot(arguments)
|
||||
return try #require(root as? A, sourceLocation: sourceLocation)
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseIdentifyCommand() throws {
|
||||
let id = try parse(
|
||||
IdentifyCommand.self,
|
||||
[
|
||||
"id",
|
||||
"--sasl", "plain:foo bar",
|
||||
"--server", "bar.example.com",
|
||||
]
|
||||
)
|
||||
#expect(id.connectionInfo.username == nil)
|
||||
#expect(id.connectionInfo.sasl == "plain:foo bar")
|
||||
#expect(id.connectionInfo.disableSASLIR == false)
|
||||
#expect(id.connectionInfo.server == "bar.example.com")
|
||||
#expect(id.outputFormat == .text)
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseAppendCommand() throws {
|
||||
let sut = try parse(
|
||||
AppendCommand.self,
|
||||
[
|
||||
"append",
|
||||
"--username", "foo:bar",
|
||||
"--server", "bar.example.com",
|
||||
"foo.eml",
|
||||
"baz/bar.eml",
|
||||
]
|
||||
)
|
||||
#expect(sut.connectionInfo.username == "foo:bar")
|
||||
#expect(sut.connectionInfo.sasl == nil)
|
||||
#expect(sut.connectionInfo.disableSASLIR == false)
|
||||
#expect(sut.connectionInfo.server == "bar.example.com")
|
||||
#expect(sut.input == ["foo.eml", "baz/bar.eml"])
|
||||
#expect(sut.outputFormat == .text)
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseDeleteMessagesCommand() throws {
|
||||
let sut = try parse(
|
||||
DeleteMessagesCommand.self,
|
||||
[
|
||||
"delete-messages",
|
||||
"--username", "foo:bar",
|
||||
"--server", "bar.example.com",
|
||||
"--messages", "foo.json",
|
||||
]
|
||||
)
|
||||
#expect(sut.connectionInfo.username == "foo:bar")
|
||||
#expect(sut.connectionInfo.sasl == nil)
|
||||
#expect(sut.connectionInfo.disableSASLIR == false)
|
||||
#expect(sut.connectionInfo.server == "bar.example.com")
|
||||
#expect(sut.action == .deleteSpecific(filePath: "foo.json"))
|
||||
#expect(sut.mailboxName == .inbox)
|
||||
#expect(sut.outputFormat == .text)
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseDeleteMessagesCommand_2() throws {
|
||||
let sut = try parse(
|
||||
DeleteMessagesCommand.self,
|
||||
[
|
||||
"delete-messages",
|
||||
"--username", "foo:bar",
|
||||
"--server", "bar.example.com",
|
||||
"--messages", "foo.json",
|
||||
"--mailbox", "work",
|
||||
"--output-format", "json",
|
||||
]
|
||||
)
|
||||
#expect(sut.connectionInfo.username == "foo:bar")
|
||||
#expect(sut.connectionInfo.sasl == nil)
|
||||
#expect(sut.connectionInfo.disableSASLIR == false)
|
||||
#expect(sut.connectionInfo.server == "bar.example.com")
|
||||
#expect(sut.action == .deleteSpecific(filePath: "foo.json"))
|
||||
#expect(sut.mailboxName.debugDescription == "work")
|
||||
#expect(sut.outputFormat == .json)
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseDeleteMessagesCommand_3() throws {
|
||||
let sut = try parse(
|
||||
DeleteMessagesCommand.self,
|
||||
[
|
||||
"delete-messages",
|
||||
"--username", "foo:bar",
|
||||
"--server", "bar.example.com",
|
||||
"--all",
|
||||
"--mailbox", "work",
|
||||
"--output-format", "json",
|
||||
]
|
||||
)
|
||||
#expect(sut.connectionInfo.username == "foo:bar")
|
||||
#expect(sut.connectionInfo.sasl == nil)
|
||||
#expect(sut.connectionInfo.disableSASLIR == false)
|
||||
#expect(sut.connectionInfo.server == "bar.example.com")
|
||||
#expect(sut.action == .deleteAll)
|
||||
#expect(sut.mailboxName.debugDescription == "work")
|
||||
#expect(sut.outputFormat == .json)
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseDeleteMessagesCommand_4() throws {
|
||||
let sut = try parse(
|
||||
DeleteMessagesCommand.self,
|
||||
[
|
||||
"delete-messages",
|
||||
"--username", "foo:bar",
|
||||
"--server", "bar.example.com",
|
||||
"--all",
|
||||
"--messages", "foo.json",
|
||||
"--mailbox", "work",
|
||||
"--output-format", "json",
|
||||
]
|
||||
)
|
||||
#expect(sut.action == .fail("Can not specify both --all and a file to read message info from."))
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseDeleteMessagesCommand_5() throws {
|
||||
let sut = try parse(
|
||||
DeleteMessagesCommand.self,
|
||||
[
|
||||
"delete-messages",
|
||||
"--username", "foo:bar",
|
||||
"--server", "bar.example.com",
|
||||
"--mailbox", "work",
|
||||
"--output-format", "json",
|
||||
]
|
||||
)
|
||||
#expect(sut.action == .fail("Need to specify a file to read message info from."))
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseAppendCommand_1() throws {
|
||||
let sut = try parse(
|
||||
AppendCommand.self,
|
||||
[
|
||||
"append",
|
||||
"--username", "foo:bar",
|
||||
"--server", "bar.example.com",
|
||||
"a",
|
||||
"b",
|
||||
]
|
||||
)
|
||||
#expect(sut.connectionInfo.username == "foo:bar")
|
||||
#expect(sut.connectionInfo.server == "bar.example.com")
|
||||
#expect(sut.mailbox == .inbox)
|
||||
#expect(sut.appendOptions == [.skipErrors, .sort])
|
||||
#expect(sut.input == ["a", "b"])
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseAppendCommand_2() throws {
|
||||
let sut = try parse(
|
||||
AppendCommand.self,
|
||||
[
|
||||
"append",
|
||||
"--username", "foo:bar",
|
||||
"--server", "bar.example.com",
|
||||
"--sort-by-date",
|
||||
"--skip-unreadable",
|
||||
"a",
|
||||
"b",
|
||||
]
|
||||
)
|
||||
#expect(sut.connectionInfo.username == "foo:bar")
|
||||
#expect(sut.connectionInfo.server == "bar.example.com")
|
||||
#expect(sut.mailbox == .inbox)
|
||||
#expect(sut.appendOptions == [.skipErrors, .sort])
|
||||
#expect(sut.input == ["a", "b"])
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseAppendCommand_3() throws {
|
||||
let sut = try parse(
|
||||
AppendCommand.self,
|
||||
[
|
||||
"append",
|
||||
"--username", "foo:bar",
|
||||
"--server", "bar.example.com",
|
||||
"--no-sort-by-date",
|
||||
"--create-mailbox",
|
||||
"a",
|
||||
"b",
|
||||
]
|
||||
)
|
||||
#expect(sut.connectionInfo.username == "foo:bar")
|
||||
#expect(sut.connectionInfo.server == "bar.example.com")
|
||||
#expect(sut.mailbox == .inbox)
|
||||
#expect(sut.appendOptions == [.skipErrors, .createMailbox([])])
|
||||
#expect(sut.input == ["a", "b"])
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseAppendCommand_4() throws {
|
||||
let sut = try parse(
|
||||
AppendCommand.self,
|
||||
[
|
||||
"append",
|
||||
"--username", "foo:bar",
|
||||
"--server", "bar.example.com",
|
||||
"--no-skip-unreadable",
|
||||
"a",
|
||||
"b",
|
||||
]
|
||||
)
|
||||
#expect(sut.connectionInfo.username == "foo:bar")
|
||||
#expect(sut.connectionInfo.server == "bar.example.com")
|
||||
#expect(sut.mailbox == .inbox)
|
||||
#expect(sut.appendOptions == [.sort])
|
||||
#expect(sut.input == ["a", "b"])
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseAppendCommand_5() throws {
|
||||
let sut = try parse(
|
||||
AppendCommand.self,
|
||||
[
|
||||
"append",
|
||||
"--username", "foo:bar",
|
||||
"--server", "bar.example.com",
|
||||
"--mailbox", "A",
|
||||
"a",
|
||||
"b",
|
||||
]
|
||||
)
|
||||
#expect(sut.connectionInfo.username == "foo:bar")
|
||||
#expect(sut.connectionInfo.server == "bar.example.com")
|
||||
#expect(sut.mailbox == MailboxName(ByteBuffer(string: "A")))
|
||||
#expect(sut.appendOptions == [.skipErrors, .sort])
|
||||
#expect(sut.input == ["a", "b"])
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseListMailboxes_1() throws {
|
||||
let sut = try parse(
|
||||
MailboxCommand.List.self,
|
||||
[
|
||||
"mailboxes",
|
||||
"list",
|
||||
"--username", "foo:bar",
|
||||
"--server", "bar.example.com",
|
||||
]
|
||||
)
|
||||
#expect(sut.connectionInfo.username == "foo:bar")
|
||||
#expect(sut.connectionInfo.server == "bar.example.com")
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseListMailboxes_2() throws {
|
||||
let sut = try parse(
|
||||
MailboxCommand.List.self,
|
||||
[
|
||||
"mailbox",
|
||||
"list",
|
||||
"--username", "foo:bar",
|
||||
"--server", "bar.example.com",
|
||||
]
|
||||
)
|
||||
#expect(sut.connectionInfo.username == "foo:bar")
|
||||
#expect(sut.connectionInfo.server == "bar.example.com")
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseCreateMailboxes_1() throws {
|
||||
let sut = try parse(
|
||||
MailboxCommand.Create.self,
|
||||
[
|
||||
"mailbox",
|
||||
"create",
|
||||
"--username", "foo:bar",
|
||||
"--server", "bar.example.com",
|
||||
"--name", "foo",
|
||||
"--name", "bar",
|
||||
]
|
||||
)
|
||||
#expect(sut.connectionInfo.username == "foo:bar")
|
||||
#expect(sut.connectionInfo.server == "bar.example.com")
|
||||
#expect(sut.names == ["foo", "bar"])
|
||||
#expect(sut.paths == [])
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseCreateMailboxes_2() throws {
|
||||
let sut = try parse(
|
||||
MailboxCommand.Create.self,
|
||||
[
|
||||
"mailbox",
|
||||
"create",
|
||||
"--username", "foo:bar",
|
||||
"--server", "bar.example.com",
|
||||
"--name", "a",
|
||||
"--name-json", #"path: ["foo"]"#,
|
||||
"--name-json", #"{path: ["bar"]}"#,
|
||||
"--name-json", #"{path: ["foo", "baz"], specialUse: "trash"}"#,
|
||||
"--name-json", #"name: "qux""#,
|
||||
"--name", "b",
|
||||
]
|
||||
)
|
||||
#expect(sut.connectionInfo.username == "foo:bar")
|
||||
#expect(sut.connectionInfo.server == "bar.example.com")
|
||||
#expect(sut.names == ["a", "b"])
|
||||
#expect(
|
||||
sut.paths == [
|
||||
.init(namePath: ["foo"]),
|
||||
.init(namePath: ["bar"]),
|
||||
.init(namePath: ["foo", "baz"], specialUse: .trash),
|
||||
.init(namePath: ["qux"]),
|
||||
]
|
||||
)
|
||||
#expect(
|
||||
sut.mailboxDisplayNamesWithSpecialUse == [
|
||||
.init(namePath: ["a"], parameters: []),
|
||||
.init(namePath: ["b"], parameters: []),
|
||||
.init(namePath: ["foo"], parameters: []),
|
||||
.init(namePath: ["bar"], parameters: []),
|
||||
.init(namePath: ["foo", "baz"], parameters: [.attributes([.trash])]),
|
||||
.init(namePath: ["qux"], parameters: []),
|
||||
]
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
static func seedParsing() {
|
||||
#expect(
|
||||
SeededRandomNumberGenerator.Seed(argument: "hex:3501_404A_0218_5150_F23C_78DA_2C09_7E04")
|
||||
== SeededRandomNumberGenerator.Seed(a: 0x3501_404A_0218_5150, b: 0xF23C_78DA_2C09_7E04)
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseAppendCommand_withFlags() throws {
|
||||
let sut = try parse(
|
||||
AppendCommand.self,
|
||||
[
|
||||
"append",
|
||||
"--username", "test:pass",
|
||||
"--server", "imap.example.com",
|
||||
"--flag", "seen",
|
||||
"--flag", "flagged",
|
||||
"message.eml",
|
||||
]
|
||||
)
|
||||
#expect(sut.flags == [.seen, .flagged])
|
||||
#expect(sut.input == ["message.eml"])
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseAppendCommand_withFlags_2() throws {
|
||||
let sut = try parse(
|
||||
AppendCommand.self,
|
||||
[
|
||||
"append",
|
||||
"--username", "test:pass",
|
||||
"--server", "imap.example.com",
|
||||
"--flag", "answered",
|
||||
"message.eml",
|
||||
]
|
||||
)
|
||||
#expect(sut.flags == [.answered])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import ArgumentParser
|
||||
@testable import IMAPToolLib
|
||||
import Foundation
|
||||
import NIO
|
||||
import NIOIMAP
|
||||
import SystemPackage
|
||||
import Testing
|
||||
|
||||
private struct ArgumentFixture<A: ExpressibleByArgument & Equatable & Sendable>: Sendable {
|
||||
var input: String
|
||||
var expected: A?
|
||||
}
|
||||
|
||||
@Suite
|
||||
private enum ExpressibleByArgumentTests {
|
||||
@Test(arguments: [
|
||||
ArgumentFixture<MessageID>(
|
||||
input: "<foo@apple.com>",
|
||||
expected: MessageID("<foo@apple.com>")
|
||||
),
|
||||
ArgumentFixture<MessageID>(
|
||||
input: "foo@apple.com",
|
||||
expected: MessageID("<foo@apple.com>")
|
||||
),
|
||||
ArgumentFixture<MessageID>(
|
||||
input: "<foo@apple.com",
|
||||
expected: nil
|
||||
),
|
||||
ArgumentFixture<MessageID>(
|
||||
input: "foo@apple.com>",
|
||||
expected: nil
|
||||
),
|
||||
ArgumentFixture<MessageID>(
|
||||
input: "",
|
||||
expected: nil
|
||||
),
|
||||
ArgumentFixture<MessageID>(
|
||||
input: " ",
|
||||
expected: nil
|
||||
),
|
||||
ArgumentFixture<MessageID>(
|
||||
input: "<>",
|
||||
expected: nil
|
||||
),
|
||||
])
|
||||
static func messageID(
|
||||
fixture: ArgumentFixture<MessageID>
|
||||
) {
|
||||
if let expected = fixture.expected {
|
||||
#expect(MessageID(argument: fixture.input) == expected)
|
||||
} else {
|
||||
#expect(MessageID(argument: fixture.input) == nil)
|
||||
}
|
||||
}
|
||||
|
||||
@Test(arguments: [
|
||||
ArgumentFixture<MailboxName>(
|
||||
input: "INBOX",
|
||||
expected: try? MailboxPath.makeRootMailbox(displayName: "INBOX").name
|
||||
),
|
||||
ArgumentFixture<MailboxName>(
|
||||
input: "Sent",
|
||||
expected: try? MailboxPath.makeRootMailbox(displayName: "Sent").name
|
||||
),
|
||||
ArgumentFixture<MailboxName>(
|
||||
input: "Archive/2024",
|
||||
expected: try? MailboxPath.makeRootMailbox(displayName: "Archive/2024").name
|
||||
),
|
||||
])
|
||||
static func mailboxName(
|
||||
fixture: ArgumentFixture<MailboxName>
|
||||
) {
|
||||
if let expected = fixture.expected {
|
||||
#expect(MailboxName(argument: fixture.input) == expected)
|
||||
} else {
|
||||
#expect(MailboxName(argument: fixture.input) == nil)
|
||||
}
|
||||
}
|
||||
|
||||
@Test(arguments: [
|
||||
ArgumentFixture<FilePath>(
|
||||
input: "/path/to/file",
|
||||
expected: FilePath("/path/to/file")
|
||||
),
|
||||
ArgumentFixture<FilePath>(
|
||||
input: "relative/path",
|
||||
expected: FilePath("relative/path")
|
||||
),
|
||||
ArgumentFixture<FilePath>(
|
||||
input: "",
|
||||
expected: FilePath("")
|
||||
),
|
||||
])
|
||||
static func filePath(
|
||||
fixture: ArgumentFixture<FilePath>
|
||||
) {
|
||||
if let expected = fixture.expected {
|
||||
#expect(FilePath(argument: fixture.input) == expected)
|
||||
} else {
|
||||
#expect(FilePath(argument: fixture.input) == nil)
|
||||
}
|
||||
}
|
||||
|
||||
@Test(arguments: [
|
||||
ArgumentFixture<UID>(
|
||||
input: "1",
|
||||
expected: UID(exactly: 1)
|
||||
),
|
||||
ArgumentFixture<UID>(
|
||||
input: "42",
|
||||
expected: UID(exactly: 42)
|
||||
),
|
||||
ArgumentFixture<UID>(
|
||||
input: "4294967295",
|
||||
expected: UID(exactly: 4_294_967_295)
|
||||
),
|
||||
ArgumentFixture<UID>(
|
||||
input: "0",
|
||||
expected: nil
|
||||
),
|
||||
ArgumentFixture<UID>(
|
||||
input: "-1",
|
||||
expected: nil
|
||||
),
|
||||
ArgumentFixture<UID>(
|
||||
input: "abc",
|
||||
expected: nil
|
||||
),
|
||||
ArgumentFixture<UID>(
|
||||
input: "4294967296",
|
||||
expected: nil
|
||||
),
|
||||
])
|
||||
static func uid(
|
||||
fixture: ArgumentFixture<UID>
|
||||
) {
|
||||
if let expected = fixture.expected {
|
||||
#expect(UID(argument: fixture.input) == expected)
|
||||
} else {
|
||||
#expect(UID(argument: fixture.input) == nil)
|
||||
}
|
||||
}
|
||||
|
||||
@Test(arguments: [
|
||||
ArgumentFixture<RecordSeparator>(input: "1e", expected: .recordSeparator),
|
||||
ArgumentFixture<RecordSeparator>(input: "rs", expected: .recordSeparator),
|
||||
ArgumentFixture<RecordSeparator>(input: "recordSeparator", expected: .recordSeparator),
|
||||
ArgumentFixture<RecordSeparator>(input: "json-seq", expected: .recordSeparator),
|
||||
ArgumentFixture<RecordSeparator>(input: "0a", expected: .lineFeed),
|
||||
ArgumentFixture<RecordSeparator>(input: "lf", expected: .lineFeed),
|
||||
ArgumentFixture<RecordSeparator>(input: "linefeed", expected: .lineFeed),
|
||||
// Case-insensitive: these used to fail because the labels were mixed-case.
|
||||
ArgumentFixture<RecordSeparator>(input: "lineFeed", expected: .lineFeed),
|
||||
ArgumentFixture<RecordSeparator>(input: "LINEFEED", expected: .lineFeed),
|
||||
ArgumentFixture<RecordSeparator>(input: "0d", expected: .carriageReturn),
|
||||
ArgumentFixture<RecordSeparator>(input: "cr", expected: .carriageReturn),
|
||||
ArgumentFixture<RecordSeparator>(input: "carriageReturn", expected: .carriageReturn),
|
||||
ArgumentFixture<RecordSeparator>(input: "carriagereturn", expected: .carriageReturn),
|
||||
ArgumentFixture<RecordSeparator>(input: "", expected: nil),
|
||||
ArgumentFixture<RecordSeparator>(input: "nope", expected: nil),
|
||||
])
|
||||
static func recordSeparator(
|
||||
fixture: ArgumentFixture<RecordSeparator>
|
||||
) {
|
||||
#expect(RecordSeparator(argument: fixture.input) == fixture.expected)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,288 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import ArgumentParser
|
||||
@testable import IMAPToolLib
|
||||
@testable import IMAPCommands
|
||||
import Foundation
|
||||
import NIO
|
||||
import NIOIMAP
|
||||
import Testing
|
||||
|
||||
private enum MailboxCommandTests {
|
||||
static func parseDelete(
|
||||
_ arguments: [String],
|
||||
sourceLocation: SourceLocation = #_sourceLocation
|
||||
) throws -> MailboxCommand.Delete {
|
||||
try ArgumentParsingTests.parse(
|
||||
MailboxCommand.Delete.self,
|
||||
arguments,
|
||||
sourceLocation: sourceLocation
|
||||
)
|
||||
}
|
||||
|
||||
static func parseRename(
|
||||
_ arguments: [String],
|
||||
sourceLocation: SourceLocation = #_sourceLocation
|
||||
) throws -> MailboxCommand.Rename {
|
||||
try ArgumentParsingTests.parse(
|
||||
MailboxCommand.Rename.self,
|
||||
arguments,
|
||||
sourceLocation: sourceLocation
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - Delete Command Argument Parsing Tests
|
||||
|
||||
@Test
|
||||
static func parseDeleteCommand_singleMailbox() throws {
|
||||
let sut = try parseDelete([
|
||||
"mailbox",
|
||||
"delete",
|
||||
"--sasl", "plain:foo bar",
|
||||
"--server", "imap.example.com",
|
||||
"TestFolder",
|
||||
])
|
||||
|
||||
#expect(sut.connectionInfo.server == "imap.example.com")
|
||||
#expect(sut.connectionInfo.sasl == "plain:foo bar")
|
||||
#expect(sut.names == ["TestFolder"])
|
||||
#expect(sut.outputFormat == .text)
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseDeleteCommand_multipleMailboxes() throws {
|
||||
let sut = try parseDelete([
|
||||
"mailbox",
|
||||
"delete",
|
||||
"--username", "user:pass",
|
||||
"--server", "mail.example.com",
|
||||
"OldFolder1",
|
||||
"OldFolder2",
|
||||
"TempFolder",
|
||||
])
|
||||
|
||||
#expect(sut.connectionInfo.server == "mail.example.com")
|
||||
#expect(sut.connectionInfo.username == "user:pass")
|
||||
#expect(
|
||||
sut.names == [
|
||||
"OldFolder1",
|
||||
"OldFolder2",
|
||||
"TempFolder",
|
||||
]
|
||||
)
|
||||
#expect(sut.outputFormat == .text)
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseDeleteCommand_withOutputFormat() throws {
|
||||
let sut = try parseDelete([
|
||||
"mailbox",
|
||||
"delete",
|
||||
"--sasl", "plain:foo bar",
|
||||
"--server", "imap.example.com",
|
||||
"TestFolder",
|
||||
"--output-format", "json",
|
||||
])
|
||||
|
||||
#expect(sut.connectionInfo.server == "imap.example.com")
|
||||
#expect(sut.names == ["TestFolder"])
|
||||
#expect(sut.outputFormat == .json)
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseDeleteCommand_nestedMailboxNames() throws {
|
||||
let sut = try parseDelete([
|
||||
"mailbox",
|
||||
"delete",
|
||||
"--sasl", "plain:foo bar",
|
||||
"--server", "imap.example.com",
|
||||
"INBOX.Work.OldProject",
|
||||
"INBOX.Archives.2023",
|
||||
])
|
||||
|
||||
#expect(sut.connectionInfo.server == "imap.example.com")
|
||||
#expect(
|
||||
sut.names == [
|
||||
"INBOX.Work.OldProject",
|
||||
"INBOX.Archives.2023",
|
||||
]
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseDeleteCommand_validation_noNames() throws {
|
||||
#expect(
|
||||
performing: {
|
||||
_ = try parseDelete([
|
||||
"mailbox",
|
||||
"delete",
|
||||
"--sasl", "plain:foo bar",
|
||||
"--server", "imap.example.com",
|
||||
])
|
||||
},
|
||||
throws: {
|
||||
#expect(
|
||||
RootCommand.fullMessage(for: $0).prefix(while: { !$0.isNewline })
|
||||
== "Error: Must specify at least one mailbox"
|
||||
)
|
||||
return true
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - Rename Command Argument Parsing Tests
|
||||
|
||||
@Test
|
||||
static func parseRenameCommand_basic() throws {
|
||||
let sut = try parseRename([
|
||||
"mailbox",
|
||||
"rename",
|
||||
"--sasl", "plain:foo bar",
|
||||
"--server", "imap.example.com",
|
||||
"--old-name", "OldFolder",
|
||||
"--new-name", "NewFolder",
|
||||
])
|
||||
|
||||
#expect(sut.connectionInfo.server == "imap.example.com")
|
||||
#expect(sut.connectionInfo.sasl == "plain:foo bar")
|
||||
#expect(sut.oldName == "OldFolder")
|
||||
#expect(sut.newName == "NewFolder")
|
||||
#expect(sut.outputFormat == .text)
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseRenameCommand_withOutputFormat() throws {
|
||||
let sut = try parseRename([
|
||||
"mailbox",
|
||||
"rename",
|
||||
"--username", "user:pass",
|
||||
"--server", "mail.example.com",
|
||||
"--old-name", "OldName",
|
||||
"--new-name", "NewName",
|
||||
"--output-format", "json",
|
||||
])
|
||||
|
||||
#expect(sut.connectionInfo.server == "mail.example.com")
|
||||
#expect(sut.connectionInfo.username == "user:pass")
|
||||
#expect(sut.oldName == "OldName")
|
||||
#expect(sut.newName == "NewName")
|
||||
#expect(sut.outputFormat == .json)
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseRenameCommand_nestedMailboxNames() throws {
|
||||
let sut = try parseRename([
|
||||
"mailbox",
|
||||
"rename",
|
||||
"--sasl", "plain:foo bar",
|
||||
"--server", "imap.example.com",
|
||||
"--old-name", "INBOX.Work.Project1",
|
||||
"--new-name", "INBOX.Archives.CompletedProject1",
|
||||
])
|
||||
|
||||
#expect(sut.connectionInfo.server == "imap.example.com")
|
||||
#expect(sut.oldName == "INBOX.Work.Project1")
|
||||
#expect(sut.newName == "INBOX.Archives.CompletedProject1")
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseRenameCommand_allConnectionOptions() throws {
|
||||
let sut = try parseRename([
|
||||
"mailbox",
|
||||
"rename",
|
||||
"--username", "testuser:testpass",
|
||||
"--server", "imap.example.com:143",
|
||||
"--old-name", "OldFolder",
|
||||
"--new-name", "NewFolder",
|
||||
])
|
||||
|
||||
#expect(sut.connectionInfo.username == "testuser:testpass")
|
||||
#expect(sut.connectionInfo.server == "imap.example.com:143")
|
||||
#expect(sut.oldName == "OldFolder")
|
||||
#expect(sut.newName == "NewFolder")
|
||||
}
|
||||
|
||||
// MARK: - Command Alias Tests
|
||||
|
||||
@Test
|
||||
static func parseDeleteCommand_usingMailboxAlias() throws {
|
||||
let sut = try parseDelete([
|
||||
"mailboxes", // Using alias instead of "mailbox"
|
||||
"delete",
|
||||
"--sasl", "plain:foo bar",
|
||||
"--server", "imap.example.com",
|
||||
"TestFolder",
|
||||
])
|
||||
|
||||
#expect(sut.connectionInfo.server == "imap.example.com")
|
||||
#expect(sut.names == ["TestFolder"])
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseRenameCommand_usingMaildirAlias() throws {
|
||||
let sut = try parseRename([
|
||||
"maildir", // Using alias instead of "mailbox"
|
||||
"rename",
|
||||
"--sasl", "plain:foo bar",
|
||||
"--server", "imap.example.com",
|
||||
"--old-name", "OldFolder",
|
||||
"--new-name", "NewFolder",
|
||||
])
|
||||
|
||||
#expect(sut.connectionInfo.server == "imap.example.com")
|
||||
#expect(sut.oldName == "OldFolder")
|
||||
#expect(sut.newName == "NewFolder")
|
||||
}
|
||||
|
||||
// MARK: - Validation Tests
|
||||
|
||||
@Test
|
||||
static func parseDeleteCommand_duplicateNames() throws {
|
||||
#expect(
|
||||
performing: {
|
||||
_ = try parseDelete([
|
||||
"mailbox",
|
||||
"delete",
|
||||
"--sasl", "plain:foo bar",
|
||||
"--server", "imap.example.com",
|
||||
"TestFolder",
|
||||
"TestFolder",
|
||||
"OtherFolder",
|
||||
])
|
||||
},
|
||||
throws: {
|
||||
#expect(
|
||||
RootCommand.fullMessage(for: $0).prefix(while: { !$0.isNewline })
|
||||
== "Error: Duplicate mailbox name 'TestFolder'"
|
||||
)
|
||||
return true
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseRenameCommand_sameSourceAndTarget() throws {
|
||||
// This shouldn’t throw. Server might return an error
|
||||
// at run-time, though.
|
||||
_ = try parseRename([
|
||||
"mailbox",
|
||||
"rename",
|
||||
"--sasl", "plain:foo bar",
|
||||
"--server", "imap.example.com",
|
||||
"--old-name", "SameFolder",
|
||||
"--new-name", "SameFolder",
|
||||
])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,306 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import ArgumentParser
|
||||
@testable import IMAPToolLib
|
||||
@testable import IMAPCommands
|
||||
import Foundation
|
||||
import NIO
|
||||
import NIOIMAP
|
||||
import Testing
|
||||
|
||||
private enum MessageFlagCommandTests {
|
||||
static func parse(
|
||||
_ arguments: [String],
|
||||
sourceLocation: SourceLocation = #_sourceLocation
|
||||
) throws -> MessageFlagCommand {
|
||||
try ArgumentParsingTests.parse(
|
||||
MessageFlagCommand.self,
|
||||
arguments,
|
||||
sourceLocation: sourceLocation
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseFlagsCommand_withUID() throws {
|
||||
let sut = try parse([
|
||||
"flags",
|
||||
"--sasl", "plain:foo bar",
|
||||
"--server", "bar.example.com",
|
||||
"--mailbox", "INBOX",
|
||||
"--uid", "123",
|
||||
"--flag", "seen",
|
||||
"--flag", "flagged",
|
||||
])
|
||||
#expect(sut.connectionInfo.server == "bar.example.com")
|
||||
#expect(sut.mailbox == .inbox)
|
||||
#expect(sut.uids == [123])
|
||||
#expect(sut.messages == nil)
|
||||
#expect(sut.setFlags == [.seen, .flagged])
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseFlagsCommand_withMessages() throws {
|
||||
let sut = try parse([
|
||||
"flags",
|
||||
"--sasl", "plain:foo bar",
|
||||
"--server", "bar.example.com",
|
||||
"--mailbox", "INBOX",
|
||||
"--flag", "seen",
|
||||
"--flag", "flagged",
|
||||
"--messages", "messages.json",
|
||||
])
|
||||
#expect(sut.connectionInfo.server == "bar.example.com")
|
||||
#expect(sut.mailbox == .inbox)
|
||||
#expect(sut.uids == [])
|
||||
#expect(sut.messages == "messages.json")
|
||||
#expect(sut.setFlags == [.seen, .flagged])
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseFlagsCommand_validation_noFlags() throws {
|
||||
// This should actually be valid - you can specify UIDs without flags
|
||||
// if you want to just select the messages (though not very useful)
|
||||
let sut = try parse([
|
||||
"flags",
|
||||
"--sasl", "plain:foo bar",
|
||||
"--server", "bar.example.com",
|
||||
"--uid", "123",
|
||||
// No flags specified - this is technically valid
|
||||
])
|
||||
#expect(sut.setFlags == [])
|
||||
#expect(sut.unsetFlags == [])
|
||||
#expect(sut.uids == [123])
|
||||
#expect(sut.messageIDs == [])
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseFlagsCommand_multipleUIDs() throws {
|
||||
let sut = try parse([
|
||||
"flags",
|
||||
"--sasl", "plain:foo bar",
|
||||
"--server", "example.com",
|
||||
"--uid", "123",
|
||||
"--uid", "456",
|
||||
"--uid", "789",
|
||||
"--flag", "seen",
|
||||
])
|
||||
#expect(sut.uids == [123, 456, 789])
|
||||
#expect(sut.messageIDs == [])
|
||||
#expect(sut.setFlags == [.seen])
|
||||
#expect(sut.unsetFlags == [])
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseFlagsCommand_singleMessageID() throws {
|
||||
let sut = try parse([
|
||||
"flags",
|
||||
"--sasl", "plain:foo bar",
|
||||
"--server", "example.com",
|
||||
"--message-id", "foo@mail.example.com",
|
||||
"--flag", "seen",
|
||||
])
|
||||
#expect(sut.uids == [])
|
||||
#expect(sut.messageIDs == ["<foo@mail.example.com>"])
|
||||
#expect(sut.setFlags == [.seen])
|
||||
#expect(sut.unsetFlags == [])
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseFlagsCommand_messageIDsAndUID() throws {
|
||||
let sut = try parse([
|
||||
"flags",
|
||||
"--sasl", "plain:foo bar",
|
||||
"--server", "example.com",
|
||||
"--message-id", "foo@mail.example.com",
|
||||
"--uid", "123",
|
||||
"--flag", "seen",
|
||||
])
|
||||
#expect(sut.uids == [123])
|
||||
#expect(sut.messageIDs == ["<foo@mail.example.com>"])
|
||||
#expect(sut.setFlags == [.seen])
|
||||
#expect(sut.unsetFlags == [])
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseFlagsCommand_multipleMessageIDs() throws {
|
||||
let sut = try parse([
|
||||
"flags",
|
||||
"--sasl", "plain:foo bar",
|
||||
"--server", "example.com",
|
||||
"--message-id", "foo@mail.example.com",
|
||||
"--message-id", "<bar@mail.example.com>",
|
||||
"--flag", "seen",
|
||||
])
|
||||
#expect(sut.uids == [])
|
||||
#expect(sut.messageIDs == ["<foo@mail.example.com>", "<bar@mail.example.com>"])
|
||||
#expect(sut.setFlags == [.seen])
|
||||
#expect(sut.unsetFlags == [])
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseFlagsCommand_unsetFlags() throws {
|
||||
let sut = try parse([
|
||||
"flags",
|
||||
"--sasl", "plain:foo bar",
|
||||
"--server", "example.com",
|
||||
"--uid", "123",
|
||||
"--unset", "seen",
|
||||
"--unset", "flagged",
|
||||
])
|
||||
#expect(sut.setFlags == [])
|
||||
#expect(sut.unsetFlags == [.seen, .flagged])
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseFlagsCommand_setBothSetAndUnset() throws {
|
||||
let sut = try parse([
|
||||
"flags",
|
||||
"--sasl", "plain:foo bar",
|
||||
"--server", "example.com",
|
||||
"--uid", "123",
|
||||
"--set", "seen",
|
||||
"--set", "draft",
|
||||
"--remove", "flagged",
|
||||
"--remove", "deleted",
|
||||
])
|
||||
#expect(sut.setFlags == [.seen, .draft])
|
||||
#expect(sut.unsetFlags == [.flagged, .deleted])
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseFlagsCommand_allStandardFlags() throws {
|
||||
let sut = try parse([
|
||||
"flags",
|
||||
"--sasl", "plain:foo bar",
|
||||
"--server", "example.com",
|
||||
"--uid", "123",
|
||||
"--flag", "answered",
|
||||
"--flag", "flagged",
|
||||
"--flag", "deleted",
|
||||
"--flag", "seen",
|
||||
"--flag", "draft",
|
||||
])
|
||||
#expect(sut.setFlags == [.answered, .flagged, .deleted, .seen, .draft])
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseFlagsCommand_colorFlags() throws {
|
||||
let sut = try parse([
|
||||
"flags",
|
||||
"--sasl", "plain:foo bar",
|
||||
"--server", "example.com",
|
||||
"--uid", "123",
|
||||
"--flag", "red",
|
||||
"--flag", "orange",
|
||||
"--flag", "yellow",
|
||||
"--flag", "green",
|
||||
"--flag", "blue",
|
||||
"--flag", "purple",
|
||||
"--flag", "gray",
|
||||
])
|
||||
#expect(sut.setFlags == [.red, .orange, .yellow, .green, .blue, .purple, .gray])
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseFlagsCommand_customMailbox() throws {
|
||||
let sut = try parse([
|
||||
"flags",
|
||||
"--sasl", "plain:foo bar",
|
||||
"--server", "example.com",
|
||||
"--mailbox", "Sent",
|
||||
"--uid", "123",
|
||||
"--flag", "seen",
|
||||
])
|
||||
#expect(sut.mailbox == "Sent")
|
||||
#expect(sut.uids == [123])
|
||||
#expect(sut.setFlags == [.seen])
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseFlagsCommand_outputFormat() throws {
|
||||
let sut = try parse([
|
||||
"flags",
|
||||
"--sasl", "plain:foo bar",
|
||||
"--server", "example.com",
|
||||
"--uid", "123",
|
||||
"--flag", "seen",
|
||||
"--output-format", "json",
|
||||
])
|
||||
#expect(sut.outputFormat == .json)
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseFlagsCommand_aliasCommand() throws {
|
||||
let sut = try parse([
|
||||
"flag", // Using the alias instead of "flags"
|
||||
"--sasl", "plain:foo bar",
|
||||
"--server", "example.com",
|
||||
"--uid", "123",
|
||||
"--flag", "seen",
|
||||
])
|
||||
#expect(sut.uids == [123])
|
||||
#expect(sut.setFlags == [.seen])
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseFlagsCommand_longFormOptions() throws {
|
||||
let sut = try parse([
|
||||
"flags",
|
||||
"--sasl", "plain:foo bar",
|
||||
"--server", "example.com",
|
||||
"--uid", "123",
|
||||
"--set", "seen", // Using --set instead of --flag
|
||||
"--remove", "flagged", // Using --remove instead of --unset
|
||||
])
|
||||
#expect(sut.setFlags == [.seen])
|
||||
#expect(sut.unsetFlags == [.flagged])
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseFlagsCommand_validation_bothUIDsAndMessages() throws {
|
||||
// This should be valid - having both UIDs and messages file is allowed
|
||||
let sut = try parse([
|
||||
"flags",
|
||||
"--sasl", "plain:foo bar",
|
||||
"--server", "example.com",
|
||||
"--uid", "123",
|
||||
"--messages", "messages.json",
|
||||
"--flag", "seen",
|
||||
])
|
||||
#expect(sut.uids == [123])
|
||||
#expect(sut.messages == "messages.json")
|
||||
#expect(sut.setFlags == [.seen])
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseFlagsCommand_flagChangesConversion() throws {
|
||||
let sut = try parse([
|
||||
"flags",
|
||||
"--sasl", "plain:foo bar",
|
||||
"--server", "example.com",
|
||||
"--uid", "123",
|
||||
"--set", "seen",
|
||||
"--set", "flagged",
|
||||
"--unset", "deleted",
|
||||
"--unset", "draft",
|
||||
])
|
||||
|
||||
let flagChanges = sut.imapFlags
|
||||
|
||||
// Test that the conversion works correctly
|
||||
#expect(flagChanges.set == [.flagged, .seen])
|
||||
#expect(flagChanges.unset == [.deleted, .draft])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,290 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
@testable import IMAPToolLib
|
||||
import Foundation
|
||||
import NIOIMAP
|
||||
import Testing
|
||||
import ArgumentParser
|
||||
|
||||
extension NIOIMAP.Flag {
|
||||
static var mailFlagBit0: NIOIMAP.Flag { NIOIMAP.Flag("$MailFlagBit0") }
|
||||
static var mailFlagBit1: NIOIMAP.Flag { NIOIMAP.Flag("$MailFlagBit1") }
|
||||
static var mailFlagBit2: NIOIMAP.Flag { NIOIMAP.Flag("$MailFlagBit2") }
|
||||
}
|
||||
|
||||
@Suite
|
||||
private enum MessageFlagTests {
|
||||
struct FlagsToSetFixture: Hashable, CustomTestStringConvertible {
|
||||
var input: String
|
||||
var expected: Set<NIOIMAP.Flag>?
|
||||
|
||||
var testDescription: String { input }
|
||||
}
|
||||
|
||||
@Test(arguments: [
|
||||
// Standard IMAP flags
|
||||
FlagsToSetFixture(
|
||||
input: "answered",
|
||||
expected: [.answered]
|
||||
),
|
||||
FlagsToSetFixture(
|
||||
input: "flagged",
|
||||
expected: [.flagged]
|
||||
),
|
||||
FlagsToSetFixture(
|
||||
input: "deleted",
|
||||
expected: [.deleted]
|
||||
),
|
||||
FlagsToSetFixture(
|
||||
input: "seen",
|
||||
expected: [.seen]
|
||||
),
|
||||
FlagsToSetFixture(
|
||||
input: "draft",
|
||||
expected: [.draft]
|
||||
),
|
||||
|
||||
// Color flags (use mail flag bits)
|
||||
FlagsToSetFixture(
|
||||
input: "red",
|
||||
expected: [.flagged]
|
||||
),
|
||||
FlagsToSetFixture(
|
||||
input: "orange",
|
||||
expected: [.flagged, .mailFlagBit0]
|
||||
),
|
||||
FlagsToSetFixture(
|
||||
input: "yellow",
|
||||
expected: [.flagged, .mailFlagBit1]
|
||||
),
|
||||
FlagsToSetFixture(
|
||||
input: "green",
|
||||
expected: [.flagged, .mailFlagBit0, .mailFlagBit1, .mailFlagBit2]
|
||||
),
|
||||
FlagsToSetFixture(
|
||||
input: "blue",
|
||||
expected: [.flagged, .mailFlagBit2]
|
||||
),
|
||||
FlagsToSetFixture(
|
||||
input: "purple",
|
||||
expected: [.flagged, .mailFlagBit0, .mailFlagBit2]
|
||||
),
|
||||
FlagsToSetFixture(
|
||||
input: "gray",
|
||||
expected: [.flagged, .mailFlagBit1, .mailFlagBit2]
|
||||
),
|
||||
|
||||
// Invalid inputs (should return nil)
|
||||
FlagsToSetFixture(
|
||||
input: "invalid",
|
||||
expected: nil
|
||||
),
|
||||
FlagsToSetFixture(
|
||||
input: "ANSWERED", // case sensitive
|
||||
expected: nil
|
||||
),
|
||||
FlagsToSetFixture(
|
||||
input: "",
|
||||
expected: nil
|
||||
),
|
||||
FlagsToSetFixture(
|
||||
input: "unseen", // not a valid flag
|
||||
expected: nil
|
||||
),
|
||||
FlagsToSetFixture(
|
||||
input: "flag", // partial match
|
||||
expected: nil
|
||||
),
|
||||
])
|
||||
static func flagsToSet(
|
||||
fixture: FlagsToSetFixture
|
||||
) throws {
|
||||
let parsed = MessageFlag(argument: fixture.input)
|
||||
if let expected = fixture.expected {
|
||||
let p = try #require(parsed)
|
||||
#expect(p.flagsToSet == expected)
|
||||
} else {
|
||||
#expect(parsed == nil)
|
||||
}
|
||||
}
|
||||
|
||||
@Test(arguments: [
|
||||
// Standard IMAP flags (unset themselves)
|
||||
FlagsToSetFixture(
|
||||
input: "answered",
|
||||
expected: [.answered]
|
||||
),
|
||||
FlagsToSetFixture(
|
||||
input: "flagged",
|
||||
expected: [.flagged]
|
||||
),
|
||||
FlagsToSetFixture(
|
||||
input: "deleted",
|
||||
expected: [.deleted]
|
||||
),
|
||||
FlagsToSetFixture(
|
||||
input: "seen",
|
||||
expected: [.seen]
|
||||
),
|
||||
FlagsToSetFixture(
|
||||
input: "draft",
|
||||
expected: [.draft]
|
||||
),
|
||||
|
||||
// Color flags (unset all color flags)
|
||||
FlagsToSetFixture(
|
||||
input: "red",
|
||||
expected: [.flagged, .mailFlagBit0, .mailFlagBit1, .mailFlagBit2]
|
||||
),
|
||||
FlagsToSetFixture(
|
||||
input: "orange",
|
||||
expected: [.flagged, .mailFlagBit0, .mailFlagBit1, .mailFlagBit2]
|
||||
),
|
||||
FlagsToSetFixture(
|
||||
input: "yellow",
|
||||
expected: [.flagged, .mailFlagBit0, .mailFlagBit1, .mailFlagBit2]
|
||||
),
|
||||
FlagsToSetFixture(
|
||||
input: "green",
|
||||
expected: [.flagged, .mailFlagBit0, .mailFlagBit1, .mailFlagBit2]
|
||||
),
|
||||
FlagsToSetFixture(
|
||||
input: "blue",
|
||||
expected: [.flagged, .mailFlagBit0, .mailFlagBit1, .mailFlagBit2]
|
||||
),
|
||||
FlagsToSetFixture(
|
||||
input: "purple",
|
||||
expected: [.flagged, .mailFlagBit0, .mailFlagBit1, .mailFlagBit2]
|
||||
),
|
||||
FlagsToSetFixture(
|
||||
input: "gray",
|
||||
expected: [.flagged, .mailFlagBit0, .mailFlagBit1, .mailFlagBit2]
|
||||
),
|
||||
|
||||
// Invalid inputs (should return nil)
|
||||
FlagsToSetFixture(
|
||||
input: "invalid",
|
||||
expected: nil
|
||||
),
|
||||
FlagsToSetFixture(
|
||||
input: "ANSWERED", // case sensitive
|
||||
expected: nil
|
||||
),
|
||||
FlagsToSetFixture(
|
||||
input: "",
|
||||
expected: nil
|
||||
),
|
||||
FlagsToSetFixture(
|
||||
input: "unseen", // not a valid flag
|
||||
expected: nil
|
||||
),
|
||||
FlagsToSetFixture(
|
||||
input: "flag", // partial match
|
||||
expected: nil
|
||||
),
|
||||
])
|
||||
static func flagsToUnset(
|
||||
fixture: FlagsToSetFixture
|
||||
) throws {
|
||||
let parsed = MessageFlag(argument: fixture.input)
|
||||
if let expected = fixture.expected {
|
||||
let p = try #require(parsed)
|
||||
#expect(p.flagsToUnset == expected)
|
||||
} else {
|
||||
#expect(parsed == nil)
|
||||
}
|
||||
}
|
||||
|
||||
struct FlagsToSearchFixture: Hashable, CustomTestStringConvertible {
|
||||
var flag: MessageFlag
|
||||
var expectedSet: Set<NIOIMAP.Flag>
|
||||
var expectedNotSet: Set<NIOIMAP.Flag>
|
||||
|
||||
var testDescription: String { flag.rawValue }
|
||||
}
|
||||
|
||||
@Test(arguments: [
|
||||
// Standard IMAP flags (set the flag, notSet is empty)
|
||||
FlagsToSearchFixture(
|
||||
flag: .answered,
|
||||
expectedSet: [.answered],
|
||||
expectedNotSet: []
|
||||
),
|
||||
FlagsToSearchFixture(
|
||||
flag: .flagged,
|
||||
expectedSet: [.flagged],
|
||||
expectedNotSet: []
|
||||
),
|
||||
FlagsToSearchFixture(
|
||||
flag: .deleted,
|
||||
expectedSet: [.deleted],
|
||||
expectedNotSet: []
|
||||
),
|
||||
FlagsToSearchFixture(
|
||||
flag: .seen,
|
||||
expectedSet: [.seen],
|
||||
expectedNotSet: []
|
||||
),
|
||||
FlagsToSearchFixture(
|
||||
flag: .draft,
|
||||
expectedSet: [.draft],
|
||||
expectedNotSet: []
|
||||
),
|
||||
|
||||
// Color flags (set flagged + specific bits, notSet contains other bits)
|
||||
FlagsToSearchFixture(
|
||||
flag: .red,
|
||||
expectedSet: [.flagged],
|
||||
expectedNotSet: [.mailFlagBit0, .mailFlagBit1, .mailFlagBit2]
|
||||
),
|
||||
FlagsToSearchFixture(
|
||||
flag: .orange,
|
||||
expectedSet: [.flagged, .mailFlagBit0],
|
||||
expectedNotSet: [.mailFlagBit1, .mailFlagBit2]
|
||||
),
|
||||
FlagsToSearchFixture(
|
||||
flag: .yellow,
|
||||
expectedSet: [.flagged, .mailFlagBit1],
|
||||
expectedNotSet: [.mailFlagBit0, .mailFlagBit2]
|
||||
),
|
||||
FlagsToSearchFixture(
|
||||
flag: .green,
|
||||
expectedSet: [.flagged, .mailFlagBit0, .mailFlagBit1, .mailFlagBit2],
|
||||
expectedNotSet: []
|
||||
),
|
||||
FlagsToSearchFixture(
|
||||
flag: .blue,
|
||||
expectedSet: [.flagged, .mailFlagBit2],
|
||||
expectedNotSet: [.mailFlagBit0, .mailFlagBit1]
|
||||
),
|
||||
FlagsToSearchFixture(
|
||||
flag: .purple,
|
||||
expectedSet: [.flagged, .mailFlagBit0, .mailFlagBit2],
|
||||
expectedNotSet: [.mailFlagBit1]
|
||||
),
|
||||
FlagsToSearchFixture(
|
||||
flag: .gray,
|
||||
expectedSet: [.flagged, .mailFlagBit1, .mailFlagBit2],
|
||||
expectedNotSet: [.mailFlagBit0]
|
||||
),
|
||||
])
|
||||
static func flagsToSearch(
|
||||
fixture: FlagsToSearchFixture
|
||||
) throws {
|
||||
let result = fixture.flag.flagsToSearch
|
||||
#expect(result.set == fixture.expectedSet)
|
||||
#expect(result.notSet == fixture.expectedNotSet)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import Testing
|
||||
import ArgumentParser
|
||||
@testable import IMAPToolLib
|
||||
import NIOIMAP
|
||||
|
||||
@Suite
|
||||
enum MoveMessageCommandTests {
|
||||
static func parse(_ arguments: [String]) throws -> MoveMessageCommand {
|
||||
try ArgumentParsingTests.parse(MoveMessageCommand.self, arguments)
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseBasicMoveCommand_withUID() throws {
|
||||
let sut = try parse([
|
||||
"move-message",
|
||||
"--server", "imap.example.com",
|
||||
"--username", "testuser:testpass",
|
||||
"--source", "INBOX",
|
||||
"--destination", "Sent",
|
||||
"--uid", "123",
|
||||
])
|
||||
|
||||
#expect(sut.connectionInfo.server == "imap.example.com")
|
||||
#expect(sut.connectionInfo.username == "testuser:testpass")
|
||||
#expect(sut.sourceMailbox == "INBOX")
|
||||
#expect(sut.destinationMailbox == "Sent")
|
||||
#expect(sut.uids == [123])
|
||||
#expect(sut.messageIDs == [])
|
||||
#expect(sut.outputFormat == .text)
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseMultipleUIDs() throws {
|
||||
let sut = try parse([
|
||||
"move-message",
|
||||
"--server", "imap.example.com",
|
||||
"--username", "user:pass",
|
||||
"--source", "INBOX",
|
||||
"--destination", "Archive",
|
||||
"--uid", "1",
|
||||
"--uid", "2",
|
||||
"--uid", "100",
|
||||
])
|
||||
|
||||
#expect(sut.uids == [1, 2, 100])
|
||||
#expect(sut.messageIDs == [])
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseWithMessageID() throws {
|
||||
let sut = try parse([
|
||||
"move-message",
|
||||
"--server", "imap.example.com",
|
||||
"--username", "user:pass",
|
||||
"--source", "INBOX",
|
||||
"--destination", "Trash",
|
||||
"--message-id", "<msg123@example.com>",
|
||||
])
|
||||
|
||||
#expect(sut.uids == [])
|
||||
#expect(sut.messageIDs == [MessageID("<msg123@example.com>")])
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseMultipleMessageIDs() throws {
|
||||
let sut = try parse([
|
||||
"move-message",
|
||||
"--server", "imap.example.com",
|
||||
"--username", "user:pass",
|
||||
"--source", "INBOX",
|
||||
"--destination", "Archive",
|
||||
"--message-id", "<msg1@example.com>",
|
||||
"--message-id", "<msg2@example.com>",
|
||||
"--message-id", "<msg3@example.com>",
|
||||
])
|
||||
|
||||
#expect(sut.uids == [])
|
||||
#expect(
|
||||
sut.messageIDs == [
|
||||
MessageID("<msg1@example.com>"),
|
||||
MessageID("<msg2@example.com>"),
|
||||
MessageID("<msg3@example.com>"),
|
||||
]
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseMixedUIDsAndMessageIDs() throws {
|
||||
let sut = try parse([
|
||||
"move-message",
|
||||
"--server", "imap.example.com",
|
||||
"--username", "user:pass",
|
||||
"--source", "INBOX",
|
||||
"--destination", "Spam",
|
||||
"--uid", "42",
|
||||
"--message-id", "<msg@example.com>",
|
||||
"--uid", "99",
|
||||
])
|
||||
|
||||
#expect(sut.uids == [42, 99])
|
||||
#expect(sut.messageIDs == [MessageID("<msg@example.com>")])
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseAlternativeMailboxNames() throws {
|
||||
let sut = try parse([
|
||||
"move-message",
|
||||
"--server", "imap.example.com",
|
||||
"--username", "user:pass",
|
||||
"--from", "INBOX",
|
||||
"--to", "Sent",
|
||||
"--uid", "1",
|
||||
])
|
||||
|
||||
#expect(sut.sourceMailbox == "INBOX")
|
||||
#expect(sut.destinationMailbox == "Sent")
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseWithJSONOutputFormat() throws {
|
||||
let sut = try parse([
|
||||
"move-message",
|
||||
"--server", "imap.example.com",
|
||||
"--username", "user:pass",
|
||||
"--source", "INBOX",
|
||||
"--destination", "Archive",
|
||||
"--uid", "1",
|
||||
"--output-format", "json",
|
||||
])
|
||||
|
||||
#expect(sut.outputFormat == .json)
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseWithMessagesFile() throws {
|
||||
let sut = try parse([
|
||||
"move-message",
|
||||
"--server", "imap.example.com",
|
||||
"--username", "user:pass",
|
||||
"--source", "INBOX",
|
||||
"--destination", "Archive",
|
||||
"--messages", "/path/to/messages.json",
|
||||
])
|
||||
|
||||
#expect(sut.messages == "/path/to/messages.json")
|
||||
#expect(sut.uids == [])
|
||||
#expect(sut.messageIDs == [])
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseWithMessagesFileAndUIDs() throws {
|
||||
let sut = try parse([
|
||||
"move-message",
|
||||
"--server", "imap.example.com",
|
||||
"--username", "user:pass",
|
||||
"--source", "INBOX",
|
||||
"--destination", "Archive",
|
||||
"--messages", "/path/to/messages.json",
|
||||
"--uid", "123",
|
||||
])
|
||||
|
||||
#expect(sut.messages == "/path/to/messages.json")
|
||||
#expect(sut.uids == [123])
|
||||
}
|
||||
|
||||
@Test
|
||||
static func validationFailsWithNoMessageIdentifiers() throws {
|
||||
#expect(
|
||||
performing: {
|
||||
_ = try parse([
|
||||
"move-message",
|
||||
"--server", "imap.example.com",
|
||||
"--username", "user:pass",
|
||||
"--source", "INBOX",
|
||||
"--destination", "Archive",
|
||||
])
|
||||
},
|
||||
throws: {
|
||||
#expect(
|
||||
firstLineOfErrorMessage(for: $0)
|
||||
== "Error: Must specify at least one UID (--uid), Message-ID (--message-id), or a file to read from (--messages)."
|
||||
)
|
||||
return true
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,739 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import ArgumentParser
|
||||
@testable import IMAPToolLib
|
||||
@testable import IMAPCommands
|
||||
import Foundation
|
||||
import NIO
|
||||
@testable import NIOIMAPCore
|
||||
import Testing
|
||||
|
||||
@Suite("SearchMessagesCommand Tests")
|
||||
private enum SearchMessagesCommandTests {
|
||||
static func parse(
|
||||
_ arguments: [String],
|
||||
sourceLocation: SourceLocation = #_sourceLocation
|
||||
) throws -> SearchMessagesCommand {
|
||||
try ArgumentParsingTests.parse(
|
||||
SearchMessagesCommand.self,
|
||||
arguments,
|
||||
sourceLocation: sourceLocation
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - Command Argument Parsing Tests
|
||||
|
||||
@Test
|
||||
static func parseSearchCommand_basic() throws {
|
||||
let sut = try parse([
|
||||
"search-messages",
|
||||
"--sasl", "plain:foo bar",
|
||||
"--server", "bar.example.com",
|
||||
])
|
||||
#expect(sut.connectionInfo.server == "bar.example.com")
|
||||
#expect(sut.connectionInfo.sasl == "plain:foo bar")
|
||||
#expect(sut.mailbox == .inbox)
|
||||
#expect(sut.outputFormat == .text)
|
||||
#expect(sut.predicate.olderThanDays == nil)
|
||||
#expect(sut.predicate.newerThanDays == nil)
|
||||
#expect(sut.predicate.subject == nil)
|
||||
#expect(sut.predicate.fromAddress == nil)
|
||||
#expect(sut.predicate.flags == [])
|
||||
#expect(sut.shouldFetchMessageInfo == false)
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseSearchCommand_customMailbox() throws {
|
||||
let sut = try parse([
|
||||
"search-messages",
|
||||
"--sasl", "plain:foo bar",
|
||||
"--server", "example.com",
|
||||
"--mailbox", "Sent",
|
||||
])
|
||||
#expect(sut.mailbox == "Sent")
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseSearchCommand_outputFormat() throws {
|
||||
let sut = try parse([
|
||||
"search-messages",
|
||||
"--sasl", "plain:foo bar",
|
||||
"--server", "example.com",
|
||||
"--output-format", "json",
|
||||
])
|
||||
#expect(sut.outputFormat == .json)
|
||||
}
|
||||
|
||||
// MARK: - Date-based Search Parsing Tests
|
||||
|
||||
@Test
|
||||
static func parseSearchCommand_olderThanDays() throws {
|
||||
let sut = try parse([
|
||||
"search-messages",
|
||||
"--sasl", "plain:foo bar",
|
||||
"--server", "example.com",
|
||||
"--older-than-days", "30",
|
||||
])
|
||||
#expect(sut.predicate.olderThanDays == 30)
|
||||
#expect(sut.predicate.newerThanDays == nil)
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseSearchCommand_newerThanDays() throws {
|
||||
let sut = try parse([
|
||||
"search-messages",
|
||||
"--sasl", "plain:foo bar",
|
||||
"--server", "example.com",
|
||||
"--newer-than-days", "7",
|
||||
])
|
||||
#expect(sut.predicate.newerThanDays == 7)
|
||||
#expect(sut.predicate.olderThanDays == nil)
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseSearchCommand_bothDateRanges() throws {
|
||||
let sut = try parse([
|
||||
"search-messages",
|
||||
"--sasl", "plain:foo bar",
|
||||
"--server", "example.com",
|
||||
"--older-than-days", "90",
|
||||
"--newer-than-days", "30",
|
||||
])
|
||||
#expect(sut.predicate.olderThanDays == 90)
|
||||
#expect(sut.predicate.newerThanDays == 30)
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseSearchCommand_zeroDays() throws {
|
||||
let sut = try parse([
|
||||
"search-messages",
|
||||
"--sasl", "plain:foo bar",
|
||||
"--server", "example.com",
|
||||
"--older-than-days", "0",
|
||||
"--newer-than-days", "0",
|
||||
])
|
||||
#expect(sut.predicate.olderThanDays == 0)
|
||||
#expect(sut.predicate.newerThanDays == 0)
|
||||
}
|
||||
|
||||
// MARK: - Flag-based Search Parsing Tests
|
||||
|
||||
@Test
|
||||
static func parseSearchCommand_singleFlag() throws {
|
||||
let sut = try parse([
|
||||
"search-messages",
|
||||
"--sasl", "plain:foo bar",
|
||||
"--server", "example.com",
|
||||
"--flag", "seen",
|
||||
])
|
||||
#expect(sut.predicate.flags == [.seen])
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseSearchCommand_multipleFlags() throws {
|
||||
let sut = try parse([
|
||||
"search-messages",
|
||||
"--sasl", "plain:foo bar",
|
||||
"--server", "example.com",
|
||||
"--flag", "seen",
|
||||
"--flag", "flagged",
|
||||
"--flag", "answered",
|
||||
])
|
||||
#expect(sut.predicate.flags == [.seen, .flagged, .answered])
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseSearchCommand_allStandardFlags() throws {
|
||||
let sut = try parse([
|
||||
"search-messages",
|
||||
"--sasl", "plain:foo bar",
|
||||
"--server", "example.com",
|
||||
"--flag", "seen",
|
||||
"--flag", "flagged",
|
||||
"--flag", "answered",
|
||||
"--flag", "deleted",
|
||||
"--flag", "draft",
|
||||
])
|
||||
#expect(sut.predicate.flags == [.seen, .flagged, .answered, .deleted, .draft])
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseSearchCommand_mixedCaseFlags() throws {
|
||||
let sut = try parse([
|
||||
"search-messages",
|
||||
"--sasl", "plain:foo bar",
|
||||
"--server", "example.com",
|
||||
"--flag", "seen",
|
||||
"--flag", "flagged",
|
||||
"--flag", "answered",
|
||||
])
|
||||
#expect(sut.predicate.flags == [.seen, .flagged, .answered])
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseSearchCommand_unknownFlags() throws {
|
||||
// Unknown flags should fail to parse
|
||||
#expect(
|
||||
performing: {
|
||||
_ = try parse([
|
||||
"search-messages",
|
||||
"--sasl", "plain:foo bar",
|
||||
"--server", "example.com",
|
||||
"--flag", "seen",
|
||||
"--flag", "nonexistent",
|
||||
"--flag", "custom",
|
||||
])
|
||||
},
|
||||
throws: { _ in true }
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - Subject and From Search Parsing Tests
|
||||
|
||||
@Test
|
||||
static func parseSearchCommand_subject() throws {
|
||||
let sut = try parse([
|
||||
"search-messages",
|
||||
"--sasl", "plain:foo bar",
|
||||
"--server", "example.com",
|
||||
"--subject", "Meeting Tomorrow",
|
||||
])
|
||||
#expect(sut.predicate.subject == "Meeting Tomorrow")
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseSearchCommand_from() throws {
|
||||
let sut = try parse([
|
||||
"search-messages",
|
||||
"--sasl", "plain:foo bar",
|
||||
"--server", "example.com",
|
||||
"--from", "john@example.com",
|
||||
])
|
||||
#expect(sut.predicate.fromAddress == "john@example.com")
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseSearchCommand_subjectAndFrom() throws {
|
||||
let sut = try parse([
|
||||
"search-messages",
|
||||
"--sasl", "plain:foo bar",
|
||||
"--server", "example.com",
|
||||
"--subject", "Important",
|
||||
"--from", "boss@company.com",
|
||||
])
|
||||
#expect(sut.predicate.subject == "Important")
|
||||
#expect(sut.predicate.fromAddress == "boss@company.com")
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseSearchCommand_emptySubjectAndFrom() throws {
|
||||
let sut = try parse([
|
||||
"search-messages",
|
||||
"--sasl", "plain:foo bar",
|
||||
"--server", "example.com",
|
||||
"--subject", "",
|
||||
"--from", "",
|
||||
])
|
||||
#expect(sut.predicate.subject == "")
|
||||
#expect(sut.predicate.fromAddress == "")
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseSearchCommand_subjectWithSpaces() throws {
|
||||
let sut = try parse([
|
||||
"search-messages",
|
||||
"--sasl", "plain:foo bar",
|
||||
"--server", "example.com",
|
||||
"--subject", "Meeting scheduled for next week",
|
||||
])
|
||||
#expect(sut.predicate.subject == "Meeting scheduled for next week")
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseSearchCommand_fromWithDisplayName() throws {
|
||||
let sut = try parse([
|
||||
"search-messages",
|
||||
"--sasl", "plain:foo bar",
|
||||
"--server", "example.com",
|
||||
"--from", "John Doe <john@example.com>",
|
||||
])
|
||||
#expect(sut.predicate.fromAddress == "John Doe <john@example.com>")
|
||||
}
|
||||
|
||||
// MARK: - Message Info Return Flag Tests
|
||||
|
||||
@Test
|
||||
static func parseSearchCommand_returnMessageInfo() throws {
|
||||
let sut = try parse([
|
||||
"search-messages",
|
||||
"--sasl", "plain:foo bar",
|
||||
"--server", "example.com",
|
||||
"--fetch-message-info",
|
||||
])
|
||||
#expect(sut.shouldFetchMessageInfo == true)
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseSearchCommand_noReturnMessageInfo() throws {
|
||||
let sut = try parse([
|
||||
"search-messages",
|
||||
"--sasl", "plain:foo bar",
|
||||
"--server", "example.com",
|
||||
])
|
||||
#expect(sut.shouldFetchMessageInfo == false)
|
||||
}
|
||||
|
||||
// MARK: - Combined Search Criteria Tests
|
||||
|
||||
@Test
|
||||
static func parseSearchCommand_allCriteria() throws {
|
||||
let sut = try parse([
|
||||
"search-messages",
|
||||
"--sasl", "plain:foo bar",
|
||||
"--server", "example.com",
|
||||
"--mailbox", "Work",
|
||||
"--older-than-days", "30",
|
||||
"--newer-than-days", "7",
|
||||
"--subject", "Project Update",
|
||||
"--from", "manager@company.com",
|
||||
"--flag", "seen",
|
||||
"--flag", "flagged",
|
||||
"--fetch-message-info",
|
||||
"--output-format", "json",
|
||||
])
|
||||
#expect(sut.connectionInfo.server == "example.com")
|
||||
#expect(sut.mailbox == "Work")
|
||||
#expect(sut.predicate.olderThanDays == 30)
|
||||
#expect(sut.predicate.newerThanDays == 7)
|
||||
#expect(sut.predicate.subject == "Project Update")
|
||||
#expect(sut.predicate.fromAddress == "manager@company.com")
|
||||
#expect(sut.predicate.flags == [.seen, .flagged])
|
||||
#expect(sut.shouldFetchMessageInfo == true)
|
||||
#expect(sut.outputFormat == .json)
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseSearchCommand_multipleFlagsAndDates() throws {
|
||||
let sut = try parse([
|
||||
"search-messages",
|
||||
"--sasl", "plain:foo bar",
|
||||
"--server", "example.com",
|
||||
"--older-than-days", "90",
|
||||
"--newer-than-days", "30",
|
||||
"--flag", "seen",
|
||||
"--flag", "answered",
|
||||
"--flag", "flagged",
|
||||
])
|
||||
#expect(sut.predicate.olderThanDays == 90)
|
||||
#expect(sut.predicate.newerThanDays == 30)
|
||||
#expect(sut.predicate.flags == [.seen, .answered, .flagged])
|
||||
}
|
||||
|
||||
// MARK: - Edge Cases and Validation Tests
|
||||
|
||||
@Test
|
||||
static func parseSearchCommand_largeDayValues() throws {
|
||||
let sut = try parse([
|
||||
"search-messages",
|
||||
"--sasl", "plain:foo bar",
|
||||
"--server", "example.com",
|
||||
"--older-than-days", "365",
|
||||
"--newer-than-days", "1000",
|
||||
])
|
||||
#expect(sut.predicate.olderThanDays == 365)
|
||||
#expect(sut.predicate.newerThanDays == 1000)
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseSearchCommand_unicodeSubject() throws {
|
||||
let sut = try parse([
|
||||
"search-messages",
|
||||
"--sasl", "plain:foo bar",
|
||||
"--server", "example.com",
|
||||
"--subject", "测试邮件 🎉",
|
||||
])
|
||||
#expect(sut.predicate.subject == "测试邮件 🎉")
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseSearchCommand_specialCharactersInFrom() throws {
|
||||
let sut = try parse([
|
||||
"search-messages",
|
||||
"--sasl", "plain:foo bar",
|
||||
"--server", "example.com",
|
||||
"--from", "user+tag@example.com",
|
||||
])
|
||||
#expect(sut.predicate.fromAddress == "user+tag@example.com")
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseSearchCommand_duplicateFlags() throws {
|
||||
let sut = try parse([
|
||||
"search-messages",
|
||||
"--sasl", "plain:foo bar",
|
||||
"--server", "example.com",
|
||||
"--flag", "seen",
|
||||
"--flag", "seen",
|
||||
"--flag", "flagged",
|
||||
"--flag", "seen",
|
||||
])
|
||||
#expect(sut.predicate.flags == [.seen, .seen, .flagged, .seen])
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseSearchCommand_noSearchCriteria() throws {
|
||||
let sut = try parse([
|
||||
"search-messages",
|
||||
"--sasl", "plain:foo bar",
|
||||
"--server", "example.com",
|
||||
])
|
||||
// Should be valid - will use SearchKey.all
|
||||
#expect(sut.predicate.olderThanDays == nil)
|
||||
#expect(sut.predicate.newerThanDays == nil)
|
||||
#expect(sut.predicate.subject == nil)
|
||||
#expect(sut.predicate.fromAddress == nil)
|
||||
#expect(sut.predicate.flags == [])
|
||||
}
|
||||
|
||||
// MARK: - Search Logic Integration Tests
|
||||
|
||||
@Test
|
||||
static func searchLogic_dateCalculation() throws {
|
||||
// Test that date calculations work correctly
|
||||
let calendar = Calendar.current
|
||||
let today = Date()
|
||||
|
||||
// Test older than 30 days
|
||||
let olderDate = calendar.date(byAdding: .day, value: -30, to: today)!
|
||||
let olderComponents = calendar.dateComponents([.year, .month, .day], from: olderDate)
|
||||
let olderIMAPDate = IMAPCalendarDay(
|
||||
year: olderComponents.year!,
|
||||
month: olderComponents.month!,
|
||||
day: olderComponents.day!
|
||||
)
|
||||
#expect(olderIMAPDate != nil)
|
||||
|
||||
// Test newer than 7 days
|
||||
let newerDate = calendar.date(byAdding: .day, value: -7, to: today)!
|
||||
let newerComponents = calendar.dateComponents([.year, .month, .day], from: newerDate)
|
||||
let newerIMAPDate = IMAPCalendarDay(
|
||||
year: newerComponents.year!,
|
||||
month: newerComponents.month!,
|
||||
day: newerComponents.day!
|
||||
)
|
||||
#expect(newerIMAPDate != nil)
|
||||
|
||||
// Newer date should be more recent than older date
|
||||
if let older = olderIMAPDate, let newer = newerIMAPDate {
|
||||
#expect(newer.year >= older.year)
|
||||
if newer.year == older.year {
|
||||
#expect(newer.month >= older.month)
|
||||
if newer.month == older.month {
|
||||
#expect(newer.day >= older.day)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
static func searchLogic_flagMapping() throws {
|
||||
// Test that flag strings map correctly to lowercase
|
||||
let flagMappings: [String: String] = [
|
||||
"seen": "seen",
|
||||
"flagged": "flagged",
|
||||
"answered": "answered",
|
||||
"deleted": "deleted",
|
||||
"draft": "draft",
|
||||
]
|
||||
|
||||
for (input, expected) in flagMappings {
|
||||
// Test lowercase
|
||||
#expect(input.lowercased() == expected)
|
||||
|
||||
// Test that uppercase works too
|
||||
#expect(input.uppercased().lowercased() == expected)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
static func searchLogic_byteBufferCreation() throws {
|
||||
// Test ByteBuffer creation for subject and from strings
|
||||
let testStrings = [
|
||||
"Simple subject",
|
||||
"Subject with unicode 🎉",
|
||||
"Empty string: ",
|
||||
"Subject with\nnewlines\nand\ttabs",
|
||||
"user@example.com",
|
||||
"User Name <user@example.com>",
|
||||
"用户@example.com", // Unicode email
|
||||
]
|
||||
|
||||
for testString in testStrings {
|
||||
let buffer = ByteBuffer(string: testString)
|
||||
#expect(buffer.readableBytes > 0 || testString.isEmpty)
|
||||
|
||||
// Verify we can read the string back
|
||||
let reconstructed = buffer.getString(at: 0, length: buffer.readableBytes)
|
||||
#expect(reconstructed == testString)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
static func searchLogic_combinedSearchKeys() throws {
|
||||
// Test the logic for combining multiple search criteria
|
||||
var searchKeys: [SearchKey] = []
|
||||
|
||||
// Add various criteria
|
||||
searchKeys.append(.seen)
|
||||
searchKeys.append(.flagged)
|
||||
let subjectBuffer = ByteBuffer(string: "test")
|
||||
searchKeys.append(.subject(subjectBuffer))
|
||||
|
||||
// Test single key
|
||||
let singleKey = searchKeys.first!
|
||||
let singleKeyDesc = String(describing: singleKey).uppercased()
|
||||
#expect(singleKeyDesc.contains("SEEN"))
|
||||
|
||||
// Test combined key
|
||||
if searchKeys.count > 1 {
|
||||
let combinedKey = SearchKey.and(searchKeys)
|
||||
// The combined key should contain multiple search terms
|
||||
let combinedKeyDesc = String(describing: combinedKey).uppercased()
|
||||
#expect(combinedKeyDesc.contains("SEEN"))
|
||||
#expect(combinedKeyDesc.contains("FLAGGED"))
|
||||
#expect(combinedKeyDesc.contains("SUBJECT"))
|
||||
}
|
||||
|
||||
// Test empty case (should use .all)
|
||||
let emptyKeys: [SearchKey] = []
|
||||
if emptyKeys.isEmpty {
|
||||
let allKey = SearchKey.all
|
||||
let allKeyDesc = String(describing: allKey).uppercased()
|
||||
#expect(allKeyDesc.contains("ALL"))
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Invalid Input Tests
|
||||
|
||||
@Test
|
||||
static func parseSearchCommand_negativeOlderThanDays() throws {
|
||||
// Negative day values should be treated as invalid by ArgumentParser
|
||||
#expect(
|
||||
performing: {
|
||||
_ = try parse([
|
||||
"search-messages",
|
||||
"--sasl", "plain:foo bar",
|
||||
"--server", "example.com",
|
||||
"--older-than-days", "-5",
|
||||
])
|
||||
},
|
||||
throws: { _ in true }
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseSearchCommand_negativeNewerThanDays() throws {
|
||||
// Negative day values should be treated as invalid by ArgumentParser
|
||||
#expect(
|
||||
performing: {
|
||||
_ = try parse([
|
||||
"search-messages",
|
||||
"--sasl", "plain:foo bar",
|
||||
"--server", "example.com",
|
||||
"--newer-than-days", "-10",
|
||||
])
|
||||
},
|
||||
throws: { _ in true }
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - IMAPConnection Info Tests
|
||||
|
||||
@Test
|
||||
static func parseSearchCommand_usernameAuth() throws {
|
||||
let sut = try parse([
|
||||
"search-messages",
|
||||
"--username", "user:password",
|
||||
"--server", "example.com",
|
||||
])
|
||||
#expect(sut.connectionInfo.username == "user:password")
|
||||
#expect(sut.connectionInfo.sasl == nil)
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseSearchCommand_saslAuth() throws {
|
||||
let sut = try parse([
|
||||
"search-messages",
|
||||
"--sasl", "oauth:token123",
|
||||
"--server", "example.com",
|
||||
])
|
||||
#expect(sut.connectionInfo.sasl == "oauth:token123")
|
||||
#expect(sut.connectionInfo.username == nil)
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseSearchCommand_customPort() throws {
|
||||
let sut = try parse([
|
||||
"search-messages",
|
||||
"--username", "user:pass",
|
||||
"--server", "example.com:143",
|
||||
])
|
||||
#expect(sut.connectionInfo.server == "example.com:143")
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseSearchCommand_forceLogin() throws {
|
||||
let sut = try parse([
|
||||
"search-messages",
|
||||
"--username", "user:pass",
|
||||
"--server", "example.com",
|
||||
"--force-login",
|
||||
])
|
||||
#expect(sut.connectionInfo.forceLogin == true)
|
||||
#expect(sut.connectionInfo.authenticationMethod == .login)
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseSearchCommand_withoutForceLogin() throws {
|
||||
let sut = try parse([
|
||||
"search-messages",
|
||||
"--username", "user:pass",
|
||||
"--server", "example.com",
|
||||
])
|
||||
#expect(sut.connectionInfo.authenticationMethod == .automatic)
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseSearchCommand_forceLoginConflictsWithSASL() throws {
|
||||
let saslArguments = [
|
||||
"search-messages",
|
||||
"--sasl", "plain:dG9rZW4=",
|
||||
"--server", "example.com",
|
||||
]
|
||||
// The same arguments parse without the flag, so the flag is what’s rejected.
|
||||
_ = try parse(saslArguments)
|
||||
#expect(throws: (any Error).self) {
|
||||
try parse(saslArguments + ["--force-login"])
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Real-world Usage Pattern Tests
|
||||
|
||||
@Test
|
||||
static func parseSearchCommand_findUnreadMessagesFromLastWeek() throws {
|
||||
let sut = try parse([
|
||||
"search-messages",
|
||||
"--sasl", "oauth:token123",
|
||||
"--server", "imap.gmail.com",
|
||||
"--newer-than-days", "7",
|
||||
"--flag", "seen",
|
||||
"--fetch-message-info",
|
||||
])
|
||||
#expect(sut.predicate.newerThanDays == 7)
|
||||
#expect(sut.predicate.flags == [.seen])
|
||||
#expect(sut.shouldFetchMessageInfo == true)
|
||||
}
|
||||
|
||||
@Test
|
||||
static func searchLogic_sequenceNumberToMessageInfoMapping() throws {
|
||||
// Test that we understand the difference between sequence numbers and UIDs
|
||||
// This test documents the fix for the sequence number vs UID confusion
|
||||
|
||||
// Simulate search results (sequence numbers)
|
||||
let searchResults: [SequenceNumber] = [SequenceNumber(1), SequenceNumber(3), SequenceNumber(5)]
|
||||
|
||||
// Simulate message infos (with UIDs that are different from sequence numbers)
|
||||
struct MockMessageInfo {
|
||||
let uid: UInt32
|
||||
let sequenceNumber: Int
|
||||
}
|
||||
|
||||
let allMessageInfos = [
|
||||
MockMessageInfo(uid: 1001, sequenceNumber: 1), // seq 1, uid 1001
|
||||
MockMessageInfo(uid: 1005, sequenceNumber: 2), // seq 2, uid 1005
|
||||
MockMessageInfo(uid: 1007, sequenceNumber: 3), // seq 3, uid 1007
|
||||
MockMessageInfo(uid: 1012, sequenceNumber: 4), // seq 4, uid 1012
|
||||
MockMessageInfo(uid: 1015, sequenceNumber: 5), // seq 5, uid 1015
|
||||
]
|
||||
|
||||
// Test the WRONG approach (matching sequence numbers against UIDs)
|
||||
let searchUIDs = Set(searchResults.map { UInt32($0) }) // [1, 3, 5]
|
||||
let wrongFiltered = allMessageInfos.filter { searchUIDs.contains($0.uid) }
|
||||
#expect(wrongFiltered.isEmpty) // This fails because UIDs don't match sequence numbers
|
||||
|
||||
// Test the CORRECT approach (matching by sequence number position)
|
||||
let searchSequenceNumbers = Set(searchResults.map { Int($0) }) // [1, 3, 5]
|
||||
let correctFiltered = allMessageInfos.enumerated().compactMap { (index, messageInfo) in
|
||||
let sequenceNumber = index + 1 // Convert 0-based index to 1-based sequence
|
||||
return searchSequenceNumbers.contains(sequenceNumber) ? messageInfo : nil
|
||||
}
|
||||
#expect(correctFiltered.count == 3) // Should find 3 messages
|
||||
#expect(correctFiltered[0].uid == 1001) // seq 1 -> uid 1001
|
||||
#expect(correctFiltered[1].uid == 1007) // seq 3 -> uid 1007
|
||||
#expect(correctFiltered[2].uid == 1015) // seq 5 -> uid 1015
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseSearchCommand_findImportantEmailsFromBoss() throws {
|
||||
let sut = try parse([
|
||||
"search-messages",
|
||||
"--username", "employee:password",
|
||||
"--server", "company.com",
|
||||
"--from", "boss@company.com",
|
||||
"--flag", "flagged",
|
||||
"--subject", "urgent",
|
||||
"--mailbox", "INBOX",
|
||||
])
|
||||
#expect(sut.predicate.fromAddress == "boss@company.com")
|
||||
#expect(sut.predicate.flags == [.flagged])
|
||||
#expect(sut.predicate.subject == "urgent")
|
||||
#expect(sut.mailbox == .inbox)
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseSearchCommand_cleanupOldDrafts() throws {
|
||||
let sut = try parse([
|
||||
"search-messages",
|
||||
"--username", "user:pass",
|
||||
"--server", "example.com",
|
||||
"--mailbox", "Drafts",
|
||||
"--older-than-days", "90",
|
||||
"--flag", "draft",
|
||||
"--output-format", "json",
|
||||
])
|
||||
#expect(sut.mailbox == "Drafts")
|
||||
#expect(sut.predicate.olderThanDays == 90)
|
||||
#expect(sut.predicate.flags == [.draft])
|
||||
#expect(sut.outputFormat == .json)
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parseSearchCommand_findAnsweredEmailsInDateRange() throws {
|
||||
let sut = try parse([
|
||||
"search-messages",
|
||||
"--sasl", "plain:token123",
|
||||
"--server", "imap.example.com",
|
||||
"--older-than-days", "30",
|
||||
"--newer-than-days", "7",
|
||||
"--flag", "answered",
|
||||
"--flag", "seen",
|
||||
"--fetch-message-info",
|
||||
])
|
||||
#expect(sut.predicate.olderThanDays == 30)
|
||||
#expect(sut.predicate.newerThanDays == 7)
|
||||
#expect(sut.predicate.flags == [.answered, .seen])
|
||||
#expect(sut.shouldFetchMessageInfo == true)
|
||||
}
|
||||
}
|
||||
+310
@@ -0,0 +1,310 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import ArgumentParser
|
||||
@testable import IMAPToolLib
|
||||
import Foundation
|
||||
import NIO
|
||||
import NIOIMAP
|
||||
import Testing
|
||||
|
||||
@Suite("SearchMessagesCommand Tests")
|
||||
private enum SearchMessagesCommandPredicateTests {
|
||||
struct ParseFixture: Sendable, CustomTestStringConvertible {
|
||||
var arguments: [String]
|
||||
var expected: Expected
|
||||
|
||||
enum Expected: Sendable {
|
||||
case parse(SearchKey.Predicate)
|
||||
case fail(String)
|
||||
}
|
||||
|
||||
var testDescription: String { arguments.joined(separator: " ") }
|
||||
}
|
||||
|
||||
@Test(arguments: [
|
||||
ParseFixture(
|
||||
arguments: ["--from", "foo"],
|
||||
expected: .parse(
|
||||
SearchKey.Predicate(
|
||||
from: "foo"
|
||||
)
|
||||
)
|
||||
),
|
||||
ParseFixture(
|
||||
arguments: ["--to", "bar"],
|
||||
expected: .parse(
|
||||
SearchKey.Predicate(
|
||||
to: "bar"
|
||||
)
|
||||
)
|
||||
),
|
||||
ParseFixture(
|
||||
arguments: ["--cc", "baz"],
|
||||
expected: .parse(
|
||||
SearchKey.Predicate(
|
||||
cc: "baz"
|
||||
)
|
||||
)
|
||||
),
|
||||
ParseFixture(
|
||||
arguments: ["--subject", "test subject"],
|
||||
expected: .parse(
|
||||
SearchKey.Predicate(
|
||||
subject: "test subject"
|
||||
)
|
||||
)
|
||||
),
|
||||
ParseFixture(
|
||||
arguments: ["--text", "search text"],
|
||||
expected: .parse(
|
||||
SearchKey.Predicate(
|
||||
text: "search text"
|
||||
)
|
||||
)
|
||||
),
|
||||
ParseFixture(
|
||||
arguments: ["--older-than-days", "10"],
|
||||
expected: .parse(
|
||||
SearchKey.Predicate(
|
||||
olderThanDays: 10
|
||||
)
|
||||
)
|
||||
),
|
||||
ParseFixture(
|
||||
arguments: ["--newer-than-days", "5"],
|
||||
expected: .parse(
|
||||
SearchKey.Predicate(
|
||||
newerThanDays: 5
|
||||
)
|
||||
)
|
||||
),
|
||||
ParseFixture(
|
||||
arguments: ["--message-size-smaller-than", "1000"],
|
||||
expected: .parse(
|
||||
SearchKey.Predicate(
|
||||
messageSizeSmallerThan: 1000
|
||||
)
|
||||
)
|
||||
),
|
||||
ParseFixture(
|
||||
arguments: ["--message-size-larger-than", "500"],
|
||||
expected: .parse(
|
||||
SearchKey.Predicate(
|
||||
messageSizeLargerThan: 500
|
||||
)
|
||||
)
|
||||
),
|
||||
ParseFixture(
|
||||
arguments: ["--message-id", "<test@example.com>"],
|
||||
expected: .parse(
|
||||
SearchKey.Predicate(
|
||||
messageID: MessageID("<test@example.com>")
|
||||
)
|
||||
)
|
||||
),
|
||||
ParseFixture(
|
||||
arguments: ["--email-id", "test123"],
|
||||
expected: .parse(
|
||||
SearchKey.Predicate(
|
||||
emailID: EmailID("test123")
|
||||
)
|
||||
)
|
||||
),
|
||||
ParseFixture(
|
||||
arguments: ["--thread-id", "thread456"],
|
||||
expected: .parse(
|
||||
SearchKey.Predicate(
|
||||
threadID: ThreadID("thread456")
|
||||
)
|
||||
)
|
||||
),
|
||||
ParseFixture(
|
||||
arguments: ["--flag", "seen"],
|
||||
expected: .parse(
|
||||
SearchKey.Predicate(
|
||||
flagsSet: [.seen]
|
||||
)
|
||||
)
|
||||
),
|
||||
ParseFixture(
|
||||
arguments: ["--flag", "red"],
|
||||
expected: .parse(
|
||||
SearchKey.Predicate(
|
||||
flagsSet: [.flagged],
|
||||
flagsNotSet: [.mailFlagBit0, .mailFlagBit1, .mailFlagBit2]
|
||||
)
|
||||
)
|
||||
),
|
||||
ParseFixture(
|
||||
arguments: ["--flag", "orange"],
|
||||
expected: .parse(
|
||||
SearchKey.Predicate(
|
||||
flagsSet: [.flagged, .mailFlagBit0],
|
||||
flagsNotSet: [.mailFlagBit1, .mailFlagBit2]
|
||||
)
|
||||
)
|
||||
),
|
||||
ParseFixture(
|
||||
arguments: ["--flag", "seen", "--flag", "deleted"],
|
||||
expected: .parse(
|
||||
SearchKey.Predicate(
|
||||
flagsSet: [.seen, .deleted]
|
||||
)
|
||||
)
|
||||
),
|
||||
ParseFixture(
|
||||
arguments: ["--flag", "red", "--flag", "orange"],
|
||||
expected: .fail("Error: Invalid combination of flags {red, orange}")
|
||||
),
|
||||
ParseFixture(
|
||||
arguments: ["--flag", "red", "--flag", "orange", "--flag", "answered"],
|
||||
expected: .fail("Error: Invalid combination of flags {red, orange}")
|
||||
),
|
||||
ParseFixture(
|
||||
arguments: ["--from", "sender@example.com", "--to", "recipient@example.com", "--flag", "seen"],
|
||||
expected: .parse(
|
||||
SearchKey.Predicate(
|
||||
from: "sender@example.com",
|
||||
to: "recipient@example.com",
|
||||
flagsSet: [.seen]
|
||||
)
|
||||
)
|
||||
),
|
||||
ParseFixture(
|
||||
arguments: ["--from", "boss@example.com", "--subject", "urgent", "--older-than-days", "7"],
|
||||
expected: .parse(
|
||||
SearchKey.Predicate(
|
||||
olderThanDays: 7,
|
||||
subject: "urgent",
|
||||
from: "boss@example.com"
|
||||
)
|
||||
)
|
||||
),
|
||||
ParseFixture(
|
||||
arguments: ["--from", "newsletter@example.com", "--message-size-larger-than", "1000000"],
|
||||
expected: .parse(
|
||||
SearchKey.Predicate(
|
||||
from: "newsletter@example.com",
|
||||
messageSizeLargerThan: 1_000_000
|
||||
)
|
||||
)
|
||||
),
|
||||
ParseFixture(
|
||||
arguments: [
|
||||
"--text", "verification code", "--newer-than-days", "1", "--message-size-smaller-than", "5000",
|
||||
],
|
||||
expected: .parse(
|
||||
SearchKey.Predicate(
|
||||
newerThanDays: 1,
|
||||
text: "verification code",
|
||||
messageSizeSmallerThan: 5000
|
||||
)
|
||||
)
|
||||
),
|
||||
ParseFixture(
|
||||
arguments: [
|
||||
"--from", "team@example.com", "--to", "me@example.com", "--cc", "manager@example.com", "--subject",
|
||||
"project update",
|
||||
],
|
||||
expected: .parse(
|
||||
SearchKey.Predicate(
|
||||
subject: "project update",
|
||||
from: "team@example.com",
|
||||
to: "me@example.com",
|
||||
cc: "manager@example.com"
|
||||
)
|
||||
)
|
||||
),
|
||||
ParseFixture(
|
||||
arguments: ["--subject", "invoice", "--text", "payment due", "--newer-than-days", "30"],
|
||||
expected: .parse(
|
||||
SearchKey.Predicate(
|
||||
newerThanDays: 30,
|
||||
subject: "invoice",
|
||||
text: "payment due"
|
||||
)
|
||||
)
|
||||
),
|
||||
ParseFixture(
|
||||
arguments: ["--thread-id", "thread789", "--flag", "seen", "--flag", "answered"],
|
||||
expected: .parse(
|
||||
SearchKey.Predicate(
|
||||
threadID: ThreadID("thread789"),
|
||||
flagsSet: [.seen, .answered]
|
||||
)
|
||||
)
|
||||
),
|
||||
ParseFixture(
|
||||
arguments: ["--older-than-days", "365", "--message-size-larger-than", "10000000", "--flag", "seen"],
|
||||
expected: .parse(
|
||||
SearchKey.Predicate(
|
||||
olderThanDays: 365,
|
||||
messageSizeLargerThan: 10_000_000,
|
||||
flagsSet: [.seen]
|
||||
)
|
||||
)
|
||||
),
|
||||
ParseFixture(
|
||||
arguments: ["--older-than-days", "10", "--newer-than-days", "20"],
|
||||
expected: .parse(
|
||||
SearchKey.Predicate(
|
||||
olderThanDays: 10,
|
||||
newerThanDays: 20,
|
||||
)
|
||||
)
|
||||
),
|
||||
ParseFixture(
|
||||
arguments: ["--older-than-days", "20", "--newer-than-days", "10"],
|
||||
expected: .fail("Error: Messages can not be older than 20 and newer than 10 at the same time.")
|
||||
),
|
||||
])
|
||||
static func parse(
|
||||
fixture: ParseFixture
|
||||
) throws {
|
||||
switch fixture.expected {
|
||||
case .parse(let expected):
|
||||
let commandPredicate = try SearchMessagesCommand.Predicate.parse(fixture.arguments)
|
||||
let p = try SearchKey.Predicate(commandPredicate)
|
||||
#expect(p.olderThanDays == expected.olderThanDays)
|
||||
#expect(p.newerThanDays == expected.newerThanDays)
|
||||
#expect(p.subject == expected.subject)
|
||||
#expect(p.from == expected.from)
|
||||
#expect(p.to == expected.to)
|
||||
#expect(p.cc == expected.cc)
|
||||
#expect(p.text == expected.text)
|
||||
#expect(p.messageSizeSmallerThan == expected.messageSizeSmallerThan)
|
||||
#expect(p.messageSizeLargerThan == expected.messageSizeLargerThan)
|
||||
#expect(p.messageID == expected.messageID)
|
||||
#expect(p.emailID == expected.emailID)
|
||||
#expect(p.threadID == expected.threadID)
|
||||
#expect(p.flagsSet == expected.flagsSet)
|
||||
#expect(p.flagsNotSet == expected.flagsNotSet)
|
||||
case .fail(let expected):
|
||||
#expect(
|
||||
performing: {
|
||||
let commandPredicate = try SearchMessagesCommand.Predicate.parse(fixture.arguments)
|
||||
_ = try SearchKey.Predicate(commandPredicate)
|
||||
},
|
||||
throws: {
|
||||
#expect(
|
||||
firstLineOfErrorMessage(for: $0)
|
||||
== expected
|
||||
)
|
||||
return true
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import ArgumentParser
|
||||
@testable import IMAPToolLib
|
||||
import Testing
|
||||
|
||||
/// Verifies how ``main()`` decides to terminate: `--help`/`--version` must be
|
||||
/// treated as "clean" exits (standard output, exit code `0`), while genuine
|
||||
/// parsing errors must be non-clean (standard error, non-zero exit code).
|
||||
@Suite("Termination Info")
|
||||
enum TerminationInfoTests {
|
||||
/// Mirrors ``main()``: parse, then run, returning whichever step throws.
|
||||
///
|
||||
/// This matters because ArgumentParser signals `--help`/`--version` by
|
||||
/// having `run()` throw a clean-exit error — `parseAsRoot` itself does not
|
||||
/// throw for those. None of the arguments used below parse to a runnable
|
||||
/// subcommand that performs I/O.
|
||||
private static func terminationError(for arguments: [String]) async -> (any Error)? {
|
||||
do {
|
||||
var command = try RootCommand.parseAsRoot(arguments)
|
||||
if var asyncCommand = command as? AsyncParsableCommand {
|
||||
try await asyncCommand.run()
|
||||
} else {
|
||||
try command.run()
|
||||
}
|
||||
return nil
|
||||
} catch {
|
||||
return error
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
static func helpRequestIsACleanExit() async throws {
|
||||
let info = terminationInfo(for: try #require(await terminationError(for: ["--help"])))
|
||||
#expect(info.isCleanExit)
|
||||
#expect(info.code == 0)
|
||||
#expect(!info.message.isEmpty)
|
||||
}
|
||||
|
||||
@Test
|
||||
static func subcommandHelpRequestIsACleanExit() async throws {
|
||||
let info = terminationInfo(for: try #require(await terminationError(for: ["idle", "--help"])))
|
||||
#expect(info.isCleanExit)
|
||||
#expect(info.code == 0)
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parsingErrorIsNotACleanExit() async throws {
|
||||
// An unknown flag on a known subcommand is a usage error, not a clean exit.
|
||||
let info = terminationInfo(
|
||||
for: try #require(await terminationError(for: ["idle", "--this-flag-does-not-exist"]))
|
||||
)
|
||||
#expect(!info.isCleanExit)
|
||||
#expect(info.code != 0)
|
||||
}
|
||||
|
||||
@Test
|
||||
static func unknownSubcommandIsNotACleanExit() async throws {
|
||||
let info = terminationInfo(
|
||||
for: try #require(await terminationError(for: ["definitely-not-a-subcommand"]))
|
||||
)
|
||||
#expect(!info.isCleanExit)
|
||||
#expect(info.code != 0)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
@testable import IMAPToolLib
|
||||
import Foundation
|
||||
import NIO
|
||||
import NIOIMAP
|
||||
import Testing
|
||||
|
||||
@Suite
|
||||
enum UIDsAndMessageIDsTests {
|
||||
@Test
|
||||
static func parsingJSON_1() throws {
|
||||
let ids = try UIDsAndMessageIDs.parse(
|
||||
input: Data(
|
||||
#"""
|
||||
{"messages" : [{"filename" : "Available now_ Bayonetta 3.eml","id" : "<61bed42d-59c4-4734-b501-c903d3ba8952@atl1s07mta2958.xt.local>","uid" : 34},{"filename" : "New sign-in to your account 5.eml","id" : "<010001762fc8b627-39331a9f-265d-4135-8367-8fdaf93a44ed-000000@email.amazonses.com>","uid" : 5678}]}
|
||||
"""#.utf8
|
||||
)
|
||||
)
|
||||
#expect(ids.uids == [34, 5678])
|
||||
#expect(ids.messageIDs == [])
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parsingJSON_2() throws {
|
||||
let ids = try UIDsAndMessageIDs.parse(
|
||||
input: Data(
|
||||
#"""
|
||||
{"messages" : [{"uid" : 34},{"uid" : 5678}]}
|
||||
"""#.utf8
|
||||
)
|
||||
)
|
||||
#expect(ids.uids == [34, 5678])
|
||||
#expect(ids.messageIDs == [])
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parsingJSON_3() throws {
|
||||
let ids = try UIDsAndMessageIDs.parse(
|
||||
input: Data(
|
||||
#"""
|
||||
{"messages" : [{"uid" : 30}]}
|
||||
"""#.utf8
|
||||
)
|
||||
)
|
||||
#expect(ids.uids == [30])
|
||||
#expect(ids.messageIDs == [])
|
||||
}
|
||||
|
||||
@Test
|
||||
static func parsingJSON_4() throws {
|
||||
let ids = try UIDsAndMessageIDs.parse(
|
||||
input: Data(
|
||||
#"""
|
||||
{"messages" : [{"id" : "<61bed42d-59c4-4734-b501-c903d3ba8952@atl1s07mta2958.xt.local>"},{"id" : "<010001762fc8b627-39331a9f-265d-4135-8367-8fdaf93a44ed-000000@email.amazonses.com>"}]}
|
||||
"""#.utf8
|
||||
)
|
||||
)
|
||||
#expect(ids.uids == [])
|
||||
#expect(
|
||||
ids.messageIDs == [
|
||||
"<61bed42d-59c4-4734-b501-c903d3ba8952@atl1s07mta2958.xt.local>",
|
||||
"<010001762fc8b627-39331a9f-265d-4135-8367-8fdaf93a44ed-000000@email.amazonses.com>",
|
||||
]
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import ArgumentParser
|
||||
@testable import IMAPCommands
|
||||
import Foundation
|
||||
@testable import IMAPToolLib
|
||||
import NIO
|
||||
import NIOIMAP
|
||||
import Testing
|
||||
import SystemPackage
|
||||
#if canImport(Glibc)
|
||||
import Glibc
|
||||
#elseif canImport(Darwin)
|
||||
import Darwin
|
||||
#endif
|
||||
|
||||
/// `URL(filePath:)` is Darwin-only; on Linux the initializer takes a `String`.
|
||||
extension URL {
|
||||
init(_ filePath: FilePath) {
|
||||
self.init(fileURLWithPath: filePath.string)
|
||||
}
|
||||
}
|
||||
|
||||
func firstLineOfErrorMessage(for error: any Error) -> Substring {
|
||||
RootCommand
|
||||
.fullMessage(for: error)
|
||||
.prefix(while: { !$0.isNewline })
|
||||
}
|
||||
|
||||
struct ConnectionHelper {
|
||||
var sent: [CommandStreamPart] = []
|
||||
mutating func send(_ c: CommandStreamPart) {
|
||||
self.sent.append(c)
|
||||
}
|
||||
}
|
||||
|
||||
extension IMAPCredential {
|
||||
static var testUsername: IMAPCredential {
|
||||
.username("foo", password: "bar")
|
||||
}
|
||||
}
|
||||
|
||||
extension CommandStreamPart {
|
||||
static func continuationResponse(_ data: Data) -> CommandStreamPart {
|
||||
.continuationResponse(ByteBuffer(data))
|
||||
}
|
||||
}
|
||||
|
||||
extension NIOIMAP.MailboxName: @retroactive ExpressibleByStringLiteral {
|
||||
public init(stringLiteral value: String) {
|
||||
// Test code only:
|
||||
self = try! MailboxPath.makeRootMailbox(displayName: value).name
|
||||
}
|
||||
}
|
||||
|
||||
extension NIOIMAP.MailboxPath: @retroactive ExpressibleByStringLiteral {
|
||||
public init(stringLiteral value: String) {
|
||||
try! self.init(name: MailboxName(stringLiteral: value), pathSeparator: ".")
|
||||
}
|
||||
}
|
||||
|
||||
extension IMAPConnection.Tag: @retroactive ExpressibleByStringLiteral {
|
||||
public init(stringLiteral value: String) {
|
||||
self = IMAPConnection.Tag(value)!
|
||||
}
|
||||
}
|
||||
|
||||
extension CommandStreamPart {
|
||||
func getCommand() throws -> TaggedCommand {
|
||||
guard case .tagged(let tagged) = self else {
|
||||
struct NotACommand: Swift.Error {}
|
||||
throw NotACommand()
|
||||
}
|
||||
return tagged
|
||||
}
|
||||
}
|
||||
|
||||
func withTemporaryDirectory<R>(
|
||||
closure: (FilePath) async throws -> R
|
||||
) async throws -> R {
|
||||
let a = FilePath(NSTemporaryDirectory()).appending("DownloadDirectoryTests-XXXXXXXXXXXXXXXX")
|
||||
let p = a.withPlatformString { pointer -> FilePath? in
|
||||
let count = strlen(pointer)
|
||||
let immutable = UnsafeBufferPointer(start: pointer, count: count)
|
||||
return withUnsafeTemporaryAllocation(
|
||||
of: CInterop.PlatformChar.self,
|
||||
capacity: count + 1
|
||||
) { buffer -> FilePath? in
|
||||
let (_, index) = buffer.initialize(from: immutable)
|
||||
buffer[index] = 0
|
||||
// Glibc’s `mkdtemp` takes a non-optional pointer.
|
||||
guard
|
||||
let template = buffer.baseAddress,
|
||||
mkdtemp(template) != nil
|
||||
else { return nil }
|
||||
return FilePath(platformString: template)
|
||||
}
|
||||
}
|
||||
guard let p else { throw FailedToCreateTemporaryDirectory() }
|
||||
let r = try await closure(p)
|
||||
deleteDirectory(p)
|
||||
return r
|
||||
}
|
||||
|
||||
private struct FailedToCreateTemporaryDirectory: Swift.Error {}
|
||||
|
||||
private func deleteDirectory(_ root: FilePath) {
|
||||
// `nftw` is not exposed by Swift’s Glibc overlay, so this walks the tree
|
||||
// with `FileManager`, which is portable. Deletion is best effort.
|
||||
try? FileManager.default.removeItem(at: URL(root))
|
||||
}
|
||||
@@ -0,0 +1,373 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import Foundation
|
||||
@testable import IMAPToolLib
|
||||
import NIOIMAP
|
||||
import Testing
|
||||
|
||||
@Suite("InternetMessageDate parsing")
|
||||
private enum InternetMessageDateParsingTests {
|
||||
// MARK: - Fast path: parseWithoutFoundation
|
||||
|
||||
struct FixedTZParseFixture: Sendable, CustomTestStringConvertible {
|
||||
var input: String
|
||||
var expected: TimeInterval
|
||||
|
||||
var testDescription: String { input }
|
||||
}
|
||||
|
||||
/// Cases that the strptime-based path can parse — that is, dates with a
|
||||
/// numeric `±HHMM` offset (or no offset) and no obs-zone abbreviation.
|
||||
///
|
||||
/// The `parseWithoutFoundation` fast path is Darwin-only (glibc has no
|
||||
/// `strptime_l`), so this test only runs there. The same inputs are covered
|
||||
/// through `parse()` — which falls back to Foundation — on all platforms.
|
||||
#if canImport(Darwin)
|
||||
@Test(arguments: [
|
||||
// IMAP-style quoted dates
|
||||
FixedTZParseFixture(input: #""29-Jul-2013 11:45:15 -0700""#, expected: 396_816_315),
|
||||
FixedTZParseFixture(input: #"" 8-Nov-2004 08:00:00 -0700""#, expected: 121_618_800),
|
||||
FixedTZParseFixture(input: #""08-May-1985 15:00:00 +0100""#, expected: -493_898_400),
|
||||
FixedTZParseFixture(input: #""4-Nov-1980 14:49:00 -0500""#, expected: -636_091_860),
|
||||
// RFC 2822
|
||||
FixedTZParseFixture(input: "Tue, 29 Oct 2012 10:00:00 -0800", expected: 373_226_400),
|
||||
FixedTZParseFixture(input: "29 Oct 2012 10:00 -0800", expected: 373_226_400),
|
||||
FixedTZParseFixture(input: " Tue, 29 Oct 2012 10:00:00 -0800 ", expected: 373_226_400),
|
||||
FixedTZParseFixture(input: "Thu, 1 Apr 1976 17:00:00 -0800", expected: -781_052_400),
|
||||
FixedTZParseFixture(input: "Mon, May 20 2002 10:18:51 -0700", expected: 43_607_931),
|
||||
// Time zone offset followed by a parenthesised time-zone name (seen in the wild):
|
||||
FixedTZParseFixture(input: "Sat, 5 Sep 2020 02:25:49 +0000 (GMT)", expected: 620_965_549),
|
||||
FixedTZParseFixture(input: "Fri, 18 Oct 2019 14:03:42 -0700 (PDT)", expected: 593_125_422),
|
||||
])
|
||||
static func parsingWithoutFoundation(fixture: FixedTZParseFixture) {
|
||||
let date = InternetMessageDate(fixture.input).parseWithoutFoundation()
|
||||
expectDate(date, equals: fixture.expected, input: fixture.input)
|
||||
}
|
||||
#endif
|
||||
|
||||
// MARK: - Empty / unparseable
|
||||
|
||||
@Test(arguments: ["", " \t\n"])
|
||||
static func emptyDates(input: String) {
|
||||
#expect(InternetMessageDate(input).parse() == nil)
|
||||
}
|
||||
|
||||
// MARK: - IMAP calendar-day form
|
||||
|
||||
@Test(arguments: [
|
||||
FixedTZParseFixture(input: #""29-Jul-2013 11:45:15 -0700""#, expected: 396_816_315),
|
||||
FixedTZParseFixture(input: #"" 8-Nov-2004 08:00:00 -0700""#, expected: 121_618_800),
|
||||
FixedTZParseFixture(input: #""08-May-1945 15:00:00 +0100""#, expected: -1_756_202_400),
|
||||
])
|
||||
static func imapCalendarDays(fixture: FixedTZParseFixture) {
|
||||
let date = InternetMessageDate(fixture.input).parse()
|
||||
expectDate(date, equals: fixture.expected, input: fixture.input)
|
||||
}
|
||||
|
||||
// MARK: - RFC 2822 dates
|
||||
|
||||
@Test(arguments: [
|
||||
FixedTZParseFixture(input: "Tue, 29 Oct 2012 10:00:00 -0800", expected: 373_226_400),
|
||||
FixedTZParseFixture(input: "29 Oct 2012 10:00 -0800", expected: 373_226_400),
|
||||
FixedTZParseFixture(input: " Tue, 29 Oct 2012 10:00:00 -0800 ", expected: 373_226_400),
|
||||
FixedTZParseFixture(input: "Thu, 1 Apr 1976 17:00:00 -0800", expected: -781_052_400),
|
||||
])
|
||||
static func internetMessageDates(fixture: FixedTZParseFixture) {
|
||||
let date = InternetMessageDate(fixture.input).parse()
|
||||
expectDate(date, equals: fixture.expected, input: fixture.input)
|
||||
}
|
||||
|
||||
// MARK: - Obsolete dates (RFC 2822 §4.3 obs-zone, 2-digit years)
|
||||
|
||||
@Test(arguments: [
|
||||
// The military time zones from RFC 5322 §4.3 don't work with NSDateFormatter/ICU;
|
||||
// they aren't covered here.
|
||||
FixedTZParseFixture(input: "24 Mar 2001 12:00:00 UT", expected: 7_128_000),
|
||||
FixedTZParseFixture(input: "24 Mar 2001 12:00:00 GMT", expected: 7_128_000),
|
||||
FixedTZParseFixture(input: "24 Mar 2001 07:00:00 EST", expected: 7_128_000),
|
||||
FixedTZParseFixture(input: "24 Mar 2001 08:00 EDT", expected: 7_128_000),
|
||||
FixedTZParseFixture(input: "24 Mar 2001 06:00:00 CST", expected: 7_128_000),
|
||||
FixedTZParseFixture(input: "24 Mar 2001 07:00 CDT", expected: 7_128_000),
|
||||
FixedTZParseFixture(input: "24 Mar 2001 05:00:00 MST", expected: 7_128_000),
|
||||
FixedTZParseFixture(input: "24 Mar 2001 06:00:00 MDT", expected: 7_128_000),
|
||||
FixedTZParseFixture(input: "24 Mar 2001 04:00 PST", expected: 7_128_000),
|
||||
FixedTZParseFixture(input: "24 Mar 2001 05:00:00 PDT", expected: 7_128_000),
|
||||
// 2-digit years before 50 are 20xx; 50 and later are 19xx.
|
||||
FixedTZParseFixture(input: "24 Jun 13 10:45 -0700", expected: 393_788_700),
|
||||
FixedTZParseFixture(input: "3 Jun 77 01:25 -0500", expected: -744_140_100),
|
||||
])
|
||||
static func obsoleteInternetMessageDates(fixture: FixedTZParseFixture) {
|
||||
let date = InternetMessageDate(fixture.input).parse()
|
||||
expectDate(date, equals: fixture.expected, input: fixture.input)
|
||||
}
|
||||
|
||||
// MARK: - Illegal-but-tolerated forms
|
||||
|
||||
@Test
|
||||
static func illegalDatesFromICloud() {
|
||||
// iCloud's quirky form:
|
||||
let date = InternetMessageDate("Sat, 5 Sep 2020 02:25:49 +0000 (GMT)").parse()
|
||||
expectDate(date, equals: 620_965_549, input: "iCloud")
|
||||
}
|
||||
|
||||
@Test(arguments: [
|
||||
FixedTZParseFixture(input: "29-Jul-2013 11:45:15 -0700", expected: 396_816_315),
|
||||
FixedTZParseFixture(input: "8-Nov-04 08:00 -0700", expected: 121_618_800),
|
||||
FixedTZParseFixture(input: "8-Nov-04 08:00 PDT", expected: 121_618_800),
|
||||
])
|
||||
static func illegalIMAPLikeDates(fixture: FixedTZParseFixture) {
|
||||
let date = InternetMessageDate(fixture.input).parse()
|
||||
expectDate(date, equals: fixture.expected, input: fixture.input)
|
||||
}
|
||||
|
||||
@Test(arguments: [
|
||||
FixedTZParseFixture(input: "Jun 5, 2011 7:59:47 AM US/Eastern", expected: 328_942_787),
|
||||
FixedTZParseFixture(input: "Mon, May 20 2002 10:18:51 -0700", expected: 43_607_931),
|
||||
FixedTZParseFixture(input: "January 08, 2004 12:01:13 EST", expected: 95_274_073),
|
||||
FixedTZParseFixture(input: "January 27, 2004 11:42:03 EST", expected: 96_914_523),
|
||||
FixedTZParseFixture(input: "Tue Oct 21, 2003 15:59:25 US/Eastern", expected: 88_459_165),
|
||||
FixedTZParseFixture(input: "Sun, Mar 31, 1996 07:57 EDT", expected: -150_033_780),
|
||||
FixedTZParseFixture(input: "December 30, 2003 12:30:43 EST", expected: 94_498_243),
|
||||
FixedTZParseFixture(input: "Mon Sep 22, 2003 14:49:00 US/Eastern", expected: 85_949_340),
|
||||
FixedTZParseFixture(input: "Fri May 23 12:00:00 EDT", expected: 359_438_400),
|
||||
FixedTZParseFixture(input: #""4-Nov-1980 14:49:00 -0500""#, expected: -636_091_860),
|
||||
FixedTZParseFixture(input: "1984-5-4 15:00:00 -0700", expected: -525_751_200),
|
||||
FixedTZParseFixture(input: "2/9 3:42 AM", expected: -28_250_280),
|
||||
FixedTZParseFixture(input: "02/09/87 3:42 am", expected: -438_477_480),
|
||||
])
|
||||
static func illegalDates(fixture: FixedTZParseFixture) {
|
||||
let date = InternetMessageDate(fixture.input).parse()
|
||||
expectDate(date, equals: fixture.expected, input: fixture.input)
|
||||
}
|
||||
|
||||
// MARK: - Local-timezone dates (no offset in the string)
|
||||
//
|
||||
// These dates omit the time-zone, so the parser interprets them in the
|
||||
// local time zone. We compute the expected timestamp the same way, which
|
||||
// means these tests are sensitive to the test machine's time zone — but
|
||||
// also mirror the parser's behavior exactly. `Calendar.current` resolves
|
||||
// the wall-clock components against the local zone including DST, so a
|
||||
// summer date is read as e.g. CEST rather than CET.
|
||||
|
||||
struct LocalTZParseFixture: Sendable, CustomTestStringConvertible {
|
||||
var input: String
|
||||
var year: Int
|
||||
var month: Int
|
||||
var day: Int
|
||||
var hour: Int
|
||||
var minute: Int
|
||||
var second: Int = 0
|
||||
|
||||
var testDescription: String { input }
|
||||
}
|
||||
|
||||
@Test(arguments: [
|
||||
LocalTZParseFixture(
|
||||
input: "Tue, Dec 30, 2008 at 3:22 PM",
|
||||
year: 2008,
|
||||
month: 12,
|
||||
day: 30,
|
||||
hour: 15,
|
||||
minute: 22
|
||||
),
|
||||
LocalTZParseFixture(
|
||||
input: "Mon Mar 30 11:45:00 2003",
|
||||
year: 2003,
|
||||
month: 3,
|
||||
day: 30,
|
||||
hour: 11,
|
||||
minute: 45
|
||||
),
|
||||
LocalTZParseFixture(
|
||||
input: "Tue, 19 Aug 2003 14:49:00",
|
||||
year: 2003,
|
||||
month: 8,
|
||||
day: 19,
|
||||
hour: 14,
|
||||
minute: 49
|
||||
),
|
||||
LocalTZParseFixture(
|
||||
input: "5 Nov 1982 14:49:00",
|
||||
year: 1982,
|
||||
month: 11,
|
||||
day: 5,
|
||||
hour: 14,
|
||||
minute: 49
|
||||
),
|
||||
])
|
||||
static func datesParsedInLocalTimeZone(fixture: LocalTZParseFixture) {
|
||||
guard let actual = InternetMessageDate(fixture.input).parse() else {
|
||||
Issue.record("Failed to parse '\(fixture.input)'")
|
||||
return
|
||||
}
|
||||
let components = DateComponents(
|
||||
year: fixture.year,
|
||||
month: fixture.month,
|
||||
day: fixture.day,
|
||||
hour: fixture.hour,
|
||||
minute: fixture.minute,
|
||||
second: fixture.second
|
||||
)
|
||||
let expectedDate = Calendar.current.date(from: components)!
|
||||
let expected = expectedDate.timeIntervalSinceReferenceDate
|
||||
let actualInterval = actual.timeIntervalSinceReferenceDate
|
||||
#expect(
|
||||
abs(actualInterval - expected) < 0.000_5,
|
||||
"Parsed '\(fixture.input)' as \(actual); expected interval \(expected), got \(actualInterval)"
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - Formatting (Date → InternetMessageDate)
|
||||
|
||||
struct FormatFixture: Sendable, CustomTestStringConvertible {
|
||||
var date: Date
|
||||
var calendar: Calendar
|
||||
var calendarLabel: String
|
||||
var expected: String
|
||||
|
||||
var testDescription: String { "\(date) / \(calendarLabel)" }
|
||||
}
|
||||
|
||||
@Test(arguments: [
|
||||
FormatFixture(
|
||||
date: Date(timeIntervalSinceReferenceDate: 590_000_000),
|
||||
calendar: .testCalendar,
|
||||
calendarLabel: "+0700",
|
||||
expected: "Thu, 12 Sep 2019 23:53:20 +0700"
|
||||
),
|
||||
FormatFixture(
|
||||
date: Date(timeIntervalSinceReferenceDate: 590_012_345),
|
||||
calendar: .testCalendar,
|
||||
calendarLabel: "+0700",
|
||||
expected: "Fri, 13 Sep 2019 03:19:05 +0700"
|
||||
),
|
||||
FormatFixture(
|
||||
date: Date(timeIntervalSinceReferenceDate: 590_018_888),
|
||||
calendar: .testCalendar,
|
||||
calendarLabel: "+0700",
|
||||
expected: "Fri, 13 Sep 2019 05:08:08 +0700"
|
||||
),
|
||||
FormatFixture(
|
||||
date: Date(timeIntervalSinceReferenceDate: 596_737_019),
|
||||
calendar: .testCalendar,
|
||||
calendarLabel: "+0700",
|
||||
expected: "Fri, 29 Nov 2019 23:16:59 +0700"
|
||||
),
|
||||
FormatFixture(
|
||||
date: Date(timeIntervalSinceReferenceDate: 596_737_019),
|
||||
calendar: .testCalendarB,
|
||||
calendarLabel: "Sao_Paulo",
|
||||
expected: "Fri, 29 Nov 2019 13:16:59 -0300"
|
||||
),
|
||||
FormatFixture(
|
||||
date: Date(timeIntervalSinceReferenceDate: -150_033_780),
|
||||
calendar: .testCalendar,
|
||||
calendarLabel: "+0700",
|
||||
expected: "Sun, 31 Mar 1996 18:57:00 +0700"
|
||||
),
|
||||
FormatFixture(
|
||||
date: Date(timeIntervalSinceReferenceDate: -150_033_780),
|
||||
calendar: .testCalendarB,
|
||||
calendarLabel: "Sao_Paulo",
|
||||
expected: "Sun, 31 Mar 1996 08:57:00 -0300"
|
||||
),
|
||||
FormatFixture(
|
||||
date: Date(timeIntervalSinceReferenceDate: 88_459_165),
|
||||
calendar: .testCalendar,
|
||||
calendarLabel: "+0700",
|
||||
expected: "Wed, 22 Oct 2003 02:59:25 +0700"
|
||||
),
|
||||
FormatFixture(
|
||||
date: Date(timeIntervalSinceReferenceDate: 88_459_165),
|
||||
calendar: .testCalendarB,
|
||||
calendarLabel: "Sao_Paulo",
|
||||
expected: "Tue, 21 Oct 2003 17:59:25 -0200"
|
||||
),
|
||||
])
|
||||
static func formatAsRFC822(fixture: FormatFixture) {
|
||||
let formatted = String(InternetMessageDate(from: fixture.date, calendar: fixture.calendar))
|
||||
#expect(formatted == fixture.expected)
|
||||
}
|
||||
|
||||
// MARK: - Round trip (format → parse)
|
||||
|
||||
@Test(arguments: [
|
||||
Date(timeIntervalSinceReferenceDate: 590_000_000),
|
||||
Date(timeIntervalSinceReferenceDate: 596_737_019),
|
||||
Date(timeIntervalSinceReferenceDate: -150_033_780),
|
||||
Date(timeIntervalSinceReferenceDate: 88_459_165),
|
||||
Date(timeIntervalSinceReferenceDate: 0),
|
||||
Date(timeIntervalSinceReferenceDate: 1_000_000_000),
|
||||
])
|
||||
static func roundTrip(date: Date) {
|
||||
for calendar in [Calendar.testCalendar, .testCalendarB, .testCalendarUTC] {
|
||||
let formatted = InternetMessageDate(from: date, calendar: calendar)
|
||||
guard let parsed = formatted.parse() else {
|
||||
Issue.record("Failed to parse '\(String(formatted))'")
|
||||
continue
|
||||
}
|
||||
// The wire format has second precision, so allow up to ~1 second of drift.
|
||||
let drift = abs(parsed.timeIntervalSinceReferenceDate - date.timeIntervalSinceReferenceDate)
|
||||
#expect(
|
||||
drift < 1.1,
|
||||
"'\(String(formatted))' round-tripped with \(drift)s drift"
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Helpers
|
||||
|
||||
private func expectDate(
|
||||
_ date: Date?,
|
||||
equals expectedInterval: TimeInterval,
|
||||
input: String,
|
||||
sourceLocation: SourceLocation = #_sourceLocation
|
||||
) {
|
||||
guard let date else {
|
||||
Issue.record("Failed to parse '\(input)'", sourceLocation: sourceLocation)
|
||||
return
|
||||
}
|
||||
let actual = date.timeIntervalSinceReferenceDate
|
||||
#expect(
|
||||
abs(actual - expectedInterval) < 0.000_5,
|
||||
"Parsed '\(input)' as \(date); expected interval \(expectedInterval), got \(actual)",
|
||||
sourceLocation: sourceLocation
|
||||
)
|
||||
}
|
||||
|
||||
extension Calendar {
|
||||
/// Gregorian calendar fixed at UTC+07:00 (no DST).
|
||||
fileprivate static var testCalendar: Calendar {
|
||||
var c = Calendar(identifier: .gregorian)
|
||||
c.timeZone = TimeZone(secondsFromGMT: 7 * 3600)!
|
||||
return c
|
||||
}
|
||||
|
||||
/// Gregorian calendar in `America/Sao_Paulo` — historically observes DST,
|
||||
/// which is what we want to exercise the formatter's offset handling.
|
||||
fileprivate static var testCalendarB: Calendar {
|
||||
var c = Calendar(identifier: .gregorian)
|
||||
c.timeZone = TimeZone(identifier: "America/Sao_Paulo")!
|
||||
return c
|
||||
}
|
||||
|
||||
/// Gregorian calendar fixed at UTC.
|
||||
fileprivate static var testCalendarUTC: Calendar {
|
||||
var c = Calendar(identifier: .gregorian)
|
||||
c.timeZone = TimeZone(secondsFromGMT: 0)!
|
||||
return c
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import Testing
|
||||
import NIOCore
|
||||
import Foundation
|
||||
import NIOIMAPCore
|
||||
@testable import IMAPToolLib
|
||||
|
||||
@Suite("MIMEMessage line scanning")
|
||||
struct MIMEMessageLineScanningTests {
|
||||
|
||||
@Test("Finds Date header with CRLF line endings")
|
||||
func dateHeaderCRLF() {
|
||||
let input =
|
||||
"From: sender@example.com\r\nDate: Fri, 15 Mar 2024 10:30:45 +0100\r\nSubject: Hello\r\n\r\nBody here"
|
||||
#expect(dateFrom(input) == "Fri, 15 Mar 2024 10:30:45 +0100")
|
||||
}
|
||||
|
||||
@Test("Finds Date header with LF line endings")
|
||||
func dateHeaderLF() {
|
||||
let input = "From: sender@example.com\nDate: Fri, 15 Mar 2024 10:30:45 +0100\nSubject: Hello\n\nBody here"
|
||||
#expect(dateFrom(input) == "Fri, 15 Mar 2024 10:30:45 +0100")
|
||||
}
|
||||
|
||||
@Test("Case-insensitive header name matching")
|
||||
func caseInsensitive() {
|
||||
let input = "DATE: Mon, 01 Jan 2024 00:00:00 +0000\r\n\r\n"
|
||||
#expect(dateFrom(input) == "Mon, 01 Jan 2024 00:00:00 +0000")
|
||||
}
|
||||
|
||||
@Test("Mixed case header name")
|
||||
func mixedCase() {
|
||||
let input = "dAtE: Tue, 02 Jan 2024 12:00:00 -0500\r\n\r\n"
|
||||
#expect(dateFrom(input) == "Tue, 02 Jan 2024 12:00:00 -0500")
|
||||
}
|
||||
|
||||
@Test("Stops at empty line — Date in body is not found")
|
||||
func stopsAtEmptyLine() {
|
||||
let input = "From: sender@example.com\r\n\r\nDate: Fri, 15 Mar 2024 10:30:45 +0100\r\n"
|
||||
#expect(dateFrom(input) == nil)
|
||||
}
|
||||
|
||||
@Test("Returns nil when no Date header present")
|
||||
func noDateHeader() {
|
||||
let input = "From: sender@example.com\r\nSubject: Hello\r\n\r\nBody"
|
||||
#expect(dateFrom(input) == nil)
|
||||
}
|
||||
|
||||
@Test("Trims leading whitespace from value")
|
||||
func trimsLeadingWhitespace() {
|
||||
let input = "Date: Fri, 15 Mar 2024 10:30:45 +0100\r\n\r\n"
|
||||
#expect(dateFrom(input) == "Fri, 15 Mar 2024 10:30:45 +0100")
|
||||
}
|
||||
|
||||
@Test("Trims trailing whitespace from value")
|
||||
func trimsTrailingWhitespace() {
|
||||
let input = "Date: Fri, 15 Mar 2024 10:30:45 +0100 \r\n\r\n"
|
||||
#expect(dateFrom(input) == "Fri, 15 Mar 2024 10:30:45 +0100")
|
||||
}
|
||||
|
||||
@Test("Handles tab after colon")
|
||||
func tabAfterColon() {
|
||||
let input = "Date:\tFri, 15 Mar 2024 10:30:45 +0100\r\n\r\n"
|
||||
#expect(dateFrom(input) == "Fri, 15 Mar 2024 10:30:45 +0100")
|
||||
}
|
||||
|
||||
@Test("Returns nil for empty buffer")
|
||||
func emptyBuffer() {
|
||||
#expect(dateFrom("") == nil)
|
||||
}
|
||||
|
||||
@Test("Headers without terminating empty line still finds Date")
|
||||
func noTerminatingEmptyLine() {
|
||||
let input = "Date: Fri, 15 Mar 2024 10:30:45 +0100\r\nSubject: Hello"
|
||||
#expect(dateFrom(input) == "Fri, 15 Mar 2024 10:30:45 +0100")
|
||||
}
|
||||
|
||||
@Test("Does not match partial header name like X-Date")
|
||||
func doesNotMatchPartialName() {
|
||||
let input = "X-Date: not this one\r\nDate: the real one\r\n\r\n"
|
||||
#expect(dateFrom(input) == "the real one")
|
||||
}
|
||||
|
||||
@Test("Enumerates multiple headers in order")
|
||||
func enumeratesMultipleHeaders() {
|
||||
let input = "From: alice\r\nTo: bob\r\nSubject: hi\r\n\r\n"
|
||||
var names: [String] = []
|
||||
let message = MIMEMessage.data(Data(input.utf8))
|
||||
message.withContiguousBytes { buffer in
|
||||
message.enumerateHeaderLines(in: buffer) { name, _ in
|
||||
names.append(name.utf8String)
|
||||
return true
|
||||
}
|
||||
}
|
||||
#expect(names == ["From", "To", "Subject"])
|
||||
}
|
||||
|
||||
@Test("Stops enumeration when body returns false")
|
||||
func stopsOnFalse() {
|
||||
let input = "A: 1\r\nB: 2\r\nC: 3\r\n\r\n"
|
||||
var count = 0
|
||||
let message = MIMEMessage.data(Data(input.utf8))
|
||||
message.withContiguousBytes { buffer in
|
||||
message.enumerateHeaderLines(in: buffer) { _, _ in
|
||||
count += 1
|
||||
return count < 2
|
||||
}
|
||||
}
|
||||
#expect(count == 2)
|
||||
}
|
||||
|
||||
private func dateFrom(_ string: String) -> String? {
|
||||
let message = MIMEMessage.data(Data(string.utf8))
|
||||
guard let date = message.dateHeader() else { return nil }
|
||||
return String(date)
|
||||
}
|
||||
}
|
||||
|
||||
@Suite("MIMEMessage.messageIDHeader()")
|
||||
struct MIMEMessageMessageIDTests {
|
||||
|
||||
@Test("Finds Message-ID header")
|
||||
func findsMessageID() {
|
||||
let input = "Date: Mon, 01 Jan 2024 00:00:00 +0000\r\nMessage-ID: <abc@example.com>\r\n\r\n"
|
||||
let message = MIMEMessage.data(Data(input.utf8))
|
||||
let result = message.messageIDHeader()
|
||||
#expect(result != nil)
|
||||
#expect(String(result!) == "<abc@example.com>")
|
||||
}
|
||||
|
||||
@Test("Case-insensitive Message-ID matching")
|
||||
func caseInsensitive() {
|
||||
let input = "MESSAGE-ID: <XYZ@host>\r\n\r\n"
|
||||
let message = MIMEMessage.data(Data(input.utf8))
|
||||
#expect(String(message.messageIDHeader()!) == "<XYZ@host>")
|
||||
}
|
||||
|
||||
@Test("Returns nil when not present")
|
||||
func notPresent() {
|
||||
let input = "Date: Mon, 01 Jan 2024 00:00:00 +0000\r\n\r\n"
|
||||
let message = MIMEMessage.data(Data(input.utf8))
|
||||
#expect(message.messageIDHeader() == nil)
|
||||
}
|
||||
|
||||
@Test("Does not match partial name like X-Message-ID")
|
||||
func doesNotMatchPartial() {
|
||||
let input = "X-Message-ID: <wrong>\r\nMessage-ID: <right@host>\r\n\r\n"
|
||||
let message = MIMEMessage.data(Data(input.utf8))
|
||||
#expect(String(message.messageIDHeader()!) == "<right@host>")
|
||||
}
|
||||
}
|
||||
|
||||
@Suite("MIMEMessage.headersOfInterest()")
|
||||
struct MIMEMessageHeadersOfInterestTests {
|
||||
|
||||
@Test("Returns both date and message-id in a single pass")
|
||||
func returnsBoth() {
|
||||
let input = "Message-ID: <id@host>\r\nDate: Wed, 10 Apr 2024 08:15:30 +0000\r\nSubject: Hello\r\n\r\nBody"
|
||||
let message = MIMEMessage.data(Data(input.utf8))
|
||||
let result = message.headersOfInterest()
|
||||
#expect(result != nil)
|
||||
#expect(String(result!.date) == "Wed, 10 Apr 2024 08:15:30 +0000")
|
||||
#expect(String(result!.messageID) == "<id@host>")
|
||||
}
|
||||
|
||||
@Test("Returns nil when date is missing")
|
||||
func missingDate() {
|
||||
let input = "Message-ID: <id@host>\r\nSubject: Hello\r\n\r\n"
|
||||
let message = MIMEMessage.data(Data(input.utf8))
|
||||
#expect(message.headersOfInterest() == nil)
|
||||
}
|
||||
|
||||
@Test("Returns nil when message-id is missing")
|
||||
func missingMessageID() {
|
||||
let input = "Date: Wed, 10 Apr 2024 08:15:30 +0000\r\nSubject: Hello\r\n\r\n"
|
||||
let message = MIMEMessage.data(Data(input.utf8))
|
||||
#expect(message.headersOfInterest() == nil)
|
||||
}
|
||||
|
||||
@Test("Stops scanning once both are found")
|
||||
func stopsEarly() {
|
||||
let input =
|
||||
"Date: Wed, 10 Apr 2024 08:15:30 +0000\r\nMessage-ID: <id@host>\r\nX-Extra: should not be reached\r\n\r\n"
|
||||
var headerCount = 0
|
||||
let data = Data(input.utf8)
|
||||
let message = MIMEMessage.data(data)
|
||||
message.withContiguousBytes { buffer in
|
||||
var date: InternetMessageDate?
|
||||
var messageID: MessageID?
|
||||
message.enumerateHeaderLines(in: buffer) { name, value in
|
||||
headerCount += 1
|
||||
let nameStr = name.utf8String.lowercased()
|
||||
if nameStr == "date" {
|
||||
date = InternetMessageDate("x")
|
||||
} else if nameStr == "message-id" {
|
||||
messageID = MessageID("x")
|
||||
}
|
||||
return date == nil || messageID == nil
|
||||
}
|
||||
}
|
||||
#expect(headerCount == 2)
|
||||
}
|
||||
|
||||
@Test("Works with ByteBuffer")
|
||||
func worksWithByteBuffer() {
|
||||
let input = "Message-ID: <dd@host>\r\nDate: Fri, 01 Jan 2024 00:00:00 +0000\r\n\r\n"
|
||||
let message = MIMEMessage.byteBuffer(ByteBuffer(string: input))
|
||||
let result = message.headersOfInterest()
|
||||
#expect(result != nil)
|
||||
#expect(String(result!.messageID) == "<dd@host>")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,439 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
@testable import IMAPCommands
|
||||
@testable import IMAPToolLib
|
||||
import Foundation
|
||||
import NIO
|
||||
import NIOIMAP
|
||||
import Testing
|
||||
|
||||
@Suite("Append", .timeLimit(.minutes(1)))
|
||||
private struct AppendTests {
|
||||
let messageA = #"""
|
||||
From: foo@example.apple.com
|
||||
To: bar@example.apple.com
|
||||
Message-ID: <1@example.apple.com>
|
||||
Subject: Test A
|
||||
Date: Tue, 30 Apr 2024 14:31:07 +0000
|
||||
|
||||
Hello!
|
||||
|
||||
"""#.replacingOccurrences(of: "\n", with: "\r\n")
|
||||
|
||||
let dateA = ServerMessageDate(
|
||||
.init(year: 2024, month: 4, day: 30, hour: 14, minute: 31, second: 7, timeZoneMinutes: 0)!
|
||||
)
|
||||
|
||||
func singleMessageExpectedCommand(
|
||||
message: String,
|
||||
internalDate: ServerMessageDate?,
|
||||
completion: TaggedResponse.State = .ok(.init(text: "Done"))
|
||||
) -> TestServer.ExpectedCommand {
|
||||
.init(
|
||||
part: .append(
|
||||
MailboxName("Food"),
|
||||
[
|
||||
.beginMessage(
|
||||
message: AppendMessage(
|
||||
options: AppendOptions(
|
||||
internalDate: internalDate
|
||||
),
|
||||
data: AppendData(byteCount: message.utf8.count)
|
||||
)
|
||||
),
|
||||
.messageBytes(ByteBuffer(string: message)),
|
||||
.endMessage,
|
||||
.finish,
|
||||
]
|
||||
),
|
||||
responses: [],
|
||||
completion: completion
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
func singleMessage_noInternalDate() async throws {
|
||||
let message: MessageToAppend = try {
|
||||
var m = try MessageToAppend(
|
||||
message: EmailMessage(
|
||||
data: Data(messageA.utf8)
|
||||
),
|
||||
id: "foobar"
|
||||
)
|
||||
m.serverMessageDate = nil
|
||||
return m
|
||||
}()
|
||||
|
||||
await TestServer.runSingleConnectionServer(
|
||||
greeting: .ok(.init(text: "Hello")),
|
||||
expectedCommands: [
|
||||
singleMessageExpectedCommand(
|
||||
message: messageA,
|
||||
internalDate: nil
|
||||
)
|
||||
]
|
||||
) { path in
|
||||
try await IMAPConnection.withConnection(
|
||||
configuration: IMAPConnection.Configuration(path)
|
||||
) { greeting, connection in
|
||||
let result = try await connection.append(
|
||||
message: message,
|
||||
into: MailboxName("Food")
|
||||
)
|
||||
#expect(result == nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
func singleMessage_withInternalDate() async throws {
|
||||
await TestServer.runSingleConnectionServer(
|
||||
greeting: .ok(.init(text: "Hello")),
|
||||
expectedCommands: [
|
||||
singleMessageExpectedCommand(
|
||||
message: messageA,
|
||||
internalDate: dateA
|
||||
)
|
||||
]
|
||||
) { path in
|
||||
try await IMAPConnection.withConnection(
|
||||
configuration: IMAPConnection.Configuration(path)
|
||||
) { greeting, connection in
|
||||
let result = try await connection.append(
|
||||
message: MessageToAppend(
|
||||
message: EmailMessage(
|
||||
data: Data(messageA.utf8)
|
||||
),
|
||||
id: "foobar"
|
||||
),
|
||||
into: MailboxName("Food")
|
||||
)
|
||||
#expect(result == nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
func singleMessage_literalPlus() async throws {
|
||||
await TestServer.runSingleConnectionServer(
|
||||
greeting: .ok(.init(text: "Hello")),
|
||||
expectedCommands: [
|
||||
singleMessageExpectedCommand(
|
||||
message: messageA,
|
||||
internalDate: dateA
|
||||
)
|
||||
]
|
||||
) { path in
|
||||
try await IMAPConnection.withConnection(
|
||||
configuration: IMAPConnection.Configuration(path)
|
||||
) { greeting, connection in
|
||||
// Turn on LITERAL+ support:
|
||||
try await connection.setEncodingOptions(
|
||||
.fixed(
|
||||
CommandEncodingOptions(
|
||||
useQuotedString: true,
|
||||
useSynchronizingLiteral: false,
|
||||
useNonSynchronizingLiteralPlus: true,
|
||||
useNonSynchronizingLiteralMinus: false,
|
||||
useBinaryLiteral: false
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
let result = try await connection.append(
|
||||
message: MessageToAppend(
|
||||
message: EmailMessage(
|
||||
data: Data(messageA.utf8)
|
||||
),
|
||||
id: "foobar"
|
||||
),
|
||||
into: MailboxName("Food")
|
||||
)
|
||||
#expect(result == nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
func singleMessage_serverReturnsNo() async throws {
|
||||
await TestServer.runSingleConnectionServer(
|
||||
greeting: .ok(.init(text: "Hello")),
|
||||
expectedCommands: [
|
||||
singleMessageExpectedCommand(
|
||||
message: messageA,
|
||||
internalDate: dateA,
|
||||
completion: .no(ResponseText(text: "Not allowed"))
|
||||
)
|
||||
]
|
||||
) { path in
|
||||
try await IMAPConnection.withConnection(
|
||||
configuration: IMAPConnection.Configuration(path)
|
||||
) { greeting, connection -> Void in
|
||||
await #expect(
|
||||
throws: FailedToAppendMessage(state: .no(ResponseText(text: "Not allowed")))
|
||||
) {
|
||||
_ = try await connection.append(
|
||||
message: MessageToAppend(
|
||||
message: EmailMessage(
|
||||
data: Data(messageA.utf8)
|
||||
),
|
||||
id: "foobar"
|
||||
),
|
||||
into: MailboxName("Food")
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
func singleMessageWithUIDPLUS() async throws {
|
||||
await TestServer.runSingleConnectionServer(
|
||||
greeting: .ok(.init(text: "Hello")),
|
||||
expectedCommands: [
|
||||
singleMessageExpectedCommand(
|
||||
message: messageA,
|
||||
internalDate: dateA,
|
||||
completion: .ok(
|
||||
ResponseText(
|
||||
code: .uidAppend(
|
||||
ResponseCodeAppend(
|
||||
uidValidity: 0x123456,
|
||||
uids: [785_048]
|
||||
)
|
||||
),
|
||||
text: "Done appending"
|
||||
)
|
||||
)
|
||||
)
|
||||
]
|
||||
) { path in
|
||||
try await IMAPConnection.withConnection(
|
||||
configuration: IMAPConnection.Configuration(path)
|
||||
) { greeting, connection in
|
||||
let result = try await connection.append(
|
||||
message: MessageToAppend(
|
||||
message: EmailMessage(
|
||||
data: Data(messageA.utf8)
|
||||
),
|
||||
id: "foobar"
|
||||
),
|
||||
into: MailboxName("Food")
|
||||
)
|
||||
#expect(result?.uidValidity == 0x123456)
|
||||
#expect(result?.uids == [785_048])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Helper function for creating expected commands with flags
|
||||
func singleMessageExpectedCommandWithFlags(
|
||||
message: String,
|
||||
flags: [NIOIMAP.Flag],
|
||||
internalDate: ServerMessageDate?,
|
||||
completion: TaggedResponse.State = .ok(.init(text: "Done"))
|
||||
) -> TestServer.ExpectedCommand {
|
||||
.init(
|
||||
part: .append(
|
||||
MailboxName("Food"),
|
||||
[
|
||||
.beginMessage(
|
||||
message: AppendMessage(
|
||||
options: AppendOptions(
|
||||
flagList: flags,
|
||||
internalDate: internalDate
|
||||
),
|
||||
data: AppendData(byteCount: message.utf8.count)
|
||||
)
|
||||
),
|
||||
.messageBytes(ByteBuffer(string: message)),
|
||||
.endMessage,
|
||||
.finish,
|
||||
]
|
||||
),
|
||||
responses: [],
|
||||
completion: completion
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
func singleMessage_withFlags() async throws {
|
||||
let flags: [NIOIMAP.Flag] = [.seen, .flagged]
|
||||
|
||||
await TestServer.runSingleConnectionServer(
|
||||
greeting: .ok(.init(text: "Hello")),
|
||||
expectedCommands: [
|
||||
singleMessageExpectedCommandWithFlags(
|
||||
message: messageA,
|
||||
flags: flags,
|
||||
internalDate: dateA
|
||||
)
|
||||
]
|
||||
) { path in
|
||||
try await IMAPConnection.withConnection(
|
||||
configuration: IMAPConnection.Configuration(path)
|
||||
) { greeting, connection in
|
||||
var message = try MessageToAppend(
|
||||
message: EmailMessage(
|
||||
data: Data(messageA.utf8)
|
||||
),
|
||||
id: "foobar"
|
||||
)
|
||||
message.flags = flags
|
||||
|
||||
let result = try await connection.append(
|
||||
message: message,
|
||||
into: MailboxName("Food")
|
||||
)
|
||||
#expect(result == nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
func singleMessage_withMultipleFlags() async throws {
|
||||
let flags: [NIOIMAP.Flag] = [.seen, .flagged, .answered, .draft]
|
||||
|
||||
await TestServer.runSingleConnectionServer(
|
||||
greeting: .ok(.init(text: "Hello")),
|
||||
expectedCommands: [
|
||||
singleMessageExpectedCommandWithFlags(
|
||||
message: messageA,
|
||||
flags: flags,
|
||||
internalDate: dateA
|
||||
)
|
||||
]
|
||||
) { path in
|
||||
try await IMAPConnection.withConnection(
|
||||
configuration: IMAPConnection.Configuration(path)
|
||||
) { greeting, connection in
|
||||
var message = try MessageToAppend(
|
||||
message: EmailMessage(
|
||||
data: Data(messageA.utf8)
|
||||
),
|
||||
id: "foobar"
|
||||
)
|
||||
message.flags = flags
|
||||
|
||||
let result = try await connection.append(
|
||||
message: message,
|
||||
into: MailboxName("Food")
|
||||
)
|
||||
#expect(result == nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
func singleMessage_withCustomFlags() async throws {
|
||||
let customFlag = NIOIMAP.Flag("\\CustomFlag")
|
||||
let recentFlag = NIOIMAP.Flag("\\Recent")
|
||||
let flags: [NIOIMAP.Flag] = [.seen, customFlag, recentFlag]
|
||||
|
||||
await TestServer.runSingleConnectionServer(
|
||||
greeting: .ok(.init(text: "Hello")),
|
||||
expectedCommands: [
|
||||
singleMessageExpectedCommandWithFlags(
|
||||
message: messageA,
|
||||
flags: flags,
|
||||
internalDate: dateA
|
||||
)
|
||||
]
|
||||
) { path in
|
||||
try await IMAPConnection.withConnection(
|
||||
configuration: IMAPConnection.Configuration(path)
|
||||
) { greeting, connection in
|
||||
var message = try MessageToAppend(
|
||||
message: EmailMessage(
|
||||
data: Data(messageA.utf8)
|
||||
),
|
||||
id: "foobar"
|
||||
)
|
||||
message.flags = flags
|
||||
|
||||
let result = try await connection.append(
|
||||
message: message,
|
||||
into: MailboxName("Food")
|
||||
)
|
||||
#expect(result == nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
func singleMessage_withEmptyFlags() async throws {
|
||||
let flags: [NIOIMAP.Flag] = []
|
||||
|
||||
await TestServer.runSingleConnectionServer(
|
||||
greeting: .ok(.init(text: "Hello")),
|
||||
expectedCommands: [
|
||||
singleMessageExpectedCommandWithFlags(
|
||||
message: messageA,
|
||||
flags: flags,
|
||||
internalDate: dateA
|
||||
)
|
||||
]
|
||||
) { path in
|
||||
try await IMAPConnection.withConnection(
|
||||
configuration: IMAPConnection.Configuration(path)
|
||||
) { greeting, connection in
|
||||
var message = try MessageToAppend(
|
||||
message: EmailMessage(
|
||||
data: Data(messageA.utf8)
|
||||
),
|
||||
id: "foobar"
|
||||
)
|
||||
message.flags = flags
|
||||
|
||||
let result = try await connection.append(
|
||||
message: message,
|
||||
into: MailboxName("Food")
|
||||
)
|
||||
#expect(result == nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
func singleMessage_nilFlags() async throws {
|
||||
await TestServer.runSingleConnectionServer(
|
||||
greeting: .ok(.init(text: "Hello")),
|
||||
expectedCommands: [
|
||||
singleMessageExpectedCommand(
|
||||
message: messageA,
|
||||
internalDate: dateA
|
||||
)
|
||||
]
|
||||
) { path in
|
||||
try await IMAPConnection.withConnection(
|
||||
configuration: IMAPConnection.Configuration(path)
|
||||
) { greeting, connection in
|
||||
var message = try MessageToAppend(
|
||||
message: EmailMessage(
|
||||
data: Data(messageA.utf8)
|
||||
),
|
||||
id: "foobar"
|
||||
)
|
||||
message.flags = nil
|
||||
|
||||
let result = try await connection.append(
|
||||
message: message,
|
||||
into: MailboxName("Food")
|
||||
)
|
||||
#expect(result == nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,581 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import Foundation
|
||||
@testable import NIOIMAP
|
||||
import SystemPackage
|
||||
import Testing
|
||||
@testable import IMAPToolLib
|
||||
|
||||
@Suite("Append Files")
|
||||
private enum Append_FilesTests {
|
||||
static func createFile(
|
||||
dir: FilePath,
|
||||
name: String,
|
||||
content: String
|
||||
) throws -> FilePath {
|
||||
let path = dir.appending(name)
|
||||
try Data(content.utf8).write(to: URL(path))
|
||||
return path
|
||||
}
|
||||
|
||||
static func createFiles(
|
||||
dir: FilePath,
|
||||
content: [String]
|
||||
) throws -> [FilePath] {
|
||||
return try content.enumerated().map { index, content in
|
||||
try createFile(
|
||||
dir: dir,
|
||||
name: "\(index)",
|
||||
content: content
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
static func create3Files(
|
||||
dir: FilePath,
|
||||
) throws -> (FilePath, FilePath, FilePath) {
|
||||
let all = try createFiles(
|
||||
dir: dir,
|
||||
content: [
|
||||
#"""
|
||||
From: a@example.apple.com
|
||||
Subject: A
|
||||
Message-id: <a-1@example.apple.com>
|
||||
Date: Tue, 13 Sep 2016 04:08:04 -0700
|
||||
|
||||
a
|
||||
"""#,
|
||||
#"""
|
||||
From: b@example.apple.com
|
||||
Subject: B
|
||||
Message-id: <b-2@example.apple.com>
|
||||
Date: Tue, 30 Apr 2024 14:31:07 +0000
|
||||
|
||||
b
|
||||
"""#,
|
||||
#"""
|
||||
From: c@example.apple.com
|
||||
Subject: C
|
||||
Message-id: <c-3@example.apple.com>
|
||||
Date: Thu, 25 Apr 2024 16:41:32 +0200
|
||||
|
||||
c
|
||||
"""#,
|
||||
]
|
||||
)
|
||||
try #require(all.count == 3)
|
||||
let a = all[0]
|
||||
let b = all[1]
|
||||
let c = all[2]
|
||||
return (a, b, c)
|
||||
}
|
||||
|
||||
@Test
|
||||
static func readingSingleFile() async throws {
|
||||
try await withTemporaryDirectory { dir in
|
||||
let all = try createFiles(
|
||||
dir: dir,
|
||||
content: [
|
||||
#"""
|
||||
From: a@example.apple.com
|
||||
Subject: A
|
||||
Message-id: <a-1@example.apple.com>
|
||||
Date: Tue, 13 Sep 2016 04:08:04 -0700
|
||||
|
||||
a
|
||||
"""#
|
||||
]
|
||||
)
|
||||
let path = try #require(all.first)
|
||||
|
||||
let result = try await FileBasedMessageToAppendSequence.readSingleMessage(
|
||||
path: path,
|
||||
originalIndex: 95_824
|
||||
)
|
||||
#expect(
|
||||
result
|
||||
== FileBasedMessageToAppendSequence.IndexedFilePath(
|
||||
originalIndex: 95_824,
|
||||
nestedIndex: 0,
|
||||
path: .init(
|
||||
filePath: path,
|
||||
date: Date(timeIntervalSinceReferenceDate: 495_457_684)
|
||||
)
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
static func readingSingleFileWithInvalidDate() async throws {
|
||||
try await withTemporaryDirectory { dir in
|
||||
let all = try createFiles(
|
||||
dir: dir,
|
||||
content: [
|
||||
#"""
|
||||
From: a@example.apple.com
|
||||
Subject: A
|
||||
Message-id: <a-1@example.apple.com>
|
||||
Date: foo bar baz
|
||||
|
||||
a
|
||||
"""#
|
||||
]
|
||||
)
|
||||
let path = try #require(all.first)
|
||||
|
||||
do {
|
||||
_ = try await FileBasedMessageToAppendSequence.readSingleMessage(
|
||||
path: path,
|
||||
originalIndex: 95_824
|
||||
)
|
||||
Issue.record("Should have thrown an error")
|
||||
} catch let error as FileBasedMessageToAppendSequence.UnableToParseFile {
|
||||
#expect(error.filePath == path)
|
||||
#expect(
|
||||
(error.underlying as? FileBasedMessageToAppendSequence.UnableToParseDate)?.date == "foo bar baz"
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
static func readingSingleFileWithoutDate() async throws {
|
||||
try await withTemporaryDirectory { dir in
|
||||
let all = try createFiles(
|
||||
dir: dir,
|
||||
content: [
|
||||
#"""
|
||||
From: a@example.apple.com
|
||||
Subject: A
|
||||
Message-id: <a-1@example.apple.com>
|
||||
|
||||
a
|
||||
"""#
|
||||
]
|
||||
)
|
||||
let path = try #require(all.first)
|
||||
|
||||
do {
|
||||
_ = try await FileBasedMessageToAppendSequence.readSingleMessage(
|
||||
path: path,
|
||||
originalIndex: 95_824
|
||||
)
|
||||
Issue.record("Should have thrown an error")
|
||||
} catch let error as FileBasedMessageToAppendSequence.UnableToParseFile {
|
||||
#expect(error.filePath == path)
|
||||
#expect((error.underlying as? FileBasedMessageToAppendSequence.NoMessageDateInFile) != nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
static func readDirectory() async throws {
|
||||
try await withTemporaryDirectory { dir in
|
||||
let (a, b, c) = try create3Files(dir: dir)
|
||||
|
||||
let files = try FileBasedMessageToAppendSequence.allRegularFiles(in: dir)
|
||||
#expect(Set(files) == Set([a, b, c]))
|
||||
|
||||
let messages = try await FileBasedMessageToAppendSequence.readDirectory(
|
||||
directoryPath: dir,
|
||||
originalIndex: 75_465
|
||||
).compactMap {
|
||||
try? $0.get()
|
||||
}.sorted(by: { $0.sortIndex < $1.sortIndex })
|
||||
#expect(messages.map { $0.originalIndex } == [75_465, 75_465, 75_465])
|
||||
#expect(messages.map { $0.nestedIndex } == [0, 1, 2])
|
||||
#expect(Set(messages.map { $0.path.filePath }) == Set([a, b, c]))
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
static func readDirectorySkippingUnreadableFiles() async throws {
|
||||
try await withTemporaryDirectory { dir in
|
||||
let all = try createFiles(
|
||||
dir: dir,
|
||||
content: [
|
||||
#"""
|
||||
This is not an email
|
||||
"""#,
|
||||
#"""
|
||||
From: a@example.apple.com
|
||||
Subject: A
|
||||
Message-id: <a-1@example.apple.com>
|
||||
Date: Tue, 13 Sep 2016 04:08:04 -0700
|
||||
|
||||
a
|
||||
"""#,
|
||||
#"""
|
||||
From: b@example.apple.com
|
||||
Subject: B
|
||||
Message-id: <b-2@example.apple.com>
|
||||
Date: invalid date
|
||||
|
||||
b
|
||||
"""#,
|
||||
]
|
||||
)
|
||||
try #require(all.count == 3)
|
||||
let a = all[0]
|
||||
let b = all[1]
|
||||
let c = all[2]
|
||||
|
||||
let files = try FileBasedMessageToAppendSequence.allRegularFiles(in: dir)
|
||||
#expect(Set(files) == Set(all))
|
||||
|
||||
let result = try await FileBasedMessageToAppendSequence.readDirectory(
|
||||
directoryPath: dir,
|
||||
originalIndex: 75_465
|
||||
)
|
||||
let messages = result.compactMap {
|
||||
try? $0.get()
|
||||
}.sorted(by: { $0.sortIndex < $1.sortIndex })
|
||||
#expect(messages.map { $0.originalIndex } == [75_465])
|
||||
#expect(messages.map { $0.path.filePath } == [b])
|
||||
|
||||
let errors: [FileBasedMessageToAppendSequence.UnableToParseFile] = result.compactMap {
|
||||
guard case .failure(let error) = $0 else { return nil }
|
||||
return error
|
||||
}
|
||||
#expect(Set(errors.map { $0.filePath }) == Set([a, c]))
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
static func sortedFileSequence() async throws {
|
||||
try await withTemporaryDirectory { dir in
|
||||
let (a, b, c) = try create3Files(dir: dir)
|
||||
|
||||
let seq = FileBasedMessageToAppendSequence(
|
||||
paths: [
|
||||
a,
|
||||
b,
|
||||
c,
|
||||
],
|
||||
options: [.sort] // <-- Messages should be sorted by date
|
||||
)
|
||||
|
||||
let messages: [MessageToAppend<FilePath>] = try await seq.reduce(into: []) {
|
||||
$0.append($1)
|
||||
}
|
||||
|
||||
#expect(
|
||||
messages.map { $0.id } == [a, c, b]
|
||||
)
|
||||
#expect(
|
||||
messages.map { $0.messageID } == [
|
||||
MessageID("<a-1@example.apple.com>"),
|
||||
MessageID("<c-3@example.apple.com>"),
|
||||
MessageID("<b-2@example.apple.com>"),
|
||||
]
|
||||
)
|
||||
|
||||
#expect(
|
||||
messages.map { $0.serverMessageDate } == [
|
||||
ServerMessageDate(
|
||||
.init(year: 2016, month: 9, day: 13, hour: 11, minute: 8, second: 4, timeZoneMinutes: 0)!
|
||||
),
|
||||
ServerMessageDate(
|
||||
.init(year: 2024, month: 4, day: 25, hour: 14, minute: 41, second: 32, timeZoneMinutes: 0)!
|
||||
),
|
||||
ServerMessageDate(
|
||||
.init(year: 2024, month: 4, day: 30, hour: 14, minute: 31, second: 7, timeZoneMinutes: 0)!
|
||||
),
|
||||
],
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
static func unsortedFileSequence() async throws {
|
||||
try await withTemporaryDirectory { dir in
|
||||
let (a, b, c) = try create3Files(dir: dir)
|
||||
|
||||
let seq = FileBasedMessageToAppendSequence(
|
||||
paths: [
|
||||
a,
|
||||
b,
|
||||
c,
|
||||
],
|
||||
options: [] // <-- no sorting
|
||||
)
|
||||
|
||||
let messages: [MessageToAppend<FilePath>] = try await seq.reduce(into: []) {
|
||||
$0.append($1)
|
||||
}
|
||||
|
||||
#expect(
|
||||
messages.map { $0.id } == [a, b, c]
|
||||
)
|
||||
#expect(
|
||||
messages.map { $0.messageID } == [
|
||||
MessageID("<a-1@example.apple.com>"),
|
||||
MessageID("<b-2@example.apple.com>"),
|
||||
MessageID("<c-3@example.apple.com>"),
|
||||
]
|
||||
)
|
||||
|
||||
#expect(
|
||||
messages.map { $0.serverMessageDate } == [
|
||||
ServerMessageDate(
|
||||
.init(year: 2016, month: 9, day: 13, hour: 11, minute: 8, second: 4, timeZoneMinutes: 0)!
|
||||
),
|
||||
ServerMessageDate(
|
||||
.init(year: 2024, month: 4, day: 30, hour: 14, minute: 31, second: 7, timeZoneMinutes: 0)!
|
||||
),
|
||||
ServerMessageDate(
|
||||
.init(year: 2024, month: 4, day: 25, hour: 14, minute: 41, second: 32, timeZoneMinutes: 0)!
|
||||
),
|
||||
],
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
static func fileSequenceSkippingInvalid() async throws {
|
||||
try await withTemporaryDirectory { dir in
|
||||
let all = try createFiles(
|
||||
dir: dir,
|
||||
content: [
|
||||
#"""
|
||||
This is not an email
|
||||
"""#,
|
||||
#"""
|
||||
From: b@example.apple.com
|
||||
Subject: B
|
||||
Message-id: <b-2@example.apple.com>
|
||||
Date: Tue, 30 Apr 2024 14:31:07 +0000
|
||||
|
||||
b
|
||||
"""#,
|
||||
]
|
||||
)
|
||||
try #require(all.count == 2)
|
||||
let a = all[0]
|
||||
let b = all[1]
|
||||
let c = dir.appending("does-not-exist")
|
||||
|
||||
let seq = FileBasedMessageToAppendSequence(
|
||||
paths: [
|
||||
a,
|
||||
b,
|
||||
c,
|
||||
],
|
||||
options: [.skipErrors]
|
||||
)
|
||||
|
||||
let messages: [MessageToAppend<FilePath>] = try await seq.reduce(into: []) {
|
||||
$0.append($1)
|
||||
}
|
||||
|
||||
#expect(
|
||||
messages.map { $0.id } == [b]
|
||||
)
|
||||
#expect(
|
||||
messages.map { $0.messageID } == [
|
||||
MessageID("<b-2@example.apple.com>")
|
||||
]
|
||||
)
|
||||
|
||||
#expect(
|
||||
messages.map { $0.serverMessageDate } == [
|
||||
ServerMessageDate(
|
||||
.init(year: 2024, month: 4, day: 30, hour: 14, minute: 31, second: 7, timeZoneMinutes: 0)!
|
||||
)
|
||||
],
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
struct UnableToCreateDirectory: Swift.Error {}
|
||||
|
||||
@Test
|
||||
static func fileSequenceWithDirectories() async throws {
|
||||
try await withTemporaryDirectory { topLevelDir in
|
||||
let dirA = topLevelDir.appending("A")
|
||||
try dirA.withPlatformString { path in
|
||||
guard mkdir(path, 0o777) == 0 else { throw UnableToCreateDirectory() }
|
||||
}
|
||||
|
||||
let dirB = topLevelDir.appending("B")
|
||||
try dirB.withPlatformString { path in
|
||||
guard mkdir(path, 0o777) == 0 else { throw UnableToCreateDirectory() }
|
||||
}
|
||||
|
||||
let filesA = try createFiles(
|
||||
dir: dirA,
|
||||
content: [
|
||||
#"""
|
||||
From: b@example.apple.com
|
||||
Subject: B
|
||||
Message-id: <b-2@example.apple.com>
|
||||
Date: Tue, 30 Apr 2024 14:31:07 +0000
|
||||
|
||||
b
|
||||
"""#
|
||||
]
|
||||
)
|
||||
try #require(filesA.count == 1)
|
||||
let b = filesA[0]
|
||||
|
||||
let filesB = try createFiles(
|
||||
dir: dirB,
|
||||
content: [
|
||||
#"""
|
||||
This is not an email
|
||||
"""#,
|
||||
#"""
|
||||
From: a@example.apple.com
|
||||
Subject: A
|
||||
Message-id: <a-1@example.apple.com>
|
||||
Date: Tue, 13 Sep 2016 04:08:04 -0700
|
||||
|
||||
a
|
||||
"""#,
|
||||
#"""
|
||||
From: c@example.apple.com
|
||||
Subject: C
|
||||
Message-id: <c-3@example.apple.com>
|
||||
Date: Thu, 25 Apr 2024 16:41:32 +0200
|
||||
|
||||
c
|
||||
"""#,
|
||||
]
|
||||
)
|
||||
try #require(filesB.count == 3)
|
||||
let a = filesB[1]
|
||||
let c = filesB[2]
|
||||
|
||||
let seq = FileBasedMessageToAppendSequence(
|
||||
paths: [
|
||||
dirA,
|
||||
dirB,
|
||||
],
|
||||
options: [.skipErrors, .sort]
|
||||
)
|
||||
|
||||
let messages: [MessageToAppend<FilePath>] = try await seq.reduce(into: []) {
|
||||
$0.append($1)
|
||||
}
|
||||
|
||||
#expect(
|
||||
messages.map { $0.id } == [a, c, b]
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
static func flagExtraction_fromOptions() async throws {
|
||||
try await withTemporaryDirectory { dir in
|
||||
let (file, _, _) = try create3Files(dir: dir)
|
||||
let flags: [NIOIMAP.Flag] = [.seen, .flagged, .answered]
|
||||
|
||||
let seq = FileBasedMessageToAppendSequence(
|
||||
paths: [file],
|
||||
options: [.flags(flags)]
|
||||
)
|
||||
|
||||
let message = try await seq.first { _ in true }
|
||||
#expect(message?.flags == flags)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
static func flagExtraction_noFlags() async throws {
|
||||
try await withTemporaryDirectory { dir in
|
||||
let (file, _, _) = try create3Files(dir: dir)
|
||||
|
||||
let seq = FileBasedMessageToAppendSequence(
|
||||
paths: [file],
|
||||
options: []
|
||||
)
|
||||
|
||||
let message = try await seq.first { _ in true }
|
||||
#expect(message?.flags == nil || message?.flags?.isEmpty == true)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
static func flagExtraction_emptyFlags() async throws {
|
||||
try await withTemporaryDirectory { dir in
|
||||
let (file, _, _) = try create3Files(dir: dir)
|
||||
|
||||
let seq = FileBasedMessageToAppendSequence(
|
||||
paths: [file],
|
||||
options: [.flags([])]
|
||||
)
|
||||
|
||||
let message = try await seq.first { _ in true }
|
||||
#expect(message?.flags == nil)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
static func flagExtraction_multipleFiles() async throws {
|
||||
try await withTemporaryDirectory { dir in
|
||||
let (a, b, c) = try create3Files(dir: dir)
|
||||
let flags: [NIOIMAP.Flag] = [.seen, .draft]
|
||||
|
||||
let seq = FileBasedMessageToAppendSequence(
|
||||
paths: [a, b, c],
|
||||
options: [.flags(flags)]
|
||||
)
|
||||
|
||||
let messages: [MessageToAppend<FilePath>] = try await seq.reduce(into: []) {
|
||||
$0.append($1)
|
||||
}
|
||||
|
||||
// All messages should have the same flags
|
||||
for message in messages {
|
||||
#expect(message.flags == flags)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
static func flagExtraction_customFlags() async throws {
|
||||
try await withTemporaryDirectory { dir in
|
||||
let (file, _, _) = try create3Files(dir: dir)
|
||||
let customFlag = NIOIMAP.Flag("\\CustomFlag")
|
||||
let recentFlag = NIOIMAP.Flag("\\Recent")
|
||||
let flags: [NIOIMAP.Flag] = [.seen, customFlag, recentFlag]
|
||||
|
||||
let seq = FileBasedMessageToAppendSequence(
|
||||
paths: [file],
|
||||
options: [.flags(flags)]
|
||||
)
|
||||
|
||||
let message = try await seq.first { _ in true }
|
||||
#expect(message?.flags == flags)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
static func flagExtraction_mixedOptions() async throws {
|
||||
try await withTemporaryDirectory { dir in
|
||||
let (file, _, _) = try create3Files(dir: dir)
|
||||
let flags: [NIOIMAP.Flag] = [.flagged, .answered]
|
||||
|
||||
let seq = FileBasedMessageToAppendSequence(
|
||||
paths: [file],
|
||||
options: [.skipErrors, .sort, .flags(flags), .createMailbox([])]
|
||||
)
|
||||
|
||||
let message = try await seq.first { _ in true }
|
||||
#expect(message?.flags == flags)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import Foundation
|
||||
import NIOCore
|
||||
@testable import NIOIMAP
|
||||
import SystemPackage
|
||||
import Testing
|
||||
@testable import IMAPToolLib
|
||||
|
||||
@Suite("Async Read File")
|
||||
private enum AsyncReadFileTests {
|
||||
static func createFile(
|
||||
dir: FilePath,
|
||||
name: String,
|
||||
content: String
|
||||
) throws -> FilePath {
|
||||
let path = dir.appending(name)
|
||||
try Data(content.utf8).write(to: URL(path))
|
||||
return path
|
||||
}
|
||||
|
||||
@Test
|
||||
static func filePathComponent() async throws {
|
||||
try await withTemporaryDirectory { dir in
|
||||
let count = 10
|
||||
|
||||
let paths = try (1...count).map { index -> (Int, FilePath) in
|
||||
(
|
||||
index,
|
||||
try createFile(
|
||||
dir: dir,
|
||||
name: "\(index)",
|
||||
content: "\(index)"
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
let all = try await withThrowingTaskGroup { group in
|
||||
for element in paths {
|
||||
let index = element.0
|
||||
let path = element.1
|
||||
group.addTask {
|
||||
let buffer = try await ByteBuffer(asyncContentsOf: path)
|
||||
let s = String(buffer: buffer)
|
||||
return (index, s)
|
||||
}
|
||||
}
|
||||
|
||||
var result: [(Int, String)] = []
|
||||
for try await element in group {
|
||||
result.append(element)
|
||||
}
|
||||
result.sort(by: { $0.0 < $1.0 })
|
||||
return result.map { $0.1 }
|
||||
}
|
||||
|
||||
#expect(all == (1...count).map { "\($0)" })
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,470 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import ArgumentParser
|
||||
@testable import IMAPCommands
|
||||
import Foundation
|
||||
@testable import IMAPToolLib
|
||||
import NIO
|
||||
import NIOIMAP
|
||||
import Testing
|
||||
|
||||
@Suite("Authentication", .timeLimit(.minutes(1)))
|
||||
private struct AuthenticationTests {
|
||||
@Test
|
||||
func testLogin() async throws {
|
||||
await TestServer.runSingleConnectionServer(
|
||||
greeting: .ok(.init(text: "Hello")),
|
||||
expectedCommands: [
|
||||
.init(
|
||||
command: .capability,
|
||||
untagged: [
|
||||
.capabilityData([.imap4rev1, .imap4, .authenticate(AuthenticationMechanism("FOOBAR")!)])
|
||||
],
|
||||
completion: .ok(.init(text: "Done"))
|
||||
),
|
||||
.init(
|
||||
command: .login(username: "john", password: "secret"),
|
||||
completion: .ok(.init(text: "Welcome to the test server"))
|
||||
),
|
||||
.init(
|
||||
command: .capability,
|
||||
untagged: [.capabilityData([.imap4rev1, .imap4, .move])],
|
||||
completion: .ok(.init(text: "Done"))
|
||||
),
|
||||
]
|
||||
) { path in
|
||||
try await IMAPConnection.withConnection(
|
||||
configuration: IMAPConnection.Configuration(path)
|
||||
) { greeting, connection in
|
||||
let result = try await connection.authenticate(
|
||||
greeting: greeting,
|
||||
credential: .username("john", password: "secret"),
|
||||
disableSASLIR: false,
|
||||
method: .automatic
|
||||
)
|
||||
|
||||
#expect(result.responseText == "Welcome to the test server")
|
||||
#expect(result.capabilities == [.imap4rev1, .imap4, .move])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
func testSASL() async throws {
|
||||
await TestServer.runSingleConnectionServer(
|
||||
greeting: .ok(.init(text: "Hello")),
|
||||
expectedCommands: [
|
||||
.init(
|
||||
command: .capability,
|
||||
untagged: [
|
||||
.capabilityData([.imap4rev1, .imap4, .saslIR, .authenticate(.plain)])
|
||||
],
|
||||
completion: .ok(.init(text: "Capabilities Done"))
|
||||
),
|
||||
.init(
|
||||
command: .authenticate(
|
||||
mechanism: .plain,
|
||||
initialResponse: InitialResponse(
|
||||
ByteBuffer(bytes: [
|
||||
0x0, 0x6a, 0x6f, 0x68, 0x6e, 0x0, 0x73, 0x65, 0x63, 0x72, 0x65, 0x74,
|
||||
])
|
||||
)
|
||||
),
|
||||
completion: .ok(.init(text: "Welcome to the test server"))
|
||||
),
|
||||
.init(
|
||||
command: .capability,
|
||||
untagged: [.capabilityData([.imap4rev1, .imap4, .move])],
|
||||
completion: .ok(.init(text: "Capabilities Done 2"))
|
||||
),
|
||||
]
|
||||
) { path in
|
||||
try await IMAPConnection.withConnection(
|
||||
configuration: IMAPConnection.Configuration(path)
|
||||
) { greeting, connection in
|
||||
let result = try await connection.authenticate(
|
||||
greeting: greeting,
|
||||
credential: .username("john", password: "secret"),
|
||||
disableSASLIR: false,
|
||||
method: .automatic
|
||||
)
|
||||
|
||||
#expect(result.responseText == "Welcome to the test server")
|
||||
#expect(result.capabilities == [.imap4rev1, .imap4, .move])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
func testSASL_capabilitiesInResponse() async throws {
|
||||
await TestServer.runSingleConnectionServer(
|
||||
greeting: .ok(.init(text: "Hello")),
|
||||
expectedCommands: [
|
||||
.init(
|
||||
command: .capability,
|
||||
untagged: [
|
||||
.capabilityData([.imap4rev1, .imap4, .saslIR, .authenticate(.plain)])
|
||||
],
|
||||
completion: .ok(.init(text: "Capabilities Done"))
|
||||
),
|
||||
.init(
|
||||
command: .authenticate(
|
||||
mechanism: .plain,
|
||||
initialResponse: InitialResponse(
|
||||
ByteBuffer(bytes: [
|
||||
0x0, 0x6a, 0x6f, 0x68, 0x6e, 0x0, 0x73, 0x65, 0x63, 0x72, 0x65, 0x74,
|
||||
])
|
||||
)
|
||||
),
|
||||
completion: .ok(
|
||||
.init(
|
||||
code: .capability([.imap4rev1, .imap4, .move]),
|
||||
text: "Welcome to the test server"
|
||||
)
|
||||
)
|
||||
),
|
||||
]
|
||||
) { path in
|
||||
try await IMAPConnection.withConnection(
|
||||
configuration: IMAPConnection.Configuration(path)
|
||||
) { greeting, connection in
|
||||
let result = try await connection.authenticate(
|
||||
greeting: greeting,
|
||||
credential: .username("john", password: "secret"),
|
||||
disableSASLIR: false,
|
||||
method: .automatic
|
||||
)
|
||||
|
||||
#expect(result.responseText == "Welcome to the test server")
|
||||
#expect(result.capabilities == [.imap4rev1, .imap4, .move])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
func testSASL_capabilitiesInGreetingAndResponse() async throws {
|
||||
await TestServer.runSingleConnectionServer(
|
||||
greeting: .ok(
|
||||
.init(
|
||||
code: .capability([.imap4rev1, .imap4, .saslIR, .authenticate(.plain)]),
|
||||
text: "Hello"
|
||||
)
|
||||
),
|
||||
expectedCommands: [
|
||||
.init(
|
||||
command: .authenticate(
|
||||
mechanism: .plain,
|
||||
initialResponse: InitialResponse(
|
||||
ByteBuffer(bytes: [
|
||||
0x0, 0x6a, 0x6f, 0x68, 0x6e, 0x0, 0x73, 0x65, 0x63, 0x72, 0x65, 0x74,
|
||||
])
|
||||
)
|
||||
),
|
||||
completion: .ok(
|
||||
.init(
|
||||
code: .capability([.imap4rev1, .imap4, .move]),
|
||||
text: "Welcome to the test server"
|
||||
)
|
||||
)
|
||||
)
|
||||
]
|
||||
) { path in
|
||||
try await IMAPConnection.withConnection(
|
||||
configuration: IMAPConnection.Configuration(path)
|
||||
) { greeting, connection in
|
||||
let result = try await connection.authenticate(
|
||||
greeting: greeting,
|
||||
credential: .username("john", password: "secret"),
|
||||
disableSASLIR: false,
|
||||
method: .automatic
|
||||
)
|
||||
|
||||
#expect(result.responseText == "Welcome to the test server")
|
||||
#expect(result.capabilities == [.imap4rev1, .imap4, .move])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
func testSASL_noIR() async throws {
|
||||
// If the server doesn’t support SASL-IR, we’ll have to wait
|
||||
// for an authentication challenge and then send the IR
|
||||
// in the continuation response:
|
||||
await TestServer.runSingleConnectionServer(
|
||||
greeting: .ok(
|
||||
.init(
|
||||
code: .capability([.imap4rev1, .imap4, .authenticate(.plain)]),
|
||||
text: "Hello"
|
||||
)
|
||||
),
|
||||
expectedCommands: [
|
||||
.init(
|
||||
part: .command(
|
||||
.authenticate(
|
||||
mechanism: .plain,
|
||||
initialResponse: nil
|
||||
)
|
||||
),
|
||||
responses: [
|
||||
.authenticationChallenge(ByteBuffer(string: "Go ahead"))
|
||||
],
|
||||
completion: nil
|
||||
),
|
||||
.init(
|
||||
part: .continuationResponse(
|
||||
ByteBuffer(bytes: [
|
||||
0x0, 0x6a, 0x6f, 0x68, 0x6e, 0x0, 0x73, 0x65, 0x63, 0x72, 0x65, 0x74,
|
||||
])
|
||||
),
|
||||
responses: [],
|
||||
completion: .ok(
|
||||
.init(
|
||||
code: .capability([.imap4rev1, .imap4, .move]),
|
||||
text: "Welcome to the test server"
|
||||
)
|
||||
)
|
||||
),
|
||||
]
|
||||
) { path in
|
||||
try await IMAPConnection.withConnection(
|
||||
configuration: IMAPConnection.Configuration(path)
|
||||
) { greeting, connection in
|
||||
let result = try await connection.authenticate(
|
||||
greeting: greeting,
|
||||
credential: .username("john", password: "secret"),
|
||||
disableSASLIR: false,
|
||||
method: .automatic
|
||||
)
|
||||
|
||||
#expect(result.responseText == "Welcome to the test server")
|
||||
#expect(result.capabilities == [.imap4rev1, .imap4, .move])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
func testThatItFailsWhenTheServerDoesNotReturnCapabilities() async throws {
|
||||
await TestServer.runSingleConnectionServer(
|
||||
greeting: .ok(.init(text: "Hello")),
|
||||
expectedCommands: [
|
||||
.init(
|
||||
command: .capability,
|
||||
untagged: [], // <--- no capabilities
|
||||
completion: .ok(.init(text: "Done"))
|
||||
)
|
||||
]
|
||||
) { path in
|
||||
try await IMAPConnection.withConnection(
|
||||
configuration: IMAPConnection.Configuration(path)
|
||||
) { greeting, connection in
|
||||
_ = await #expect(
|
||||
throws: AuthenticationError(message: "Server did not return Capabilities")
|
||||
) {
|
||||
try await connection.authenticate(
|
||||
greeting: greeting,
|
||||
credential: .username("john", password: "secret"),
|
||||
disableSASLIR: false,
|
||||
method: .automatic
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
func login() async throws {
|
||||
// If the server doesn’t support SASL PLAIN, we’ll have
|
||||
// use LOGIN
|
||||
await TestServer.runSingleConnectionServer(
|
||||
greeting: .ok(
|
||||
.init(
|
||||
code: .capability([.imap4rev1, .imap4]),
|
||||
text: "Hello"
|
||||
)
|
||||
),
|
||||
expectedCommands: [
|
||||
.init(
|
||||
part: .command(.login(username: "john", password: "secret")),
|
||||
responses: [],
|
||||
completion: .ok(
|
||||
.init(
|
||||
code: .capability([.imap4rev1, .imap4, .move]),
|
||||
text: "Welcome to the test server"
|
||||
)
|
||||
)
|
||||
)
|
||||
]
|
||||
) { path in
|
||||
try await IMAPConnection.withConnection(
|
||||
configuration: IMAPConnection.Configuration(path)
|
||||
) { greeting, connection in
|
||||
let result = try await connection.authenticate(
|
||||
greeting: greeting,
|
||||
credential: .username("john", password: "secret"),
|
||||
disableSASLIR: false,
|
||||
method: .automatic
|
||||
)
|
||||
|
||||
#expect(result.responseText == "Welcome to the test server")
|
||||
#expect(result.capabilities == [.imap4rev1, .imap4, .move])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
func forceLogin() async throws {
|
||||
// Even though the server advertises AUTH=PLAIN, `.login` must use LOGIN.
|
||||
await TestServer.runSingleConnectionServer(
|
||||
greeting: .ok(
|
||||
.init(
|
||||
code: .capability([.imap4rev1, .imap4, .saslIR, .authenticate(.plain)]),
|
||||
text: "Hello"
|
||||
)
|
||||
),
|
||||
expectedCommands: [
|
||||
.init(
|
||||
command: .login(username: "john", password: "secret"),
|
||||
completion: .ok(
|
||||
.init(
|
||||
code: .capability([.imap4rev1, .imap4, .move]),
|
||||
text: "Welcome to the test server"
|
||||
)
|
||||
)
|
||||
)
|
||||
]
|
||||
) { path in
|
||||
try await IMAPConnection.withConnection(
|
||||
configuration: IMAPConnection.Configuration(path)
|
||||
) { greeting, connection in
|
||||
let result = try await connection.authenticate(
|
||||
greeting: greeting,
|
||||
credential: .username("john", password: "secret"),
|
||||
disableSASLIR: false,
|
||||
method: .login
|
||||
)
|
||||
|
||||
#expect(result.responseText == "Welcome to the test server")
|
||||
#expect(result.capabilities == [.imap4rev1, .imap4, .move])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
func forceLoginWithSASLCredential() async throws {
|
||||
// A SASL credential has no username and password, so LOGIN can’t be used.
|
||||
await TestServer.runSingleConnectionServer(
|
||||
greeting: .ok(
|
||||
.init(
|
||||
code: .capability([.imap4rev1, .imap4, .authenticate(.plain)]),
|
||||
text: "Hello"
|
||||
)
|
||||
),
|
||||
expectedCommands: []
|
||||
) { path in
|
||||
try await IMAPConnection.withConnection(
|
||||
configuration: IMAPConnection.Configuration(path)
|
||||
) { greeting, connection in
|
||||
_ = await #expect(
|
||||
throws: AuthenticationError(
|
||||
message: "The given credential can only be used with AUTHENTICATE, not LOGIN."
|
||||
)
|
||||
) {
|
||||
try await connection.authenticate(
|
||||
greeting: greeting,
|
||||
credential: .sasl(mechanism: .plain, response: Data([0x41])),
|
||||
disableSASLIR: false,
|
||||
method: .login
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
func loginDisabled() async throws {
|
||||
// LOGINDISABLED (RFC 3501) prohibits LOGIN, so don’t even try.
|
||||
await TestServer.runSingleConnectionServer(
|
||||
greeting: .ok(
|
||||
.init(
|
||||
code: .capability([.imap4rev1, .imap4, .loginDisabled]),
|
||||
text: "Hello"
|
||||
)
|
||||
),
|
||||
expectedCommands: []
|
||||
) { path in
|
||||
try await IMAPConnection.withConnection(
|
||||
configuration: IMAPConnection.Configuration(path)
|
||||
) { greeting, connection in
|
||||
_ = await #expect(
|
||||
throws: AuthenticationError(
|
||||
message: "The server advertises LOGINDISABLED, which prohibits the LOGIN command."
|
||||
)
|
||||
) {
|
||||
try await connection.authenticate(
|
||||
greeting: greeting,
|
||||
credential: .username("john", password: "secret"),
|
||||
disableSASLIR: false,
|
||||
method: .automatic
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
func loginDisabledDoesNotAffectAUTHENTICATE() async throws {
|
||||
// LOGINDISABLED only prohibits LOGIN. When the mechanism is advertised,
|
||||
// `.automatic` must still authenticate.
|
||||
await TestServer.runSingleConnectionServer(
|
||||
greeting: .ok(
|
||||
.init(
|
||||
code: .capability([.imap4rev1, .imap4, .loginDisabled, .saslIR, .authenticate(.plain)]),
|
||||
text: "Hello"
|
||||
)
|
||||
),
|
||||
expectedCommands: [
|
||||
.init(
|
||||
command: .authenticate(
|
||||
mechanism: .plain,
|
||||
initialResponse: InitialResponse(
|
||||
ByteBuffer(bytes: [
|
||||
0x0, 0x6a, 0x6f, 0x68, 0x6e, 0x0, 0x73, 0x65, 0x63, 0x72, 0x65, 0x74,
|
||||
])
|
||||
)
|
||||
),
|
||||
completion: .ok(
|
||||
.init(
|
||||
code: .capability([.imap4rev1, .imap4, .move]),
|
||||
text: "Welcome to the test server"
|
||||
)
|
||||
)
|
||||
)
|
||||
]
|
||||
) { path in
|
||||
try await IMAPConnection.withConnection(
|
||||
configuration: IMAPConnection.Configuration(path)
|
||||
) { greeting, connection in
|
||||
let result = try await connection.authenticate(
|
||||
greeting: greeting,
|
||||
credential: .username("john", password: "secret"),
|
||||
disableSASLIR: false,
|
||||
method: .automatic
|
||||
)
|
||||
|
||||
#expect(result.capabilities == [.imap4rev1, .imap4, .move])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
@testable import IMAPToolLib
|
||||
import NIOIMAP
|
||||
import Testing
|
||||
|
||||
@Suite
|
||||
private enum BatchSizeTests {
|
||||
@Test(arguments: [0, -1])
|
||||
static func rejectsNonPositive(_ count: Int) {
|
||||
#expect(BatchSize(count) == nil)
|
||||
}
|
||||
|
||||
struct MessageLimitFixture: Sendable, CustomTestStringConvertible {
|
||||
var capabilities: [Capability]
|
||||
var expected: BatchSize
|
||||
|
||||
var testDescription: String { "\(capabilities)" }
|
||||
}
|
||||
|
||||
@Test(arguments: [
|
||||
MessageLimitFixture(capabilities: [], expected: 1_000),
|
||||
MessageLimitFixture(capabilities: [.messageLimit(999)], expected: 1_000),
|
||||
MessageLimitFixture(capabilities: [.messageLimit(1_000)], expected: 1_000),
|
||||
MessageLimitFixture(capabilities: [.messageLimit(10_000)], expected: 10_000),
|
||||
MessageLimitFixture(capabilities: [Capability("MESSAGELIMIT=4294967295")], expected: 4_294_967_295),
|
||||
])
|
||||
static func messageLimit(_ fixture: MessageLimitFixture) {
|
||||
#expect(BatchSize(capabilities: fixture.capabilities) == fixture.expected)
|
||||
}
|
||||
|
||||
/// Missing, unparsable, or out-of-range `MESSAGELIMIT` falls back to `minimum`.
|
||||
@Test(arguments: [
|
||||
Capability("MESSAGELIMIT"),
|
||||
Capability("MESSAGELIMIT=abc"),
|
||||
Capability("MESSAGELIMIT=0"),
|
||||
Capability("MESSAGELIMIT=-5000"),
|
||||
Capability("MESSAGELIMIT=4294967296"),
|
||||
Capability("MESSAGELIMIT=99999999999"),
|
||||
])
|
||||
static func invalidMessageLimit(_ capability: Capability) {
|
||||
#expect(BatchSize(capabilities: [capability]) == .minimum)
|
||||
}
|
||||
|
||||
struct PartialRangeFixture: Sendable, CustomTestStringConvertible {
|
||||
var size: BatchSize
|
||||
var batch: Int
|
||||
var expected: ClosedRange<SequenceNumber>
|
||||
|
||||
var testDescription: String { "\(size) #\(batch)" }
|
||||
}
|
||||
|
||||
@Test(arguments: [
|
||||
PartialRangeFixture(size: 1_000, batch: 0, expected: 1...1_000),
|
||||
PartialRangeFixture(size: 1_000, batch: 1, expected: 1_001...2_000),
|
||||
PartialRangeFixture(size: 1_200, batch: 2, expected: 2_401...3_600),
|
||||
PartialRangeFixture(size: 1, batch: 0, expected: 1...1),
|
||||
PartialRangeFixture(size: 1, batch: 4, expected: 5...5),
|
||||
// End clamped to `SequenceNumber.max`:
|
||||
PartialRangeFixture(size: 3_000_000_000, batch: 1, expected: 3_000_000_001...4_294_967_295),
|
||||
])
|
||||
static func partialRange(_ fixture: PartialRangeFixture) {
|
||||
#expect(fixture.size.partialRange(batch: fixture.batch) == fixture.expected)
|
||||
}
|
||||
|
||||
/// A batch size above `UInt32.max / 2` must not overflow past the last batch.
|
||||
@Test
|
||||
static func partialFetchBatches_hugeBatchSize() {
|
||||
let batches = PartialFetchBatches(last: 5, batchSize: 3_000_000_000)
|
||||
#expect(Array(batches) == [.partialLast(.last(1...5))])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import ArgumentParser
|
||||
@testable import IMAPCommands
|
||||
@testable import IMAPToolLib
|
||||
@testable import IMAPToolLib
|
||||
import NIO
|
||||
import NIOIMAP
|
||||
import Testing
|
||||
|
||||
@Suite("Create Mailbox")
|
||||
struct CreateMailboxTests {
|
||||
@Test
|
||||
static func endToEnd() async throws {
|
||||
let connection = try TestConnection(
|
||||
expectedOrdering: .anyOrder,
|
||||
expectedCommands: [
|
||||
.init(
|
||||
command: .create("foo", []),
|
||||
untagged: []
|
||||
),
|
||||
.init(
|
||||
command: .listIndependent(
|
||||
[],
|
||||
reference: MailboxName([]),
|
||||
.mailbox(ByteBuffer(string: "foo")),
|
||||
[]
|
||||
),
|
||||
untagged: [
|
||||
.mailboxData(
|
||||
.list(
|
||||
MailboxInfo(
|
||||
attributes: [
|
||||
.hasNoChildren
|
||||
],
|
||||
path: MailboxPath(
|
||||
name: "foo",
|
||||
pathSeparator: "."
|
||||
),
|
||||
extensions: [:]
|
||||
)
|
||||
)
|
||||
)
|
||||
]
|
||||
),
|
||||
.init(
|
||||
command: .status(
|
||||
"foo",
|
||||
[
|
||||
.messageCount,
|
||||
.uidNext,
|
||||
.uidValidity,
|
||||
.unseenCount,
|
||||
.highestModificationSequence,
|
||||
]
|
||||
),
|
||||
untagged: [
|
||||
.mailboxData(
|
||||
.status(
|
||||
"foo",
|
||||
MailboxStatus(
|
||||
messageCount: 8_640_873,
|
||||
recentCount: nil,
|
||||
nextUID: 25_922_595,
|
||||
uidValidity: 34_563_456,
|
||||
unseenCount: 17_234,
|
||||
size: nil,
|
||||
highestModificationSequence: 9_604_355,
|
||||
appendLimit: nil
|
||||
)
|
||||
)
|
||||
)
|
||||
]
|
||||
),
|
||||
]
|
||||
)
|
||||
|
||||
let info = try await connection.createIfNeededAndList(
|
||||
capabilities: [.imap4rev1, .condStore],
|
||||
mailbox: .create("foo", [])
|
||||
)
|
||||
|
||||
#expect(
|
||||
try info
|
||||
== MailboxInfoAndStatus(
|
||||
path: MailboxPath(
|
||||
name: "foo",
|
||||
pathSeparator: "."
|
||||
),
|
||||
attributes: [
|
||||
.hasNoChildren
|
||||
],
|
||||
status: MailboxStatus(
|
||||
messageCount: 8_640_873,
|
||||
recentCount: nil,
|
||||
nextUID: 25_922_595,
|
||||
uidValidity: 34_563_456,
|
||||
unseenCount: 17_234,
|
||||
size: nil,
|
||||
highestModificationSequence: 9_604_355,
|
||||
appendLimit: nil
|
||||
)
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
static func endToEnd_alreadyExists() async throws {
|
||||
let connection = try TestConnection(
|
||||
expectedOrdering: .anyOrder,
|
||||
expectedCommands: [
|
||||
.init(
|
||||
command: .listIndependent(
|
||||
[],
|
||||
reference: MailboxName([]),
|
||||
.mailbox(ByteBuffer(string: "foo")),
|
||||
[]
|
||||
),
|
||||
untagged: [
|
||||
.mailboxData(
|
||||
.list(
|
||||
MailboxInfo(
|
||||
attributes: [
|
||||
.hasNoChildren
|
||||
],
|
||||
path: MailboxPath(
|
||||
name: "foo",
|
||||
pathSeparator: "."
|
||||
),
|
||||
extensions: [:]
|
||||
)
|
||||
)
|
||||
)
|
||||
]
|
||||
),
|
||||
.init(
|
||||
command: .status(
|
||||
"foo",
|
||||
[
|
||||
.messageCount,
|
||||
.uidNext,
|
||||
.uidValidity,
|
||||
.unseenCount,
|
||||
.highestModificationSequence,
|
||||
]
|
||||
),
|
||||
untagged: [
|
||||
.mailboxData(
|
||||
.status(
|
||||
"foo",
|
||||
MailboxStatus(
|
||||
messageCount: 8_640_873,
|
||||
recentCount: nil,
|
||||
nextUID: 25_922_595,
|
||||
uidValidity: 34_563_456,
|
||||
unseenCount: 17_234,
|
||||
size: nil,
|
||||
highestModificationSequence: 9_604_355,
|
||||
appendLimit: nil
|
||||
)
|
||||
)
|
||||
)
|
||||
]
|
||||
),
|
||||
]
|
||||
)
|
||||
|
||||
let info = try await connection.createIfNeededAndList(
|
||||
capabilities: [.imap4rev1, .condStore],
|
||||
mailbox: .alreadyExists("foo")
|
||||
)
|
||||
|
||||
#expect(
|
||||
try info
|
||||
== MailboxInfoAndStatus(
|
||||
path: MailboxPath(
|
||||
name: "foo",
|
||||
pathSeparator: "."
|
||||
),
|
||||
attributes: [
|
||||
.hasNoChildren
|
||||
],
|
||||
status: MailboxStatus(
|
||||
messageCount: 8_640_873,
|
||||
recentCount: nil,
|
||||
nextUID: 25_922_595,
|
||||
uidValidity: 34_563_456,
|
||||
unseenCount: 17_234,
|
||||
size: nil,
|
||||
highestModificationSequence: 9_604_355,
|
||||
appendLimit: nil
|
||||
)
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import Testing
|
||||
import IMAPCommands
|
||||
@testable import IMAPToolLib
|
||||
import NIOIMAP
|
||||
|
||||
@Suite
|
||||
enum DeleteMailboxTests {
|
||||
|
||||
// MARK: - Happy Path Tests
|
||||
|
||||
@Test
|
||||
static func deleteMailbox_success() async throws {
|
||||
let connection = TestConnection(expectedCommands: [
|
||||
.init(
|
||||
command: .delete("TestMailbox"),
|
||||
responses: [],
|
||||
completion: .ok(.init(text: "DELETE completed"))
|
||||
)
|
||||
])
|
||||
|
||||
try await connection.deleteMailbox(
|
||||
capabilities: [.imap4rev1],
|
||||
mailbox: "TestMailbox"
|
||||
)
|
||||
|
||||
await #expect(connection.expectedCommands == [])
|
||||
}
|
||||
|
||||
@Test
|
||||
static func deleteMailbox_nestedMailbox() async throws {
|
||||
let connection = TestConnection(expectedCommands: [
|
||||
.init(
|
||||
command: .delete("Projects/Work/Archive"),
|
||||
responses: [],
|
||||
completion: .ok(.init(text: "DELETE completed"))
|
||||
)
|
||||
])
|
||||
|
||||
try await connection.deleteMailbox(
|
||||
capabilities: [.imap4rev1],
|
||||
mailbox: "Projects/Work/Archive"
|
||||
)
|
||||
|
||||
await #expect(connection.expectedCommands == [])
|
||||
}
|
||||
|
||||
// MARK: - Error Handling Tests
|
||||
|
||||
@Test
|
||||
static func deleteMailbox_notFound() async throws {
|
||||
let connection = TestConnection(expectedCommands: [
|
||||
.init(
|
||||
command: .delete("NonExistentMailbox"),
|
||||
responses: [],
|
||||
completion: .no(.init(text: "Mailbox does not exist"))
|
||||
)
|
||||
])
|
||||
|
||||
await #expect(throws: TaggedResponse.StateNotOK.self) {
|
||||
_ = try await connection.deleteMailbox(
|
||||
capabilities: [.imap4rev1],
|
||||
mailbox: "NonExistentMailbox"
|
||||
)
|
||||
}
|
||||
|
||||
await #expect(connection.expectedCommands == [])
|
||||
}
|
||||
|
||||
@Test
|
||||
static func deleteMailbox_specialCharacters() async throws {
|
||||
let connection = TestConnection(expectedCommands: [
|
||||
.init(
|
||||
command: .delete("Special & Characters (Test)"),
|
||||
responses: [],
|
||||
completion: .ok(.init(text: "DELETE completed"))
|
||||
)
|
||||
])
|
||||
|
||||
try await connection.deleteMailbox(
|
||||
capabilities: [.imap4rev1],
|
||||
mailbox: "Special & Characters (Test)"
|
||||
)
|
||||
|
||||
await #expect(connection.expectedCommands == [])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
@testable import IMAPCommands
|
||||
import Foundation
|
||||
@testable import IMAPToolLib
|
||||
import NIO
|
||||
import NIOIMAP
|
||||
import Testing
|
||||
|
||||
@Suite
|
||||
enum DeleteMessagesTests {
|
||||
@Test
|
||||
static func test() async throws {
|
||||
let connection = TestConnection(expectedCommands: [
|
||||
.init(
|
||||
command: .uidStore(
|
||||
.set([309_727, 967_986]),
|
||||
[],
|
||||
.flags(
|
||||
StoreFlags.add(
|
||||
silent: true,
|
||||
list: [.deleted]
|
||||
)
|
||||
)
|
||||
),
|
||||
responses: [],
|
||||
completion: .ok(.init(text: "Updated"))
|
||||
),
|
||||
.init(
|
||||
command: .expunge,
|
||||
responses: [
|
||||
.untagged(.messageData(.expunge(44))),
|
||||
.untagged(.messageData(.expunge(55))),
|
||||
],
|
||||
completion: .ok(.init(text: "Done"))
|
||||
),
|
||||
])
|
||||
try await connection.deleteMessages(
|
||||
uids: [309_727, 967_986]
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
static func empty() async throws {
|
||||
let connection = TestConnection(
|
||||
expectedCommands: []
|
||||
)
|
||||
try await connection.deleteMessages(
|
||||
uids: []
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import Foundation
|
||||
import NIOCore
|
||||
import NIOIMAP
|
||||
import SystemPackage
|
||||
import Testing
|
||||
@testable import IMAPToolLib
|
||||
|
||||
@Suite
|
||||
enum DownloadDirectoryTests {
|
||||
@Test
|
||||
static func filePathComponent() async throws {
|
||||
#expect(
|
||||
FilePath.Component(DownloadDirectory.Filename.message(1, 1)).description
|
||||
== "1.01.message"
|
||||
)
|
||||
#expect(
|
||||
FilePath.Component(DownloadDirectory.Filename.message(790_954, 212_451)).description
|
||||
== "790954.033de3.message"
|
||||
)
|
||||
#expect(
|
||||
FilePath.Component(DownloadDirectory.Filename.message(121_047_307, 8_445_624)).description
|
||||
== "121047307.80deb8.message"
|
||||
)
|
||||
#expect(
|
||||
FilePath.Component(DownloadDirectory.Filename.temporary("12bt3x434A56")).description
|
||||
== ".12bt3x434A56.message"
|
||||
)
|
||||
}
|
||||
|
||||
@Test(arguments: [
|
||||
(
|
||||
"790954.033de3.message",
|
||||
DownloadDirectory.Filename.message(790_954, 212_451)
|
||||
),
|
||||
(
|
||||
"1.01.message",
|
||||
DownloadDirectory.Filename.message(1, 1)
|
||||
),
|
||||
(
|
||||
".12bt3x434A56.message",
|
||||
DownloadDirectory.Filename.temporary("12bt3x434A56")
|
||||
),
|
||||
])
|
||||
static func initFromFilename(
|
||||
fixture: (String, DownloadDirectory.Filename)
|
||||
) async throws {
|
||||
var name = fixture.0
|
||||
name.withUTF8 { buffer in
|
||||
#expect(
|
||||
DownloadDirectory.Filename(regularFilename: buffer.span)
|
||||
== fixture.1
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Malformed filenames — in particular ones whose UID or UID-validity would
|
||||
/// overflow `UInt32` — must be rejected (returning `nil`) without trapping,
|
||||
/// so a stray file in the download directory is simply skipped.
|
||||
@Test(arguments: [
|
||||
"9999999999.0001.message", // UID overflows UInt32
|
||||
"4294967296.01.message", // UID = UInt32.max + 1
|
||||
"0.01.message", // UID 0 is invalid
|
||||
"1.ffffffffff.message", // UID-validity overflows UInt32
|
||||
"1.0100000000.message", // UID-validity = UInt32.max + 1
|
||||
])
|
||||
static func initFromFilenameRejectsOverflow(name: String) async throws {
|
||||
var name = name
|
||||
name.withUTF8 { buffer in
|
||||
#expect(DownloadDirectory.Filename(regularFilename: buffer.span) == nil)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
static func directoryEnumeration() async throws {
|
||||
try await withTemporaryDirectory { dir in
|
||||
func create(name: FilePath.Component) throws {
|
||||
let path = dir.appending(name)
|
||||
try Data().write(to: URL(path))
|
||||
}
|
||||
|
||||
try create(name: "790954.033de3.message")
|
||||
try create(name: ".12bt3x434A56.message")
|
||||
try create(name: "121047307.80deb8.message")
|
||||
try create(name: ".aXmooQRwysCmrgQG.message")
|
||||
|
||||
var all = Set<DownloadDirectory.Filename>()
|
||||
var count = 0
|
||||
try DownloadDirectory.withFilenames(in: dir) {
|
||||
count += 1
|
||||
all.insert($0)
|
||||
}
|
||||
|
||||
#expect(count == 4)
|
||||
#expect(
|
||||
all == [
|
||||
.message(790_954, 212_451),
|
||||
.message(121_047_307, 8_445_624),
|
||||
.temporary("12bt3x434A56"),
|
||||
.temporary("aXmooQRwysCmrgQG"),
|
||||
]
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
static func deletingOtherFiles() async throws {
|
||||
try await withTemporaryDirectory { dir in
|
||||
func create(name: FilePath.Component) throws {
|
||||
let path = dir.appending(name)
|
||||
try Data().write(to: URL(path))
|
||||
}
|
||||
|
||||
try create(name: "790954.033de3.message")
|
||||
try create(name: ".12bt3x434A56.message")
|
||||
try create(name: "121047307.80deb8.message")
|
||||
try create(name: ".aXmooQRwysCmrgQG.message")
|
||||
try create(name: "545548.033de3.message")
|
||||
|
||||
let sut = try DownloadDirectory.openDeletingInvalidFiles(
|
||||
directory: dir,
|
||||
uidValidity: 212_451,
|
||||
deleteUnknown: true
|
||||
)
|
||||
|
||||
#expect(fileExists(at: dir.appending("790954.033de3.message")))
|
||||
#expect(!fileExists(at: dir.appending(".12bt3x434A56.message")))
|
||||
#expect(!fileExists(at: dir.appending("121047307.80deb8.message")))
|
||||
#expect(!fileExists(at: dir.appending(".aXmooQRwysCmrgQG.message")))
|
||||
#expect(fileExists(at: dir.appending("545548.033de3.message")))
|
||||
|
||||
#expect(sut.root == dir)
|
||||
#expect(sut.downloadedUIDs == [790_954, 545_548])
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
static func notDeletingOtherFiles() async throws {
|
||||
try await withTemporaryDirectory { dir in
|
||||
func create(name: FilePath.Component) throws {
|
||||
let path = dir.appending(name)
|
||||
try Data().write(to: URL(path))
|
||||
}
|
||||
|
||||
try create(name: "790954.033de3.message")
|
||||
try create(name: ".12bt3x434A56.message")
|
||||
try create(name: "121047307.80deb8.message")
|
||||
try create(name: ".aXmooQRwysCmrgQG.message")
|
||||
try create(name: "545548.033de3.message")
|
||||
|
||||
let sut = try DownloadDirectory.openDeletingInvalidFiles(
|
||||
directory: dir,
|
||||
uidValidity: 212_451,
|
||||
deleteUnknown: false
|
||||
)
|
||||
|
||||
#expect(fileExists(at: dir.appending("790954.033de3.message")))
|
||||
#expect(fileExists(at: dir.appending(".12bt3x434A56.message")))
|
||||
#expect(fileExists(at: dir.appending("121047307.80deb8.message")))
|
||||
#expect(fileExists(at: dir.appending(".aXmooQRwysCmrgQG.message")))
|
||||
#expect(fileExists(at: dir.appending("545548.033de3.message")))
|
||||
|
||||
#expect(sut.root == dir)
|
||||
#expect(sut.downloadedUIDs == [790_954, 545_548])
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
static func fileWriter() async throws {
|
||||
try await withTemporaryDirectory { dir in
|
||||
print("A: ", String(decoding: dir))
|
||||
|
||||
let sut = try DownloadDirectory.openDeletingInvalidFiles(
|
||||
directory: dir,
|
||||
uidValidity: 212_451,
|
||||
deleteUnknown: false
|
||||
)
|
||||
|
||||
do {
|
||||
let writer = try sut.makeWriter(uid: 790_954)
|
||||
writer.write(ByteBuffer(bytes: [0x1, 0x2, 0x3, 0x4]))
|
||||
writer.write(ByteBuffer(bytes: [0xa1, 0xa2, 0xa3, 0xa4]))
|
||||
writer.closeAndSucceed()
|
||||
await writer.waitForCompletion()
|
||||
|
||||
#expect(fileExists(at: dir.appending("790954.033de3.message")))
|
||||
|
||||
#expect(
|
||||
Data(contentsOf: dir.appending("790954.033de3.message"))
|
||||
== Data([0x1, 0x2, 0x3, 0x4, 0xa1, 0xa2, 0xa3, 0xa4])
|
||||
)
|
||||
}
|
||||
|
||||
do {
|
||||
let writer = try sut.makeWriter(uid: 545_548)
|
||||
writer.write(ByteBuffer(bytes: [0x1, 0x2, 0x3, 0x4]))
|
||||
writer.write(ByteBuffer(bytes: [0xa1, 0xa2, 0xa3, 0xa4]))
|
||||
writer.closeAndFail() // <- Failing here.
|
||||
await writer.waitForCompletion()
|
||||
|
||||
#expect(!fileExists(at: dir.appending("545548.033de3.message")))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: -
|
||||
|
||||
func fileExists(at path: FilePath) -> Bool {
|
||||
(try? URL(path).checkResourceIsReachable()) == true
|
||||
}
|
||||
|
||||
extension Data {
|
||||
init?(contentsOf path: FilePath) {
|
||||
guard
|
||||
let data = try? Data(contentsOf: URL(path))
|
||||
else { return nil }
|
||||
self = data
|
||||
}
|
||||
}
|
||||
|
||||
extension String {
|
||||
init?(contentsOf path: FilePath) {
|
||||
guard
|
||||
let data = Data(contentsOf: path)
|
||||
else { return nil }
|
||||
self = String(decoding: data, as: UTF8.self)
|
||||
}
|
||||
|
||||
func write(to path: FilePath) throws {
|
||||
try Data(utf8).write(to: URL(path))
|
||||
}
|
||||
}
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import Foundation
|
||||
import NIOCore
|
||||
@testable import IMAPToolLib
|
||||
import NIOIMAP
|
||||
import Synchronization
|
||||
import SystemPackage
|
||||
import Testing
|
||||
|
||||
@Suite("DownloadDirectory.Writer stall")
|
||||
enum DownloadDirectoryWriterStallTests {
|
||||
|
||||
/// Bug #4 (regression): `waitForCompletion()` must return even when the writer has
|
||||
/// already finished everything — including moving the file into place — before it is
|
||||
/// called. The original DispatchIO implementation parked a continuation that the
|
||||
/// already-fired, one-shot cleanup handler could never resume, stalling the download.
|
||||
///
|
||||
/// This test forces that ordering by waiting until the file exists at its final path
|
||||
/// before calling `waitForCompletion()`.
|
||||
@Test(.timeLimit(.minutes(1)))
|
||||
static func waitForCompletionDoesNotStallWhenCleanupRanFirst() async throws {
|
||||
try await withTemporaryDirectory { dir in
|
||||
let uid: UID = 42
|
||||
let uidValidity: UIDValidity = 1
|
||||
let finalPath = dir.appending(.message(uid, uidValidity))
|
||||
|
||||
let setupError = Mutex<String?>(nil)
|
||||
let reachedWait = Mutex<Bool>(false)
|
||||
|
||||
let finished = await finishesWithoutStalling(within: 10) {
|
||||
do {
|
||||
let tempPath = dir.appending(.temporary("stalltest.\(uid)"))
|
||||
let writer = try DownloadDirectory.Writer(
|
||||
uid: uid,
|
||||
path: tempPath,
|
||||
finalPath: finalPath
|
||||
)
|
||||
writer.write(ByteBuffer(string: "From: test\r\n\r\nbody\r\n"))
|
||||
writer.closeAndSucceed()
|
||||
|
||||
// Wait until the writing task has moved the file into place, so that
|
||||
// it has finished before `waitForCompletion()` is called.
|
||||
var attempts = 0
|
||||
while !FileManager.default.fileExists(atPath: finalPath.string) {
|
||||
attempts += 1
|
||||
if attempts > 1_000 {
|
||||
setupError.withLock { $0 = "writing task never ran (final file was not created)" }
|
||||
return
|
||||
}
|
||||
try await Task.sleep(for: .milliseconds(10))
|
||||
}
|
||||
// Let the writing task finish completely.
|
||||
try await Task.sleep(for: .milliseconds(50))
|
||||
|
||||
reachedWait.withLock { $0 = true }
|
||||
// With the bug, this parked a continuation that nothing could resume.
|
||||
await writer.waitForCompletion()
|
||||
} catch {
|
||||
setupError.withLock { $0 = "\(error)" }
|
||||
}
|
||||
}
|
||||
|
||||
#expect(
|
||||
setupError.withLock { $0 } == nil,
|
||||
"Test setup failed: \(setupError.withLock { $0 } ?? "")"
|
||||
)
|
||||
#expect(
|
||||
reachedWait.withLock { $0 },
|
||||
"Test never reached waitForCompletion()."
|
||||
)
|
||||
#expect(
|
||||
finished,
|
||||
"Writer.waitForCompletion() stalled after the writer had already completed."
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
@testable import IMAPCommands
|
||||
import Foundation
|
||||
@testable import IMAPToolLib
|
||||
import NIO
|
||||
import NIOIMAP
|
||||
import Testing
|
||||
|
||||
@Suite
|
||||
enum DownloadTests {
|
||||
@Test
|
||||
static func downloadingUIDs() async throws {
|
||||
let section = SectionSpecifier(part: [], kind: .complete)
|
||||
|
||||
let connection = TestConnection(
|
||||
expectedOrdering: .anyOrder,
|
||||
expectedCommands: [
|
||||
.init(
|
||||
command: .uidFetch(
|
||||
.set(UIDSetNonEmpty(range: 309_727...309_727)),
|
||||
[.uid, .bodySection(peek: true, section, nil)],
|
||||
[]
|
||||
),
|
||||
fetchResponses: [
|
||||
.start(50_683),
|
||||
.simpleAttribute(.uid(309_727)),
|
||||
.streamingBegin(kind: .body(section: section, offset: nil), byteCount: 10),
|
||||
.streamingBytes(ByteBuffer(string: "0123456")),
|
||||
.streamingBytes(ByteBuffer(string: "789")),
|
||||
.streamingEnd,
|
||||
.finish,
|
||||
],
|
||||
completion: .ok(.init(text: "Done"))
|
||||
),
|
||||
.init(
|
||||
command: .uidFetch(
|
||||
.set(UIDSetNonEmpty(range: 967_986...967_986)),
|
||||
[.uid, .bodySection(peek: true, SectionSpecifier(part: [], kind: .complete), nil)],
|
||||
[]
|
||||
),
|
||||
fetchResponses: [
|
||||
.start(81_434),
|
||||
.simpleAttribute(.uid(967_986)),
|
||||
.streamingBegin(kind: .body(section: section, offset: nil), byteCount: 10),
|
||||
.streamingBytes(ByteBuffer(string: "abcdefghij")),
|
||||
.streamingEnd,
|
||||
.finish,
|
||||
],
|
||||
completion: .ok(.init(text: "Done"))
|
||||
),
|
||||
]
|
||||
)
|
||||
try await withTemporaryDirectory { root in
|
||||
var dir = try DownloadDirectory.openDeletingInvalidFiles(
|
||||
directory: root,
|
||||
uidValidity: 543,
|
||||
deleteUnknown: false
|
||||
)
|
||||
try await connection.download(
|
||||
uids: [309_727, 967_986],
|
||||
into: &dir
|
||||
)
|
||||
|
||||
#expect(dir.downloadedUIDs == [309_727, 967_986])
|
||||
#expect(fileExists(at: root.appending("309727.021f.message")))
|
||||
#expect(fileExists(at: root.appending("967986.021f.message")))
|
||||
|
||||
#expect(String(contentsOf: root.appending("309727.021f.message")) == "0123456789")
|
||||
#expect(String(contentsOf: root.appending("967986.021f.message")) == "abcdefghij")
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
static func skippingAlreadyExistingUIDs() async throws {
|
||||
// Should not download UID 309_727 because it already exists.
|
||||
let section = SectionSpecifier(part: [], kind: .complete)
|
||||
|
||||
let connection = TestConnection(expectedCommands: [
|
||||
.init(
|
||||
command: .uidFetch(
|
||||
.set(UIDSetNonEmpty(range: 967_986...967_986)),
|
||||
[.uid, .bodySection(peek: true, SectionSpecifier(part: [], kind: .complete), nil)],
|
||||
[]
|
||||
),
|
||||
fetchResponses: [
|
||||
.start(81_434),
|
||||
.simpleAttribute(.uid(967_986)),
|
||||
.streamingBegin(kind: .body(section: section, offset: nil), byteCount: 10),
|
||||
.streamingBytes(ByteBuffer(string: "abcdefghij")),
|
||||
.streamingEnd,
|
||||
.finish,
|
||||
],
|
||||
completion: .ok(.init(text: "Done"))
|
||||
)
|
||||
])
|
||||
try await withTemporaryDirectory { root in
|
||||
try "0123456789".write(to: root.appending("309727.021f.message"))
|
||||
var dir = try DownloadDirectory.openDeletingInvalidFiles(
|
||||
directory: root,
|
||||
uidValidity: 543,
|
||||
deleteUnknown: false
|
||||
)
|
||||
#expect(dir.downloadedUIDs == [309_727])
|
||||
|
||||
try await connection.download(
|
||||
uids: [309_727, 967_986],
|
||||
into: &dir
|
||||
)
|
||||
|
||||
#expect(dir.downloadedUIDs == [309_727, 967_986])
|
||||
#expect(fileExists(at: root.appending("309727.021f.message")))
|
||||
#expect(fileExists(at: root.appending("967986.021f.message")))
|
||||
|
||||
#expect(String(contentsOf: root.appending("309727.021f.message")) == "0123456789")
|
||||
#expect(String(contentsOf: root.appending("967986.021f.message")) == "abcdefghij")
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
static func downloadingNoUIDs() async throws {
|
||||
let connection = TestConnection(expectedCommands: [])
|
||||
try await withTemporaryDirectory { root in
|
||||
try "0123456789".write(to: root.appending("309727.021f.message"))
|
||||
try "abcdefghij".write(to: root.appending("967986.021f.message"))
|
||||
|
||||
var dir = try DownloadDirectory.openDeletingInvalidFiles(
|
||||
directory: root,
|
||||
uidValidity: 543,
|
||||
deleteUnknown: false
|
||||
)
|
||||
#expect(dir.downloadedUIDs == [309_727, 967_986])
|
||||
|
||||
try await connection.download(
|
||||
uids: [309_727, 967_986],
|
||||
into: &dir
|
||||
)
|
||||
|
||||
#expect(dir.downloadedUIDs == [309_727, 967_986])
|
||||
#expect(fileExists(at: root.appending("309727.021f.message")))
|
||||
#expect(fileExists(at: root.appending("967986.021f.message")))
|
||||
|
||||
#expect(String(contentsOf: root.appending("309727.021f.message")) == "0123456789")
|
||||
#expect(String(contentsOf: root.appending("967986.021f.message")) == "abcdefghij")
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
static func downloadingManyUIDs() async throws {
|
||||
let section = SectionSpecifier(part: [], kind: .complete)
|
||||
|
||||
let allUIDs = UIDSet([
|
||||
13_719, 15_358, 15_802, 16_274, 19_494, 25_159, 27_002, 34_672, 37_566, 38_755,
|
||||
38_787, 40_041, 42_625, 45_739, 49_607, 51_759, 60_241, 74_413, 74_769, 79_327,
|
||||
88_869, 93_311, 94_624, 94_799,
|
||||
128_233, 183_861, 222_318, 223_884, 349_921, 363_045, 410_554, 480_784, 497_318, 505_423,
|
||||
508_061, 549_435, 558_588, 583_859, 611_911, 617_912, 630_519, 727_792, 748_941, 762_112,
|
||||
778_651, 787_041, 788_830, 984_143,
|
||||
])
|
||||
|
||||
let expectedCommands: [TestConnection.CommandAndResponses] =
|
||||
allUIDs
|
||||
.enumerated()
|
||||
.map { index, uid in
|
||||
let seq = SequenceNumber.min.advanced(by: Int64(index))
|
||||
let messageA = "message"
|
||||
let messageB = "-\(uid)"
|
||||
return TestConnection.CommandAndResponses(
|
||||
command: .uidFetch(
|
||||
.set(UIDSetNonEmpty(range: uid...uid)),
|
||||
[.uid, .bodySection(peek: true, section, nil)],
|
||||
[]
|
||||
),
|
||||
fetchResponses: [
|
||||
.start(seq),
|
||||
.simpleAttribute(.uid(uid)),
|
||||
.streamingBegin(
|
||||
kind: .body(section: section, offset: nil),
|
||||
byteCount: messageA.utf8.count + messageB.utf8.count
|
||||
),
|
||||
.streamingBytes(ByteBuffer(string: messageA)),
|
||||
.streamingBytes(ByteBuffer(string: messageB)),
|
||||
.streamingEnd,
|
||||
.finish,
|
||||
],
|
||||
completion: .ok(.init(text: "Done \(uid)"))
|
||||
)
|
||||
}
|
||||
|
||||
let connection = TestConnection(
|
||||
expectedOrdering: .anyOrder,
|
||||
expectedCommands: expectedCommands
|
||||
)
|
||||
try await withTemporaryDirectory { root in
|
||||
var dir = try DownloadDirectory.openDeletingInvalidFiles(
|
||||
directory: root,
|
||||
uidValidity: 543,
|
||||
deleteUnknown: false
|
||||
)
|
||||
try await connection.download(
|
||||
uids: allUIDs,
|
||||
into: &dir
|
||||
)
|
||||
|
||||
#expect(dir.downloadedUIDs == allUIDs)
|
||||
for uid in allUIDs {
|
||||
#expect(fileExists(at: root.appending("\(uid).021f.message")), "\(uid)")
|
||||
#expect(String(contentsOf: root.appending("\(uid).021f.message")) == "message-\(uid)", "\(uid)")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import ArgumentParser
|
||||
import Foundation
|
||||
@testable import IMAPToolLib
|
||||
import Testing
|
||||
import SystemPackage
|
||||
|
||||
@Suite("EmailMessage")
|
||||
private enum EmailMessageTests {
|
||||
@Test
|
||||
static func convertLineEndings() throws {
|
||||
let sut = EmailMessage.convertingLineEndings(
|
||||
#"""
|
||||
To: noreply@apple.com
|
||||
Subject: Test
|
||||
|
||||
Hello
|
||||
"""#.data(using: .utf8)!
|
||||
)
|
||||
|
||||
#expect(
|
||||
Array(sut.data) == [
|
||||
0x54, 0x6F, 0x3A, 0x20, 0x6E, 0x6F, 0x72, 0x65, 0x70, 0x6C, 0x79, 0x40, 0x61, 0x70, 0x70, 0x6C, 0x65,
|
||||
0x2E, 0x63, 0x6F, 0x6D,
|
||||
0xD, 0xA,
|
||||
0x53, 0x75, 0x62, 0x6A, 0x65, 0x63, 0x74, 0x3A, 0x20, 0x54, 0x65, 0x73, 0x74,
|
||||
0xD, 0xA,
|
||||
0xD, 0xA,
|
||||
0x48, 0x65, 0x6C, 0x6C, 0x6F,
|
||||
]
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
static func findMessageID() throws {
|
||||
let sut = EmailMessage.convertingLineEndings(
|
||||
#"""
|
||||
From: bar@none.com
|
||||
To: phooey@all.com
|
||||
Subject: Here's how to do it
|
||||
Message-ID: <970701.32784@VIers.none.com>
|
||||
Date: Tue, 10 Jun 2025 21:49:03 +0000 (GMT)
|
||||
Content-type: text/html; charset=usascii
|
||||
|
||||
<A HREF= "mid:960830.1639@XIson.com/partA.960830.1639@XIson.com">
|
||||
previous message</A>, shows how the approach you propose can be
|
||||
used to accomplish
|
||||
"""#.data(using: .utf8)!
|
||||
)
|
||||
|
||||
#expect(sut.headersOfInterest?.messageID == "<970701.32784@VIers.none.com>")
|
||||
#expect(sut.headersOfInterest?.date == "Tue, 10 Jun 2025 21:49:03 +0000 (GMT)")
|
||||
}
|
||||
|
||||
@Test
|
||||
static func headerIsCRLFCleanWithCRLFEndings() throws {
|
||||
// The first four line breaks must all be CRLF.
|
||||
let input = "To: noreply@apple.com\r\nSubject: Test\r\nFrom: x@y.com\r\nDate: now\r\n\r\nHello\n"
|
||||
.data(using: .utf8)!
|
||||
#expect(EmailMessage.headerIsCRLFClean(input))
|
||||
}
|
||||
|
||||
@Test
|
||||
static func headerIsNotCRLFCleanWithLFEndings() throws {
|
||||
let input = "To: noreply@apple.com\nSubject: Test\n\nHello\n".data(using: .utf8)!
|
||||
#expect(!EmailMessage.headerIsCRLFClean(input))
|
||||
}
|
||||
|
||||
@Test
|
||||
static func headerIsNotCRLFCleanWithBareCR() throws {
|
||||
let input = "To: noreply@apple.com\rSubject: Test\r\n".data(using: .utf8)!
|
||||
#expect(!EmailMessage.headerIsCRLFClean(input))
|
||||
}
|
||||
}
|
||||
+162
@@ -0,0 +1,162 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
@testable import IMAPToolLib
|
||||
import Testing
|
||||
import NIOIMAP
|
||||
|
||||
@Suite
|
||||
private enum ExistingMailboxHierarchyTests {
|
||||
@Test
|
||||
static func makeMailboxPath_basics() throws {
|
||||
let sut = try ExistingMailboxHierarchy(
|
||||
mailboxPaths: [
|
||||
.init(
|
||||
name: .inbox,
|
||||
pathSeparator: "/"
|
||||
),
|
||||
.init(
|
||||
name: "a/b",
|
||||
pathSeparator: "/"
|
||||
),
|
||||
.init(
|
||||
name: "a",
|
||||
pathSeparator: "/"
|
||||
),
|
||||
]
|
||||
)
|
||||
|
||||
#expect(sut.bestParent(displayStrings: ["c"]) == nil)
|
||||
#expect(try sut.makeMailboxPath(displayStrings: ["c"]) == MailboxPath(name: "c", pathSeparator: "/"))
|
||||
|
||||
#expect(sut.bestParent(displayStrings: ["a", "c"])?.mailboxPath.name == "a")
|
||||
#expect(try sut.makeMailboxPath(displayStrings: ["a", "c"]) == MailboxPath(name: "a/c", pathSeparator: "/"))
|
||||
|
||||
#expect(sut.bestParent(displayStrings: ["a", "b", "c"])?.mailboxPath.name == "a/b")
|
||||
#expect(
|
||||
try sut.makeMailboxPath(displayStrings: ["a", "b", "c"]) == MailboxPath(name: "a/b/c", pathSeparator: "/")
|
||||
)
|
||||
|
||||
#expect(sut.bestParent(displayStrings: ["foo", "bar"]) == nil)
|
||||
#expect(
|
||||
try sut.makeMailboxPath(displayStrings: ["foo", "bar"]) == MailboxPath(name: "foo/bar", pathSeparator: "/")
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
static func makeMailboxPath_differentPathSeparators() throws {
|
||||
let sut = try ExistingMailboxHierarchy(
|
||||
mailboxPaths: [
|
||||
.init(
|
||||
name: .inbox,
|
||||
pathSeparator: "/"
|
||||
),
|
||||
.init(
|
||||
name: "a",
|
||||
pathSeparator: "."
|
||||
),
|
||||
.init(
|
||||
name: "b",
|
||||
pathSeparator: "-"
|
||||
),
|
||||
]
|
||||
)
|
||||
|
||||
#expect(sut.bestParent(displayStrings: ["c"]) == nil)
|
||||
#expect(try sut.makeMailboxPath(displayStrings: ["c"]) == MailboxPath(name: "c", pathSeparator: "/"))
|
||||
|
||||
#expect(sut.bestParent(displayStrings: ["a", "c"])?.mailboxPath.name == "a")
|
||||
#expect(try sut.makeMailboxPath(displayStrings: ["a", "c"]) == MailboxPath(name: "a.c", pathSeparator: "."))
|
||||
|
||||
#expect(sut.bestParent(displayStrings: ["b", "c"])?.mailboxPath.name == "b")
|
||||
#expect(try sut.makeMailboxPath(displayStrings: ["b", "c"]) == MailboxPath(name: "b-c", pathSeparator: "-"))
|
||||
|
||||
#expect(sut.bestParent(displayStrings: ["a", "c", "d"])?.mailboxPath.name == "a")
|
||||
#expect(
|
||||
try sut.makeMailboxPath(displayStrings: ["a", "c", "d"]) == MailboxPath(name: "a.c.d", pathSeparator: ".")
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
static func makeMailboxNamesForCreation() throws {
|
||||
let sut = try ExistingMailboxHierarchy(
|
||||
mailboxPaths: [
|
||||
.init(
|
||||
name: .inbox,
|
||||
pathSeparator: "/"
|
||||
),
|
||||
.init(
|
||||
name: "a",
|
||||
pathSeparator: "/"
|
||||
),
|
||||
.init(
|
||||
name: "b",
|
||||
pathSeparator: "."
|
||||
),
|
||||
]
|
||||
)
|
||||
|
||||
let result = try sut.makeMailboxNamesForCreation([
|
||||
.init(namePath: ["a", "b", "c"], parameters: []),
|
||||
.init(namePath: ["a", "b"], parameters: []),
|
||||
.init(namePath: ["b", "a"], parameters: []),
|
||||
])
|
||||
#expect(
|
||||
result == [
|
||||
.create("a/b", []),
|
||||
.create("b.a", []),
|
||||
.create("a/b/c", []),
|
||||
]
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
static func makeMailboxNamesForCreation_withExisting() throws {
|
||||
let sut = try ExistingMailboxHierarchy(
|
||||
mailboxPaths: [
|
||||
.init(
|
||||
name: .inbox,
|
||||
pathSeparator: "/"
|
||||
),
|
||||
.init(
|
||||
name: "a",
|
||||
pathSeparator: "/"
|
||||
),
|
||||
.init(
|
||||
name: "a/b",
|
||||
pathSeparator: "/"
|
||||
),
|
||||
.init(
|
||||
name: "b",
|
||||
pathSeparator: "."
|
||||
),
|
||||
]
|
||||
)
|
||||
|
||||
let result = try sut.makeMailboxNamesForCreation([
|
||||
.init(namePath: ["a", "b", "c"], parameters: []),
|
||||
.init(namePath: ["a", "b"], parameters: []),
|
||||
.init(namePath: ["b", "a"], parameters: []),
|
||||
.init(namePath: ["b", "a"], parameters: []),
|
||||
])
|
||||
#expect(
|
||||
result == [
|
||||
.alreadyExists("a/b"),
|
||||
.create("b.a", []),
|
||||
.alreadyExists("b.a"),
|
||||
.create("a/b/c", []),
|
||||
]
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
@testable import IMAPCommands
|
||||
import Foundation
|
||||
@testable import IMAPToolLib
|
||||
import NIO
|
||||
import NIOIMAP
|
||||
import Testing
|
||||
|
||||
@Suite("FetchBatch — count honoring")
|
||||
enum FetchBatchCountTests {
|
||||
|
||||
/// Bug #6 (fixed): On a server without RFC 9394 `PARTIAL`, `makeBoundaryFetchBatch`
|
||||
/// used an early guard that only inspected `mailboxMessageCount` (not the requested
|
||||
/// `count`) and short-circuited to `.fixed([UID.min...UID.max])` for small mailboxes.
|
||||
/// So a `.last(count:)` request on a small mailbox fetched the *entire* mailbox,
|
||||
/// ignoring `--count`. Now the whole-mailbox shortcut applies only to `.all`, and
|
||||
/// `.last(count:)` issues a bounded SEARCH for the last `count` messages.
|
||||
///
|
||||
/// Here `BatchSize.minimum` is 1,000, so `batchSize / 2 == 500 > 400`, which
|
||||
/// previously triggered the over-fetch: `.last(count: 100)` on 400 messages fetched
|
||||
/// all 400. It now searches sequence numbers `301...*` (the last 100 of 400).
|
||||
@Test
|
||||
static func lastCountDoesNotFetchWholeMailbox() async throws {
|
||||
let connection = TestConnection(expectedCommands: [
|
||||
.init(
|
||||
command: .uidSearch(
|
||||
key: .sequenceNumbers(.set(.init(set: [301...])!)),
|
||||
charset: nil,
|
||||
returnOptions: []
|
||||
),
|
||||
responses: [
|
||||
.untagged(.mailboxData(.search([512, 4_096], nil)))
|
||||
],
|
||||
completion: .ok(.init(text: "Done searching"))
|
||||
)
|
||||
])
|
||||
let batches = try await connection.makeBatches(
|
||||
query: .last(count: 100),
|
||||
mailboxMessageCount: 400,
|
||||
capabilities: [.imap4rev1]
|
||||
)
|
||||
#expect(
|
||||
Array(batches) != [.uidRange(.all)],
|
||||
"Requesting the last 100 of 400 messages must not fetch the entire mailbox."
|
||||
)
|
||||
#expect(Array(batches) == [.uidRange(512...4_096)])
|
||||
#expect(
|
||||
await connection.expectedCommands == [],
|
||||
"Should have issued the bounded boundary SEARCH for the last 100 messages."
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,455 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
@testable import IMAPCommands
|
||||
import Foundation
|
||||
@testable import IMAPToolLib
|
||||
import NIO
|
||||
import NIOIMAP
|
||||
import Testing
|
||||
|
||||
@Suite
|
||||
private enum `FetchBatch makeBatches Tests` {
|
||||
struct MakeBatchesFixture: Sendable, CustomTestStringConvertible {
|
||||
var name: String
|
||||
var query: FetchQuery
|
||||
var mailboxMessageCount: Int
|
||||
var capabilities: [Capability]
|
||||
var expectedCommands: [TestConnection.CommandAndResponses]
|
||||
var expectedBatches: [FetchBatch]
|
||||
|
||||
var testDescription: String { name }
|
||||
}
|
||||
|
||||
@Test(arguments: [
|
||||
MakeBatchesFixture(
|
||||
name: "plain, RFC 3501, low count, low mailbox count",
|
||||
query: .last(count: 100),
|
||||
mailboxMessageCount: 400,
|
||||
capabilities: [.imap4rev1],
|
||||
expectedCommands: [
|
||||
.init(
|
||||
command: .uidSearch(
|
||||
key: .sequenceNumbers(.set(.init(set: [301...])!)),
|
||||
charset: nil,
|
||||
returnOptions: []
|
||||
),
|
||||
responses: [
|
||||
.untagged(
|
||||
.mailboxData(
|
||||
.search(
|
||||
[512, 4_096],
|
||||
nil
|
||||
)
|
||||
)
|
||||
)
|
||||
],
|
||||
completion: .ok(.init(text: "Done searching"))
|
||||
)
|
||||
],
|
||||
expectedBatches: [
|
||||
.uidRange(512...4_096)
|
||||
]
|
||||
),
|
||||
MakeBatchesFixture(
|
||||
name: "plain, RFC 3501, low count",
|
||||
query: .last(count: 100),
|
||||
mailboxMessageCount: 10_000,
|
||||
capabilities: [.imap4rev1],
|
||||
expectedCommands: [
|
||||
.init(
|
||||
command: .uidSearch(
|
||||
key: .sequenceNumbers(.set(.init(set: [9_901...])!)),
|
||||
charset: nil,
|
||||
returnOptions: []
|
||||
),
|
||||
responses: [
|
||||
.untagged(
|
||||
.mailboxData(
|
||||
.search(
|
||||
[
|
||||
1_079, 1_283, 2_322, 5_182, 6_006, 7_819, 7_883, 8_070, 8_474, 8_528,
|
||||
8_620, 9_807, 10_005, 12_082, 12_597, 12_691, 14_703, 15_888, 16_782, 16_872,
|
||||
17_454, 17_555, 19_137, 19_828, 20_042, 20_086, 20_377, 20_431, 21_962, 26_433,
|
||||
26_812, 29_345, 30_321, 30_489, 30_888, 31_770, 32_312, 34_426, 34_729, 36_694,
|
||||
40_553, 42_606, 45_058, 47_190, 48_397, 49_179, 49_180, 49_465, 49_870, 50_844,
|
||||
54_726, 54_832, 57_006, 57_560, 58_010, 58_370, 60_014, 60_205, 60_658, 61_121,
|
||||
63_208, 64_805, 65_387, 66_388, 68_296, 69_005, 69_826, 71_466, 72_523, 73_406,
|
||||
74_642, 75_624, 76_758, 76_852, 77_549, 77_758, 77_999, 79_296, 80_852, 83_383,
|
||||
83_793, 84_020, 85_746, 86_013, 86_383, 87_165, 87_551, 88_094, 88_206, 88_709,
|
||||
91_139, 91_531, 92_567, 92_941, 93_030, 93_158, 94_107, 94_577, 94_882, 98_793,
|
||||
],
|
||||
nil
|
||||
)
|
||||
)
|
||||
)
|
||||
],
|
||||
completion: .ok(.init(text: "Done searching"))
|
||||
)
|
||||
],
|
||||
expectedBatches: [
|
||||
.uidRange(1_079...98_793)
|
||||
]
|
||||
),
|
||||
MakeBatchesFixture(
|
||||
name: "plain, RFC 3501, larger count",
|
||||
query: .last(count: 900),
|
||||
mailboxMessageCount: 100_000,
|
||||
capabilities: [.imap4rev1],
|
||||
expectedCommands: [
|
||||
.init(
|
||||
command: .uidSearch(
|
||||
key: .sequenceNumbers(.set(.init(set: [99_101, 100_000])!)),
|
||||
charset: nil,
|
||||
returnOptions: []
|
||||
),
|
||||
responses: [
|
||||
.untagged(
|
||||
.mailboxData(
|
||||
.search(
|
||||
[
|
||||
6_987_831,
|
||||
9_879_779,
|
||||
],
|
||||
nil
|
||||
)
|
||||
)
|
||||
)
|
||||
],
|
||||
completion: .ok(.init(text: "Done searching"))
|
||||
)
|
||||
],
|
||||
expectedBatches: [
|
||||
.uidRange(6_987_831...9_879_779)
|
||||
]
|
||||
),
|
||||
MakeBatchesFixture(
|
||||
name: "plain, RFC 3501, count spanning multiple batches",
|
||||
query: .last(count: 2_300),
|
||||
mailboxMessageCount: 100_000,
|
||||
capabilities: [.imap4rev1],
|
||||
expectedCommands: [
|
||||
.init(
|
||||
command: .uidSearch(
|
||||
key: .sequenceNumbers(
|
||||
.set(
|
||||
.init(set: [
|
||||
97_701,
|
||||
98_000,
|
||||
99_000,
|
||||
100_000,
|
||||
])!
|
||||
)
|
||||
),
|
||||
charset: nil,
|
||||
returnOptions: []
|
||||
),
|
||||
responses: [
|
||||
.untagged(
|
||||
.mailboxData(
|
||||
.search(
|
||||
[
|
||||
1_132_068,
|
||||
3_842_087,
|
||||
7_706_447,
|
||||
9_155_708,
|
||||
],
|
||||
nil
|
||||
)
|
||||
)
|
||||
)
|
||||
],
|
||||
completion: .ok(.init(text: "Done searching"))
|
||||
)
|
||||
],
|
||||
expectedBatches: [
|
||||
.uidRange(7_706_448...9_155_708),
|
||||
.uidRange(3_842_088...7_706_447),
|
||||
.uidRange(1_132_068...3_842_087),
|
||||
]
|
||||
),
|
||||
MakeBatchesFixture(
|
||||
name: "plain, RFC 3501, count spanning multiple batches, message limit, extended search",
|
||||
query: .last(count: 2_300),
|
||||
mailboxMessageCount: 100_000,
|
||||
capabilities: [
|
||||
.imap4rev1,
|
||||
.messageLimit(2_000),
|
||||
.extendedSearch,
|
||||
],
|
||||
expectedCommands: [
|
||||
.init(
|
||||
command: .uidSearch(
|
||||
key: .sequenceNumbers(
|
||||
.set(
|
||||
.init(set: [
|
||||
97_701,
|
||||
98_000,
|
||||
100_000,
|
||||
])!
|
||||
)
|
||||
),
|
||||
charset: nil,
|
||||
returnOptions: [.all]
|
||||
),
|
||||
responses: [
|
||||
.untagged(
|
||||
.mailboxData(
|
||||
.extendedSearch(
|
||||
ExtendedSearchResponse(
|
||||
correlator: SearchCorrelator(tag: "A1"),
|
||||
kind: .uid,
|
||||
returnData: [
|
||||
.all(
|
||||
.set([
|
||||
3_344_364,
|
||||
5_503_918,
|
||||
9_920_245,
|
||||
])
|
||||
)
|
||||
]
|
||||
)
|
||||
)
|
||||
)
|
||||
)
|
||||
],
|
||||
completion: .ok(.init(text: "Done searching"))
|
||||
)
|
||||
],
|
||||
expectedBatches: [
|
||||
.uidRange(5_503_919...9_920_245),
|
||||
.uidRange(3_344_364...5_503_918),
|
||||
]
|
||||
),
|
||||
MakeBatchesFixture(
|
||||
name: "partial, RFC 9394, low count",
|
||||
query: .last(count: 100),
|
||||
mailboxMessageCount: 10_000,
|
||||
capabilities: [.imap4rev1, .partial, .messageLimit(1_200)],
|
||||
expectedCommands: [],
|
||||
expectedBatches: [
|
||||
.partialLast(.last(1...100))
|
||||
]
|
||||
),
|
||||
MakeBatchesFixture(
|
||||
name: "partial, RFC 9394",
|
||||
query: .last(count: 3_000),
|
||||
mailboxMessageCount: 10_000,
|
||||
capabilities: [.imap4rev1, .partial, .messageLimit(1_200)],
|
||||
expectedCommands: [],
|
||||
expectedBatches: [
|
||||
.partialLast(.last(1...1_200)),
|
||||
.partialLast(.last(1_201...2_400)),
|
||||
.partialLast(.last(2_401...3_000)),
|
||||
]
|
||||
),
|
||||
MakeBatchesFixture(
|
||||
name: ".uids with Partial, sparse UIDs",
|
||||
query: .uids([100, 5_000, 10_000]),
|
||||
mailboxMessageCount: 10_000,
|
||||
capabilities: [.imap4rev1, .partial, .messageLimit(1_200)],
|
||||
expectedCommands: [],
|
||||
expectedBatches: [
|
||||
.partialLast(.last(1...3))
|
||||
]
|
||||
),
|
||||
MakeBatchesFixture(
|
||||
name: ".uids without Partial, sparse UIDs spanning multiple batches",
|
||||
query: .uids([100, 200, 5_000, 10_000]),
|
||||
mailboxMessageCount: 20_000,
|
||||
capabilities: [.imap4rev1],
|
||||
expectedCommands: [],
|
||||
expectedBatches: [
|
||||
.uidRange(100...10_000)
|
||||
]
|
||||
),
|
||||
MakeBatchesFixture(
|
||||
name: ".all without Partial, multiple batches",
|
||||
query: .all,
|
||||
mailboxMessageCount: 2_300,
|
||||
capabilities: [.imap4rev1],
|
||||
expectedCommands: [
|
||||
.init(
|
||||
command: .uidSearch(
|
||||
key: .sequenceNumbers(
|
||||
.set(
|
||||
.init(set: [
|
||||
1,
|
||||
300,
|
||||
1_300,
|
||||
2_300,
|
||||
])!
|
||||
)
|
||||
),
|
||||
charset: nil,
|
||||
returnOptions: []
|
||||
),
|
||||
responses: [
|
||||
.untagged(
|
||||
.mailboxData(
|
||||
.search(
|
||||
[
|
||||
100,
|
||||
5_000,
|
||||
8_000,
|
||||
15_000,
|
||||
],
|
||||
nil
|
||||
)
|
||||
)
|
||||
)
|
||||
],
|
||||
completion: .ok(.init(text: "Done searching"))
|
||||
)
|
||||
],
|
||||
expectedBatches: [
|
||||
.uidRange(8_001...15_000),
|
||||
.uidRange(5_001...8_000),
|
||||
.uidRange(100...5_000),
|
||||
]
|
||||
),
|
||||
MakeBatchesFixture(
|
||||
name: ".all with Partial, multiple batches",
|
||||
query: .all,
|
||||
mailboxMessageCount: 2_300,
|
||||
capabilities: [.imap4rev1, .partial, .messageLimit(1_000)],
|
||||
expectedCommands: [],
|
||||
expectedBatches: [
|
||||
.partialLast(.last(1...1_000)),
|
||||
.partialLast(.last(1_001...2_000)),
|
||||
.partialLast(.last(2_001...2_300)),
|
||||
]
|
||||
),
|
||||
MakeBatchesFixture(
|
||||
name: ".uids with Partial, large UID set needing multiple batches",
|
||||
query: .uids(UIDSet(1...3_000)),
|
||||
mailboxMessageCount: 10_000,
|
||||
capabilities: [.imap4rev1, .partial, .messageLimit(1_000)],
|
||||
expectedCommands: [],
|
||||
expectedBatches: [
|
||||
.partialLast(.last(1...1_000)),
|
||||
.partialLast(.last(1_001...2_000)),
|
||||
.partialLast(.last(2_001...3_000)),
|
||||
]
|
||||
),
|
||||
MakeBatchesFixture(
|
||||
name: ".all without Partial, empty mailbox",
|
||||
query: .all,
|
||||
mailboxMessageCount: 0,
|
||||
capabilities: [.imap4rev1],
|
||||
expectedCommands: [],
|
||||
expectedBatches: [
|
||||
.uidRange(.all)
|
||||
]
|
||||
),
|
||||
MakeBatchesFixture(
|
||||
name: ".all without Partial, mailbox with few messages",
|
||||
query: .all,
|
||||
mailboxMessageCount: 400,
|
||||
capabilities: [.imap4rev1],
|
||||
expectedCommands: [],
|
||||
expectedBatches: [
|
||||
.uidRange(.all)
|
||||
]
|
||||
),
|
||||
MakeBatchesFixture(
|
||||
name: ".uids without Partial, empty UID set",
|
||||
query: .uids([]),
|
||||
mailboxMessageCount: 1_000,
|
||||
capabilities: [.imap4rev1],
|
||||
expectedCommands: [],
|
||||
expectedBatches: []
|
||||
),
|
||||
MakeBatchesFixture(
|
||||
name: ".uids without Partial, large UID set forcing batching",
|
||||
query: .uids(UIDSet(1_000...2_500)),
|
||||
mailboxMessageCount: 10_000,
|
||||
capabilities: [.imap4rev1, .messageLimit(1_000)],
|
||||
expectedCommands: [],
|
||||
expectedBatches: [
|
||||
.uidRange(1_501...2_500),
|
||||
.uidRange(1_000...1_500),
|
||||
]
|
||||
),
|
||||
MakeBatchesFixture(
|
||||
name: ".uids without Partial, contiguous UIDs split into batches",
|
||||
query: .uids(UIDSet(5_000...7_000)),
|
||||
mailboxMessageCount: 10_000,
|
||||
capabilities: [.imap4rev1, .messageLimit(1_000)],
|
||||
expectedCommands: [],
|
||||
expectedBatches: [
|
||||
.uidRange(6_001...7_000),
|
||||
.uidRange(5_001...6_000),
|
||||
.uidRange(5_000...5_000),
|
||||
]
|
||||
),
|
||||
MakeBatchesFixture(
|
||||
name: ".all with message limit, multiple batches",
|
||||
query: .all,
|
||||
mailboxMessageCount: 2_300,
|
||||
capabilities: [.imap4rev1, .messageLimit(1_000)],
|
||||
expectedCommands: [
|
||||
.init(
|
||||
command: .uidSearch(
|
||||
key: .sequenceNumbers(
|
||||
.set(
|
||||
.init(set: [
|
||||
1,
|
||||
300,
|
||||
1_300,
|
||||
2_300,
|
||||
])!
|
||||
)
|
||||
),
|
||||
charset: nil,
|
||||
returnOptions: []
|
||||
),
|
||||
responses: [
|
||||
.untagged(
|
||||
.mailboxData(
|
||||
.search(
|
||||
[
|
||||
100,
|
||||
5_000,
|
||||
8_000,
|
||||
15_000,
|
||||
],
|
||||
nil
|
||||
)
|
||||
)
|
||||
)
|
||||
],
|
||||
completion: .ok(.init(text: "Done searching"))
|
||||
)
|
||||
],
|
||||
expectedBatches: [
|
||||
.uidRange(8_001...15_000),
|
||||
.uidRange(5_001...8_000),
|
||||
.uidRange(100...5_000),
|
||||
]
|
||||
),
|
||||
])
|
||||
static func `test makeBatches`(
|
||||
_ fixture: MakeBatchesFixture
|
||||
) async throws {
|
||||
let connection = TestConnection(expectedCommands: fixture.expectedCommands)
|
||||
let batches = try await connection.makeBatches(
|
||||
query: fixture.query,
|
||||
mailboxMessageCount: fixture.mailboxMessageCount,
|
||||
capabilities: fixture.capabilities
|
||||
)
|
||||
#expect(Array(batches) == fixture.expectedBatches)
|
||||
#expect(await connection.expectedCommands == [], "Should not have any commands remaining.")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,336 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
@testable import IMAPCommands
|
||||
import Foundation
|
||||
@testable import IMAPToolLib
|
||||
import NIO
|
||||
import NIOIMAP
|
||||
import Testing
|
||||
|
||||
@Suite
|
||||
private enum FetchBatchTests {
|
||||
struct FetchBatchesIteratorFixture: Sendable, CustomTestStringConvertible {
|
||||
var batches: FetchBatches
|
||||
var expected: [FetchBatch]
|
||||
|
||||
var testDescription: String { "\(batches)" }
|
||||
}
|
||||
|
||||
@Test(arguments: [
|
||||
FetchBatchesIteratorFixture(
|
||||
batches: .fixed([
|
||||
1...1_000,
|
||||
1_001...2_000,
|
||||
]),
|
||||
expected: [
|
||||
.uidRange(1...1_000),
|
||||
.uidRange(1_001...2_000),
|
||||
]
|
||||
),
|
||||
FetchBatchesIteratorFixture(
|
||||
batches: .fixed([]),
|
||||
expected: []
|
||||
),
|
||||
FetchBatchesIteratorFixture(
|
||||
batches: .fixed([100...200]),
|
||||
expected: [.uidRange(100...200)]
|
||||
),
|
||||
FetchBatchesIteratorFixture(
|
||||
batches: .partial(
|
||||
PartialFetchBatches(
|
||||
last: 2_000,
|
||||
batchSize: 1_000
|
||||
)
|
||||
),
|
||||
expected: [
|
||||
.partialLast(.last(1...1_000)),
|
||||
.partialLast(.last(1_001...2_000)),
|
||||
]
|
||||
),
|
||||
FetchBatchesIteratorFixture(
|
||||
batches: .partial(
|
||||
PartialFetchBatches(
|
||||
last: 100,
|
||||
batchSize: 1_000
|
||||
)
|
||||
),
|
||||
expected: [
|
||||
.partialLast(.last(1...100))
|
||||
]
|
||||
),
|
||||
FetchBatchesIteratorFixture(
|
||||
batches: .fromBoundaries(
|
||||
UIDBatchFromBoundaries(boundaries: [100, 5_000, 10_000, 15_000])
|
||||
),
|
||||
expected: [
|
||||
.uidRange(10_001...15_000),
|
||||
.uidRange(5_001...10_000),
|
||||
.uidRange(100...5_000),
|
||||
]
|
||||
),
|
||||
FetchBatchesIteratorFixture(
|
||||
batches: .fromBoundaries(
|
||||
UIDBatchFromBoundaries(boundaries: [100, 200])
|
||||
),
|
||||
expected: [
|
||||
.uidRange(100...200)
|
||||
]
|
||||
),
|
||||
FetchBatchesIteratorFixture(
|
||||
batches: .fromBoundaries(
|
||||
UIDBatchFromBoundaries(boundaries: [])
|
||||
),
|
||||
expected: []
|
||||
),
|
||||
])
|
||||
static func fetchBatchesIterator(
|
||||
_ fixture: FetchBatchesIteratorFixture
|
||||
) {
|
||||
var iterator = fixture.batches.makeIterator()
|
||||
var actual: [FetchBatch] = []
|
||||
while let batch = iterator.next() {
|
||||
actual.append(batch)
|
||||
guard actual.count < 50 else {
|
||||
Issue.record("Too many iterations.")
|
||||
break
|
||||
}
|
||||
}
|
||||
#expect(actual == fixture.expected)
|
||||
}
|
||||
|
||||
struct SplitUIDsIntoRangesFixture: Sendable, CustomTestStringConvertible {
|
||||
var uids: UIDSet
|
||||
var batchSize: BatchSize
|
||||
var expected: [UIDRange]
|
||||
|
||||
var testDescription: String { "uids: \(uids), batchSize: \(batchSize)" }
|
||||
}
|
||||
|
||||
@Test(arguments: [
|
||||
SplitUIDsIntoRangesFixture(
|
||||
uids: [],
|
||||
batchSize: 1_000,
|
||||
expected: []
|
||||
),
|
||||
SplitUIDsIntoRangesFixture(
|
||||
uids: [100, 200, 300],
|
||||
batchSize: 5,
|
||||
expected: [100...300]
|
||||
),
|
||||
SplitUIDsIntoRangesFixture(
|
||||
uids: [100, 200, 1_500, 2_000],
|
||||
batchSize: 2,
|
||||
expected: [
|
||||
1_500...2_000,
|
||||
100...200,
|
||||
]
|
||||
),
|
||||
SplitUIDsIntoRangesFixture(
|
||||
uids: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
|
||||
batchSize: 3,
|
||||
expected: [
|
||||
8...10,
|
||||
5...7,
|
||||
2...4,
|
||||
1...1,
|
||||
]
|
||||
),
|
||||
SplitUIDsIntoRangesFixture(
|
||||
uids: [100],
|
||||
batchSize: 1,
|
||||
expected: [100...100]
|
||||
),
|
||||
SplitUIDsIntoRangesFixture(
|
||||
uids: [100, 200, 300, 400, 500],
|
||||
batchSize: 1,
|
||||
expected: [
|
||||
500...500,
|
||||
400...400,
|
||||
300...300,
|
||||
200...200,
|
||||
100...100,
|
||||
]
|
||||
),
|
||||
SplitUIDsIntoRangesFixture(
|
||||
uids: [1, 2, 3, 100, 200, 300, 1_000, 2_000, 3_000],
|
||||
batchSize: 4,
|
||||
expected: [
|
||||
300...3_000,
|
||||
2...200,
|
||||
1...1,
|
||||
]
|
||||
),
|
||||
])
|
||||
static func splitUIDsIntoRanges_test(
|
||||
_ fixture: SplitUIDsIntoRangesFixture
|
||||
) {
|
||||
let result = splitUIDsIntoRanges(
|
||||
uids: fixture.uids,
|
||||
batchSize: fixture.batchSize
|
||||
)
|
||||
#expect(result == fixture.expected)
|
||||
}
|
||||
|
||||
struct PartialSequenceFixture: Sendable, CustomTestStringConvertible {
|
||||
var batches: PartialFetchBatches
|
||||
var expected: [FetchBatch]
|
||||
|
||||
var testDescription: String { "\(batches)" }
|
||||
}
|
||||
|
||||
@Test(arguments: [
|
||||
PartialSequenceFixture(
|
||||
batches: PartialFetchBatches(
|
||||
last: 200,
|
||||
batchSize: 1_000
|
||||
),
|
||||
expected: [
|
||||
.partialLast(.last(1...200))
|
||||
]
|
||||
),
|
||||
PartialSequenceFixture(
|
||||
batches: PartialFetchBatches(
|
||||
last: 1,
|
||||
batchSize: 1_000
|
||||
),
|
||||
expected: [
|
||||
.partialLast(.last(1...1))
|
||||
]
|
||||
),
|
||||
PartialSequenceFixture(
|
||||
batches: PartialFetchBatches(
|
||||
last: 1_000,
|
||||
batchSize: 1_000
|
||||
),
|
||||
expected: [
|
||||
.partialLast(.last(1...1_000))
|
||||
]
|
||||
),
|
||||
PartialSequenceFixture(
|
||||
batches: PartialFetchBatches(
|
||||
last: 2_000,
|
||||
batchSize: 1_000
|
||||
),
|
||||
expected: [
|
||||
.partialLast(.last(1...1_000)),
|
||||
.partialLast(.last(1_001...2_000)),
|
||||
]
|
||||
),
|
||||
PartialSequenceFixture(
|
||||
batches: PartialFetchBatches(
|
||||
last: 2_100,
|
||||
batchSize: 1_000
|
||||
),
|
||||
expected: [
|
||||
.partialLast(.last(1...1_000)),
|
||||
.partialLast(.last(1_001...2_000)),
|
||||
.partialLast(.last(2_001...2_100)),
|
||||
]
|
||||
),
|
||||
PartialSequenceFixture(
|
||||
batches: PartialFetchBatches(
|
||||
last: 2_999,
|
||||
batchSize: 1_000
|
||||
),
|
||||
expected: [
|
||||
.partialLast(.last(1...1_000)),
|
||||
.partialLast(.last(1_001...2_000)),
|
||||
.partialLast(.last(2_001...2_999)),
|
||||
]
|
||||
),
|
||||
])
|
||||
static func partialSequence(
|
||||
_ fixture: PartialSequenceFixture
|
||||
) {
|
||||
#expect(Array(fixture.batches) == fixture.expected)
|
||||
}
|
||||
|
||||
@Test
|
||||
static func partialSequence_all() {
|
||||
#expect(
|
||||
PartialFetchBatches(
|
||||
query: .all,
|
||||
mailboxMessageCount: 765,
|
||||
batchSize: 1_000
|
||||
)
|
||||
== PartialFetchBatches(
|
||||
last: 765,
|
||||
batchSize: 1_000
|
||||
)
|
||||
)
|
||||
#expect(
|
||||
PartialFetchBatches(
|
||||
query: .all,
|
||||
mailboxMessageCount: 0,
|
||||
batchSize: 1_000
|
||||
) == nil
|
||||
)
|
||||
#expect(
|
||||
PartialFetchBatches(
|
||||
query: .all,
|
||||
mailboxMessageCount: 1,
|
||||
batchSize: 1_000
|
||||
)
|
||||
== PartialFetchBatches(
|
||||
last: 1,
|
||||
batchSize: 1_000
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
static func partialSequence_last() {
|
||||
#expect(
|
||||
PartialFetchBatches(
|
||||
query: .last(count: 2_000),
|
||||
mailboxMessageCount: 765,
|
||||
batchSize: 1_000
|
||||
)
|
||||
== PartialFetchBatches(
|
||||
last: 765,
|
||||
batchSize: 1_000
|
||||
)
|
||||
)
|
||||
#expect(
|
||||
PartialFetchBatches(
|
||||
query: .last(count: 2_000),
|
||||
mailboxMessageCount: 0,
|
||||
batchSize: 1_000
|
||||
) == nil
|
||||
)
|
||||
#expect(
|
||||
PartialFetchBatches(
|
||||
query: .last(count: 2_000),
|
||||
mailboxMessageCount: 2_001,
|
||||
batchSize: 1_000
|
||||
)
|
||||
== PartialFetchBatches(
|
||||
last: 2_000,
|
||||
batchSize: 1_000
|
||||
)
|
||||
)
|
||||
#expect(
|
||||
PartialFetchBatches(
|
||||
query: .last(count: 2_000),
|
||||
mailboxMessageCount: 77_777,
|
||||
batchSize: 1_000
|
||||
)
|
||||
== PartialFetchBatches(
|
||||
last: 2_000,
|
||||
batchSize: 1_000
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,383 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
@testable import IMAPCommands
|
||||
import Foundation
|
||||
@testable import IMAPToolLib
|
||||
import NIO
|
||||
import NIOIMAP
|
||||
import Testing
|
||||
|
||||
@Suite
|
||||
enum FetchTests {
|
||||
struct MessageInfoFixture: Sendable, CustomTestStringConvertible {
|
||||
var name: String
|
||||
var mailboxMessageCount: Int
|
||||
var capabilities: [Capability]
|
||||
var query: FetchQuery
|
||||
var expectedCommands: [TestConnection.CommandAndResponses]
|
||||
var expectedResults: [ExpectedMessageInfo]
|
||||
|
||||
var testDescription: String { name }
|
||||
|
||||
struct ExpectedMessageInfo: Sendable {
|
||||
var uid: UID
|
||||
var date: String?
|
||||
var subject: String?
|
||||
var from: String?
|
||||
var to: String?
|
||||
var cc: String?
|
||||
var messageID: String?
|
||||
var inReplyTo: String?
|
||||
var flags: [String]
|
||||
}
|
||||
}
|
||||
|
||||
@Test(arguments: [
|
||||
MessageInfoFixture(
|
||||
name: "last 2 messages",
|
||||
mailboxMessageCount: 10_000,
|
||||
capabilities: [],
|
||||
query: .last(count: 2),
|
||||
expectedCommands: [
|
||||
.init(
|
||||
command: .uidSearch(
|
||||
key: .sequenceNumbers(.set(.init(set: [9_999...])!)),
|
||||
charset: nil,
|
||||
returnOptions: []
|
||||
),
|
||||
responses: [
|
||||
.untagged(
|
||||
.mailboxData(
|
||||
.search(
|
||||
[
|
||||
309_727,
|
||||
967_986,
|
||||
],
|
||||
nil
|
||||
)
|
||||
)
|
||||
)
|
||||
],
|
||||
completion: .ok(.init(text: "Done searching"))
|
||||
),
|
||||
.init(
|
||||
command: .uidFetch(
|
||||
.set([309_727...967_986]),
|
||||
[.uid, .flags, .envelope],
|
||||
[]
|
||||
),
|
||||
responses: [
|
||||
.fetch(.start(5)),
|
||||
.fetch(.simpleAttribute(.uid(309_727))),
|
||||
.fetch(.simpleAttribute(.flags([.seen]))),
|
||||
.fetch(
|
||||
.simpleAttribute(
|
||||
.envelope(
|
||||
Envelope(
|
||||
date: InternetMessageDate("Mon, 10 Feb 2025 12:14:53 -0700 (MST)"),
|
||||
subject: ByteBuffer(string: "Fwd: iOS email"),
|
||||
from: [.a],
|
||||
sender: [.b],
|
||||
reply: [.c],
|
||||
to: [.d],
|
||||
cc: [.e],
|
||||
bcc: [.f],
|
||||
inReplyTo: "<13D87EC32432@example.apple.com>",
|
||||
messageID: "<2F89B1064815@example.apple.com>"
|
||||
)
|
||||
)
|
||||
)
|
||||
),
|
||||
.fetch(.finish),
|
||||
.fetch(.start(55)),
|
||||
.fetch(.simpleAttribute(.uid(967_986))),
|
||||
.fetch(.simpleAttribute(.flags([.answered]))),
|
||||
.fetch(
|
||||
.simpleAttribute(
|
||||
.envelope(
|
||||
Envelope(
|
||||
date: InternetMessageDate("Sat, 29 Jun 2024 22:25:38 +0900"),
|
||||
subject: ByteBuffer(string: "Fotowelt"),
|
||||
from: [.f],
|
||||
sender: [.e],
|
||||
reply: [],
|
||||
to: [.a],
|
||||
cc: [],
|
||||
bcc: [],
|
||||
inReplyTo: nil,
|
||||
messageID: "<7A9EEFC3D051@example.apple.com>"
|
||||
)
|
||||
)
|
||||
)
|
||||
),
|
||||
.fetch(.finish),
|
||||
],
|
||||
completion: .ok(.init(text: "Fetch done"))
|
||||
),
|
||||
],
|
||||
expectedResults: [
|
||||
.init(
|
||||
uid: 309_727,
|
||||
date: "Mon, 10 Feb 2025 12:14:53 -0700 (MST)",
|
||||
subject: "Fwd: iOS email",
|
||||
from: "a@example.apple.com",
|
||||
to: "d@example.apple.com",
|
||||
cc: "e@example.apple.com",
|
||||
messageID: "<2F89B1064815@example.apple.com>",
|
||||
inReplyTo: "<13D87EC32432@example.apple.com>",
|
||||
flags: ["\\Seen"]
|
||||
),
|
||||
.init(
|
||||
uid: 967_986,
|
||||
date: "Sat, 29 Jun 2024 22:25:38 +0900",
|
||||
subject: "Fotowelt",
|
||||
from: "f@example.apple.com",
|
||||
to: "a@example.apple.com",
|
||||
cc: nil,
|
||||
messageID: "<7A9EEFC3D051@example.apple.com>",
|
||||
inReplyTo: nil,
|
||||
flags: ["\\Answered"]
|
||||
),
|
||||
]
|
||||
),
|
||||
MessageInfoFixture(
|
||||
name: "specific UIDs",
|
||||
mailboxMessageCount: 1_000,
|
||||
capabilities: [],
|
||||
query: .uids([10, 20]),
|
||||
expectedCommands: [
|
||||
.init(
|
||||
command: .uidFetch(
|
||||
.set([10, 20]),
|
||||
[.uid, .flags, .envelope],
|
||||
[]
|
||||
),
|
||||
responses: [
|
||||
.fetch(.start(1)),
|
||||
.fetch(.simpleAttribute(.uid(10))),
|
||||
.fetch(.simpleAttribute(.flags([.draft]))),
|
||||
.fetch(
|
||||
.simpleAttribute(
|
||||
.envelope(
|
||||
Envelope(
|
||||
date: InternetMessageDate("Wed, 15 Jan 2025 08:00:00 +0000"),
|
||||
subject: ByteBuffer(string: "Test Subject"),
|
||||
from: [.a],
|
||||
sender: [.a],
|
||||
reply: [.a],
|
||||
to: [.b],
|
||||
cc: [],
|
||||
bcc: [],
|
||||
inReplyTo: nil,
|
||||
messageID: "<TEST001@example.apple.com>"
|
||||
)
|
||||
)
|
||||
)
|
||||
),
|
||||
.fetch(.finish),
|
||||
.fetch(.start(2)),
|
||||
.fetch(.simpleAttribute(.uid(20))),
|
||||
.fetch(.simpleAttribute(.flags([]))),
|
||||
.fetch(
|
||||
.simpleAttribute(
|
||||
.envelope(
|
||||
Envelope(
|
||||
date: InternetMessageDate("Thu, 16 Jan 2025 09:30:00 +0000"),
|
||||
subject: ByteBuffer(string: "Another Test"),
|
||||
from: [.b],
|
||||
sender: [.b],
|
||||
reply: [.b],
|
||||
to: [.a],
|
||||
cc: [],
|
||||
bcc: [],
|
||||
inReplyTo: nil,
|
||||
messageID: "<TEST002@example.apple.com>"
|
||||
)
|
||||
)
|
||||
)
|
||||
),
|
||||
.fetch(.finish),
|
||||
],
|
||||
completion: .ok(.init(text: "Fetch done"))
|
||||
)
|
||||
],
|
||||
expectedResults: [
|
||||
.init(
|
||||
uid: 10,
|
||||
date: "Wed, 15 Jan 2025 08:00:00 +0000",
|
||||
subject: "Test Subject",
|
||||
from: "a@example.apple.com",
|
||||
to: "b@example.apple.com",
|
||||
cc: nil,
|
||||
messageID: "<TEST001@example.apple.com>",
|
||||
inReplyTo: nil,
|
||||
flags: ["\\Draft"]
|
||||
),
|
||||
.init(
|
||||
uid: 20,
|
||||
date: "Thu, 16 Jan 2025 09:30:00 +0000",
|
||||
subject: "Another Test",
|
||||
from: "b@example.apple.com",
|
||||
to: "a@example.apple.com",
|
||||
cc: nil,
|
||||
messageID: "<TEST002@example.apple.com>",
|
||||
inReplyTo: nil,
|
||||
flags: []
|
||||
),
|
||||
]
|
||||
),
|
||||
])
|
||||
static func messageInfo(_ fixture: MessageInfoFixture) async throws {
|
||||
let connection = TestConnection(expectedCommands: fixture.expectedCommands)
|
||||
let result = try await connection.fetchMessageInfo(
|
||||
mailboxMessageCount: fixture.mailboxMessageCount,
|
||||
capabilities: fixture.capabilities,
|
||||
query: fixture.query
|
||||
)
|
||||
#expect(await connection.expectedCommands.isEmpty)
|
||||
#expect(result.count == fixture.expectedResults.count)
|
||||
|
||||
for (actual, expected) in zip(result, fixture.expectedResults) {
|
||||
#expect(actual.uid == expected.uid)
|
||||
#expect(actual.date == expected.date)
|
||||
#expect(actual.subject == expected.subject)
|
||||
#expect(actual.from == expected.from)
|
||||
#expect(actual.to == expected.to)
|
||||
#expect(actual.cc == expected.cc)
|
||||
#expect(actual.messageID == expected.messageID)
|
||||
#expect(actual.inReplyTo == expected.inReplyTo)
|
||||
#expect(actual.flags == expected.flags)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
static func simpleAttributes() async throws {
|
||||
let connection = TestConnection(expectedCommands: [
|
||||
.init(
|
||||
command: .uidFetch(
|
||||
.set([309_727, 967_986]),
|
||||
[.uid, .flags, .internalDate],
|
||||
[]
|
||||
),
|
||||
responses: [
|
||||
.fetch(.start(5)),
|
||||
.fetch(.simpleAttribute(.uid(309_727))),
|
||||
.fetch(.simpleAttribute(.flags([.seen]))),
|
||||
.fetch(
|
||||
.simpleAttribute(
|
||||
.internalDate(
|
||||
ServerMessageDate(
|
||||
.init(
|
||||
year: 2025,
|
||||
month: 4,
|
||||
day: 7,
|
||||
hour: 17,
|
||||
minute: 46,
|
||||
second: 22,
|
||||
timeZoneMinutes: 600
|
||||
)!
|
||||
)
|
||||
)
|
||||
)
|
||||
),
|
||||
.fetch(.finish),
|
||||
|
||||
.fetch(.start(55)),
|
||||
.fetch(.simpleAttribute(.uid(967_986))),
|
||||
.fetch(.simpleAttribute(.flags([.answered]))),
|
||||
.fetch(
|
||||
.simpleAttribute(
|
||||
.internalDate(
|
||||
ServerMessageDate(
|
||||
.init(
|
||||
year: 2025,
|
||||
month: 4,
|
||||
day: 7,
|
||||
hour: 17,
|
||||
minute: 47,
|
||||
second: 55,
|
||||
timeZoneMinutes: 600
|
||||
)!
|
||||
)
|
||||
)
|
||||
)
|
||||
),
|
||||
.fetch(.finish),
|
||||
],
|
||||
completion: .ok(.init(text: "Fetch done"))
|
||||
)
|
||||
])
|
||||
let result: [(UID, SequenceNumber?, [MessageAttribute])]
|
||||
result = try await connection.fetchSimpleAttributes(
|
||||
capabilities: [],
|
||||
uids: [309_727, 967_986],
|
||||
attributes: [.flags, .internalDate],
|
||||
modifiers: [],
|
||||
into: []
|
||||
) { all, uid, seq, attr in
|
||||
all.append((uid, seq, attr))
|
||||
}
|
||||
#expect(await connection.expectedCommands.isEmpty)
|
||||
#expect(result.count == 2)
|
||||
|
||||
#expect(result.first?.0 == 309_727)
|
||||
#expect(result.first?.1 == 5)
|
||||
#expect(
|
||||
result.first?.2 == [
|
||||
.uid(309_727),
|
||||
.flags([.seen]),
|
||||
.internalDate(
|
||||
ServerMessageDate(
|
||||
.init(year: 2025, month: 4, day: 7, hour: 17, minute: 46, second: 22, timeZoneMinutes: 600)!
|
||||
)
|
||||
),
|
||||
]
|
||||
)
|
||||
|
||||
#expect(result.last?.0 == 967_986)
|
||||
#expect(result.last?.1 == 55)
|
||||
#expect(
|
||||
result.last?.2 == [
|
||||
.uid(967_986),
|
||||
.flags([.answered]),
|
||||
.internalDate(
|
||||
ServerMessageDate(
|
||||
.init(year: 2025, month: 4, day: 7, hour: 17, minute: 47, second: 55, timeZoneMinutes: 600)!
|
||||
)
|
||||
),
|
||||
]
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
extension EmailAddressListElement {
|
||||
static var a: EmailAddressListElement { .example("a") }
|
||||
static var b: EmailAddressListElement { .example("b") }
|
||||
static var c: EmailAddressListElement { .example("c") }
|
||||
static var d: EmailAddressListElement { .example("d") }
|
||||
static var e: EmailAddressListElement { .example("e") }
|
||||
static var f: EmailAddressListElement { .example("f") }
|
||||
|
||||
static func example(_ name: String) -> EmailAddressListElement {
|
||||
.singleAddress(
|
||||
EmailAddress(
|
||||
personName: nil,
|
||||
sourceRoot: nil,
|
||||
mailbox: ByteBuffer(string: name),
|
||||
host: ByteBuffer(string: "example.apple.com")
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
Loaded 100 of 164 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user