diff --git a/.travis.yml b/.travis.yml index 042fab17f32..7c1c0b4d779 100644 --- a/.travis.yml +++ b/.travis.yml @@ -13,6 +13,7 @@ before_install: - bundle exec pod install --project-directory=Example --repo-update - bundle exec pod install --project-directory=Firestore/Example --no-repo-update - brew install clang-format + - brew install swiftformat - brew install cmake - brew install go # Somehow the build for Abseil requires this. - echo "$TRAVIS_COMMIT_RANGE" diff --git a/Example/tvOSSample/tvOSSample/AppDelegate.swift b/Example/tvOSSample/tvOSSample/AppDelegate.swift index 9a0d05278b7..723a3c4122f 100644 --- a/Example/tvOSSample/tvOSSample/AppDelegate.swift +++ b/Example/tvOSSample/tvOSSample/AppDelegate.swift @@ -17,7 +17,6 @@ import FirebaseCore @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { - var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { @@ -26,4 +25,3 @@ class AppDelegate: UIResponder, UIApplicationDelegate { return true } } - diff --git a/Example/tvOSSample/tvOSSample/AuthLoginViewController.swift b/Example/tvOSSample/tvOSSample/AuthLoginViewController.swift index dcf72d4eb24..65e0316e048 100644 --- a/Example/tvOSSample/tvOSSample/AuthLoginViewController.swift +++ b/Example/tvOSSample/tvOSSample/AuthLoginViewController.swift @@ -16,25 +16,14 @@ import UIKit import FirebaseAuth class AuthLoginViewController: UIViewController { + override func viewDidLoad() { + super.viewDidLoad() - override func viewDidLoad() { - super.viewDidLoad() + // Do any additional setup after loading the view. + } - // Do any additional setup after loading the view. - } - - override func didReceiveMemoryWarning() { - super.didReceiveMemoryWarning() - // Dispose of any resources that can be recreated. - } - - /* - // MARK: - Navigation - - // In a storyboard-based application, you will often want to do a little preparation before navigation - override func prepare(for segue: UIStoryboardSegue, sender: Any?) { - // Get the new view controller using segue.destinationViewController. - // Pass the selected object to the new view controller. - } - */ + override func didReceiveMemoryWarning() { + super.didReceiveMemoryWarning() + // Dispose of any resources that can be recreated. + } } diff --git a/Example/tvOSSample/tvOSSample/AuthViewController.swift b/Example/tvOSSample/tvOSSample/AuthViewController.swift index 72351d31540..56276ed353b 100644 --- a/Example/tvOSSample/tvOSSample/AuthViewController.swift +++ b/Example/tvOSSample/tvOSSample/AuthViewController.swift @@ -20,13 +20,13 @@ class AuthViewController: UIViewController { // MARK: - User Interface /// A stackview containing all of the buttons to providers (Email, OAuth, etc). - @IBOutlet weak var providers: UIStackView! + @IBOutlet var providers: UIStackView! /// A stackview containing a signed in label and sign out button. - @IBOutlet weak var signedIn: UIStackView! + @IBOutlet var signedIn: UIStackView! /// A label to display the status for the signed in user. - @IBOutlet weak var signInStatus: UILabel! + @IBOutlet var signInStatus: UILabel! // MARK: - User Actions diff --git a/Example/tvOSSample/tvOSSample/DatabaseViewController.swift b/Example/tvOSSample/tvOSSample/DatabaseViewController.swift index 712c48f3954..2b710fa1645 100644 --- a/Example/tvOSSample/tvOSSample/DatabaseViewController.swift +++ b/Example/tvOSSample/tvOSSample/DatabaseViewController.swift @@ -30,7 +30,7 @@ class DatabaseViewController: UIViewController { // MARK: - Interface /// Label to display the current value. - @IBOutlet weak var currentValue: UILabel! + @IBOutlet var currentValue: UILabel! // MARK: - User Actions @@ -65,7 +65,7 @@ class DatabaseViewController: UIViewController { // Observe the current value, and update the UI every time it changes. let ref = Database.database().reference(withPath: Constants.databasePath) - ref.observe(.value) { [weak self] (snapshot) in + ref.observe(.value) { [weak self] snapshot in guard let value = snapshot.value as? Int else { print("Error grabbing value from Snapshot!") return diff --git a/Example/tvOSSample/tvOSSample/EmailLoginViewController.swift b/Example/tvOSSample/tvOSSample/EmailLoginViewController.swift index 60dfc43bfb1..9bea765c686 100644 --- a/Example/tvOSSample/tvOSSample/EmailLoginViewController.swift +++ b/Example/tvOSSample/tvOSSample/EmailLoginViewController.swift @@ -19,6 +19,7 @@ protocol EmailLoginDelegate { func emailLogin(_ controller: EmailLoginViewController, signedInAs user: User) func emailLogin(_ controller: EmailLoginViewController, failedWithError error: Error) } + class EmailLoginViewController: UIViewController { // MARK: - Public Properties @@ -27,15 +28,15 @@ class EmailLoginViewController: UIViewController { // MARK: - User Interface - @IBOutlet private weak var emailAddress: UITextField! - @IBOutlet private weak var password: UITextField! + @IBOutlet private var emailAddress: UITextField! + @IBOutlet private var password: UITextField! // MARK: - User Actions @IBAction func logInButtonHit(_ sender: UIButton) { guard let (email, password) = validatedInputs() else { return } - Auth.auth().signIn(withEmail: email, password: password) { [unowned self] (user, error) in + Auth.auth().signIn(withEmail: email, password: password) { [unowned self] user, error in guard let user = user else { print("Error signing in: \(error!)") self.delegate?.emailLogin(self, failedWithError: error!) @@ -50,7 +51,7 @@ class EmailLoginViewController: UIViewController { @IBAction func signUpButtonHit(_ sender: UIButton) { guard let (email, password) = validatedInputs() else { return } - Auth.auth().createUser(withEmail: email, password: password) { [unowned self] (user, error) in + Auth.auth().createUser(withEmail: email, password: password) { [unowned self] user, error in guard let user = user else { print("Error signing up: \(error!)") self.delegate?.emailLogin(self, failedWithError: error!) diff --git a/Example/tvOSSample/tvOSSample/StorageViewController.swift b/Example/tvOSSample/tvOSSample/StorageViewController.swift index 4416649c94c..2e91d92ae01 100644 --- a/Example/tvOSSample/tvOSSample/StorageViewController.swift +++ b/Example/tvOSSample/tvOSSample/StorageViewController.swift @@ -31,7 +31,7 @@ class StorageViewController: UIViewController { case failed(String) /// Equatable support for UIState. - static func ==(lhs: StorageViewController.UIState, rhs: StorageViewController.UIState) -> Bool { + static func == (lhs: StorageViewController.UIState, rhs: StorageViewController.UIState) -> Bool { switch (lhs, rhs) { case (.cleared, .cleared): return true case (.downloading, .downloading): return true @@ -52,16 +52,16 @@ class StorageViewController: UIViewController { // MARK: Interface /// Image view to display the downloaded image. - @IBOutlet weak var imageView: UIImageView! + @IBOutlet var imageView: UIImageView! /// The download button. - @IBOutlet weak var downloadButton: UIButton! + @IBOutlet var downloadButton: UIButton! /// The clear button. - @IBOutlet weak var clearButton: UIButton! + @IBOutlet var clearButton: UIButton! /// A visual representation of the state. - @IBOutlet weak var stateLabel: UILabel! + @IBOutlet var stateLabel: UILabel! // MARK: - User Actions @@ -72,7 +72,7 @@ class StorageViewController: UIViewController { let storage = Storage.storage() let ref = storage.reference(withPath: Constants.downloadPath) // TODO: Show progress bar here using proper API. - let task = ref.getData(maxSize: Constants.maxSize) { [unowned self] (data, error) in + let task = ref.getData(maxSize: Constants.maxSize) { [unowned self] data, error in guard let data = data else { self.state = .failed("Error downloading: \(error!.localizedDescription)") return @@ -114,7 +114,7 @@ class StorageViewController: UIViewController { stateLabel.text = "State: Downloading..." // Download complete, ensure the download button is still off and enable the clear button. - case (_, .downloaded(let image)): + case let (_, .downloaded(image)): imageView.image = image stateLabel.text = "State: Image downloaded!" @@ -124,7 +124,7 @@ class StorageViewController: UIViewController { stateLabel.text = "State: Pending download" // An error occurred. - case (_, .failed(let error)): + case let (_, .failed(error)): stateLabel.text = "State: \(error)" // For now, as the default, throw a fatal error because it's an unexpected state. This will diff --git a/Firestore/Example/SwiftBuildTest/main.swift b/Firestore/Example/SwiftBuildTest/main.swift index 260735b1ee1..cd2462b24c2 100644 --- a/Firestore/Example/SwiftBuildTest/main.swift +++ b/Firestore/Example/SwiftBuildTest/main.swift @@ -19,223 +19,215 @@ import Foundation import FirebaseFirestore func main() { - let db = initializeDb(); + let db = initializeDb() - let (collectionRef, documentRef) = makeRefs(database: db); + let (collectionRef, documentRef) = makeRefs(database: db) - let query = makeQuery(collection: collectionRef); + let query = makeQuery(collection: collectionRef) - writeDocument(at: documentRef); + writeDocument(at: documentRef) - writeDocuments(at: documentRef, database: db); + writeDocuments(at: documentRef, database: db) - addDocument(to: collectionRef); + addDocument(to: collectionRef) - readDocument(at: documentRef); + readDocument(at: documentRef) - readDocuments(matching: query); + readDocuments(matching: query) - listenToDocument(at: documentRef); + listenToDocument(at: documentRef) - listenToDocuments(matching: query); + listenToDocuments(matching: query) - enableDisableNetwork(database: db); + enableDisableNetwork(database: db) - types(); + types() } func initializeDb() -> Firestore { + // Initialize with ProjectID. + let firestore = Firestore.firestore() - // Initialize with ProjectID. - let firestore = Firestore.firestore() + // Apply settings + let settings = FirestoreSettings() + settings.host = "localhost" + settings.isPersistenceEnabled = true + firestore.settings = settings - // Apply settings - let settings = FirestoreSettings() - settings.host = "localhost" - settings.isPersistenceEnabled = true - firestore.settings = settings - - return firestore; + return firestore } func makeRefs(database db: Firestore) -> (CollectionReference, DocumentReference) { + var collectionRef = db.collection("my-collection") - var collectionRef = db.collection("my-collection") - - var documentRef: DocumentReference; - documentRef = collectionRef.document("my-doc") - // or - documentRef = db.document("my-collection/my-doc") + var documentRef: DocumentReference + documentRef = collectionRef.document("my-doc") + // or + documentRef = db.document("my-collection/my-doc") - // deeper collection (my-collection/my-doc/some/deep/collection) - collectionRef = documentRef.collection("some/deep/collection") + // deeper collection (my-collection/my-doc/some/deep/collection) + collectionRef = documentRef.collection("some/deep/collection") - // parent doc (my-collection/my-doc/some/deep) - documentRef = collectionRef.parent! + // parent doc (my-collection/my-doc/some/deep) + documentRef = collectionRef.parent! - // print paths. - print("Collection: \(collectionRef.path), document: \(documentRef.path)") + // print paths. + print("Collection: \(collectionRef.path), document: \(documentRef.path)") - return (collectionRef, documentRef); + return (collectionRef, documentRef) } func makeQuery(collection collectionRef: CollectionReference) -> Query { - - let query = collectionRef.whereField(FieldPath(["name"]), isEqualTo: "Fred") - .whereField("age", isGreaterThanOrEqualTo: 24) - .whereField(FieldPath.documentID(), isEqualTo: "fred") - .order(by: FieldPath(["age"])) - .order(by: "name", descending: true) - .limit(to: 10) - - return query; + let query = collectionRef.whereField(FieldPath(["name"]), isEqualTo: "Fred") + .whereField("age", isGreaterThanOrEqualTo: 24) + .whereField(FieldPath.documentID(), isEqualTo: "fred") + .order(by: FieldPath(["age"])) + .order(by: "name", descending: true) + .limit(to: 10) + + return query } func writeDocument(at docRef: DocumentReference) { - - let setData = [ - "foo": 42, - "bar": [ - "baz": "Hello world!" - ] - ] as [String : Any]; - - let updateData = [ - "bar.baz": 42, - FieldPath(["foobar"]) : 42 - ] as [AnyHashable : Any]; - - docRef.setData(setData) - - // Completion callback (via trailing closure syntax). - docRef.setData(setData) { error in - if let error = error { - print("Uh oh! \(error)") - return - } - - print("Set complete!") + let setData = [ + "foo": 42, + "bar": [ + "baz": "Hello world!", + ], + ] as [String: Any] + + let updateData = [ + "bar.baz": 42, + FieldPath(["foobar"]): 42, + ] as [AnyHashable: Any] + + docRef.setData(setData) + + // Completion callback (via trailing closure syntax). + docRef.setData(setData) { error in + if let error = error { + print("Uh oh! \(error)") + return } - // SetOptions - docRef.setData(setData, options:SetOptions.merge()) + print("Set complete!") + } - docRef.updateData(updateData) - docRef.delete(); + // SetOptions + docRef.setData(setData, options: SetOptions.merge()) - docRef.delete() { error in - if let error = error { - print("Uh oh! \(error)") - return - } + docRef.updateData(updateData) + docRef.delete() - print("Set complete!") + docRef.delete { error in + if let error = error { + print("Uh oh! \(error)") + return } + + print("Set complete!") + } } func enableDisableNetwork(database db: Firestore) { - // closure syntax - db.disableNetwork(completion: { (error) in - if let e = error { - print("Uh oh! \(e)") - return - } - }) - // trailing block syntax - db.enableNetwork { (error) in - if let e = error { - print("Uh oh! \(e)") - return - } + // closure syntax + db.disableNetwork(completion: { error in + if let e = error { + print("Uh oh! \(e)") + return } + }) + // trailing block syntax + db.enableNetwork { error in + if let e = error { + print("Uh oh! \(e)") + return + } + } } func writeDocuments(at docRef: DocumentReference, database db: Firestore) { - var batch: WriteBatch; + var batch: WriteBatch - batch = db.batch(); - batch.setData(["a" : "b"], forDocument:docRef); - batch.setData(["c" : "d"], forDocument:docRef); + batch = db.batch() + batch.setData(["a": "b"], forDocument: docRef) + batch.setData(["c": "d"], forDocument: docRef) // commit without completion callback. - batch.commit(); - print("Batch write without completion complete!"); + batch.commit() + print("Batch write without completion complete!") - batch = db.batch(); - batch.setData(["a" : "b"], forDocument:docRef); - batch.setData(["c" : "d"], forDocument:docRef); + batch = db.batch() + batch.setData(["a": "b"], forDocument: docRef) + batch.setData(["c": "d"], forDocument: docRef) // commit with completion callback via trailing closure syntax. - batch.commit() { error in + batch.commit { error in if let error = error { - print("Uh oh! \(error)"); - return; + print("Uh oh! \(error)") + return } - print("Batch write callback complete!"); + print("Batch write callback complete!") } - print("Batch write with completion complete!"); + print("Batch write with completion complete!") } func addDocument(to collectionRef: CollectionReference) { - - collectionRef.addDocument(data: ["foo": 42]); - //or - collectionRef.document().setData(["foo": 42]); + collectionRef.addDocument(data: ["foo": 42]) + // or + collectionRef.document().setData(["foo": 42]) } func readDocument(at docRef: DocumentReference) { - - // Trailing closure syntax. - docRef.getDocument() { document, error in - if let document = document { - // Note that both document and document.data() is nullable. - if let data = document.data() { - print("Read document: \(data)") - } - if let data = document.data(with:SnapshotOptions.serverTimestampBehavior(.estimate)) { - print("Read document: \(data)") - } - if let foo = document.get("foo") { - print("Field: \(foo)") - } - if let foo = document.get("foo", options: SnapshotOptions.serverTimestampBehavior(.previous)) { - print("Field: \(foo)") - } - // Fields can also be read via subscript notation. - if let foo = document["foo"] { - print("Field: \(foo)") - } - } else { - // TODO(mikelehen): There may be a better way to do this, but it at least demonstrates - // the swift error domain / enum codes are renamed appropriately. - if let errorCode = error.flatMap({ - ($0._domain == FirestoreErrorDomain) ? FirestoreErrorCode (rawValue: $0._code) : nil - }) { - switch errorCode { - case .unavailable: - print("Can't read document due to being offline!") - case _: - print("Failed to read.") - } - } else { - print("Unknown error!") - } + // Trailing closure syntax. + docRef.getDocument { document, error in + if let document = document { + // Note that both document and document.data() is nullable. + if let data = document.data() { + print("Read document: \(data)") + } + if let data = document.data(with: SnapshotOptions.serverTimestampBehavior(.estimate)) { + print("Read document: \(data)") + } + if let foo = document.get("foo") { + print("Field: \(foo)") + } + if let foo = document.get("foo", options: SnapshotOptions.serverTimestampBehavior(.previous)) { + print("Field: \(foo)") + } + // Fields can also be read via subscript notation. + if let foo = document["foo"] { + print("Field: \(foo)") + } + } else { + // TODO(mikelehen): There may be a better way to do this, but it at least demonstrates + // the swift error domain / enum codes are renamed appropriately. + if let errorCode = error.flatMap({ + ($0._domain == FirestoreErrorDomain) ? FirestoreErrorCode(rawValue: $0._code) : nil + }) { + switch errorCode { + case .unavailable: + print("Can't read document due to being offline!") + case _: + print("Failed to read.") } - + } else { + print("Unknown error!") + } } + } } func readDocuments(matching query: Query) { - query.getDocuments() { querySnapshot, error in - // TODO(mikelehen): Figure out how to make "for..in" syntax work - // directly on documentSet. - for document in querySnapshot!.documents { - print(document.data()) - } + query.getDocuments { querySnapshot, error in + // TODO(mikelehen): Figure out how to make "for..in" syntax work + // directly on documentSet. + for document in querySnapshot!.documents { + print(document.data()) } + } } func listenToDocument(at docRef: DocumentReference) { - - let listener = docRef.addSnapshotListener() { document, error in + let listener = docRef.addSnapshotListener { document, error in if let error = error { print("Uh oh! Listen canceled: \(error)") return @@ -243,8 +235,8 @@ func listenToDocument(at docRef: DocumentReference) { if let document = document { // Note that document.data() is nullable. - if let data : [String:Any] = document.data() { - print("Current document: \(data)"); + if let data: [String: Any] = document.data() { + print("Current document: \(data)") } if document.metadata.isFromCache { print("From Cache") @@ -255,100 +247,98 @@ func listenToDocument(at docRef: DocumentReference) { } // Unsubscribe. - listener.remove(); + listener.remove() } func listenToDocuments(matching query: Query) { + let listener = query.addSnapshotListener { snap, error in + if let error = error { + print("Uh oh! Listen canceled: \(error)") + return + } - let listener = query.addSnapshotListener() { snap, error in - if let error = error { - print("Uh oh! Listen canceled: \(error)") - return - } - - if let snap = snap { - print("NEW SNAPSHOT (empty=\(snap.isEmpty) count=\(snap.count)") + if let snap = snap { + print("NEW SNAPSHOT (empty=\(snap.isEmpty) count=\(snap.count)") - // TODO(mikelehen): Figure out how to make "for..in" syntax work - // directly on documentSet. - for document in snap.documents { - // Note that document.data() is not nullable. - let data : [String:Any] = document.data() - print("Doc: ", data) - } - } + // TODO(mikelehen): Figure out how to make "for..in" syntax work + // directly on documentSet. + for document in snap.documents { + // Note that document.data() is not nullable. + let data: [String: Any] = document.data() + print("Doc: ", data) + } } + } - // Unsubscribe - listener.remove(); + // Unsubscribe + listener.remove() } func listenToQueryDiffs(onQuery query: Query) { - - let listener = query.addSnapshotListener() { snap, error in - if let snap = snap { - for change in snap.documentChanges { - switch (change.type) { - case .added: - print("New document: \(change.document.data())") - case .modified: - print("Modified document: \(change.document.data())") - case .removed: - print("Removed document: \(change.document.data())") - } - } + let listener = query.addSnapshotListener { snap, error in + if let snap = snap { + for change in snap.documentChanges { + switch change.type { + case .added: + print("New document: \(change.document.data())") + case .modified: + print("Modified document: \(change.document.data())") + case .removed: + print("Removed document: \(change.document.data())") } + } } + } - // Unsubscribe - listener.remove(); + // Unsubscribe + listener.remove() } func transactions() { - let db = Firestore.firestore() - - let collectionRef = db.collection("cities") - let accA = collectionRef.document("accountA") - let accB = collectionRef.document("accountB") - let amount = 20.0 - - db.runTransaction({ (transaction, errorPointer) -> Any? in - do { - let balanceA = try transaction.getDocument(accA)["balance"] as! Double - let balanceB = try transaction.getDocument(accB)["balance"] as! Double - - if balanceA < amount { - errorPointer?.pointee = NSError(domain: "Foo", code: 123, userInfo: nil) - return nil - } - transaction.updateData(["balance": balanceA - amount], forDocument:accA) - transaction.updateData(["balance": balanceB + amount], forDocument:accB) - } catch let error as NSError { - print("Uh oh! \(error)") - } - return 0 - }) { (result, error) in - // handle result. + let db = Firestore.firestore() + + let collectionRef = db.collection("cities") + let accA = collectionRef.document("accountA") + let accB = collectionRef.document("accountB") + let amount = 20.0 + + db.runTransaction({ (transaction, errorPointer) -> Any? in + do { + let balanceA = try transaction.getDocument(accA)["balance"] as! Double + let balanceB = try transaction.getDocument(accB)["balance"] as! Double + + if balanceA < amount { + errorPointer?.pointee = NSError(domain: "Foo", code: 123, userInfo: nil) + return nil + } + transaction.updateData(["balance": balanceA - amount], forDocument: accA) + transaction.updateData(["balance": balanceB + amount], forDocument: accB) + } catch let error as NSError { + print("Uh oh! \(error)") } + return 0 + }) { result, error in + // handle result. + } } func types() { - let _: CollectionReference; - let _: DocumentChange; - let _: DocumentListenOptions; - let _: DocumentReference; - let _: DocumentSnapshot; - let _: FieldPath; - let _: FieldValue; - let _: Firestore; - let _: FirestoreSettings; - let _: GeoPoint; - let _: ListenerRegistration; - let _: QueryListenOptions; - let _: Query; - let _: QuerySnapshot; - let _: SetOptions; - let _: SnapshotMetadata; - let _: Transaction; - let _: WriteBatch; + let _: CollectionReference + let _: DocumentChange + let _: DocumentListenOptions + let _: DocumentReference + let _: DocumentSnapshot + let _: FieldPath + let _: FieldValue + let _: Firestore + let _: FirestoreSettings + let _: GeoPoint + let _: ListenerRegistration + let _: QueryListenOptions + let _: Query + let _: QuerySnapshot + let _: SetOptions + let _: SnapshotMetadata + let _: Transaction + let _: WriteBatch } diff --git a/scripts/style.sh b/scripts/style.sh index b4c495dd779..e2f82075d52 100755 --- a/scripts/style.sh +++ b/scripts/style.sh @@ -21,19 +21,61 @@ # Commonly # ./scripts/style.sh master -if [[ $(clang-format --version) != **"version 6"** ]]; then +system=$(uname -s) + +if [[ $(clang-format --version) != *"version 6"* ]]; then echo "Please upgrade to clang-format version 6." echo "If it's installed via homebrew you can run: brew upgrade clang-format" exit 1 fi -if [[ $# -gt 0 && "$1" = "test-only" ]]; then +if [[ "$system" == "Darwin" ]]; then + version=$(swiftformat --version) + version="${version/*version /}" + # Allow an older swiftformat because travis isn't running High Sierra yet + # and the formula hasn't been updated in a while on Sierra :-/. + if [[ "$version" != "0.32.0" && "$version" != "0.33"* ]]; then + echo "Please upgrade to swiftformat 0.33.3" + echo "If it's installed via homebrew you can run: brew upgrade swiftformat" + exit 1 + fi +fi + +# Joins the given arguments with the separator given as the first argument. +function join() { + local IFS="$1" + shift + echo "$*" +} + +clang_options=(-style=file) + +# Rules to disable in swiftformat: +swift_disable=( + # sortedImports is broken, sorting into the middle of the copyright notice. + sortedImports + + # Too many of our swift files have simplistic examples. While technically + # it's correct to remove the unused argument labels, it makes our examples + # look wrong. + unusedArguments +) + +swift_options=( + # Mimic Objective-C style. + --indent 2 + + --disable $(join , "${swift_disable[@]}") +) + +if [[ $# -gt 0 && "$1" == "test-only" ]]; then test_only=true - options="-output-replacements-xml" + clang_options+=(-output-replacements-xml) + swift_options+=(--dryrun) shift else test_only=false - options="-i" + clang_options+=(-i) fi files=$( @@ -54,6 +96,8 @@ files=$( # Build outputs \%/Pods/% d \%^./build/% d +\%^./Debug/% d +\%^./Release/% d # Sources controlled outside this tree \%/third_party/% d @@ -73,19 +117,29 @@ files=$( \%\.pb\.% d # Format C-ish sources only -\%\.(h|m|mm|cc)$% p +\%\.(h|m|mm|cc|swift)$% p ' ) + needs_formatting=false for f in $files; do - clang-format -style=file $options $f | grep " /dev/null - if [[ "$test_only" = true && $? -ne 1 ]]; then + if [[ "${f: -6}" == '.swift' ]]; then + if [[ "$system" == 'Darwin' ]]; then + swiftformat "${swift_options[@]}" "$f" 2> /dev/null | grep 'would have updated' > /dev/null + else + false + fi + else + clang-format "${clang_options[@]}" "$f" | grep " /dev/null + fi + + if [[ "$test_only" == true && $? -ne 1 ]]; then echo "$f needs formatting." needs_formatting=true fi done -if [[ "$needs_formatting" = true ]]; then +if [[ "$needs_formatting" == true ]]; then echo "Proposed commit is not style compliant." echo "Run scripts/style.sh and git add the result." exit 1