Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
.LSOverride

# Icon must end with two \r
Icon
Icon


# Thumbnails
._*
Expand Down Expand Up @@ -51,3 +52,5 @@ xcuserdata

/contacts
contacts.tar.gz

/.vscode
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ PREFIX ?= /usr/local/bin
.PHONY: archive clean install uninstall

$(EXECUTABLE):
swift build --configuration release --arch x86_64 --arch arm64
swift build --configuration release --arch x86_64 --arch arm64 -Xswiftc -parse-as-library
cp .build/apple/Products/Release/$(EXECUTABLE) .

install: $(EXECUTABLE)
Expand Down
14 changes: 14 additions & 0 deletions Package.resolved

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

13 changes: 11 additions & 2 deletions Package.swift
Original file line number Diff line number Diff line change
@@ -1,9 +1,18 @@
// swift-tools-version:5.5
// swift-tools-version:5.9
import PackageDescription

let package = Package(
name: "contacts",
platforms: [
.macOS(.v13),
],
dependencies: [
.package(url: "https://github.com/apple/swift-argument-parser", from: "1.3.0"),
],

targets: [
.executableTarget(name: "contacts"),
.executableTarget(name: "contacts", dependencies: [
.product(name: "ArgumentParser", package: "swift-argument-parser"),
]),
]
)
31 changes: 28 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,13 +1,38 @@
# contacts-cli

A simple script for querying contacts from the command line.
A simple tool for querying and exporting the macOS contacts database from the command line.

## Usage:

Here's an overview of the commands:

```sh
OVERVIEW: Query and export contacts from the command line

USAGE: contacts-command [--version] <search-string> [--output-type <output-type>] [--search-field <search-field>]

ARGUMENTS:
<search-string> The query input. Use '-' to read from stdin.

OPTIONS:
--version Print out the version of the application.
--output-type <output-type>
(values: csv, json; default: csv)
--search-field <search-field>
(values: fullName, firstName, lastName, email, all; default: all)
-h, --help Show help information.
```

And some specific examples:

```sh
$ contacts query
NAME EMAIL
[email protected] First Last
fullName,firstName,lastName,email
First Last,First,Last,[email protected],First Last

$ echo '{"rowid": 1, "Name": "First Last"}' | jq -r '.Name' | xargs -I{} contacts {} --search-field fullName --output-type json | jq -r '.[0].email' | tr -d '\n'
fullName,firstName,lastName,email
First Last,First,Last,[email protected],First Last
```

## Installation
Expand Down
192 changes: 162 additions & 30 deletions Sources/contacts/main.swift
Original file line number Diff line number Diff line change
@@ -1,43 +1,175 @@
import AddressBook
import ArgumentParser

let arguments = CommandLine.arguments.dropFirst()
if arguments.isEmpty {
fputs("No arguments given\n", stderr)
exit(EXIT_FAILURE)
enum OutputType: String, CaseIterable, ExpressibleByArgument {
case csv, json
}

guard let addressBook = ABAddressBook.shared() else {
fputs("Failed to create address book (check your Contacts privacy settings)\n", stderr)
exit(EXIT_FAILURE)
enum SearchFieldType: String, CaseIterable, ExpressibleByArgument {
case fullName, firstName, lastName, email, all
}

private func comparison(forProperty property: String, string: String) -> ABSearchElement {
let comparison: ABSearchComparison = CFIndex(kABContainsSubStringCaseInsensitive.rawValue)
return ABPerson.searchElement(forProperty: property, label: nil, key: nil, value: string,
comparison: comparison)
@main
struct ContactsCommand: ParsableCommand {
static let configuration = CommandConfiguration(
abstract: "Query and export contacts from the command line"
)

@Flag(help: "Print out the version of the application.")
var version = false

@Argument(help: "The query input. Use '-' to read from stdin.")
var searchString: String

@Option
var outputType: OutputType = .csv

@Option
var searchField: SearchFieldType = .all

mutating func run() throws {
if version {
// we cannot get the latest tag version at compile time
// https://stackoverflow.com/questions/27804227/using-compiler-variables-in-swift
print("v1.1")
return
}

guard let addressBook = ABAddressBook.shared() else {
fputs("Failed to create address book (check your Contacts privacy settings)\n", stderr)
ContactsCommand.exit(withError: ExitCode.failure)
}

if searchString == "-" {
searchString = readLine() ?? ""

if searchString.isEmpty {
fputs("No search input provided through stdin\n", stderr)
ContactsCommand.exit(withError: ExitCode.failure)
}
}

var searchComparison: ABSearchElement

switch searchField {
case .all:
// search fn, ln, and email fields for the search input
searchComparison = ABSearchElement(
forConjunction: CFIndex(kABSearchOr.rawValue),
children: [
comparison(forProperty: kABFirstNameProperty, string: searchString),
comparison(forProperty: kABLastNameProperty, string: searchString),
comparison(forProperty: kABEmailProperty, string: searchString),
]
)
case .fullName:
let nameParts = searchString.split(separator: " ", maxSplits: 1)
let firstName = nameParts.count > 0 ? String(nameParts[0]) : ""
let lastName = nameParts.count > 1 ? String(nameParts[1]) : ""
searchComparison = ABSearchElement(
forConjunction: CFIndex(kABSearchAnd.rawValue),
children: [
comparison(forProperty: kABFirstNameProperty, string: firstName),
comparison(forProperty: kABLastNameProperty, string: lastName),
]
)
case .firstName:
searchComparison = ABSearchElement(
forConjunction: CFIndex(kABSearchAnd.rawValue),
children: [
comparison(forProperty: kABFirstNameProperty, string: searchString),
]
)
case .lastName:
searchComparison = ABSearchElement(
forConjunction: CFIndex(kABSearchAnd.rawValue),
children: [
comparison(forProperty: kABLastNameProperty, string: searchString),
]
)
case .email:
searchComparison = ABSearchElement(
forConjunction: CFIndex(kABSearchAnd.rawValue),
children: [
comparison(forProperty: kABEmailProperty, string: searchString),
]
)
}

let found = addressBook.records(matching: searchComparison) as? [ABRecord] ?? []

if found.count == 0 {
fputs("No contacts found\n", stderr)
ContactsCommand.exit(withError: ExitCode.failure)
}

var results: [[String: String]] = []

for person in found {
let firstName = person.value(forProperty: kABFirstNameProperty) as? String ?? ""
let lastName = person.value(forProperty: kABLastNameProperty) as? String ?? ""

let emailsProperty = person.value(forProperty: kABEmailProperty) as? ABMultiValue

// TODO: think of a better way to handle multiple phones
// although there can be more than a single phone number, we'll assume there can only be one for now
let phonesProperty = person.value(forProperty: kABPhoneProperty) as? ABMultiValue
let phone = phonesProperty?.value(at: 0) as? String ?? ""

if let emails = emailsProperty {
for i in 0 ..< emails.count() {
let email = emails.value(at: i) as? String ?? ""
let result: [String: String] = [
"firstName": firstName,
"lastName": lastName,
"fullName": "\(firstName) \(lastName)",
"email": email,
"phone": phone,
]
results.append(result)
}
} else {
let result: [String: String] = [
"firstName": firstName,
"lastName": lastName,
"fullName": "\(firstName) \(lastName)",
"email": "",
"phone": phone,
]
results.append(result)
}
}

renderOuput(rows: results, outputType: outputType)
}
}

let searchString = arguments.joined(separator: " ")
let firstNameSearch = comparison(forProperty: kABFirstNameProperty, string: searchString)
let lastNameSearch = comparison(forProperty: kABLastNameProperty, string: searchString)
let emailSearch = comparison(forProperty: kABEmailProperty, string: searchString)
let orComparison = ABSearchElement(forConjunction: CFIndex(kABSearchOr.rawValue),
children: [firstNameSearch, lastNameSearch, emailSearch])
func renderOuput(rows: [[String: String]], outputType: OutputType) {
if outputType == .csv {
print(renderCSV(rows))
return
}

let found = addressBook.records(matching: orComparison) as? [ABRecord] ?? []
if found.count == 0 {
exit(EXIT_SUCCESS)
let jsonData = try? JSONSerialization.data(withJSONObject: rows, options: .prettyPrinted)
let jsonString = String(data: jsonData!, encoding: .utf8)
print(jsonString!)
}

print("NAME\tEMAIL")
for person in found {
let firstName = person.value(forProperty: kABFirstNameProperty) as? String ?? ""
let lastName = person.value(forProperty: kABLastNameProperty) as? String ?? ""
let emailsProperty = person.value(forProperty: kABEmailProperty) as? ABMultiValue
if let emails = emailsProperty {
for i in 0..<emails.count() {
let email = emails.value(at: i) as? String ?? ""
print("\(email)\t\(firstName) \(lastName)")
}
func renderCSV(_ rows: [[String: String]]) -> String {
guard let firstRow = rows.first else {
return ""
}

let header = firstRow.keys.joined(separator: ",")
let values = rows.map { row in
row.values.joined(separator: ",")
}.joined(separator: "\n")

return header + "\n" + values
}

private func comparison(forProperty property: String, string: String) -> ABSearchElement {
let comparison: ABSearchComparison = CFIndex(kABContainsSubStringCaseInsensitive.rawValue)
return ABPerson.searchElement(forProperty: property, label: nil, key: nil, value: string,
comparison: comparison)
}