hexsha
stringlengths 40
40
| size
int64 3
1.03M
| content
stringlengths 3
1.03M
| avg_line_length
float64 1.33
100
| max_line_length
int64 2
1k
| alphanum_fraction
float64 0.25
0.99
|
---|---|---|---|---|---|
2fd0f3906db69aab26a29f53d1d0abbfa7632c7d | 360 | //
// Empty.swift
// BaseUI
//
// Copyright © 2020 E-SOFT, OOO. All rights reserved.
//
import XCTest
final class BaseUITests: XCTestCase {
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
XCTAssert(1 == 1)
}
}
| 18.947368 | 96 | 0.641667 |
6180196fe1b51149c2484cbc7b4a45e9e9d68e55 | 2,778 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift -lswiftSwiftReflectionTest %s -o %t/reflect_Character
// RUN: %target-codesign %t/reflect_Character
// RUN: %target-run %target-swift-reflection-test %t/reflect_Character | %FileCheck %s --check-prefix=CHECK-%target-ptrsize %add_num_extra_inhabitants
// REQUIRES: reflection_test_support
// REQUIRES: executable_test
// UNSUPPORTED: use_os_stdlib
import SwiftReflectionTest
class TestClass {
var t: Character
init(t: Character) {
self.t = t
}
}
var obj = TestClass(t: "A")
reflect(object: obj)
// CHECK-64: Reflecting an object.
// CHECK-64: Type reference:
// CHECK-64: (class reflect_Character.TestClass)
// CHECK-64-LABEL: Type info:
// CHECK-64: (class_instance size=32 alignment=8 stride=32 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64-NEXT: (field name=t offset=16
// CHECK-64-NEXT: (struct size=16 alignment=8 stride=16 num_extra_inhabitants=[[#num_extra_inhabitants_64bit]] bitwise_takable=1
// CHECK-64-NEXT: (field name=_str offset=0
// CHECK-64-NEXT: (struct size=16 alignment=8 stride=16 num_extra_inhabitants=[[#num_extra_inhabitants_64bit]] bitwise_takable=1
// CHECK-64-NEXT: (field name=_guts offset=0
// CHECK-64-NEXT: (struct size=16 alignment=8 stride=16 num_extra_inhabitants=[[#num_extra_inhabitants_64bit]] bitwise_takable=1
// CHECK-64-NEXT: (field name=_object offset=0
// CHECK-64-NEXT: (struct size=16 alignment=8 stride=16 num_extra_inhabitants=[[#num_extra_inhabitants_64bit]] bitwise_takable=1
// CHECK-64-NEXT: (field name=_countAndFlagsBits offset=0
// CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1))))
// CHECK-64-NEXT: (field name=_object offset=8
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=[[#num_extra_inhabitants_64bit]] bitwise_takable=1)))))))))))
// CHECK-32: Reflecting an object.
// CHECK-32: Type reference:
// CHECK-32: (class reflect_Character.TestClass)
// CHECK-32: Type info:
// CHECK-32-NEXT: (class_instance size=20 alignment=4 stride=20 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32-NEXT: (field name=t offset=8
// CHECK-32-NEXT: (struct size=12 alignment=4 stride=12 num_extra_inhabitants=253 bitwise_takable=1
// CHECK-32-NEXT: (field name=_str offset=0
// CHECK-32-NEXT: (struct size=12 alignment=4 stride=12 num_extra_inhabitants=253 bitwise_takable=1
doneReflecting()
// CHECK-64: Done.
// CHECK-32: Done.
| 45.540984 | 156 | 0.706983 |
915713b5c2f273688ddf5f2fdafc86048717b7b7 | 1,025 | // swift-tools-version:4.0
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "{PROJECT}",
products: [
// Products define the executables and libraries produced by a package, and make them visible to other packages.
.library(
name: "{PROJECT}",
targets: ["{PROJECT}"]),
],
dependencies: [
// Dependencies declare other packages that this package depends on.
// .package(url: /* package url */, from: "1.0.0"),
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages which this package depends on.
.target(
name: "{PROJECT}",
dependencies: []),
.testTarget(
name: "{PROJECT}Tests",
dependencies: ["{PROJECT}"]),
]
)
| 35.344828 | 122 | 0.60878 |
69af03da82635488df9ea55546e391debed63a0a | 5,886 | //
// Calculate.swift
// News
//
// Created by 杨蒙 on 2017/12/10.
// Copyright © 2017年 hrscy. All rights reserved.
//
import UIKit
protocol Calculatable {
// MARK: 计算宽度
static func collectionViewWidth(_ count: Int) -> CGFloat
// MARK: 计算高度
static func collectionViewHeight(_ count: Int) -> CGFloat
// MARK: 计算 collectionViewCell 的大小
static func collectionViewCellSize(_ count: Int) -> CGSize
// MARK: 计算富文本的高度
static func attributedTextHeight(text: NSAttributedString, width: CGFloat) -> CGFloat
// MARK: 计算文本的高度
static func textHeight(text: String, fontSize: CGFloat, width: CGFloat) -> CGFloat
// MARK: 计算文本的宽度
static func textHieght(text: String, fontSize: CGFloat, height: CGFloat) -> CGFloat
// MARK: 从文本内容中获取 uid 和 用户名
static func richContents(from content: String, idPattern: String, titlePattern: String) -> [RichContent]
// MARK: 计算详情里的 collectionViewCell 的大小
static func detailCollectionViewCellSize(_ thumbImageList: [ThumbImageList]) -> CGSize
// MARK: 计算详情里的高度
static func detailCollectionViewHieght(_ thumbImageList: [ThumbImageList]) -> CGFloat
}
extension Calculatable {
/// 计算高度
static func detailCollectionViewHieght(_ thumbImageList: [ThumbImageList]) -> CGFloat {
switch thumbImageList.count {
case 1:
let thumbImage = thumbImageList.first!
return (screenWidth - 30) * thumbImage.height / thumbImage.width
case 2:
return (screenWidth - 35) * 0.5
case 3:
return image3Width + 5
case 4:
return (screenWidth - 3)
case 5, 6:
return (image3Width + 5) * 2
case 7...9:
return (image3Width + 5) * 3
default:
return 0
}
}
/// 计算情里的 collectionViewCell 的大小
static func detailCollectionViewCellSize(_ thumbImageList: [ThumbImageList]) -> CGSize {
switch thumbImageList.count {
case 1:
let thumbImage = thumbImageList.first!
let height = (screenWidth - 30) * thumbImage.height / thumbImage.width
return CGSize(width: (screenWidth - 30), height: height)
case 2, 4:
let image2W = (screenWidth - 35) * 0.5
return CGSize(width: image2W, height: image2W)
case 3, 5...9:
return CGSize(width: image3Width, height: image3Width)
default:
return .zero
}
}
/// 从文本内容中获取 uid 和 用户名
static func richContents(from content: String, idPattern: String, titlePattern: String) -> [RichContent] {
// 富文本内容
var richContents = [RichContent]()
// 临时数组
var temps = [RichContent]()
// 创建正则表达式对象,匹配 id
let uidRegex = try! NSRegularExpression(pattern: idPattern, options: [])
// 开始匹配,返回结果
let uidResults = uidRegex.matches(in: content, options: [], range: NSRange(location: 0, length: content.count))
if uidResults.count != 0{
// 取出用户名,放到临时数组
temps = uidResults.map({
let uid = (content as NSString).substring(with: $0.range)
return RichContent(uid, "")
})
}
// 创建正则表达式对象
let userRegex = try! NSRegularExpression(pattern: titlePattern, options: [])
// 开始匹配,返回结果
let userResults = userRegex.matches(in: content, options: [], range: NSRange(location: 0, length: content.count))
if userResults.count != 0 {
for (index, result) in userResults.enumerated() {
// 取出临时数组中的模型
var richContent = temps[index]
// 取出用户名
richContent.name = (content as NSString).substring(with: result.range)
richContents.append(richContent)
}
}
return richContents
}
/// 计算宽度
static func collectionViewWidth(_ count: Int) -> CGFloat {
switch count {
case 1, 2:
return (image2Width + 5) * 2
case 3, 5...9:
return screenWidth - 30
case 4:
return (image3Width + 5) * 2
default:
return 0
}
}
/// 计算高度
static func collectionViewHeight(_ count: Int) -> CGFloat {
switch count {
case 1, 2:
return image2Width
case 3:
return image3Width + 5
case 4...6:
return (image3Width + 5) * 2
case 7...9:
return (image3Width + 5) * 3
default:
return 0
}
}
/// 计算 collectionViewCell 的大小
static func collectionViewCellSize(_ count: Int) -> CGSize {
switch count {
case 1, 2:
return CGSize(width: image2Width, height: image2Width)
case 3...9:
return CGSize(width: image3Width, height: image3Width)
default:
return .zero
}
}
/// 计算富文本的高度
static func attributedTextHeight(text: NSAttributedString, width: CGFloat) -> CGFloat {
return text.boundingRect(with: CGSize(width: width, height: CGFloat(MAXFLOAT)), options: .usesLineFragmentOrigin, context: nil).size.height + 5.0
}
/// 计算文本的高度
static func textHeight(text: String, fontSize: CGFloat, width: CGFloat) -> CGFloat {
return text.boundingRect(with: CGSize(width: width, height: CGFloat(MAXFLOAT)), options: .usesLineFragmentOrigin, attributes: [.font: UIFont.systemFont(ofSize: fontSize)], context: nil).size.height + 5
}
/// 计算文本的宽度
static func textHieght(text: String, fontSize: CGFloat, height: CGFloat) -> CGFloat {
return text.boundingRect(with: CGSize(width: CGFloat(MAXFLOAT), height: height), options: .usesLineFragmentOrigin, attributes: [.font: UIFont.systemFont(ofSize: fontSize)], context: nil).size.height
}
}
struct Calculate: Calculatable {}
| 35.672727 | 209 | 0.599218 |
14883300cd75c720e1c0010c0531f92fefd03acb | 4,418 | //
// DataManager.swift
// insulin_calculator
//
// Created by 李灿晨 on 10/11/19.
// Copyright © 2019 李灿晨. All rights reserved.
//
import UIKit
import CoreData
class DataManager: NSObject {
/**
The shared instance of object `DataManager`.
*/
static var shared: DataManager = DataManager()
// MARK: - `SessionRecord` manipulation.
/**
Insert a session record into the persistant container.
- parameters:
- record: The `SessionRecord` object to be inserted into the persistant container.
*/
func createSessionRecord(record: SessionRecord) {
let entity = NSEntityDescription.entity(forEntityName: "ManagedSessionRecord", in: context)
let newRecord = ManagedSessionRecord(entity: entity!, insertInto: context)
newRecord.initialize(with: record)
saveContext()
}
/**
Update a session record in the persistant container. Do not update the URL related fields.
- parameters:
- record: The `SessionRecord` object to be updated.
*/
func updateSessionRecord(record: SessionRecord) {
removeSessionRecord(record: record, withFiles: false)
createSessionRecord(record: record)
}
/**
Remove a session record from the persistant container.
- parameters:
- record: The `SessionRecord` object to be removed from the persistant container.
- withFiles: Whether the files specified by URL fields of the `SessionRecord` object should
also be removed with the record.
*/
func removeSessionRecord(record: SessionRecord, withFiles: Bool) {
let fetchRequest: NSFetchRequest = ManagedSessionRecord.fetchRequest()
fetchRequest.predicate = NSPredicate(format: "sessionId == \"\(record.sessionId)\"")
let results = try! context.fetch(fetchRequest)
for record in results {
if withFiles {
removeFile(url: record.photoURL)
removeFile(url: record.captureJSONURL)
removeFile(url: record.recognitionJSONURL)
}
context.delete(record)
}
saveContext()
}
/**
Return all stored session records in an array.
*/
func getAllSessionRecords() -> [SessionRecord] {
let fetchRequest: NSFetchRequest = ManagedSessionRecord.fetchRequest()
let managedRecords = (try! context.fetch(fetchRequest)) as [ManagedSessionRecord]
return managedRecords.map({$0.export()})
}
// MARK: - File Manipulation.
/**
Save `data` as a temporary file in `documentDirectory` with extension name `extensionName`.
The file name would be a UUID string.
- parameters:
- data: The data to be saved. Callers are responsible for converting objects to `Data` with proper encoding.
- extensionName: The extension name of the saved file.
- completion: The completion handler. This closure will be called once the saving process finished, the parameter
is the URL of the saved temporary file.
*/
func saveFile(
data: Data,
extensionName: String,
completion: ((URL) -> ())?
) {
let url = FileManager.default.urls(
for: .documentDirectory,
in: .userDomainMask
)[0].appendingPathComponent(UUID().uuidString).appendingPathExtension(extensionName)
try! data.write(to: url)
completion?(url)
}
/**
Remove the file with the given URL.
- parameters:
- url: The url of the file to be removed.
*/
func removeFile(url: URL?) {
guard url != nil else {return}
guard FileManager.default.fileExists(atPath: url!.path) else {return}
try! FileManager.default.removeItem(at: url!)
}
// MARK: - Utilties.
/**
A context representing a single object space that allows fetch, create, and remove managed objects.
*/
private var context: NSManagedObjectContext = {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
return context
}()
/**
Save CoreData context.
*/
private func saveContext() {
do {
try context.save()
} catch {
fatalError("Error occurred when saving a context.")
}
}
}
| 32.485294 | 121 | 0.628112 |
22306d2541c1481b44bff9870cbb0dc98f0f7168 | 1,141 | // swift-tools-version:5.1
// We're hiding dev, test, and danger dependencies with // dev to make sure they're not fetched by users of this package.
import PackageDescription
let package = Package(
name: "UINotifications",
platforms: [
.iOS(.v13)
],
products: [
// dev .library(name: "DangerDeps", type: .dynamic, targets: ["DangerDependencies"]), // dev
.library(name: "UINotifications", type: .static, targets: ["UINotifications"])
],
dependencies: [
// dev .package(url: "https://github.com/danger/swift", from: "3.0.0"),
// dev .package(path: "Submodules/WeTransfer-iOS-CI/Danger-Swift")
],
targets: [
// This is just an arbitrary Swift file in the app, that has
// no dependencies outside of Foundation, the dependencies section
// ensures that the library for Danger gets build also.
// dev .target(name: "DangerDependencies", dependencies: ["Danger", "WeTransferPRLinter"], path: "Submodules/WeTransfer-iOS-CI/Danger-Swift", sources: ["DangerFakeSource.swift"]),
.target(name: "UINotifications", path: "Sources")
]
)
| 43.884615 | 187 | 0.650307 |
ab7e5b4e8dc4311d717796b8ca6d9185d3012ac3 | 1,512 | //
// ContactEntity+CoreDataProperties.swift
// iOS_Example
//
// Created by Seyed Samad Gholamzadeh on 9/15/18.
// Copyright © 2018 Seyed Samad Gholamzadeh. All rights reserved.
//
//
import Foundation
import CoreData
import ModelAssistant
extension ContactEntity: MAEntity {
@nonobjc public class func fetchRequest() -> NSFetchRequest<ContactEntity> {
return NSFetchRequest<ContactEntity>(entityName: "ContactEntity")
}
@NSManaged public var displayOrder: Int64
@NSManaged public var firstName: String
@NSManaged public var id: Int32
@NSManaged public var imageURLString: String?
@NSManaged public var lastName: String
@NSManaged public var phone: String?
var imageURL: URL {
let string = imageURLString ?? "https://robohash.org/\(firstName)\(lastName)\(id).jpg?size=30x30&set=set1"
return URL(string: string)!
}
var fullName: String {
return firstName + " " + lastName
}
public var uniqueValue: Int {
return Int(self.phone ?? "0")!
}
@objc public var index: String? {
return String(Array(self.firstName)[0]).uppercased()
}
public subscript(key: String) -> String? {
if key == "firstName" {
return String(Array(self.firstName)[0]).uppercased()
}
if key == "lastName" {
return String(Array(self.firstName)[0]).uppercased()
}
return nil
}
public func update(with newFetechedEntity: ContactEntity) {
let entity = newFetechedEntity
self.firstName = entity.firstName
self.lastName = entity.lastName
}
}
| 23.625 | 108 | 0.70172 |
1e4394ba25f593496349495754d31f71b5de5f7c | 10,304 | //
// CFAlertActionSheetInteractiveTransition.swift
// CFAlertViewControllerDemo
//
// Created by Shivam Bhalla on 1/20/17.
// Copyright © 2017 Codigami Inc. All rights reserved.
//
import UIKit
class CFAlertActionSheetInteractiveTransition: CFAlertBaseInteractiveTransition {
// MARK: - Initialisation Methods
public override init(modalViewController: UIViewController,
swipeGestureView: UIView?,
contentScrollView: UIScrollView?)
{
super.init(modalViewController: modalViewController,
swipeGestureView: swipeGestureView,
contentScrollView: contentScrollView)
}
// MARK: - Override Methods
public override func classForGestureRecognizer() -> CFAlertBaseTransitionGestureRecognizer.Type {
return CFAlertActionSheetTransitionGestureRecognizer.self
}
public override func updateUIState(transitionContext: UIViewControllerContextTransitioning,
percentComplete: CGFloat,
transitionType: CFAlertTransitionType)
{
// Call Super Methods
super.updateUIState(transitionContext: transitionContext,
percentComplete: percentComplete,
transitionType: transitionType)
// Validation
var currentPercentage = percentComplete
if currentPercentage < 0.0 {
currentPercentage = 0.0
}
else if currentPercentage > 1.0 {
currentPercentage = 1.0
}
// Grab the from and to view controllers from the context
// let duration = transitionDuration(using: transitionContext)
// let containerView = transitionContext.containerView
let fromViewController = transitionContext.viewController(forKey: .from)
let toViewController = transitionContext.viewController(forKey: .to)
var viewController : UIViewController?
if transitionType == .present {
viewController = toViewController
}
else {
viewController = fromViewController
}
if let alertViewController = viewController as? CFAlertViewController, let alertContainerView = alertViewController.containerView {
// Get Safe Area Bottom Inset
var safeAreaTopInset : CGFloat = 0.0
var safeAreaBottomInset : CGFloat = 0.0
if #available(iOS 11.0, *) {
safeAreaTopInset = alertViewController.view.safeAreaInsets.top
safeAreaBottomInset = alertViewController.view.safeAreaInsets.bottom
}
// Slide Container View
let startY = alertViewController.view.frame.size.height - safeAreaTopInset - alertContainerView.frame.size.height - 10 - safeAreaBottomInset
let endY = alertViewController.view.frame.size.height - safeAreaBottomInset
let currentTopOffset = CFAlertBaseInteractiveTransition.valueBetween(start: startY,
andEnd: endY,
forProgress: (1.0-currentPercentage))
alertContainerView.frame = CGRect(x: alertContainerView.frame.origin.x,
y: currentTopOffset,
width: alertContainerView.frame.size.width,
height: alertContainerView.frame.size.height)
// Fade background View
if alertViewController.backgroundStyle == .blur {
alertViewController.backgroundBlurView?.alpha = currentPercentage
}
alertViewController.backgroundColorView?.alpha = currentPercentage
}
}
}
extension CFAlertActionSheetInteractiveTransition {
// MARK: Pan Gesture Handle Methods
@objc override public func handlePan(_ recognizer: UIPanGestureRecognizer) {
// Location reference
var location = recognizer.location(in: swipeGestureView?.window)
if let recognizerView = recognizer.view {
location = location.applying(recognizerView.transform.inverted())
}
// Velocity reference
var velocity = recognizer.velocity(in: swipeGestureView?.window)
if let recognizerView = recognizer.view {
velocity = velocity.applying(recognizerView.transform.inverted())
}
if recognizer.state == .began {
isInteracting = true
panStartLocation = location
modalViewController?.dismiss(animated: true, completion: nil)
}
else if recognizer.state == .changed {
if let alertViewController = modalViewController as? CFAlertViewController,
let alertContainerView = alertViewController.containerView,
let panStartLocation = panStartLocation
{
// Get Safe Area Bottom Inset
var safeAreaBottomInset : CGFloat = 0.0
if #available(iOS 11.0, *) {
safeAreaBottomInset = alertViewController.view.safeAreaInsets.bottom
}
let animationRatio = (location.y - panStartLocation.y) / (alertContainerView.bounds.height + 10 + safeAreaBottomInset)
update(animationRatio)
}
}
else if recognizer.state == .ended {
if velocity.y > 100.0 {
finish()
}
else {
cancel()
}
isInteracting = false
}
}
}
// MARK: - UIViewControllerAnimatedTransitioning
extension CFAlertActionSheetInteractiveTransition {
public override func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return transitionDuration
}
public override func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
// Get context vars
let duration: TimeInterval = transitionDuration(using: transitionContext)
let containerView: UIView? = transitionContext.containerView
let fromViewController: UIViewController? = transitionContext.viewController(forKey: .from)
let toViewController: UIViewController? = transitionContext.viewController(forKey: .to)
// Call Will System Methods
fromViewController?.beginAppearanceTransition(false, animated: true)
toViewController?.beginAppearanceTransition(true, animated: true)
if transitionType == .present {
/** SHOW ANIMATION **/
if let alertViewController = toViewController as? CFAlertViewController, let containerView = containerView {
alertViewController.view?.frame = containerView.frame
alertViewController.view?.autoresizingMask = [.flexibleWidth, .flexibleHeight]
alertViewController.view?.translatesAutoresizingMaskIntoConstraints = true
containerView.addSubview(alertViewController.view)
alertViewController.view?.layoutIfNeeded()
var frame: CGRect? = alertViewController.containerView?.frame
frame?.origin.y = containerView.frame.size.height
alertViewController.containerView?.frame = frame!
// Background
if alertViewController.backgroundStyle == .blur {
alertViewController.backgroundBlurView?.alpha = 0.0
}
alertViewController.backgroundColorView?.alpha = 0.0
// Animate height changes
UIView.animate(withDuration: duration, delay: 0.0, usingSpringWithDamping: 1.0, initialSpringVelocity: 0.0, options: [.curveEaseIn, .beginFromCurrentState], animations: {() -> Void in
self.updateUIState(transitionContext: transitionContext,
percentComplete: 1.0,
transitionType: .present)
}, completion: {(_ finished: Bool) -> Void in
// Call Did System Methods
toViewController?.endAppearanceTransition()
fromViewController?.endAppearanceTransition()
// Declare Animation Finished
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
})
}
else {
// Call Did System Methods
toViewController?.endAppearanceTransition()
fromViewController?.endAppearanceTransition()
// Declare Animation Finished
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
}
}
else if transitionType == .dismiss {
/** HIDE ANIMATION **/
// Animate height changes
UIView.animate(withDuration: duration, delay: 0.0, usingSpringWithDamping: 1.0, initialSpringVelocity: 0.0, options: [.curveEaseIn, .beginFromCurrentState], animations: {() -> Void in
self.updateUIState(transitionContext: transitionContext,
percentComplete: 0.0,
transitionType: .dismiss)
}, completion: {(_ finished: Bool) -> Void in
// Call Did System Methods
toViewController?.endAppearanceTransition()
fromViewController?.endAppearanceTransition()
// Declare Animation Finished
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
})
}
}
}
| 44.413793 | 199 | 0.586471 |
03929c4672e93fae63b89d4bb9df6ec837373bda | 505 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
lazy
}
func m<u>() -> (u, u -> u) -> u {
p o p.s = {
}
{
u) {
o }
}
s m {
}
class p: mass func s {}
s p {
| 22.954545 | 79 | 0.673267 |
26751a8c8513770aaa918f1216006cc527ad9a62 | 647 | //
// ElementInteraction.swift
// Skylark
//
// Created by Ross Butler on 3/3/19.
//
import Foundation
struct ElementInteraction: Codable {
typealias InteractionType = ElementInteractionType
let action: InteractionType
let element: Element.Identifier
init(action: InteractionType, element: Element.Identifier) {
self.action = action
self.element = element
}
}
extension ElementInteraction: Equatable {
public static func == (lhs: ElementInteraction, rhs: ElementInteraction) -> Bool {
return lhs.element == rhs.element && lhs.action.rawValue == rhs.action.rawValue
}
}
| 22.310345 | 87 | 0.680062 |
50d8a2fc3f2fd6cc1d59b8760cba00b0a3831722 | 403 | //: [< Sommaire](Sommaire)
/*:
# Gestion des erreurs
---
### Maxime Britto - Swift 4
*/
import Foundation
let url = URL(string: "http://www.addpple.fr")!
if let contenuHTML = try? String(contentsOf: url) {
print(contenuHTML)
}
do {
let contenuHTML = try String(contentsOf:url)
print(contenuHTML)
} catch let error as NSError {
print(error)
}
/*:
[< Sommaire](Sommaire)
*/
| 13.433333 | 51 | 0.630273 |
26e1f4b50b3c02d69109de63f7d4e7edc6e05b81 | 3,558 | /*
* Copyright IBM Corp. 2017
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import UIKit
import GPSDK
class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var resultLabel: UILabel!
@IBOutlet weak var mixOne: UIPickerView!
@IBOutlet weak var mixTwo: UIPickerView!
@IBOutlet weak var mixButton: UIButton!
let gp = GPService()
func get(key: String) -> String {
return gp.localizedString(key, nil)
}
func get(color: Color) -> String {
return get(key: color.simpleDescription())
}
override func viewDidLoad() {
super.viewDidLoad()
resultLabel.text = "Loading…"
do {
try gp.initService(url: ReaderCredentials.url,
instanceId: ReaderCredentials.instanceId,
bundleId: ReaderCredentials.bundleId,
userId: ReaderCredentials.userId,
password: ReaderCredentials.password,
languageId:nil,
alwaysLoadFromServer: false,
expireAfter: 0)
// set up strings
titleLabel.text = get(key: "title")
mixButton.setTitle(get(key: "mix"), for: UIControlState.normal)
mixButton.titleLabel?.text = get(key: "mix")
resultLabel.text = "" // clear this
} catch GPService.GPError.languageNotSupported {
resultLabel.text = ("This language is not supported...")
} catch GPService.GPError.requestServerError(let errorDescription) {
resultLabel.text = ("Request server error: " + errorDescription)
} catch GPService.GPError.HTTPError(let statusCode) {
resultLabel.text = ("Request server error: HTTP \(statusCode)")
} catch {
resultLabel.text = ("Other error")
}
}
@IBAction func doMix(_ sender: Any) {
let color1 = primaryColors[mixOne.selectedRow(inComponent: 0)]
let color2 = primaryColors[mixTwo.selectedRow(inComponent: 0)]
let newColor = color1.mix(with: color2)
resultLabel.text = get(color: newColor)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// pickerview stuff
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1;
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return 3;
}
let primaryColors = [ Color.red, Color.blue, Color.yellow ]
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return get(color: primaryColors[row])
}
}
| 35.58 | 111 | 0.606521 |
f5b94faec1926967715d018f43babc8711d49ed5 | 1,110 | //
// FooterKey.swift
// Refresh
//
// Created by Gesen on 2020/3/22.
// https://github.com/wxxsw/Refresh
import SwiftUI
@available(iOS 13.0, *)
extension EnvironmentValues {
var refreshFooterUpdate: Refresh.FooterUpdateKey.Value {
get { self[Refresh.FooterUpdateKey.self] }
set { self[Refresh.FooterUpdateKey.self] = newValue }
}
}
@available(iOS 13.0, *)
extension Refresh {
enum FooterAnchorKey {
static var defaultValue: Value = []
}
enum FooterUpdateKey {
static var defaultValue: Value = .init(enable: false)
}
}
@available(iOS 13.0, *)
extension Refresh.FooterAnchorKey: PreferenceKey {
typealias Value = [Item]
struct Item {
let bounds: Anchor<CGRect>
let preloadOffset: CGFloat
let refreshing: Bool
}
static func reduce(value: inout Value, nextValue: () -> Value) {
value.append(contentsOf: nextValue())
}
}
@available(iOS 13.0, *)
extension Refresh.FooterUpdateKey: EnvironmentKey {
struct Value: Equatable {
let enable: Bool
var refresh: Bool = false
}
}
| 21.764706 | 68 | 0.646847 |
d6e47792624b41a6ddbc297ab7246bc5472f8fe5 | 1,568 | //
// KeychainCreator.swift
// StandUp-iOS
//
// Created by Peter on 12/01/19.
// Copyright © 2019 BlockchainCommons. All rights reserved.
//
import Foundation
import LibWally
class KeychainCreator {
func createKeyChain(completion: @escaping ((mnemonic: String?, error: Bool)) -> Void) {
let bytesCount = 16
var randomBytes = [UInt8](repeating: 0, count: bytesCount)
let status = SecRandomCopyBytes(kSecRandomDefault, bytesCount, &randomBytes)
if status == errSecSuccess {
let data = Data(randomBytes)
let hex = data.hexString
if let entropy = BIP39Entropy(hex) {
if let mnemonic = BIP39Mnemonic.init(entropy) {
var words = (mnemonic.words.description).replacingOccurrences(of: "\"", with: "")
words = words.replacingOccurrences(of: ",", with: "")
words = words.replacingOccurrences(of: "[", with: "")
words = words.replacingOccurrences(of: "]", with: "")
completion((words,false))
} else {
completion((nil,true))
}
} else {
completion((nil,true))
}
} else {
completion((nil,true))
}
}
}
| 28 | 101 | 0.453444 |
265d273818d4e10279575e5e8ca51fc4a1559278 | 10,218 | //
// MultiLineChartData.swift
//
//
// Created by Will Dale on 24/01/2021.
//
import SwiftUI
import Combine
/**
Data for drawing and styling a multi line, line chart.
This model contains all the data and styling information for a single line, line chart.
*/
public final class MultiLineChartData: CTLineChartDataProtocol, GetDataProtocol, Publishable, PointOfInterestProtocol {
// MARK: Properties
public let id: UUID = UUID()
@Published public final var dataSets: MultiLineDataSet
@Published public final var metadata: ChartMetadata
@Published public final var xAxisLabels: [String]?
@Published public final var yAxisLabels: [String]?
@Published public final var chartStyle: LineChartStyle
@Published public final var legends: [LegendData]
@Published public final var viewData: ChartViewData
@Published public final var infoView: InfoViewData<LineChartDataPoint> = InfoViewData()
public final var noDataText: Text
public final var chartType: (chartType: ChartType, dataSetType: DataSetType)
@Published public final var extraLineData: ExtraLineData!
// Publishable
public var subscription = SubscriptionSet().subscription
public let touchedDataPointPublisher = PassthroughSubject<DataPoint,Never>()
// MARK: Initializers
/// Initialises a Multi Line Chart.
///
/// - Parameters:
/// - dataSets: Data to draw and style the lines.
/// - metadata: Data model containing the charts Title, Subtitle and the Title for Legend.
/// - xAxisLabels: Labels for the X axis instead of the labels in the data points.
/// - yAxisLabels: Labels for the Y axis instead of the labels generated from data point values.
/// - chartStyle: The style data for the aesthetic of the chart.
/// - noDataText: Customisable Text to display when where is not enough data to draw the chart.
public init(
dataSets: MultiLineDataSet,
metadata: ChartMetadata = ChartMetadata(),
xAxisLabels: [String]? = nil,
yAxisLabels: [String]? = nil,
chartStyle: LineChartStyle = LineChartStyle(),
noDataText: Text = Text("No Data")
) {
self.dataSets = dataSets
self.metadata = metadata
self.xAxisLabels = xAxisLabels
self.yAxisLabels = yAxisLabels
self.chartStyle = chartStyle
self.noDataText = noDataText
self.legends = [LegendData]()
self.viewData = ChartViewData()
self.chartType = (.line, .multi)
self.setupLegends()
}
// MARK: Labels
public final func getXAxisLabels() -> some View {
Group {
switch self.chartStyle.xAxisLabelsFrom {
case .dataPoint(let angle):
HStack(spacing: 0) {
ForEach(dataSets.dataSets[0].dataPoints) { data in
VStack {
if self.chartStyle.xAxisLabelPosition == .bottom {
RotatedText(chartData: self, label: data.wrappedXAxisLabel, rotation: angle)
Spacer()
} else {
Spacer()
RotatedText(chartData: self, label: data.wrappedXAxisLabel, rotation: angle)
}
}
.frame(width: min(self.getXSection(dataSet: self.dataSets.dataSets[0], chartSize: self.viewData.chartSize), self.viewData.xAxislabelWidths.min() ?? 0),
height: self.viewData.xAxisLabelHeights.max())
if data != self.dataSets.dataSets[0].dataPoints[self.dataSets.dataSets[0].dataPoints.count - 1] {
Spacer()
.frame(minWidth: 0, maxWidth: 500)
}
}
}
case .chartData(let angle):
if let labelArray = self.xAxisLabels {
HStack(spacing: 0) {
ForEach(labelArray.indices, id: \.self) { i in
VStack {
if self.chartStyle.xAxisLabelPosition == .bottom {
RotatedText(chartData: self, label: labelArray[i], rotation: angle)
Spacer()
} else {
Spacer()
RotatedText(chartData: self, label: labelArray[i], rotation: angle)
}
}
.frame(width: self.viewData.xAxislabelWidths.min(),
height: self.viewData.xAxisLabelHeights.max())
if i != labelArray.count - 1 {
Spacer()
.frame(minWidth: 0, maxWidth: 500)
}
}
}
}
}
}
}
private final func getXSection(dataSet: LineDataSet, chartSize: CGRect) -> CGFloat {
chartSize.width / CGFloat(dataSet.dataPoints.count)
}
// MARK: Points
public final func getPointMarker() -> some View {
ForEach(self.dataSets.dataSets, id: \.id) { dataSet in
PointsSubView(dataSets: dataSet,
minValue: self.minValue,
range: self.range,
animation: self.chartStyle.globalAnimation,
isFilled: false)
}
}
public final func getTouchInteraction(touchLocation: CGPoint, chartSize: CGRect) -> some View {
ZStack {
ForEach(self.dataSets.dataSets, id: \.id) { dataSet in
self.markerSubView(dataSet: dataSet,
dataPoints: dataSet.dataPoints,
lineType: dataSet.style.lineType,
touchLocation: touchLocation,
chartSize: chartSize)
}
self.extraLineData?.getTouchInteraction(touchLocation: touchLocation, chartSize: chartSize)
}
}
// MARK: Accessibility
public func getAccessibility() -> some View {
ForEach(self.dataSets.dataSets, id: \.self) { dataSet in
ForEach(dataSet.dataPoints.indices, id: \.self) { point in
AccessibilityRectangle(dataPointCount: dataSet.dataPoints.count,
dataPointNo: point)
.foregroundColor(Color(.gray).opacity(0.000000001))
.accessibilityLabel(LocalizedStringKey(self.metadata.title))
.accessibilityValue(dataSet.dataPoints[point].getCellAccessibilityValue(specifier: self.infoView.touchSpecifier))
}
}
}
public typealias SetType = MultiLineDataSet
public typealias DataPoint = LineChartDataPoint
public typealias CTStyle = LineChartStyle
}
// MARK: - Touch
extension MultiLineChartData {
public func getPointLocation(dataSet: LineDataSet, touchLocation: CGPoint, chartSize: CGRect) -> CGPoint? {
let minValue: Double = self.minValue
let range: Double = self.range
let xSection: CGFloat = chartSize.width / CGFloat(dataSet.dataPoints.count - 1)
let ySection: CGFloat = chartSize.height / CGFloat(range)
let index: Int = Int((touchLocation.x + (xSection / 2)) / xSection)
if index >= 0 && index < dataSet.dataPoints.count {
if !dataSet.style.ignoreZero {
return CGPoint(x: CGFloat(index) * xSection,
y: (CGFloat(dataSet.dataPoints[index].value - minValue) * -ySection) + chartSize.height)
} else {
if dataSet.dataPoints[index].value != 0 {
return CGPoint(x: CGFloat(index) * xSection,
y: (CGFloat(dataSet.dataPoints[index].value - minValue) * -ySection) + chartSize.height)
}
}
}
return nil
}
public func getDataPoint(touchLocation: CGPoint, chartSize: CGRect) {
self.infoView.touchOverlayInfo = dataSets.dataSets.indices.compactMap { setIndex in
let xSection: CGFloat = chartSize.width / CGFloat(dataSets.dataSets[setIndex].dataPoints.count - 1)
let index = Int((touchLocation.x + (xSection / 2)) / xSection)
if index >= 0 && index < dataSets.dataSets[setIndex].dataPoints.count {
if let data = self.extraLineData,
let point = data.getDataPoint(touchLocation: touchLocation, chartSize: chartSize) {
var dp = LineChartDataPoint(value: point.value, xAxisLabel: point.pointDescription, description: point.pointDescription)
dp.legendTag = data.legendTitle
self.infoView.touchOverlayInfo.append(dp)
}
touchedDataPointPublisher.send(dataSets.dataSets[setIndex].dataPoints[index])
if !dataSets.dataSets[setIndex].style.ignoreZero {
dataSets.dataSets[setIndex].dataPoints[index].legendTag = dataSets.dataSets[setIndex].legendTitle
return dataSets.dataSets[setIndex].dataPoints[index]
} else {
if dataSets.dataSets[setIndex].dataPoints[index].value != 0 {
dataSets.dataSets[setIndex].dataPoints[index].legendTag = dataSets.dataSets[setIndex].legendTitle
return dataSets.dataSets[setIndex].dataPoints[index]
} else {
dataSets.dataSets[setIndex].dataPoints[index].legendTag = dataSets.dataSets[setIndex].legendTitle
dataSets.dataSets[setIndex].dataPoints[index].ignoreMe = true
return dataSets.dataSets[setIndex].dataPoints[index]
}
}
}
return nil
}
}
}
| 46.445455 | 175 | 0.56146 |
67f7db629e55b7ce5e763ede0e1647ec1d05c1de | 3,929 | //
// Todo+Networking.swift
// grokRouter
//
// Created by Christina Moulton on 2018-03-28.
// Copyright © 2018 Christina Moulton. All rights reserved.
//
import Foundation
import Alamofire
enum BackendError: Error {
case parsing(reason: String)
case urlError(reason: String)
}
struct CreateTodoResult: Codable {
var id: Int
}
extension Todo {
static func todoByID(id: Int, completionHandler: @escaping (Result<Todo>) -> Void) {
Alamofire.request(TodoRouter.get(id))
.responseData { response in
let result = Todo.todoFromCodableResponse(response)
completionHandler(result)
}
}
func save(completionHandler: @escaping (Result<Int>) -> Void) {
let encoder = JSONEncoder()
do {
let newTodoAsJSONData = try encoder.encode(self)
Alamofire.request(TodoRouter.create(newTodoAsJSONData))
.responseData { response in
guard response.result.error == nil else {
// got an error in getting the data, need to handle it
print(response.result.error!)
completionHandler(.failure(response.result.error!))
return
}
// make sure we got JSON and it's a dictionary
guard let responseData = response.result.value else {
print("didn't get JSON data from API")
completionHandler(.failure(BackendError.parsing(reason:
"Did not get JSON data in response")))
return
}
let decoder = JSONDecoder()
do {
let createResult = try decoder.decode(CreateTodoResult.self, from: responseData)
completionHandler(.success(createResult.id))
} catch {
print("error parsing response from POST on /todos")
print(error)
completionHandler(.failure(error))
}
}
} catch {
print(error)
completionHandler(.failure(error))
}
}
private static func todoFromCodableResponse(_ response: DataResponse<Data>) -> Result<Todo> {
guard response.result.error == nil else {
// got an error in getting the data, need to handle it
print(response.result.error!)
return .failure(response.result.error!)
}
// make sure we got JSON and it's a dictionary
guard let responseData = response.result.value else {
print("didn't get any data from API")
return .failure(BackendError.parsing(reason:
"Did not get data in response"))
}
// turn data into Todo
let decoder = JSONDecoder()
do {
let todo = try decoder.decode(Todo.self, from: responseData)
return .success(todo)
} catch {
print("error trying to convert data to JSON")
print(error)
return .failure(error)
}
}
static func allTodos(completionHandler: @escaping (Result<[Todo]>) -> Void) {
Alamofire.request(TodoRouter.getAll)
.responseData { response in
let decoder = JSONDecoder()
completionHandler(decoder.decodeResponse([Todo].self, from: response))
}
}
private static func todosFromCodableResponse(_ response: DataResponse<Data>) -> Result<[Todo]> {
guard response.result.error == nil else {
// got an error in getting the data, need to handle it
print(response.result.error!)
return .failure(response.result.error!)
}
// make sure we got JSON and it's a dictionary
guard let responseData = response.result.value else {
print("didn't get any data from API")
return .failure(BackendError.parsing(reason:
"Did not get data in response"))
}
// turn data into Todo
let decoder = JSONDecoder()
do {
let todos = try decoder.decode([Todo].self, from: responseData)
return .success(todos)
} catch {
print("error trying to convert data to JSON")
print(error)
return .failure(error)
}
}
}
| 30.937008 | 98 | 0.63044 |
03408dff7c805aa70359d4b92292a55ef33b58e5 | 3,011 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let _ = (scene as? UIWindowScene) else { return }
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| 46.323077 | 147 | 0.726005 |
7247a6a6c585ac9f9b43a94ecead34c39d56bf32 | 240 | //
// DetailsRouterInput.swift
// SwinjectDependencyInjection
//
// Created by Igor Kotkovets on 12/24/16.
// Copyright © 2016 Igor Kotkovets. All rights reserved.
//
import Foundation
protocol DetailsRouterInput {
func close()
}
| 17.142857 | 57 | 0.725 |
5baa5b1a34c8cd7b87848aa9ef82dc8a7ced96cd | 204 | //
// Clock.swift
// VIPER-SWIFT
//
// Created by Conrad Stoll on 6/4/14.
// Copyright (c) 2014 Mutual Mobile. All rights reserved.
//
import Foundation
protocol Clock {
func today() -> NSDate
} | 15.692308 | 58 | 0.651961 |
3963ce7399893e5dbe9efecb878f81b78034e227 | 4,708 | //
// MainViewController.swift
// DaangnMarketStyleApp
//
// Created by 윤병일 on 2021/12/23.
//
import UIKit
import RxSwift
import RxCocoa
import SnapKit
class MainViewController : UIViewController {
//MARK: - Properties
let disposeBag = DisposeBag()
let tableView = UITableView()
let submitButton = UIBarButtonItem()
//MARK: - Init
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
attribute()
layout()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK: - Functions
func bind(_ viewModel : MainViewModel) {
// ViewModel 에서 View 로 전달되는거 먼저
viewModel.cellData
.drive(tableView.rx.items) { tableView, row, data in
switch row {
case 0 :
let cell = tableView.dequeueReusableCell(withIdentifier: TitleTextFieldCell.identifier, for: IndexPath(row: row, section: 0)) as! TitleTextFieldCell
cell.selectionStyle = .none
cell.titleInputField.placeholder = data
cell.bind(viewModel.titleTextFieldCellViewModel)
return cell
case 1 :
let cell = tableView.dequeueReusableCell(withIdentifier: "CategorySelectCell", for: IndexPath(row: row, section: 0))
cell.selectionStyle = .none
cell.textLabel?.text = data
cell.accessoryType = .disclosureIndicator
return cell
case 2 :
let cell = tableView.dequeueReusableCell(withIdentifier: PriceTextFieldCell.identifier, for: IndexPath(row: row, section: 0)) as! PriceTextFieldCell
cell.selectionStyle = .none
cell.priceInputField.placeholder = data
cell.bind(viewModel.priceTextFieldCellViewModel)
return cell
case 3 :
let cell = tableView.dequeueReusableCell(withIdentifier: DetailWriteFormCell.identifier, for: IndexPath(row: row, section: 0)) as! DetailWriteFormCell
cell.selectionStyle = .none
cell.contentInputView.text = data
cell.bind(viewModel.detailWriteFormCellViewModel)
return cell
default :
fatalError()
}
}.disposed(by: self.disposeBag)
viewModel.presentAlert
.emit(to: self.rx.setAlert)
.disposed(by: self.disposeBag)
viewModel.push
.drive(onNext: { viewModel in
let viewController = CategoryListViewController()
viewController.bind(viewModel)
self.show(viewController, sender: nil)
}).disposed(by: self.disposeBag)
// View 에서 ViewModel 로 전달
tableView.rx.itemSelected
.map { $0.row }
.bind(to: viewModel.itemSelected)
.disposed(by: self.disposeBag)
submitButton.rx.tap
.bind(to: viewModel.submitButtonTapped)
.disposed(by: self.disposeBag)
}
private func attribute() {
title = "중고거래 글쓰기"
view.backgroundColor = .white
self.submitButton.title = "제출"
self.submitButton.style = .done
UINavigationBar.appearance().tintColor = UIColor.black // 제출 버튼 색 변경
UINavigationBar.appearance().titleTextAttributes = [NSAttributedString.Key.foregroundColor : UIColor.black] // 네비 타이틀 색 변경
self.navigationItem.setRightBarButton(submitButton, animated: true)
self.tableView.backgroundColor = .white
self.tableView.separatorStyle = .singleLine
self.tableView.tableFooterView = UIView()
self.tableView.register(TitleTextFieldCell.self, forCellReuseIdentifier: TitleTextFieldCell.identifier) // index row 0
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "CategorySelectCell") // index row 1
self.tableView.register(PriceTextFieldCell.self, forCellReuseIdentifier: PriceTextFieldCell.identifier) // index row 2
self.tableView.register(DetailWriteFormCell.self, forCellReuseIdentifier: DetailWriteFormCell.identifier) // index row 3
}
private func layout() {
view.addSubview(tableView)
tableView.snp.makeConstraints {
$0.edges.equalToSuperview()
}
}
}
typealias Alert = (title : String, message : String?)
//MARK: - Reactive Extension
extension Reactive where Base : MainViewController {
var setAlert : Binder<Alert> {
return Binder(base) { base, data in // base 는 MainViewController, data 는 Alert안에 있는 정보
let alertController = UIAlertController(title: data.title, message: data.message, preferredStyle: .alert)
let action = UIAlertAction(title: "확인", style: .cancel, handler: nil)
alertController.addAction(action)
base.present(alertController, animated: true, completion: nil)
}
}
}
| 35.134328 | 160 | 0.684792 |
0ec4e56155fff95e0b0817567ef2c4b671c8081f | 236 | //
// File.swift
//
//
// Created by Виталий Зарубин on 31.01.2022.
//
import Foundation
struct Samsung: IPhone {
var cpu: ICPU = Snapdragon()
func call() {
print("\(cpu.work()) -> call samsung")
}
}
| 13.111111 | 46 | 0.542373 |
7168c9896afd859dae285fcbc38eabba0517c09a | 8,188 | //
// NSHTTPURLResponse+Utility.swift
// swiftlets
//
// Created by Frank Vernon on 6/27/16.
// Copyright © 2016 Frank Vernon. All rights reserved.
//
import Foundation
/**
Enumeration of HTTP result values categorized by class of status code.
This is useful in processing results of web service calls, for example.
````
switch responseStatus {
case .success:
//happy path
case .serverError(let serverStatus):
switch serverStatus {
case .internalServerError:
//blame them
case .notImplemented:
//blame me
default:
//blame everyone
}
default:
//what now?
}
````
*/
public enum HTTPURLReponseStatus {
public enum informationalStatus: Int {
case continuing = 100
case switchingProtocols = 101
case processing = 102
case checkpoint = 103
}
public enum successStatus: Int {
case ok = 200
case created = 201
case accepted = 202
case nonAuthoritative = 203
case noContent = 204
case resetContent = 205
case partialContent = 206
case multiStatus = 207
case alreadyReported = 208
case imUsed = 226
//test most common case
var isOK: Bool {
get {
self == .ok
}
}
}
public enum redirectionSatus: Int {
case multipleChoices = 300
case movedPermanently = 301
case found = 302
case seeOther = 303
case notModified = 304
case useProxy = 305
case switchProxy = 306
case temporaryRedirect = 307
case permanentRedirect = 308
}
public enum clientErrorStatus: Int {
case badRequest = 400
case unauthorized = 401
case paymentRequired = 402
case forbidden = 403
case notFound = 404
case methodNotAllowed = 405
case notAcceptable = 406
case proxyAuthenticationRequired = 407
case requestTimeout = 408
case conflict = 409
case gone = 410
case lengthRequired = 411
case preconditionFailed = 412
case payloadTooLarge = 413
case uriTooLong = 414
case unsupportedMediaType = 415
case rangeNotSatisfiable = 416
case expectationFailed = 417
case imATeapot = 418
case imAFox = 419
case enhanceYourCalm = 420
case misdirectedRequest = 421
case unprocessableEntity = 422
case locked = 423
case failedDependency = 424
case upgradeRequired = 426
case preconditionRequired = 428
case tooManyRequests = 429
case requestHeaderFieldsTooLarge = 431
case loginTimeout = 440
case noResponse = 444
case retryWith = 449
case unavailableForLegalReasons = 451
case sslCertificateError = 495
case sslCertificateRequired = 496
case httpRequestSentToHTTPSPort = 497
case invalidToken = 498
case tokenRequired = 499
}
public enum serverErrorStatus: Int {
case internalServerError = 500
case notImplemented = 501
case badGateway = 502
case serviceUnavailable = 503
case gatewayTimeout = 504
case httpVersionNotSupported = 505
case variantAlsoNegotiates = 506
case insufficientStorage = 507
case loopDetected = 508
case bandwidthLimitExceeded = 509
case notExtended = 510
case networkAuthenticationRequired = 511
case unknownError = 520
case webServerIsDown = 521
case connectionTimedOut = 522
case originIsUnreachable = 523
case timeoutOccurred = 524
case sslHandshakeFailed = 525
case invalidSSLCertificate = 526
case railgunError = 527
case siteIsFrozen = 530
var isInternalServerError: Bool {
get {
self == .internalServerError
}
}
}
case informational(informationalStatus)
case success(successStatus)
case redirection(redirectionSatus)
case clientError(clientErrorStatus)
case serverError(serverErrorStatus)
case unknown(Int)
init(statusCode: Int) {
//default to unknown in the event parsing below fails to categorize the status code
self = .unknown(statusCode)
switch statusCode {
case 100..<200:
if let info = informationalStatus(rawValue: statusCode) {
self = .informational(info)
}
case 200..<300:
if let success = successStatus(rawValue: statusCode) {
self = .success(success)
}
case 300..<400:
if let redirect = redirectionSatus(rawValue: statusCode) {
self = .redirection(redirect)
}
case 400..<500:
if let clientError = clientErrorStatus(rawValue: statusCode) {
self = .clientError(clientError)
}
case 500..<600:
if let serverError = serverErrorStatus(rawValue: statusCode) {
self = .serverError(serverError)
}
default:
//set to .unknown handled above
break
}
}
func isSuccess() -> Bool {
switch self {
case .success:
return true
default:
return false
}
}
func isSuccessOK() -> Bool {
switch self {
case .success(let value):
return value.isOK
default:
return false
}
}
}
//Extension of HTTPURLResponse to return custom response status enum
public extension HTTPURLResponse {
var status:HTTPURLReponseStatus {
HTTPURLReponseStatus(statusCode: statusCode)
}
}
//Extension of StringInterpolation to return localized strings for HTTPURLReponseStatus values
extension String.StringInterpolation {
mutating func appendInterpolation(_ status: HTTPURLReponseStatus.successStatus) {
let localized = HTTPURLResponse.localizedString(forStatusCode: status.rawValue);
appendInterpolation(localized)
}
mutating func appendInterpolation(_ status: HTTPURLReponseStatus.informationalStatus) {
let localized = HTTPURLResponse.localizedString(forStatusCode: status.rawValue);
appendInterpolation(localized)
}
mutating func appendInterpolation(_ status: HTTPURLReponseStatus.redirectionSatus) {
let localized = HTTPURLResponse.localizedString(forStatusCode: status.rawValue);
appendInterpolation(localized)
}
mutating func appendInterpolation(_ status: HTTPURLReponseStatus.clientErrorStatus) {
let localized = HTTPURLResponse.localizedString(forStatusCode: status.rawValue);
appendInterpolation(localized)
}
mutating func appendInterpolation(_ status: HTTPURLReponseStatus.serverErrorStatus) {
let localized = HTTPURLResponse.localizedString(forStatusCode: status.rawValue);
appendInterpolation(localized)
}
mutating func appendInterpolation(_ httpResponse: HTTPURLReponseStatus) {
switch httpResponse {
case .informational(let informational):
appendInterpolation("\(informational)")
case .success(let success):
appendInterpolation("\(success)")
case .redirection(let redirection):
appendInterpolation("\(redirection)")
case .clientError(let clientError):
appendInterpolation("\(clientError)")
case .serverError(let serverError):
appendInterpolation("\(serverError)")
case .unknown(let unknown):
appendInterpolation(HTTPURLResponse.localizedString(forStatusCode: unknown))
}
}
}
//Extension to print localized error string HTTPURLResponse
extension String.StringInterpolation {
mutating func appendInterpolation(_ httpResponse: HTTPURLResponse) {
let localized = HTTPURLResponse.localizedString(forStatusCode: httpResponse.statusCode);
appendInterpolation(localized)
}
}
| 30.102941 | 96 | 0.629213 |
484ef6bdaa11cafab2da6d6f0941bd67b29e9026 | 2,290 | @objc(MWMDiscoveryLocalExpertCell)
final class DiscoveryLocalExpertCell: UICollectionViewCell {
@IBOutlet private weak var avatar: UIImageView!
@IBOutlet private weak var name: UILabel!
@IBOutlet private weak var rating: RatingSummaryView! {
didSet {
rating.defaultConfig()
rating.textFont = UIFont.bold12()
rating.textSize = 12
}
}
@IBOutlet private weak var price: UIButton!
private lazy var formatter: NumberFormatter = {
let f = NumberFormatter()
f.numberStyle = .currency
return f
}()
typealias Tap = () -> ()
private var tap: Tap!
override var isHighlighted: Bool {
didSet {
UIView.animate(withDuration: kDefaultAnimationDuration,
delay: 0,
options: [.allowUserInteraction, .beginFromCurrentState],
animations: { self.alpha = self.isHighlighted ? 0.3 : 1 },
completion: nil)
}
}
@objc func config(avatarURL: String,
name: String,
ratingValue: String,
ratingType: MWMRatingSummaryViewValueType,
price: Double,
currency: String,
tap: @escaping Tap) {
if avatarURL.count > 0, let url = URL(string: avatarURL) {
avatar.af_setImage(withURL: url, placeholderImage: #imageLiteral(resourceName: "img_localsdefault"), imageTransition: .crossDissolve(kDefaultAnimationDuration))
} else {
avatar.image = #imageLiteral(resourceName: "img_localsdefault")
}
self.name.text = name
rating.value = ratingValue
rating.type = ratingType
let str: String
if currency.count > 0, let cur = stringFor(price: price, currencyCode: currency) {
str = String(coreFormat: L("price_per_hour"), arguments:[cur])
} else {
str = L("free")
}
self.price.setTitle(str, for: .normal)
self.tap = tap
}
@IBAction private func tapOnPrice() {
tap?()
}
private func stringFor(price: Double, currencyCode: String) -> String? {
formatter.currencyCode = currencyCode
return formatter.string(for: price)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
layer.borderColor = UIColor.blackDividers().cgColor
}
}
| 30.945946 | 166 | 0.632314 |
e4866b758ae6ad9d15e6da559668c6ee1f25961d | 7,971 | //
// ContactsCellContentView.swift
// MyMonero
//
// Created by Paul Shapiro on 6/15/17.
// Copyright (c) 2014-2019, MyMonero.com
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other
// materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//
import UIKit
class ContactCellContentView: UIView
{
var emojiLabel: UILabel!
var titleLabel: UILabel!
var subtitleLabel: UILabel!
//
// Lifecycle - Init
init()
{
super.init(frame: .zero)
self.setup()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setup()
{
do {
let view = UILabel()
view.font = UIFont.systemFont(ofSize: 16)
view.numberOfLines = 1
self.addSubview(view)
self.emojiLabel = view
}
do {
let view = UILabel()
view.textColor = UIColor(rgb: 0xFCFBFC)
view.font = UIFont.middlingSemiboldSansSerif
view.numberOfLines = 1
view.lineBreakMode = .byTruncatingTail
self.addSubview(view)
self.titleLabel = view
}
do {
let view = UILabel()
view.textColor = UIColor(rgb: 0x9E9C9E)
view.font = UIFont.middlingRegularMonospace
view.numberOfLines = 1
view.lineBreakMode = .byTruncatingTail
self.addSubview(view)
self.subtitleLabel = view
}
}
//
// Lifecycle - Teardown/Reuse
deinit
{
self.tearDown_object()
}
func tearDown_object()
{
if self.object != nil {
self._stopObserving_object()
self.object = nil
}
}
func prepareForReuse()
{
self.tearDown_object()
}
func _stopObserving_object()
{
assert(self.object != nil)
self.__stopObserving(specificObject: self.object!)
}
func _stopObserving(objectBeingDeinitialized object: Contact)
{
assert(self.object == nil) // special case - since it's a weak ref I expect self.object to actually be nil
assert(self.hasStoppedObservingObject_forLastNonNilSetOfObject != true) // initial expectation at least - this might be able to be deleted
//
self.__stopObserving(specificObject: object)
}
func __stopObserving(specificObject object: Contact)
{
if self.hasStoppedObservingObject_forLastNonNilSetOfObject == true {
// then we've already handled this
DDLog.Warn("ContactsCellContentView", "Not redundantly calling stopObserving")
return
}
self.hasStoppedObservingObject_forLastNonNilSetOfObject = true // must set to true so we can set back to false when object is set back to non-nil
//
NotificationCenter.default.removeObserver(self, name: Contact.NotificationNames.infoUpdated.notificationName, object: object)
NotificationCenter.default.removeObserver(self, name: PersistableObject.NotificationNames.willBeDeleted.notificationName, object: object)
NotificationCenter.default.removeObserver(self, name: PersistableObject.NotificationNames.willBeDeinitialized.notificationName, object: object)
}
//
// Accessors
//
// Imperatives - Configuration
weak var object: Contact? // prevent self from preventing object from being freed (so we still get .willBeDeinitialized)
var hasStoppedObservingObject_forLastNonNilSetOfObject = true // I'm using this addtl state var which is not weak b/c object will be niled purely by virtue of it being freed by strong reference holders (other objects)… and I still need to call stopObserving on that object - while also not doing so redundantly - therefore this variable must be set back to false after self.object is set back to non-nil or possibly more rigorously, in startObserving
func configure(withObject object: Contact)
{
if self.object != nil {
self.prepareForReuse() // in case this is not being used in an actual UITableViewCell (which has a prepareForReuse)
}
assert(self.object == nil)
self.object = object
self._configureUI()
self.startObserving_object()
}
func _configureUI()
{
assert(self.object != nil)
if self.object!.didFailToInitialize_flag == true || self.object!.didFailToBoot_flag == true { // unlikely but possible
self.emojiLabel.text = "❌"
self.titleLabel.text = NSLocalizedString("Error: Contact Support", comment: "")
self.subtitleLabel.text = self.object!.didFailToBoot_errStr ?? ""
} else {
self.emojiLabel.text = self.object!.emoji
self.titleLabel.text = self.object!.fullname
self.subtitleLabel.text = self.object!.address
}
}
//
func startObserving_object()
{
assert(self.object != nil)
assert(self.hasStoppedObservingObject_forLastNonNilSetOfObject == true) // verify that it was reset back to false
self.hasStoppedObservingObject_forLastNonNilSetOfObject = false // set to false so we make sure to stopObserving
NotificationCenter.default.addObserver(self, selector: #selector(_infoUpdated), name: Contact.NotificationNames.infoUpdated.notificationName, object: self.object!)
NotificationCenter.default.addObserver(self, selector: #selector(_willBeDeleted), name: PersistableObject.NotificationNames.willBeDeleted.notificationName, object: self.object!)
NotificationCenter.default.addObserver(self, selector: #selector(_willBeDeinitialized(_:)), name: PersistableObject.NotificationNames.willBeDeinitialized.notificationName, object: self.object!)
}
//
// Imperatives - Overrides
override func layoutSubviews()
{
super.layoutSubviews()
self.emojiLabel.frame = CGRect(
x: 17,
y: 15,
width: 24,
height: 25
)
let labels_x: CGFloat = 50
let labels_rightMargin: CGFloat = 40
let labels_width = self.frame.size.width - labels_x - labels_rightMargin
self.titleLabel.frame = CGRect(
x: labels_x,
y: 19,
width: labels_width,
height: 16 // TODO: size with font for accessibility?
).integral
self.subtitleLabel.frame = CGRect(
x: labels_x,
y: self.titleLabel.frame.origin.y + self.titleLabel.frame.size.height + 2,
width: labels_width,
height: 20 // TODO: size with font for accessibility? NOTE: must support emoji, currently, for locked icon
).integral
}
//
// Delegation - Notifications
@objc func _infoUpdated()
{
self._configureUI()
}
@objc func _willBeDeleted()
{
self.tearDown_object() // stop observing, release
}
@objc func _willBeDeinitialized(_ note: Notification)
{ // This obviously doesn't work for calling stopObserving on self.object --- because self.object is nil by the time we get here!!
let objectBeingDeinitialized = note.userInfo![PersistableObject.NotificationUserInfoKeys.object.key] as! Contact
self._stopObserving( // stopObserving specific object - self.object will be nil by now - but also call specific method for this as it has addtl check
objectBeingDeinitialized: objectBeingDeinitialized
)
}
}
| 38.694175 | 451 | 0.752478 |
5beb63691737da0c0320e660a7c938f230484415 | 5,030 | //
// BooksListViewController.swift
// BooksList
//
// Created by Andrey Konstantinov on 04/06/2017.
// Copyright © 2017 8of. All rights reserved.
//
import UIKit
final class BooksListViewController: UIViewController {
fileprivate weak var output: BooksListViewOutput?
fileprivate let collectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .vertical
layout.minimumLineSpacing = Style.Size.padding
layout.minimumInteritemSpacing = Style.Size.padding
let view = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
view.allowsSelection = false
return view
}()
fileprivate let refreshControl = UIRefreshControl()
init(output: BooksListViewOutput?) {
super.init(nibName: nil, bundle: nil)
self.output = output
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
private init() {
super.init(nibName: nil, bundle: nil)
}
private override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
override func loadView() {
view = UIView()
view.backgroundColor = UIColor.white
view.addSubview(collectionView)
collectionView.backgroundColor = view.backgroundColor
collectionView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
refreshControl.addTarget(self, action: #selector(reloadDataAction), for: .valueChanged)
collectionView.addSubview(refreshControl)
}
override func viewDidLoad() {
super.viewDidLoad()
registerCells(for: collectionView)
collectionView.dataSource = self
collectionView.delegate = self
output?.viewDidLoad()
}
// MARK: - Private
private func registerCells(for collectionView: UICollectionView) {
for type: UICollectionViewCell.Type in [BooksListMetadataItemCollectionViewCell.self, BooksListItemCollectionViewCell.self, LoadingListItemCollectionViewCell.self] {
collectionView.register(type, forCellWithReuseIdentifier: String(describing: type))
}
}
// MARK: - Actions
@objc private func reloadDataAction() {
output?.reloadBooks()
}
}
extension BooksListViewController: BooksListViewInput {
func didRefreshBooks() {
refreshControl.endRefreshing()
collectionView.reloadData()
}
func appendBooks(at indexes: [IndexPath]) {
refreshControl.endRefreshing()
collectionView.performBatchUpdates(
{
self.collectionView.insertItems(at: indexes)
},
completion: { _ in })
}
}
extension BooksListViewController: UICollectionViewDataSource, UICollectionViewDelegate {
fileprivate enum BooksListSection: Int {
case header
case books
case loading
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 3
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
guard let output = output else { return 0 }
switch BooksListSection(rawValue: section)! {
case .header:
return (output.header() != nil) ? 1 : 0
case .books:
return output.booksCount()
case .loading:
return 1
}
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let output = output else { return UICollectionViewCell() }
switch BooksListSection.init(rawValue: indexPath.section)! {
case .header:
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: BooksListMetadataItemCollectionViewCell.self), for: indexPath) as! BooksListMetadataItemCollectionViewCell
if let header = output.header() {
cell.set(header: header)
}
return cell
case .books:
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: BooksListItemCollectionViewCell.self), for: indexPath) as! BooksListItemCollectionViewCell
cell.set(book: output.book(at: indexPath.row))
return cell
case .loading:
return collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: LoadingListItemCollectionViewCell.self), for: indexPath)
}
}
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
guard let output = output else { return }
if indexPath.section == BooksListSection.loading.rawValue {
output.loadMoreBooks()
}
}
}
extension BooksListViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let height: CGFloat!
switch BooksListSection(rawValue: indexPath.section)! {
case .header:
height = 200
case .books:
height = 100
case .loading:
height = 40
}
return CGSize.init(width: collectionView.bounds.width, height: height)
}
}
| 30.670732 | 198 | 0.733002 |
46be5688a2ab1813b8393b2653ad1b87466e044f | 338 | //:## User Data
import VisualRecognitionV3
let visualRecognition = setupVisualRecognitionV3()
//:### Delete labeled data
visualRecognition.deleteUserData(customerID: "my-customer-id") {
_, error in
if let error = error {
print(error.localizedDescription)
return
}
print("delete request submitted")
}
| 17.789474 | 64 | 0.689349 |
dd87b24d7b6f615db0ba995641efa7e0794720f9 | 5,498 | //
// RSClient+Plugins.swift
// RudderStack
//
// Created by Pallab Maiti on 24/02/22.
// Copyright © 2021 Rudder Labs India Pvt Ltd. All rights reserved.
//
import Foundation
extension RSClient {
internal func addPlugins() {
add(plugin: RSReplayQueuePlugin())
let logPlugin = RSLoggerPlugin()
logPlugin.loggingEnabled(config?.logLevel != RSLogLevel.none)
add(plugin: logPlugin)
add(plugin: RSIntegrationPlugin())
add(plugin: RudderDestinationPlugin())
add(plugin: RSGDPRPlugin())
if let platformPlugins = platformPlugins() {
for plugin in platformPlugins {
add(plugin: plugin)
}
}
setupServerConfigCheck()
}
internal func platformPlugins() -> [RSPlatformPlugin]? {
var plugins = [RSPlatformPlugin]()
plugins.append(RSContextPlugin())
plugins.append(RSIdentifyTraitsPlugin())
plugins.append(RSAliasIdPlugin())
plugins.append(RSUserIdPlugin())
plugins.append(RSAnonymousIdPlugin())
plugins.append(RSAppTrackingConsentPlugin())
plugins.append(RSAdvertisingIdPlugin())
plugins += Vendor.current.requiredPlugins
if config?.trackLifecycleEvents == true {
#if os(iOS) || os(tvOS) || targetEnvironment(macCatalyst)
plugins.append(RSiOSLifecycleEvents())
#endif
#if os(watchOS)
plugins.append(RSwatchOSLifecycleEvents())
#endif
#if os(macOS)
plugins.append(RSmacOSLifecycleEvents())
#endif
}
if config?.recordScreenViews == true {
#if os(iOS) || os(tvOS) || targetEnvironment(macCatalyst)
plugins.append(RSiOSScreenViewEvents())
#endif
#if os(watchOS)
plugins.append(RSwatchOSScreenViewEvents())
#endif
#if os(macOS)
plugins.append(RSmacOSScreenViewEvents())
#endif
}
if plugins.isEmpty {
return nil
} else {
return plugins
}
}
}
#if os(iOS) || os(tvOS) || targetEnvironment(macCatalyst)
import UIKit
extension RSClient {
internal func setupServerConfigCheck() {
checkServerConfig()
NotificationCenter.default.addObserver(forName: UIApplication.willEnterForegroundNotification, object: nil, queue: OperationQueue.main) { (notification) in
guard let app = notification.object as? UIApplication else { return }
if app.applicationState == .background {
self.checkServerConfig()
}
}
}
}
#elseif os(watchOS)
extension RSClient {
internal func setupServerConfigCheck() {
checkServerConfig()
}
}
#elseif os(macOS)
import Cocoa
extension RSClient {
internal func setupServerConfigCheck() {
checkServerConfig()
RSQueueTimer.schedule(interval: .days(1), queue: .main) {
self.checkServerConfig()
}
}
}
#endif
extension RSClient {
func update(serverConfig: RSServerConfig, type: UpdateType) {
apply { (plugin) in
update(plugin: plugin, serverConfig: serverConfig, type: type)
}
}
func update(plugin: RSPlugin, serverConfig: RSServerConfig, type: UpdateType) {
plugin.update(serverConfig: serverConfig, type: type)
if let dest = plugin as? RSDestinationPlugin {
dest.apply { (subPlugin) in
subPlugin.update(serverConfig: serverConfig, type: type)
}
}
}
func checkServerConfig() {
var retryCount = 0
var isCompleted = false
while !isCompleted && retryCount < 4 {
if let serverConfig = fetchServerConfig() {
self.serverConfig = serverConfig
RSUserDefaults.saveServerConfig(serverConfig)
RSUserDefaults.updateLastUpdatedTime(RSUtils.getTimeStamp())
log(message: "server config download successful", logLevel: .debug)
isCompleted = true
} else {
if error?.code == RSErrorCode.WRONG_WRITE_KEY.rawValue {
log(message: "Wrong write key", logLevel: .debug)
retryCount = 4
} else {
log(message: "Retrying download in \(retryCount) seconds", logLevel: .debug)
retryCount += 1
sleep(UInt32(retryCount))
}
}
}
if !isCompleted {
log(message: "Server config download failed.Using last stored config from storage", logLevel: .debug)
}
}
private func fetchServerConfig() -> RSServerConfig? {
var serverConfig: RSServerConfig?
let semaphore = DispatchSemaphore(value: 0)
let serviceManager = RSServiceManager(client: self)
serviceManager.downloadServerConfig { [weak self] result in
guard let self = self else { return }
switch result {
case .success(let config):
serverConfig = config
self.update(serverConfig: config, type: .refresh)
case .failure(let error):
self.error = error
}
semaphore.signal()
}
semaphore.wait()
return serverConfig
}
}
| 32.152047 | 163 | 0.580029 |
fced4dc35bef6ecbb2bec3a7fb87d440a0666c5f | 2,030 | //
// HLSNative+ExposureContext+Creation.swift
// Exposure
//
// Created by Fredrik Sjöberg on 2017-11-27.
// Copyright © 2017 emp. All rights reserved.
//
import Foundation
import Player
import Exposure
/// Extends `Player` using `HLSNative` tech in an `ExposureContext` with a convenience initializer
extension Player where Tech == HLSNative<ExposureContext> {
// MARK: Creation
/// Convenience initializer that creates and configures `Player` for use with `HLSNative`, `ExposureContext`.
///
/// Attaches `ExposureAnalytics` to deal with *Exposure* relaed analytics dispatch.
///
/// - parameter environment: The *Exposure* environment
/// - parameter sessionToken: Token identifying this session
public convenience init(environment: Environment, sessionToken: SessionToken) {
self.init(environment: environment, sessionToken: sessionToken, analytics: ExposureAnalytics.self)
}
/// Creates and configures `Player` for use with `HLSNative` and `ExposureContext`.
///
/// - parameter environment: The *Exposure* environment
/// - parameter sessionToken: Token identifying this session
/// - parameter analytics: The *Exposure* related `AnalyticsProvider` tasked with delivering analytics to the *EMP* backend.
public convenience init<Analytics: ExposureStreamingAnalyticsProvider>(environment: Environment, sessionToken: SessionToken, analytics: Analytics.Type, cdn: CDNInfoFromEntitlement? = nil , analyticsFromPlayback: AnalyticsFromEntitlement? = nil ) {
let generator: (Tech.Context.Source?) -> AnalyticsProvider = { _ in return analytics.init(environment: environment, sessionToken: sessionToken, cdn: cdn, analytics: analyticsFromPlayback) }
let context = ExposureContext(environment: environment, sessionToken: sessionToken)
let tech = HLSNative<ExposureContext>()
tech.airplayHandler = context
context.analyticsGenerators.append(generator)
self.init(tech: tech, context: context)
}
}
| 48.333333 | 251 | 0.733498 |
6412d588f3ccab8bdfcc1c7046aa639170e56705 | 2,803 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
import Foundation
import azureSwiftRuntime
internal struct ComputeNodeRebootHeadersData : ComputeNodeRebootHeadersProtocol {
public var clientRequestId: String?
public var requestId: String?
public var eTag: String?
public var lastModified: Date?
public var dataServiceId: String?
enum CodingKeys: String, CodingKey {case clientRequestId = "client-request-id"
case requestId = "request-id"
case eTag = "ETag"
case lastModified = "Last-Modified"
case dataServiceId = "DataServiceId"
}
public init() {
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
if container.contains(.clientRequestId) {
self.clientRequestId = try container.decode(String?.self, forKey: .clientRequestId)
}
if container.contains(.requestId) {
self.requestId = try container.decode(String?.self, forKey: .requestId)
}
if container.contains(.eTag) {
self.eTag = try container.decode(String?.self, forKey: .eTag)
}
if container.contains(.lastModified) {
self.lastModified = DateConverter.fromString(dateStr: (try container.decode(String?.self, forKey: .lastModified)), format: .dateTimeRfc1123)
}
if container.contains(.dataServiceId) {
self.dataServiceId = try container.decode(String?.self, forKey: .dataServiceId)
}
if var pageDecoder = decoder as? PageDecoder {
if pageDecoder.isPagedData,
let nextLinkName = pageDecoder.nextLinkName {
pageDecoder.nextLink = try UnknownCodingKey.decodeStringForKey(decoder: decoder, keyForDecode: nextLinkName)
}
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
if self.clientRequestId != nil {try container.encode(self.clientRequestId, forKey: .clientRequestId)}
if self.requestId != nil {try container.encode(self.requestId, forKey: .requestId)}
if self.eTag != nil {try container.encode(self.eTag, forKey: .eTag)}
if self.lastModified != nil {
try container.encode(DateConverter.toString(date: self.lastModified!, format: .dateTimeRfc1123), forKey: .lastModified)
}
if self.dataServiceId != nil {try container.encode(self.dataServiceId, forKey: .dataServiceId)}
}
}
extension DataFactory {
public static func createComputeNodeRebootHeadersProtocol() -> ComputeNodeRebootHeadersProtocol {
return ComputeNodeRebootHeadersData()
}
}
| 42.469697 | 149 | 0.700321 |
de83c1f019c40660e506ab0778c0f353fece75da | 2,489 | //
// SceneDelegate.swift
// Assignment1
//
// Created by Mohmed Master on 2021/02/10.
//
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let _ = (scene as? UIWindowScene) else { return }
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
// Save changes in the application's managed object context when the application transitions to the background.
(UIApplication.shared.delegate as? AppDelegate)?.saveContext()
}
}
| 44.446429 | 147 | 0.71595 |
38989d90bf24b0dffbf6011c028c3bc8f82c6e1d | 2,526 | import Foundation
import StandardLibraries
public struct Day7 {
public init() {}
public typealias Reducer = (Int, (Int, Int)) throws -> Int
/*
Each submarine has a horizontal position (puzzle input). Moving 1 step costs 1 fuel. What is the least amount of fuel required to align all submarines to the same position?
*/
public func part1(_ input: [Int]) -> Int {
let sorted = input.sorted()
let min = sorted.first!
let max = sorted.last!
var mini = Int.max
for i in (min...max) {
let result = input.reduce(0) {
$0 + abs(i - $1)
}
if result < mini {
mini = result
} else {
break
}
}
return mini
}
public func part1b(_ input: [Int]) -> Int {
let (dict, min, max) = reduce(input)
var mini = Int.max
for i in (min...max) {
let result = dict.reduce(0) {
$0 + abs(i - $1.0) * $1.1
}
if result < mini {
mini = result
} else {
break
}
}
return mini
}
public func part2(_ input: [Int]) -> Int {
let sorted = input.sorted()
let min = sorted.first!
let max = sorted.last!
var mini = Int.max
for i in (min...max) {
let result = input.reduce(0) {
let n = abs(i - $1)
return $0 + (n * (n + 1) / 2)
}
if result < mini {
mini = result
}
}
return mini
}
public func part2b(_ input: [Int]) -> Int {
let (dict, min, max) = reduce(input)
var mini = Int.max
for i in (min...max) {
let result = dict.reduce(0) {
let n = abs(i - $1.0)
return $0 + (n * (n + 1) / 2) * $1.1
}
if result < mini {
mini = result
} else {
break
}
}
return mini
}
public func reduce(_ input: [Int]) -> ([Int:Int], Int, Int) {
var dict = [Int:Int]()
var min = Int.max
var max = 0
for i in input {
dict[i] = dict[i, default: 0] + 1
if i < min {
min = i
}
if i > max {
max = i
}
}
return (dict, min, max)
}
}
| 25.515152 | 177 | 0.41053 |
508a0bb6cbdebec5954a76c391d48db9c1ef7ec6 | 898 | //
// MinifyCSSTransform.swift
// FilestackSDK
//
// Created by Ruben Nine on 13/08/2019.
// Copyright © 2019 Filestack. All rights reserved.
//
import Foundation
/**
Minifies your CSS files.
*/
@objc(FSMinifyCSSTransform) public class MinifyCSSTransform: Transform {
/**
Initializes a `MinifyCSSTransform` object.
*/
@objc public init() {
super.init(name: "minify_css")
}
/**
Adds the `level` option.
- Parameter value: Minification level.
*/
@objc @discardableResult public func level(_ value: Int) -> Self {
return appending(key: "level", value: value)
}
/**
Adds the `gzip` option.
- Parameter value: Whether to compress file and add content encoding gzip header.
*/
@objc @discardableResult public func gzip(_ value: Bool) -> Self {
return appending(key: "gzip", value: value)
}
}
| 22.45 | 86 | 0.632517 |
b91cbbecf40dea8dab37719bc5185a3c9f0b407d | 1,580 | // swift-tools-version:5.1
//
// Package.swift
//
// Copyright (c) Ramotion Inc. (https://www.ramotion.com/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import PackageDescription
let package = Package(
name: "PreviewTransition",
platforms: [
.iOS(.v9)
],
products: [
.library(name: "PreviewTransition",
targets: ["PreviewTransition"]),
],
targets: [
.target(name: "PreviewTransition",
path: "PreviewTransition")
],
swiftLanguageVersions: [.v5]
)
| 35.909091 | 81 | 0.703165 |
f50a74722a8b70f43a42b493695236f551e8a611 | 16,011 | //
// Script.swift
//
// Copyright © 2018 BitcoinKit developers
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
import CryptoSwift
public class Script {
// An array of Data objects (pushing data) or UInt8 objects (containing opcodes)
private var chunks: [ScriptChunk]
// Cached serialized representations for -data and -string methods.
private var dataCache: Data?
private var stringCache: String?
public var data: Data {
// When we calculate data from scratch, it's important to respect actual offsets in the chunks as they may have been copied or shifted in subScript* methods.
if let cache = dataCache {
return cache
}
dataCache = chunks.reduce(Data()) { $0 + $1.chunkData }
return dataCache!
}
public var string: String {
if let cache = stringCache {
return cache
}
stringCache = chunks.map { $0.string }.joined(separator: " ")
return stringCache!
}
public var hex: String {
return data.hex
}
public func toP2SH() -> Script {
return try! Script()
.append(.OP_HASH160)
.appendData(RIPEMD160.hash(data.sha256()))
.append(.OP_EQUAL)
}
// Multisignature script attribute.
// If multisig script is not detected, this is nil
public typealias MultisigVariables = (nSigRequired: UInt, publickeys: [PublicKey])
public var multisigRequirements: MultisigVariables?
public init() {
self.chunks = [ScriptChunk]()
}
public init(chunks: [ScriptChunk]) {
self.chunks = chunks
}
public convenience init?(data: Data) {
// It's important to keep around original data to correctly identify the size of the script for BTC_MAX_SCRIPT_SIZE check
// and to correctly calculate hash for the signature because in BitcoinQT scripts are not re-serialized/canonicalized.
do {
let chunks = try Script.parseData(data)
self.init(chunks: chunks)
} catch let error {
print(error)
return nil
}
}
public convenience init(hex: String) {
self.init(data: Data(hex: hex))!
}
public convenience init?(address: Address) {
self.init()
switch address.type {
case .pubkeyHash:
// OP_DUP OP_HASH160 <hash> OP_EQUALVERIFY OP_CHECKSIG
do {
try self.append(.OP_DUP)
.append(.OP_HASH160)
.appendData(address.data)
.append(.OP_EQUALVERIFY)
.append(.OP_CHECKSIG)
} catch {
return nil
}
case .scriptHash:
// OP_HASH160 <hash> OP_EQUAL
do {
try self.append(.OP_HASH160)
.appendData(address.data)
.append(.OP_EQUAL)
} catch {
return nil
}
default:
return nil
}
}
// OP_<M> <pubkey1> ... <pubkeyN> OP_<N> OP_CHECKMULTISIG
public convenience init?(publicKeys: [PublicKey], signaturesRequired: UInt) {
// First make sure the arguments make sense.
// We need at least one signature
guard signaturesRequired > 0 else {
return nil
}
// And we cannot have more signatures than available pubkeys.
guard publicKeys.count >= signaturesRequired else {
return nil
}
// Both M and N should map to OP_<1..16>
let mOpcode: OpCode = OpCodeFactory.opcode(for: Int(signaturesRequired))
let nOpcode: OpCode = OpCodeFactory.opcode(for: publicKeys.count)
guard mOpcode != .OP_INVALIDOPCODE else {
return nil
}
guard nOpcode != .OP_INVALIDOPCODE else {
return nil
}
do {
self.init()
try append(mOpcode)
for pubkey in publicKeys {
try appendData(pubkey.data)
}
try append(nOpcode)
try append(.OP_CHECKMULTISIG)
multisigRequirements = (signaturesRequired, publicKeys)
} catch {
return nil
}
}
private static func parseData(_ data: Data) throws -> [ScriptChunk] {
guard !data.isEmpty else {
return [ScriptChunk]()
}
var chunks = [ScriptChunk]()
var i: Int = 0
let count: Int = data.count
while i < count {
// Exit if failed to parse
let chunk = try ScriptChunkHelper.parseChunk(from: data, offset: i)
chunks.append(chunk)
i += chunk.range.count
}
return chunks
}
public var isStandard: Bool {
return isPayToPublicKeyHashScript
|| isPayToScriptHashScript
|| isPublicKeyScript
|| isStandardMultisignatureScript
}
public var isPublicKeyScript: Bool {
guard chunks.count == 2 else {
return false
}
guard let pushdata = pushedData(at: 0) else {
return false
}
return pushdata.count > 1 && opcode(at: 1) == OpCode.OP_CHECKSIG
}
public var isPayToPublicKeyHashScript: Bool {
guard chunks.count == 5 else {
return false
}
guard let dataChunk = chunk(at: 2) as? DataChunk else {
return false
}
return opcode(at: 0) == OpCode.OP_DUP
&& opcode(at: 1) == OpCode.OP_HASH160
&& dataChunk.range.count == 21
&& opcode(at: 3) == OpCode.OP_EQUALVERIFY
&& opcode(at: 4) == OpCode.OP_CHECKSIG
}
public var isPayToScriptHashScript: Bool {
guard chunks.count == 3 else {
return false
}
return opcode(at: 0) == OpCode.OP_HASH160
&& pushedData(at: 1)?.count == 20 // this is enough to match the exact byte template, any other encoding will be larger.
&& opcode(at: 2) == OpCode.OP_EQUAL
}
// Returns true if the script ends with P2SH check.
// Not used in CoreBitcoin. Similar code is used in bitcoin-ruby. I don't know if we'll ever need it.
public var endsWithPayToScriptHash: Bool {
guard chunks.count >= 3 else {
return false
}
return opcode(at: -3) == OpCode.OP_HASH160
&& pushedData(at: -2)?.count == 20
&& opcode(at: -1) == OpCode.OP_EQUAL
}
public var isStandardMultisignatureScript: Bool {
guard isMultisignatureScript else {
return false
}
guard let multisigPublicKeys = multisigRequirements?.publickeys else {
return false
}
return multisigPublicKeys.count <= 3
}
public var isMultisignatureScript: Bool {
guard let requirements = multisigRequirements else {
return false
}
if requirements.nSigRequired == 0 {
detectMultisigScript()
}
return requirements.nSigRequired > 0
}
public var isStandardOpReturnScript: Bool {
guard chunks.count == 2 else {
return false
}
return opcode(at: 0) == .OP_RETURN
&& pushedData(at: 1) != nil
}
public func standardOpReturnData() -> Data? {
guard isStandardOpReturnScript else {
return nil
}
return pushedData(at: 1)
}
// If typical multisig tx is detected, sets requirements:
private func detectMultisigScript() {
// multisig script must have at least 4 ops ("OP_1 <pubkey> OP_1 OP_CHECKMULTISIG")
guard chunks.count >= 4 else {
return
}
// The last op is multisig check.
guard opcode(at: -1) == OpCode.OP_CHECKMULTISIG else {
return
}
let mOpcode: OpCode = opcode(at: 0)
let nOpcode: OpCode = opcode(at: -2)
let m: Int = OpCodeFactory.smallInteger(from: mOpcode)
let n: Int = OpCodeFactory.smallInteger(from: nOpcode)
guard m > 0 && m != Int.max else {
return
}
guard n > 0 && n != Int.max && n >= m else {
return
}
// We must have correct number of pubkeys in the script. 3 extra ops: OP_<M>, OP_<N> and OP_CHECKMULTISIG
guard chunks.count == 3 + n else {
return
}
var pubkeys: [PublicKey] = []
for i in 0...n {
guard let data = pushedData(at: i) else {
return
}
// TODO: Other coins
let pubkey = PublicKey(privateKey: data, coin: .bitcoin)
pubkeys.append(pubkey)
}
// Now we extracted all pubkeys and verified the numbers.
multisigRequirements = (UInt(m), pubkeys)
}
// Include both PUSHDATA ops and OP_0..OP_16 literals.
public var isDataOnly: Bool {
return !chunks.contains { $0.opcodeValue > OpCode.OP_16 }
}
public var scriptChunks: [ScriptChunk] {
return chunks
}
// MARK: - Modification
public func invalidateSerialization() {
dataCache = nil
stringCache = nil
multisigRequirements = nil
}
private func update(with updatedData: Data) throws {
let updatedChunks = try Script.parseData(updatedData)
chunks = updatedChunks
invalidateSerialization()
}
@discardableResult
public func append(_ opcode: OpCode) throws -> Script {
let invalidOpCodes: [OpCode] = [.OP_PUSHDATA1,
.OP_PUSHDATA2,
.OP_PUSHDATA4,
.OP_INVALIDOPCODE]
guard !invalidOpCodes.contains(where: { $0 == opcode }) else {
throw ScriptError.error("\(opcode.name) cannot be executed alone.")
}
var updatedData: Data = data
updatedData += opcode
try update(with: updatedData)
return self
}
@discardableResult
public func appendData(_ newData: Data) throws -> Script {
guard !newData.isEmpty else {
throw ScriptError.error("Data is empty.")
}
guard let addedScriptData = ScriptChunkHelper.scriptData(for: newData, preferredLengthEncoding: -1) else {
throw ScriptError.error("Parse data to pushdata failed.")
}
var updatedData: Data = data
updatedData += addedScriptData
try update(with: updatedData)
return self
}
@discardableResult
public func appendScript(_ otherScript: Script) throws -> Script {
guard !otherScript.data.isEmpty else {
throw ScriptError.error("Script is empty.")
}
var updatedData: Data = self.data
updatedData += otherScript.data
try update(with: updatedData)
return self
}
@discardableResult
public func deleteOccurrences(of data: Data) throws -> Script {
guard !data.isEmpty else {
return self
}
let updatedData = chunks.filter { ($0 as? DataChunk)?.pushedData != data }.reduce(Data()) { $0 + $1.chunkData }
try update(with: updatedData)
return self
}
@discardableResult
public func deleteOccurrences(of opcode: OpCode) throws -> Script {
let updatedData = chunks.filter { $0.opCode != opcode }.reduce(Data()) { $0 + $1.chunkData }
try update(with: updatedData)
return self
}
public func subScript(from index: Int) throws -> Script {
let subScript: Script = Script()
for chunk in chunks[index..<chunks.count] {
try subScript.appendData(chunk.chunkData)
}
return subScript
}
public func subScript(to index: Int) throws -> Script {
let subScript: Script = Script()
for chunk in chunks[0..<index] {
try subScript.appendData(chunk.chunkData)
}
return subScript
}
// MARK: - Utility methods
// Raise exception if index is out of bounds
public func chunk(at index: Int) -> ScriptChunk {
return chunks[index < 0 ? chunks.count + index : index]
}
// Returns an opcode in a chunk.
// If the chunk is data, not an opcode, returns OP_INVALIDOPCODE
// Raises exception if index is out of bounds.
public func opcode(at index: Int) -> OpCode {
let chunk = self.chunk(at: index)
// If the chunk is not actually an opcode, return invalid opcode.
guard chunk is OpcodeChunk else {
return .OP_INVALIDOPCODE
}
return chunk.opCode
}
// Returns Data in a chunk.
// If chunk is actually an opcode, returns nil.
// Raises exception if index is out of bounds.
public func pushedData(at index: Int) -> Data? {
let chunk = self.chunk(at: index)
return (chunk as? DataChunk)?.pushedData
}
public func execute(with context: ScriptExecutionContext) throws {
for chunk in chunks {
if let opChunk = chunk as? OpcodeChunk {
try opChunk.opCode.execute(context)
} else if let dataChunk = chunk as? DataChunk {
if context.shouldExecute {
try context.pushToStack(dataChunk.pushedData)
}
} else {
throw ScriptMachineError.error("Unknown chunk")
}
}
guard context.conditionStack.isEmpty else {
throw ScriptMachineError.error("Condition branches not balanced.")
}
}
}
extension Script {
// Standard Transaction to Bitcoin address (pay-to-pubkey-hash)
// scriptPubKey: OP_DUP OP_HASH160 <pubKeyHash> OP_EQUALVERIFY OP_CHECKSIG
public static func buildPublicKeyHashOut(pubKeyHash: Data) -> Data {
let tmp: Data = Data() + OpCode.OP_DUP + OpCode.OP_HASH160 + UInt8(pubKeyHash.count) + pubKeyHash
return tmp + OpCode.OP_EQUALVERIFY + OpCode.OP_CHECKSIG
}
public static func buildPublicKeyUnlockingScript(signature: Data, pubkey: PublicKey, hashType: SighashType) -> Data {
var data: Data = Data([UInt8(signature.count + 1)]) + signature + UInt8(hashType)
data += VarInt(pubkey.data.count).serialized()
data += pubkey.data
return data
}
public static func isPublicKeyHashOut(_ script: Data) -> Bool {
return script.count == 25 &&
script[0] == OpCode.OP_DUP && script[1] == OpCode.OP_HASH160 && script[2] == 20 &&
script[23] == OpCode.OP_EQUALVERIFY && script[24] == OpCode.OP_CHECKSIG
}
public static func getPublicKeyHash(from script: Data) -> Data {
return script[3..<23]
}
}
extension Script: CustomStringConvertible {
public var description: String {
return string
}
}
enum ScriptError: Error {
case error(String)
}
| 32.944444 | 165 | 0.593217 |
29061467ac3d11b0d1ebac762fb66c8af4dbc726 | 17,052 | //
// IQKeyboardReturnKeyHandler.swift
// https://github.com/hackiftekhar/IQKeyboardManager
// Copyright (c) 2013-16 Iftekhar Qurashi.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
/**
Manages the return key to work like next/done in a view hierarchy.
*/
public class IQKeyboardReturnKeyHandler: NSObject , UITextFieldDelegate, UITextViewDelegate {
///---------------
/// MARK: Settings
///---------------
/**
Delegate of textField/textView.
*/
public var delegate: protocol<UITextFieldDelegate, UITextViewDelegate>?
/**
Set the last textfield return key type. Default is UIReturnKeyDefault.
*/
public var lastTextFieldReturnKeyType : UIReturnKeyType = UIReturnKeyType.Default {
didSet {
for infoDict in textFieldInfoCache {
if let view = infoDict.objectForKey(kIQTextField) as? UIView {
updateReturnKeyTypeOnTextField(view)
}
}
}
}
///--------------------------------------
/// MARK: Initialization/Deinitialization
///--------------------------------------
public override init() {
super.init()
}
/**
Add all the textFields available in UIViewController's view.
*/
public init(controller : UIViewController) {
super.init()
addResponderFromView(controller.view)
}
deinit {
for infoDict in textFieldInfoCache {
let view : AnyObject = infoDict.objectForKey(kIQTextField)!
if let textField = view as? UITextField {
let returnKeyTypeValue = infoDict[kIQTextFieldReturnKeyType] as! NSNumber
textField.returnKeyType = UIReturnKeyType(rawValue: returnKeyTypeValue.integerValue)!
textField.delegate = infoDict[kIQTextFieldDelegate] as! UITextFieldDelegate?
} else if let textView = view as? UITextView {
textView.returnKeyType = UIReturnKeyType(rawValue: (infoDict[kIQTextFieldReturnKeyType] as! NSNumber).integerValue)!
let returnKeyTypeValue = infoDict[kIQTextFieldReturnKeyType] as! NSNumber
textView.returnKeyType = UIReturnKeyType(rawValue: returnKeyTypeValue.integerValue)!
textView.delegate = infoDict[kIQTextFieldDelegate] as! UITextViewDelegate?
}
}
textFieldInfoCache.removeAllObjects()
}
///------------------------
/// MARK: Private variables
///------------------------
private var textFieldInfoCache = NSMutableSet()
private let kIQTextField = "kIQTextField"
private let kIQTextFieldDelegate = "kIQTextFieldDelegate"
private let kIQTextFieldReturnKeyType = "kIQTextFieldReturnKeyType"
///------------------------
/// MARK: Private Functions
///------------------------
private func textFieldCachedInfo(textField : UIView) -> [String : AnyObject]? {
for infoDict in textFieldInfoCache {
if infoDict.objectForKey(kIQTextField) as! NSObject == textField {
return infoDict as? [String : AnyObject]
}
}
return nil
}
private func updateReturnKeyTypeOnTextField(view : UIView)
{
var superConsideredView : UIView?
//If find any consider responderView in it's upper hierarchy then will get deepResponderView. (Bug ID: #347)
for disabledClassString in IQKeyboardManager.sharedManager().consideredToolbarPreviousNextViewClassesString() {
if let disabledClass = NSClassFromString(disabledClassString) {
superConsideredView = view.superviewOfClassType(disabledClass)
if superConsideredView != nil {
break
}
}
}
var textFields : [UIView]?
//If there is a tableView in view's hierarchy, then fetching all it's subview that responds.
if let unwrappedTableView = superConsideredView { // (Enhancement ID: #22)
textFields = unwrappedTableView.deepResponderViews()
} else { //Otherwise fetching all the siblings
textFields = view.responderSiblings()
//Sorting textFields according to behaviour
switch IQKeyboardManager.sharedManager().toolbarManageBehaviour {
//If needs to sort it by tag
case .ByTag: textFields = textFields?.sortedArrayByTag()
//If needs to sort it by Position
case .ByPosition: textFields = textFields?.sortedArrayByPosition()
default: break
}
}
if let lastView = textFields?.last {
if let textField = view as? UITextField {
//If it's the last textField in responder view, else next
textField.returnKeyType = (view == lastView) ? lastTextFieldReturnKeyType : UIReturnKeyType.Next
} else if let textView = view as? UITextView {
//If it's the last textField in responder view, else next
textView.returnKeyType = (view == lastView) ? lastTextFieldReturnKeyType : UIReturnKeyType.Next
}
}
}
///----------------------------------------------
/// MARK: Registering/Unregistering textFieldView
///----------------------------------------------
/**
Should pass UITextField/UITextView intance. Assign textFieldView delegate to self, change it's returnKeyType.
@param textFieldView UITextField/UITextView object to register.
*/
public func addTextFieldView(view : UIView) {
var dictInfo : [String : AnyObject] = [String : AnyObject]()
dictInfo[kIQTextField] = view
if let textField = view as? UITextField {
dictInfo[kIQTextFieldReturnKeyType] = textField.returnKeyType.rawValue
if let textFieldDelegate = textField.delegate {
dictInfo[kIQTextFieldDelegate] = textFieldDelegate
}
textField.delegate = self
} else if let textView = view as? UITextView {
dictInfo[kIQTextFieldReturnKeyType] = textView.returnKeyType.rawValue
if let textViewDelegate = textView.delegate {
dictInfo[kIQTextFieldDelegate] = textViewDelegate
}
textView.delegate = self
}
textFieldInfoCache.addObject(dictInfo)
}
/**
Should pass UITextField/UITextView intance. Restore it's textFieldView delegate and it's returnKeyType.
@param textFieldView UITextField/UITextView object to unregister.
*/
public func removeTextFieldView(view : UIView) {
if let dict : [String : AnyObject] = textFieldCachedInfo(view) {
if let textField = view as? UITextField {
let returnKeyTypeValue = dict[kIQTextFieldReturnKeyType] as! NSNumber
textField.returnKeyType = UIReturnKeyType(rawValue: returnKeyTypeValue.integerValue)!
textField.delegate = dict[kIQTextFieldDelegate] as! UITextFieldDelegate?
} else if let textView = view as? UITextView {
let returnKeyTypeValue = dict[kIQTextFieldReturnKeyType] as! NSNumber
textView.returnKeyType = UIReturnKeyType(rawValue: returnKeyTypeValue.integerValue)!
textView.delegate = dict[kIQTextFieldDelegate] as! UITextViewDelegate?
}
textFieldInfoCache.removeObject(dict)
}
}
/**
Add all the UITextField/UITextView responderView's.
@param UIView object to register all it's responder subviews.
*/
public func addResponderFromView(view : UIView) {
let textFields = view.deepResponderViews()
for textField in textFields {
addTextFieldView(textField)
}
}
/**
Remove all the UITextField/UITextView responderView's.
@param UIView object to unregister all it's responder subviews.
*/
public func removeResponderFromView(view : UIView) {
let textFields = view.deepResponderViews()
for textField in textFields {
removeTextFieldView(textField)
}
}
private func goToNextResponderOrResign(view : UIView) {
var superConsideredView : UIView?
//If find any consider responderView in it's upper hierarchy then will get deepResponderView. (Bug ID: #347)
for disabledClassString in IQKeyboardManager.sharedManager().consideredToolbarPreviousNextViewClassesString() {
if let disabledClass = NSClassFromString(disabledClassString) {
superConsideredView = view.superviewOfClassType(disabledClass)
if superConsideredView != nil {
break
}
}
}
var textFields : [UIView]?
//If there is a tableView in view's hierarchy, then fetching all it's subview that responds.
if let unwrappedTableView = superConsideredView { // (Enhancement ID: #22)
textFields = unwrappedTableView.deepResponderViews()
} else { //Otherwise fetching all the siblings
textFields = view.responderSiblings()
//Sorting textFields according to behaviour
switch IQKeyboardManager.sharedManager().toolbarManageBehaviour {
//If needs to sort it by tag
case .ByTag: textFields = textFields?.sortedArrayByTag()
//If needs to sort it by Position
case .ByPosition: textFields = textFields?.sortedArrayByPosition()
default:
break
}
}
if let unwrappedTextFields = textFields {
//Getting index of current textField.
if let index = unwrappedTextFields.indexOf(view) {
//If it is not last textField. then it's next object becomeFirstResponder.
if index < (unwrappedTextFields.count - 1) {
let nextTextField = unwrappedTextFields[index+1]
nextTextField.becomeFirstResponder()
} else {
view.resignFirstResponder()
}
}
}
}
///----------------------------------------------
/// MARK: UITextField/UITextView delegates
///----------------------------------------------
public func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
if delegate?.respondsToSelector("textFieldShouldBeginEditing:") != nil {
return (delegate?.textFieldShouldBeginEditing?(textField) == true)
} else {
return true
}
}
public func textFieldShouldEndEditing(textField: UITextField) -> Bool {
if delegate?.respondsToSelector("textFieldShouldEndEditing:") != nil {
return (delegate?.textFieldShouldEndEditing?(textField) == true)
} else {
return true
}
}
public func textFieldDidBeginEditing(textField: UITextField) {
updateReturnKeyTypeOnTextField(textField)
delegate?.textFieldShouldBeginEditing?(textField)
}
public func textFieldDidEndEditing(textField: UITextField) {
delegate?.textFieldDidEndEditing?(textField)
}
public func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
if delegate?.respondsToSelector("textField:shouldChangeCharactersInRange:replacementString:") != nil {
return (delegate?.textField?(textField, shouldChangeCharactersInRange: range, replacementString: string) == true)
} else {
return true
}
}
public func textFieldShouldClear(textField: UITextField) -> Bool {
if delegate?.respondsToSelector("textFieldShouldClear:") != nil {
return (delegate?.textFieldShouldClear?(textField) == true)
} else {
return true
}
}
public func textFieldShouldReturn(textField: UITextField) -> Bool {
var shouldReturn = true
if delegate?.respondsToSelector("textFieldShouldReturn:") != nil {
shouldReturn = (delegate?.textFieldShouldReturn?(textField) == true)
}
if shouldReturn == true {
goToNextResponderOrResign(textField)
}
return shouldReturn
}
public func textViewShouldBeginEditing(textView: UITextView) -> Bool {
if delegate?.respondsToSelector("textViewShouldBeginEditing:") != nil {
return (delegate?.textViewShouldBeginEditing?(textView) == true)
} else {
return true
}
}
public func textViewShouldEndEditing(textView: UITextView) -> Bool {
if delegate?.respondsToSelector("textViewShouldEndEditing:") != nil {
return (delegate?.textViewShouldEndEditing?(textView) == true)
} else {
return true
}
}
public func textViewDidBeginEditing(textView: UITextView) {
updateReturnKeyTypeOnTextField(textView)
delegate?.textViewDidBeginEditing?(textView)
}
public func textViewDidEndEditing(textView: UITextView) {
delegate?.textViewDidEndEditing?(textView)
}
public func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
var shouldReturn = true
if delegate?.respondsToSelector("textView:shouldChangeCharactersInRange:replacementString:") != nil {
shouldReturn = ((delegate?.textView?(textView, shouldChangeTextInRange: range, replacementText: text)) == true)
}
if shouldReturn == true && text == "\n" {
goToNextResponderOrResign(textView)
}
return shouldReturn
}
public func textViewDidChange(textView: UITextView) {
delegate?.textViewDidChange?(textView)
}
public func textViewDidChangeSelection(textView: UITextView) {
delegate?.textViewDidChangeSelection?(textView)
}
public func textView(textView: UITextView, shouldInteractWithURL URL: NSURL, inRange characterRange: NSRange) -> Bool {
if delegate?.respondsToSelector("textView:shouldInteractWithURL:inRange:") != nil {
return ((delegate?.textView?(textView, shouldInteractWithURL: URL, inRange: characterRange)) == true)
} else {
return true
}
}
public func textView(textView: UITextView, shouldInteractWithTextAttachment textAttachment: NSTextAttachment, inRange characterRange: NSRange) -> Bool {
if delegate?.respondsToSelector("textView:shouldInteractWithTextAttachment:inRange:") != nil {
return ((delegate?.textView?(textView, shouldInteractWithTextAttachment: textAttachment, inRange: characterRange)) == true)
} else {
return true
}
}
}
| 36.358209 | 156 | 0.592482 |
7a5ea33310dc766c937f18f1283f772a065c17ec | 3,039 | //
// AppDelegate.swift
// iOSSwift
//
// Created by C.W. Betts on 10/3/14.
//
//
import UIKit
import CocoaLumberjack
import CocoaLumberjackSwift
let ddloglevel = DDLogLevel.verbose
private func printSomething() {
DDLogVerbose("Verbose")
DDLogDebug("Debug")
DDLogInfo("Info")
DDLogWarn("Warn")
DDLogError("Error")
}
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
let formatter = Formatter()
DDTTYLogger.sharedInstance.logFormatter = formatter
DDLog.add(DDTTYLogger.sharedInstance)
DDLogVerbose("Verbose")
DDLogDebug("Debug")
DDLogInfo("Info")
DDLogWarn("Warn")
DDLogError("Error")
printSomething()
dynamicLogLevel = ddloglevel
DDLogVerbose("Verbose")
DDLogDebug("Debug")
DDLogInfo("Info")
DDLogWarn("Warn")
DDLogError("Error")
DDLogVerbose("Verbose", level: ddloglevel)
DDLogDebug("Debug", level: ddloglevel)
DDLogInfo("Info", level: ddloglevel)
DDLogWarn("Warn", level: ddloglevel)
DDLogError("Error", level: ddloglevel)
printSomething()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 35.752941 | 279 | 0.731162 |
fe6e277c5751ee4090a3d7e3524117597ff91c4a | 653 | //
// Created by Papp Imre on 2019-02-15.
// Copyright (c) 2019 CocoaPods. All rights reserved.
//
import NMDEF_Base
import RxFlow
import Reusable
class Tab2Flow: TabFlow, FlowWithNavigationRoot, StoryboardSceneBased {
static var sceneIdentifier: String {
return "Tab2Navigation"
}
func navigate(to step: Step) -> NextFlowItems {
guard let step = step as? AppStep else {
return .none
}
switch step {
case .tab2: return pushNavigation(to: Tab2ViewController.self)
case .tab2nav1: return pushNavigation(to: Nav3ViewController.self)
default: return .none
}
}
} | 25.115385 | 74 | 0.658499 |
f575bf4ff8455e5aa6b2f8c2b6545666d1afca6a | 181 | import Foundation
#if os(Linux)
import FoundationNetworking
#endif
public extension URL {
/// Easy request generation.
var urlRequest: URLRequest {
URLRequest(url: self)
}
}
| 13.923077 | 29 | 0.745856 |
f9ccf05d36d3158143718384827213947a640a9b | 1,126 | import UIKit
/**
Batch Actions View Controller, contains the replication and batch operation actions.
*/
class HomeActionsViewController: UIViewController {
//@IBOutlet weak var dfdfgd: UIButton!
fileprivate var eventAPI: EventAPI!
fileprivate var remoteReplicator: RemoteReplicator!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
self.eventAPI = EventAPI.sharedInstance
self.remoteReplicator = RemoteReplicator.sharedInstance
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func deleteAllEventsButtonTapped(_ sender: AnyObject) {
eventAPI.deleteAllEvents()
self.navigationController?.popToRootViewController(animated: true)
}
@IBAction func replicateRemoteDataButtonTapped(_ sender: AnyObject) {
remoteReplicator.fetchData()
NotificationCenter.default.post(name: Notification.Name(rawValue: "setStateLoading"), object: nil)
self.navigationController?.popToRootViewController(animated: true)
}
}
| 30.432432 | 106 | 0.728242 |
383bff4d953659825864ce71a20ef98a38682463 | 1,161 | //: [⇐ Previous: 02 - Functions](@previous)
//: ## Episode 03: Challenge - Functions
/*:
## Challenge 1
- Create a closure version of the function below.
- Try out the function & closure!
*/
// --------------------------------------
func calculateFullName(firstName: String, lastName: String?) -> String {
firstName + " " + (lastName ?? "")
}
// --------------------------------------
// TODO: Write solution here
var calculateFullNameClosure = { (firstName: String, lastName: String?) -> String in
firstName + " " + (lastName ?? "")
}
//let philipsName = calculateFullName(firstName: Philip, lastName: Timothe)
calculateFullNameClosure("Philip", "Timothe")
/*:
## Challenge 2
- Call the `printResult` function below
- Use an inline closure as an argument
*/
// --------------------------------------
typealias Operate = (Double, Double) -> Double
func printResult(_ operate: Operate, _ a: Double, _ b: Double) {
let result = operate(a, b)
print(result)
}
// --------------------------------------
// TODO: Write solution here
printResult( { ( a: Double, b: Double) -> Double in
a * b
}, 4, 5)
//: [⇒ Next: 04 - Closure Syntax](@next)
| 25.23913 | 84 | 0.569337 |
efec532266ece66de510f196bddd897f5d44ea86 | 2,358 | //
// Context.swift
// SlackBlocksModel
//
// Created by Helge Heß.
// Copyright © 2020 ZeeZide GmbH. All rights reserved.
//
public extension Block {
struct Context: Encodable {
/**
* Context's can contain just text (w/ or w/o markdown) and images.
*/
public enum Element: Encodable {
case text (Text)
case image(ImageElement)
public func encode(to encoder: Encoder) throws {
switch self {
case .text (let element): try element.encode(to: encoder)
case .image(let element): try element.encode(to: encoder)
}
}
}
public static let validInSurfaces : [ BlockSurfaceSet ]
= [ .modals, .messages, .homeTabs ]
public var id : BlockID
public var elements : [ Element ]
public init(id: BlockID, elements: [ Element ]) {
self.id = id
self.elements = elements
}
// MARK: - Encoding
enum CodingKeys: String, CodingKey {
case id = "block_id"
case type, elements
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode("context", forKey: .type)
try container.encode(id, forKey: .id)
try container.encode(elements, forKey: .elements)
}
}
}
// MARK: - Markdown
public extension Block.Context {
@inlinable
var blocksMarkdownString : String {
var ms = ""
for element in elements {
switch element {
case .text(let text):
ms += text.blocksMarkdownString
ms += "\n"
case .image(let image):
ms += "![\(image.alt)](image.url.absoluteString)\n"
}
}
return ms
}
}
// MARK: - Markdown
extension Block.Context: CustomStringConvertible {
@inlinable
public var description : String {
var ms = "<Context[\(id.id)]:"
if elements.isEmpty { ms += " EMPTY" }
else if elements.count == 1 { ms += " \(elements[0])" }
else { ms += " \(elements)" }
ms += ">"
return ms
}
}
extension Block.Context.Element: CustomStringConvertible {
@inlinable
public var description : String {
switch self {
case .text (let text) : return text.description
case .image(let image) : return image.description
}
}
}
| 23.117647 | 73 | 0.583545 |
03574c62496676d2903d1c440612a83d3ba3c5b8 | 2,288 | //
// SceneDelegate.swift
// LableWhisperer
//
// Created by asc on 11/12/21.
//
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let _ = (scene as? UIWindowScene) else { return }
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| 43.169811 | 147 | 0.71285 |
3847619aa1e01290175ef4b71979258bd60b8e3c | 94 | public protocol SpeculidConfigurationProtocol {
var mode: SpeculidApplicationMode { get }
}
| 23.5 | 47 | 0.808511 |
db55fc8ba938f0c3ca7c79529e584addad1e0155 | 3,488 | import UIKit
//: # Lesson 2 Exercises
//: ## Optionals
//: ### Exercise 1
//: When retrieving a value from a dictionary, Swift returns an optional.
//:
//: 1a) The variable, director, is an optional type. Its value cannot be used until it is unwrapped. Use `if let` to carefully unwrap the value returned by `moviesDict[movie]`
var moviesDict:Dictionary = [ "Star Wars":"George Lucas", "Point Break":"Kathryn Bigelow"]
var movie = "Star Wars"
var director = moviesDict[movie]
//: 1b) Test your code by inserting different values for the variable `movie`.
if let director = moviesDict[movie] {
print(director)
} else {
print("nil")
}
//: ### Exercise 2
//: The LoginViewController class below needs a UITextField to hold a user's name. Declare a variable for this text field as a property of the class LoginViewController. Keep in mind that the textfield property will not be initialized until after the view controller is constructed.
class LoginViewController: UIViewController {
var userNameTextField:UITextField!
}
//: ### Exercise 3
//: The Swift Int type has an initializer that takes a string as a parameter and returns an optional of type Int?.
//:
//: 3a) Finish the code below by safely unwrapping the constant, `number`.
var numericalString = "three"
var number = Int(numericalString)
//TODO: Unwrap number to make the following print statement more readable.
if let number = number {
print("\(number) is the magic number.")
} else {
print("Not a number")
}
//: 3b) Change the value of numericalString to "three" and execute the playground again.
//: ### Exercise 4
//: The class UIViewController has a property called tabBarController. The tabBarController property is an optional of type UITabBarController?. The tabBarController itself holds a tabBar as a property. Complete the code below by filling in the appropriate use of optional chaining to access the tab bar property.
var viewController = UIViewController()
if let tabBar = viewController.tabBarController?.tabBar {
print("Here's the tab bar.")
} else {
print("No tab bar controller found.")
}
//: ### Exercise 5
//: Below is a dictionary of paintings and artists.
//:
//: 5a) The variable, artist, is an optional type. Its value cannot be used until it is unwrapped. Use `if let` to carefully unwrap the value returned by `paintingDict[painting]`.
var paintingDict:Dictionary = [ "Guernica":"Picasso", "Mona Lisa": "da Vinci", "No. 5": "Pollock"]
var painting = "Guernica"
if let artist = paintingDict[painting] {
print ("The artist is \(artist)")
} else {
print("nil")
}
//: 5b) Test your code by inserting different values for the variable `painting`.
//: ### Exercise 6
//: Set the width of the cancel button below. Notice that the cancelButton variable is declared as an implicitly unwrapped optional.
var anotherViewController = UIViewController()
var cancelButton: UIBarButtonItem!
cancelButton = UIBarButtonItem()
// TODO: Set the width of the cancel button.
cancelButton.width = 55
//: ### Exercise 7
//: The class UIViewController has a property called parent. The parent property is an optional of type UIViewController?. We can't always be sure that a given view controller has a parent view controller. Safely unwrap the parent property below using if let.
var childViewController = UIViewController()
// TODO: Safely unwrap childViewController.parent
if let parent = childViewController.parent {
print("Got it!")
} else {
print("Don't got it!")
}
| 44.717949 | 314 | 0.739392 |
ab522774bc3f8d38b66c443cee0614d99804c2e5 | 3,088 | //
// CGPointExtensions.swift
// SSTests
//
// Created by Omar Albeik on 07/12/2016.
// Copyright © 2016 Omar Albeik. All rights reserved.
//
#if os(macOS)
import Cocoa
#else
import UIKit
#endif
// MARK: - Methods
public extension CGPoint {
/// SwifterSwift: Distance from another CGPoint.
///
/// - Parameter point: CGPoint to get distance from.
/// - Returns: Distance between self and given CGPoint.
public func distance(from point: CGPoint) -> CGFloat {
return CGPoint.distance(from: self, to: point)
}
/// SwifterSwift: Distance between two CGPoints.
///
/// - Parameters:
/// - point1: first CGPoint.
/// - point2: second CGPoint.
/// - Returns: distance between the two given CGPoints.
public static func distance(from point1: CGPoint, to point2: CGPoint) -> CGFloat {
// http://stackoverflow.com/questions/6416101/calculate-the-distance-between-two-cgpoints
return sqrt(pow(point2.x - point1.x, 2) + pow(point2.y - point1.y, 2))
}
}
// MARK: - Operators
public extension CGPoint {
/// SwifterSwift: Add two CGPoints.
///
/// - Parameters:
/// - lhs: CGPoint to add to.
/// - rhs: CGPoint to add.
/// - Returns: result of addition of the two given CGPoints.
public static func + (lhs: CGPoint, rhs: CGPoint) -> CGPoint {
return CGPoint(x: lhs.x + rhs.x, y: lhs.y + rhs.y)
}
/// SwifterSwift: Add a CGPoints to self.
///
/// - Parameters:
/// - lhs: self
/// - rhs: CGPoint to add.
public static func += (lhs: inout CGPoint, rhs: CGPoint) {
lhs = lhs + rhs
}
/// SwifterSwift: Subtract two CGPoints.
///
/// - Parameters:
/// - lhs: CGPoint to subtract from.
/// - rhs: CGPoint to subtract.
/// - Returns: result of subtract of the two given CGPoints.
public static func - (lhs: CGPoint, rhs: CGPoint) -> CGPoint {
return CGPoint(x: lhs.x - rhs.x, y: lhs.y - rhs.y)
}
/// SwifterSwift: Subtract a CGPoints from self.
///
/// - Parameters:
/// - lhs: self
/// - rhs: CGPoint to subtract.
public static func -= (lhs: inout CGPoint, rhs: CGPoint) {
lhs = lhs + rhs
}
/// SwifterSwift: Multiply a CGPoint with a scalar
///
/// - Parameters:
/// - point: CGPoint to multiply.
/// - scalar: scalar value.
/// - Returns: result of multiplication of the given CGPoint with the scalar.
public static func * (point: CGPoint, scalar: CGFloat) -> CGPoint {
return CGPoint(x: point.x * scalar, y: point.y * scalar)
}
/// SwifterSwift: Multiply self with a scalar
///
/// - Parameters:
/// - point: self.
/// - scalar: scalar value.
/// - Returns: result of multiplication of the given CGPoint with the scalar.
public static func *= (point: inout CGPoint, scalar: CGFloat) {
point = point * scalar
}
/// SwifterSwift: Multiply a CGPoint with a scalar
///
/// - Parameters:
/// - scalar: scalar value.
/// - point: CGPoint to multiply.
/// - Returns: result of multiplication of the given CGPoint with the scalar.
public static func * (scalar: CGFloat, point: CGPoint) -> CGPoint {
return CGPoint(x: point.x * scalar, y: point.y * scalar)
}
}
| 27.087719 | 91 | 0.645725 |
c19a157c62fd5578fdb68363d9f9d72804bb87db | 1,244 | /*
Copyright 2017 Ryuichi Intellectual Property and the Yanagiba project contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import XCTest
@testable import Source
class SourceRangeTests : XCTestCase {
func testDummyRange() {
let range = SourceRange.EMPTY
XCTAssertEqual(range, SourceRange(start: .DUMMY, end: .DUMMY))
XCTAssertEqual(range.start.identifier, "dummy")
XCTAssertEqual(range.start.line, 0)
XCTAssertEqual(range.start.column, 0)
XCTAssertEqual(range.end.identifier, "dummy")
XCTAssertEqual(range.end.line, 0)
XCTAssertEqual(range.end.column, 0)
XCTAssertEqual(range.description, "dummy:0:0-0:0")
}
static var allTests = [
("testDummyRange", testDummyRange),
]
}
| 32.736842 | 85 | 0.737942 |
abe5534d2d4c5225008bc6df2641eb93e1a85571 | 5,332 | /*
THIS FILE WAS AUTOGENERATED! DO NOT EDIT!
file to edit: 00_load_data.ipynb
*/
import Foundation
import Just
import Path
public func shellCommand(_ launchPath: String, _ arguments: [String]) -> String?
{
let task = Process()
task.executableURL = URL.init(fileURLWithPath:launchPath)
task.arguments = arguments
let pipe = Pipe()
task.standardOutput = pipe
do {try task.run()} catch {print("Unexpected error: \(error).")}
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output = String(data: data, encoding: String.Encoding.utf8)
return output
}
public func downloadFile(_ url: String, dest: String?=nil, force: Bool=false){
let dest_name = (dest ?? (Path.cwd/url.split(separator: "/").last!).string)
let url_dest = URL.init(fileURLWithPath: (dest ?? (Path.cwd/url.split(separator: "/").last!).string))
if (force || !Path(dest_name)!.exists){
print("Downloading \(url)...")
if let cts = Just.get(url).content{
do {try cts.write(to: URL.init(fileURLWithPath:dest_name))}
catch {print("Can't write to \(url_dest).\n\(error)")}
} else {print("Can't reach \(url)")}
}
}
import TensorFlow
protocol ConvertableFromByte {
init(_ d:UInt8)
}
extension Float : ConvertableFromByte{}
extension Int32 : ConvertableFromByte{}
func loadMNIST<T:ConvertableFromByte & TensorFlowScalar>(training: Bool, labels: Bool, path: Path, flat: Bool) -> Tensor<T> {
let split = training ? "train" : "t10k"
let kind = labels ? "labels" : "images"
let batch = training ? Int32(60000) : Int32(10000)
let shape: TensorShape = labels ? [batch] : (flat ? [batch, 784] : [batch, 28, 28])
let dropK = labels ? 8 : 16
let baseUrl = "http://yann.lecun.com/exdb/mnist/"
let fname = split + "-" + kind + "-idx\(labels ? 1 : 3)-ubyte"
let file = path/fname
if !file.exists {
downloadFile("\(baseUrl)\(fname).gz", dest:(path/"\(fname).gz").string)
_ = shellCommand("/bin/gunzip", ["-fq", (path/"\(fname).gz").string])
}
let data = try! Data.init(contentsOf: URL.init(fileURLWithPath: file.string)).dropFirst(dropK)
if labels { return Tensor(data.map(T.init)) }
else { return Tensor(data.map(T.init)).reshaped(to: shape)}
}
public func loadMNIST(path:Path, flat:Bool = false) -> (Tensor<Float>, Tensor<Int32>, Tensor<Float>, Tensor<Int32>) {
try! path.mkdir(.p)
return (
loadMNIST(training: true, labels: false, path: path, flat: flat) / 255.0,
loadMNIST(training: true, labels: true, path: path, flat: flat),
loadMNIST(training: false, labels: false, path: path, flat: flat) / 255.0,
loadMNIST(training: false, labels: true, path: path, flat: flat)
)
}
public let mnistPath = Path.home/".fastai"/"data"/"mnist_tst"
import Dispatch
public func time(_ function: () -> ()) {
let start = DispatchTime.now()
function()
let end = DispatchTime.now()
let nanoseconds = Double(end.uptimeNanoseconds - start.uptimeNanoseconds)
let milliseconds = nanoseconds / 1e6
print("\(milliseconds) ms")
}
public func time(repeating: Int, _ function: () -> ()) {
function()
var times:[Double] = []
for _ in 1...repeating{
let start = DispatchTime.now()
function()
let end = DispatchTime.now()
let nanoseconds = Double(end.uptimeNanoseconds - start.uptimeNanoseconds)
let milliseconds = nanoseconds / 1e6
times.append(milliseconds)
}
print("\(times.reduce(0.0, +)/Double(times.count)) ms")
}
public func notebookToScript(fname: String){
let url_fname = URL.init(fileURLWithPath: fname)
let last = fname.lastPathComponent
let out_fname = (url_fname.deletingLastPathComponent().appendingPathComponent("FastaiNotebooks", isDirectory: true)
.appendingPathComponent("Sources", isDirectory: true)
.appendingPathComponent("FastaiNotebooks", isDirectory: true).appendingPathComponent(last)
.deletingPathExtension().appendingPathExtension("swift"))
do{
let data = try Data.init(contentsOf: url_fname)
let jsonData = try! JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String: Any]
let cells = jsonData["cells"] as! [[String:Any]]
var module = """
/*
THIS FILE WAS AUTOGENERATED! DO NOT EDIT!
file to edit: \(fname.lastPathComponent)
*/
"""
for cell in cells{
if let source = cell["source"] as? [String]{
if source.isEmpty {continue}
if source[0].range(of: #"^\s*//\s*export\s*$"#, options: .regularExpression) != nil{
module.append("\n" + source[1...].joined() + "\n")
}
}
}
try? module.write(to: out_fname, atomically: false, encoding: .utf8)
} catch {print("Can't read the content of \(fname)")}
}
public func exportNotebooks(_ path: Path){
for entry in try! path.ls(){
if entry.kind == Entry.Kind.file{
if entry.path.basename().range(of: #"^\d*_.*ipynb$"#, options: .regularExpression) != nil {
print("Converting \(entry.path.basename())")
notebookToScript(fname: entry.path.basename())
}
}
}
}
| 37.286713 | 125 | 0.626594 |
26c82d6c72bffdb0d05282386b0ef9c209c725ea | 1,746 | //
// DrawTimerBarView.swift
// drawAI
//
// Created by Alessandro Negrão on 25/10/21.
//
import UIKit
protocol DrawTimerBarDelegate: AnyObject {
func didFinishTime()
}
class DrawTimerBarView: ANView {
private var timerValue: Double = 1.0
private var progressLayer = CAShapeLayer()
weak var delegate: DrawTimerBarDelegate?
var progress: CGFloat = 1.0 {
didSet { setNeedsDisplay() }
}
override func awakeFromNib() {
backgroundColor = AppColors.primaryColor
}
override init(frame: CGRect) {
super.init(frame: frame)
layer.addSublayer(progressLayer)
}
required init?(coder: NSCoder) {
super.init(coder: coder)
layer.addSublayer(progressLayer)
}
override func draw(_ rect: CGRect) {
let backgroundMask: CAShapeLayer = CAShapeLayer()
backgroundMask.path = UIBezierPath(roundedRect: rect, cornerRadius: rect.height * 0.4).cgPath
layer.mask = backgroundMask
let progressRect = CGRect(origin: .zero, size: CGSize(width: rect.width * progress, height: rect.height))
progressLayer.frame = progressRect
progressLayer.backgroundColor = AppColors.accentColor.cgColor
layer.addSublayer(progressLayer)
}
func startTimer() {
Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true){
[weak self] timer in
guard let self = self else { return }
if self.timerValue > 0 {
self.timerValue -= 0.01
self.progress = self.timerValue
} else {
timer.invalidate()
self.delegate?.didFinishTime()
}
}
}
}
| 26.861538 | 113 | 0.607102 |
3a3136d762cbea5f878a98f045af5aad3de7e9a9 | 2,237 | //
// UIViewController+JX.swift
// JXPhotoBrowser
//
// Created by JiongXing on 2018/10/14.
//
import Foundation
import UIKit
extension UIViewController: JXNamespaceWrappable {}
extension JXTypeWrapperProtocol where JXWrappedType == UIViewController {
/// Returns the current application's top most view controller.
public static var topMost: UIViewController? {
var rootViewController: UIViewController?
for window in UIApplication.shared.windows where !window.isHidden {
if let windowRootViewController = window.rootViewController {
rootViewController = windowRootViewController
break
}
}
return self.topMost(of: rootViewController)
}
/// Returns the top most view controller from given view controller's stack.
public static func topMost(of viewController: UIViewController?) -> UIViewController? {
// presented view controller
if let presentedViewController = viewController?.presentedViewController {
return self.topMost(of: presentedViewController)
}
// UITabBarController
if let tabBarController = viewController as? UITabBarController,
let selectedViewController = tabBarController.selectedViewController {
return self.topMost(of: selectedViewController)
}
// UINavigationController
if let navigationController = viewController as? UINavigationController,
let visibleViewController = navigationController.visibleViewController {
return self.topMost(of: visibleViewController)
}
// UIPageController
if let pageViewController = viewController as? UIPageViewController,
pageViewController.viewControllers?.count == 1 {
return self.topMost(of: pageViewController.viewControllers?.first)
}
// child view controller
for subview in viewController?.view?.subviews ?? [] {
if let childViewController = subview.next as? UIViewController {
return self.topMost(of: childViewController)
}
}
return viewController
}
}
| 36.080645 | 91 | 0.664283 |
eb3749fcf1a67449f39e5903f0511e85c7c1cc9f | 68 | import Foundation
enum FormatError: Error {
case stringError
}
| 11.333333 | 25 | 0.75 |
4829cf1c3baec0fcd6d704b58d984daa744f511a | 346 | //
// EmptyReuseView.swift
// musicSheet
//
// Created by Jz D on 2020/8/24.
// Copyright © 2020 Jz D. All rights reserved.
//
import UIKit
class EmptyReuseView: UICollectionReusableView {
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
backgroundColor = .white
}
}
| 16.47619 | 48 | 0.624277 |
69dcb86b4e864ea1148b4c29a687eb5c54651023 | 8,755 | //
// Infallible+Tests.swift
// Tests
//
// Created by Shai Mishali on 11/20/20.
// Copyright © 2020 Krunoslav Zaher. All rights reserved.
//
import RxSwift
import RxCocoa
import RxRelay
import RxTest
import XCTest
class InfallibleTest: RxTest { }
extension InfallibleTest {
func testAsInfallible_OnErrorJustReturn() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
.next(300, 9),
.next(340, 13),
.next(360, 111),
.error(390, testError),
.next(480, 320),
])
let inf = xs.asInfallible(onErrorJustReturn: 600)
let observer = scheduler.createObserver(Int.self)
_ = inf.bind(to: observer)
scheduler.start()
XCTAssertEqual(observer.events, [
.next(300, 9),
.next(340, 13),
.next(360, 111),
.next(390, 600),
.completed(390)
])
}
func testAsInfallible_OnErrorFallbackTo() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
.next(300, 9),
.next(340, 13),
.next(360, 111),
.error(390, testError),
.next(480, 320),
])
let inf = xs.asInfallible(onErrorFallbackTo: Infallible<Int>.of(1, 2))
let observer = scheduler.createObserver(Int.self)
_ = inf.bind(to: observer)
scheduler.start()
XCTAssertEqual(observer.events, [
.next(300, 9),
.next(340, 13),
.next(360, 111),
.next(390, 1),
.next(390, 2),
.completed(390)
])
}
func testAsInfallible_OnErrorRecover() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
.next(300, 9),
.next(340, 13),
.next(360, 111),
.error(390, testError),
.next(480, 320),
])
let ys = scheduler.createHotObservable([
.next(500, 25),
.next(600, 33),
.completed(620)
])
let inf = xs.asInfallible(onErrorRecover: { _ in ys.asInfallible(onErrorJustReturn: -1) })
let observer = scheduler.createObserver(Int.self)
_ = inf.bind(to: observer)
scheduler.start()
XCTAssertEqual(observer.events, [
.next(300, 9),
.next(340, 13),
.next(360, 111),
.next(500, 25),
.next(600, 33),
.completed(620)
])
}
func testAsInfallible_BehaviourRelay() {
let scheduler = TestScheduler(initialClock: 0)
let xs = BehaviorRelay<Int>(value: 0)
let ys = scheduler.createHotObservable([
.next(500, 25),
.next(600, 33)
])
let inf = xs.asInfallible()
let observer = scheduler.createObserver(Int.self)
_ = inf.bind(to: observer)
_ = ys.bind(to: xs)
scheduler.start()
XCTAssertEqual(observer.events, [
.next(0, 0),
.next(500, 25),
.next(600, 33)
])
}
func testAsInfallible_PublishRelay() {
let scheduler = TestScheduler(initialClock: 0)
let xs = PublishRelay<Int>()
let ys = scheduler.createHotObservable([
.next(500, 25),
.next(600, 33)
])
let inf = xs.asInfallible()
let observer = scheduler.createObserver(Int.self)
_ = inf.bind(to: observer)
_ = ys.bind(to: xs)
scheduler.start()
XCTAssertEqual(observer.events, [
.next(500, 25),
.next(600, 33)
])
}
func testAsInfallible_ReplayRelay() {
let scheduler = TestScheduler(initialClock: 0)
let xs = ReplayRelay<Int>.create(bufferSize: 2)
let ys = scheduler.createHotObservable([
.next(500, 25),
.next(600, 33)
])
let inf = xs.asInfallible()
let observer = scheduler.createObserver(Int.self)
_ = inf.bind(to: observer)
_ = ys.bind(to: xs)
scheduler.start()
XCTAssertEqual(observer.events, [
.next(500, 25),
.next(600, 33)
])
}
func testAnonymousInfallible_detachesOnDispose() {
var observer: ((InfallibleEvent<Int>) -> Void)!
let a = Infallible.create { o in
observer = o
return Disposables.create()
} as Infallible<Int>
var elements = [Int]()
let d = a.subscribe(onNext: { n in
elements.append(n)
})
XCTAssertEqual(elements, [])
observer(.next(0))
XCTAssertEqual(elements, [0])
d.dispose()
observer(.next(1))
XCTAssertEqual(elements, [0])
}
func testAnonymousInfallible_detachesOnComplete() {
var observer: ((InfallibleEvent<Int>) -> Void)!
let a = Infallible.create { o in
observer = o
return Disposables.create()
} as Infallible<Int>
var elements = [Int]()
_ = a.subscribe(onNext: { n in
elements.append(n)
})
XCTAssertEqual(elements, [])
observer(.next(0))
XCTAssertEqual(elements, [0])
observer(.completed)
observer(.next(1))
XCTAssertEqual(elements, [0])
}
}
extension InfallibleTest {
func testAsInfallible_never() {
let scheduler = TestScheduler(initialClock: 0)
let xs: Infallible<Int> = Infallible.never()
let res = scheduler.start { xs }
let correct: [Recorded<Event<Int>>] = []
XCTAssertEqual(res.events, correct)
}
#if TRACE_RESOURCES
func testAsInfallibleReleasesResourcesOnComplete() {
_ = Observable<Int>.empty().asInfallible(onErrorJustReturn: 0).subscribe()
}
func testAsInfallibleReleasesResourcesOnError() {
_ = Observable<Int>.empty().asInfallible(onErrorJustReturn: 0).subscribe()
}
#endif
}
// MARK: - Subscribe with object
extension InfallibleTest {
func testSubscribeWithNext() {
var testObject: TestObject! = TestObject()
let scheduler = TestScheduler(initialClock: 0)
var values = [String]()
var disposed: UUID?
var completed: UUID?
let observable = scheduler.createColdObservable([
.next(10, 0),
.next(20, 1),
.next(30, 2),
.next(40, 3),
.completed(50)
])
let inf = observable.asInfallible(onErrorJustReturn: -1)
_ = inf
.subscribe(
with: testObject,
onNext: { object, value in values.append(object.id.uuidString + "\(value)") },
onCompleted: { completed = $0.id },
onDisposed: { disposed = $0.id }
)
scheduler.start()
let uuid = testObject.id
XCTAssertEqual(values, [
uuid.uuidString + "0",
uuid.uuidString + "1",
uuid.uuidString + "2",
uuid.uuidString + "3"
])
XCTAssertEqual(completed, uuid)
XCTAssertEqual(disposed, uuid)
XCTAssertNotNil(testObject)
testObject = nil
XCTAssertNil(testObject)
}
func testSubscribeWithError() {
var testObject: TestObject! = TestObject()
let scheduler = TestScheduler(initialClock: 0)
var values = [String]()
var disposed: UUID?
var completed: UUID?
let observable = scheduler.createColdObservable([
.next(10, 0),
.next(20, 1),
.error(30, testError),
.next(40, 3),
])
let inf = observable.asInfallible(onErrorJustReturn: -1)
_ = inf
.subscribe(
with: testObject,
onNext: { object, value in values.append(object.id.uuidString + "\(value)") },
onCompleted: { completed = $0.id },
onDisposed: { disposed = $0.id }
)
scheduler.start()
let uuid = testObject.id
XCTAssertEqual(values, [
uuid.uuidString + "0",
uuid.uuidString + "1",
uuid.uuidString + "-1"
])
XCTAssertEqual(completed, uuid)
XCTAssertEqual(disposed, uuid)
XCTAssertNotNil(testObject)
testObject = nil
XCTAssertNil(testObject)
}
}
private class TestObject: NSObject {
var id = UUID()
}
| 25.979228 | 98 | 0.52964 |
1646434524dbc8cab18dcffd598562c0aee6c48c | 1,812 | //
// BeNilSpec.swift
// Sleipnir
//
// Created by Artur Termenji on 7/16/14.
// Copyright (c) 2014 railsware. All rights reserved.
//
import Foundation
class BeNilSpec : SleipnirSpec {
var beNilSpec : () = describe("BeNil matcher") {
context("value") {
var value: Int?
describe("which is nil") {
beforeEach {
value = nil
}
describe("positive match") {
it("should pass") {
expect(value).to(beNil())
}
}
describe("negative match") {
it("should fail with a sensible failure message") {
let failureMessage = "Expected <nil> to not be nil"
expectFailureWithMessage(failureMessage) {
expect(value).toNot(beNil())
}
}
}
}
describe("which is not nil") {
beforeEach {
value = 3
}
describe("positive match") {
it("should fail with a sensible failure message") {
let failureMessage = "Expected <3> to be nil"
expectFailureWithMessage(failureMessage) {
expect(value).to(beNil())
}
}
}
describe("negative match") {
it("should pass") {
expect(value).toNot(beNil())
}
}
}
}
}
} | 28.761905 | 75 | 0.370861 |
7521f8bab56026d86480f1aba131e9eb2070f02c | 7,660 | //
// LogViewHelper.swift
// TTBaseUIKit
//
// Created by Tuan Truong Quang on 9/11/19.
// Copyright © 2019 Truong Quang Tuan. All rights reserved.
//
import Foundation
import UIKit
open class LogViewHelper {
fileprivate var viewModel:LogTrackingViewModel = LogTrackingViewModel()
public static let share = LogViewHelper()
private let concurrentQueue = DispatchQueue(label: "ConcurrentQueue", attributes: .concurrent, target: nil)
private init(){}
public var didTouchLogButtonHandle:( () -> ())?
public var didTouchReportlHandle:( () -> ())?
public var didTouchSettinglHandle:( () -> ())?
public var didSendCurrentRequest:( (_ request:String) -> ())?
public var didSendCurrentResponse:( (_ response:String) -> ())?
public func config(withDes des:String, isStartAppToShow:Bool) -> LogViewHelper {
self.viewModel.displayString = des
self.viewModel.isStartAppToShow = isStartAppToShow
return self
}
}
//MARK:// For Base Funcs
extension LogViewHelper {
public func getLogs() -> [LogViewModel] {
var logs: [LogViewModel] = []
self.concurrentQueue.sync { // reading always has to be sync!
logs = self.viewModel.logs.reversed()
}
return logs
}
public func add(withLog log:LogViewModel) {
self.concurrentQueue.async(flags: .barrier) {
if self.viewModel.logs.count >= 70 { self.viewModel.logs = [] }
self.viewModel.logs.append(log)
}
}
public func resetLogs() {
self.viewModel.logs = []
}
}
//MARK:// For Base View
extension LogViewHelper {
public func onShow() {
DispatchQueue.main.async {
if let windown = UIApplication.shared.keyWindow {
let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(self.addAccountLongPressGesture(_:)))
windown.addGestureRecognizer(longPressRecognizer)
}
}
}
@objc fileprivate func addAccountLongPressGesture(_ sender: UILongPressGestureRecognizer)
{
if sender.state == .ended {
if self.viewModel.isShow { return }
DispatchQueue.main.async { [weak self] in guard let strongSelf = self else { return }
let showLogVC = OptionLogPresentViewController(with: "IS DEV MODE", subTitle: strongSelf.viewModel.displayString)
if !strongSelf.viewModel.isShow {
strongSelf.viewModel.isShow = true
UIApplication.topViewController()?.present(showLogVC, animated: true, completion: {
strongSelf.viewModel.isShow = true
})
}
showLogVC.didLoad? = { [weak self] in guard let strongSelf = self else { return }
strongSelf.viewModel.isShow = true
}
showLogVC.onDissmissViewHandler = { [weak self] in guard let strongSelf = self else { return }
strongSelf.viewModel.isShow = false
}
showLogVC.showLogButton.onTouchHandler = { [weak self] _ in guard let strongSelf = self else { return }
showLogVC.dismiss(animated: true, completion: {
strongSelf.didTouchLogButtonHandle?()
strongSelf.viewModel.isShow = false
DispatchQueue.main.async {
let logVC:LogTrackingTableViewController = LogTrackingTableViewController()
UIApplication.topViewController()?.presentDef(vc: logVC, type: .overFullScreen)
logVC.didTouchTitleLabelHandle = { request in
strongSelf.didSendCurrentRequest?(request)
}
logVC.didTouchSubLabelHandle = { response in
strongSelf.didSendCurrentResponse?(response)
}
}
})
}
showLogVC.showReportBugButton.onTouchHandler = { [weak self] _ in guard let strongSelf = self else { return }
showLogVC.dismiss(animated: true, completion: {
strongSelf.didTouchReportlHandle?()
strongSelf.viewModel.isShow = false
})
}
showLogVC.showSettingButton.onTouchHandler = { [weak self] _ in guard let strongSelf = self else { return }
showLogVC.dismiss(animated: true, completion: {
strongSelf.didTouchSettinglHandle?()
strongSelf.viewModel.isShow = false
})
}
}
}
}
}
class OptionLogPresentViewController: TTCoverVerticalViewController {
let label:TTBaseUILabel = TTBaseUILabel(withType: .TITLE, text: "IS DEV MODE", align: .left)
let subLabel:TTBaseUILabel = TTBaseUILabel(withType: .SUB_TITLE, text: "View log by json or report bugs", align: .left)
let showLogButton:TTBaseUIButton = TTBaseUIButton(textString: "SHOW LOG FILE", type: .DEFAULT, isSetSize: false)
let showReportBugButton:TTBaseUIButton = TTBaseUIButton(textString: "REPORT BUG", type: .WARRING, isSetSize: false)
let showSettingButton:TTBaseUIButton = TTBaseUIButton(textString: "SETTING", type: .WARRING, isSetSize: false)
init(with title:String, subTitle:String) {
super.init()
self.label.setText(text: title)
self.subLabel.setText(text: subTitle)
}
public var didLoad:( () -> ())?
override func viewDidLoad() {
super.viewDidLoad()
self.didLoad?()
}
override func updateBaseUI() {
super.updateBaseUI()
self.bgView = UIColor.black.withAlphaComponent(0.8)
self.view.backgroundColor = UIColor.clear
self.view.addSubview(self.label)
self.view.addSubview(self.subLabel)
self.view.addSubview(self.showLogButton)
self.view.addSubview(self.showReportBugButton)
self.view.addSubview(self.showSettingButton)
self.label.setVerticalContentHuggingPriority()
.setLeadingAnchor(constant: 8).setTrailingAnchor(constant: 8)
.setTopAnchor(constant: 10)
self.subLabel.setVerticalContentHuggingPriority()
.setLeadingAnchor(constant: 8).setTrailingAnchor(constant: 8)
.setTopAnchorWithAboveView(nextToView: self.label, constant: 10)
self.showLogButton.setTopAnchorWithAboveView(nextToView: self.subLabel, constant: 30)
.setLeadingAnchor(constant: 8).setTrailingAnchor(constant: 8)
.setHeightAnchor(constant: 35)
self.showReportBugButton.setTopAnchorWithAboveView(nextToView: self.showLogButton, constant: 8)
.setLeadingAnchor(constant: 8).setTrailingAnchor(constant: 8)
.setHeightAnchor(constant: 35)
self.showSettingButton.setTopAnchorWithAboveView(nextToView: self.showReportBugButton, constant: 8)
.setLeadingAnchor(constant: 8).setTrailingAnchor(constant: 8)
.setHeightAnchor(constant: 35)
.setBottomAnchor(constant: 20, isMarginsGuide: true, priority: .defaultHigh)
}
}
| 39.282051 | 144 | 0.591253 |
87571fa5b1e094bd1211e9235e4fcee7d69d49f8 | 1,391 | //
// UIButton-Extension.swift
// YoungWeibo
//
// Created by Young on 2016/12/10.
// Copyright © 2016年 杨羽. All rights reserved.
//
import UIKit
extension UIButton {
class func creatButton(_ iamgeName : String , bgImageName : String) -> UIButton {
let btn = UIButton()
btn.setImage(UIImage.init(named: iamgeName), for: .normal)
btn.setImage(UIImage.init(named: iamgeName + "_highlighted"), for: .highlighted)
btn.setBackgroundImage(UIImage.init(named: bgImageName), for: .normal)
btn.setBackgroundImage(UIImage.init(named: bgImageName + "_highlighted"), for: .highlighted)
btn.sizeToFit()
return btn
}
/** 构造函数 */
convenience init(iamgeName : String , bgImageName : String) {
self.init()
setImage(UIImage.init(named: iamgeName), for: .normal)
setImage(UIImage.init(named: iamgeName + "_highlighted"), for: .highlighted)
setBackgroundImage(UIImage.init(named: bgImageName), for: .normal)
setBackgroundImage(UIImage.init(named: bgImageName + "_highlighted"), for: .highlighted)
sizeToFit()
}
convenience init(bgColor : UIColor , fontNum : CGFloat , title : String) {
self.init()
backgroundColor = bgColor
titleLabel?.font = UIFont.systemFont(ofSize: fontNum)
setTitle(title, for: .normal)
}
}
| 32.348837 | 100 | 0.642703 |
236df7bb0dbfaa164dbe61627bef21dce12085b5 | 1,947 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Hummingbird server framework project
//
// Copyright (c) 2021-2021 the Hummingbird authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See hummingbird/CONTRIBUTORS.txt for the list of Hummingbird authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import HummingbirdCore
/// Protocol for encodable object that can generate a response. The router will encode
/// the response using the encoder stored in `HBApplication.encoder`.
public protocol HBResponseEncodable: Encodable, HBResponseGenerator {}
/// Protocol for codable object that can generate a response
public protocol HBResponseCodable: HBResponseEncodable, Decodable {}
/// Extend ResponseEncodable to conform to ResponseGenerator
extension HBResponseEncodable {
public func response(from request: HBRequest) throws -> HBResponse {
return try request.application.encoder.encode(self, from: request)
}
}
/// Extend Array to conform to HBResponseGenerator
extension Array: HBResponseGenerator where Element: Encodable {}
/// Extend Array to conform to HBResponseEncodable
extension Array: HBResponseEncodable where Element: Encodable {
public func response(from request: HBRequest) throws -> HBResponse {
return try request.application.encoder.encode(self, from: request)
}
}
/// Extend Dictionary to conform to HBResponseGenerator
extension Dictionary: HBResponseGenerator where Key: Encodable, Value: Encodable {}
/// Extend Array to conform to HBResponseEncodable
extension Dictionary: HBResponseEncodable where Key: Encodable, Value: Encodable {
public func response(from request: HBRequest) throws -> HBResponse {
return try request.application.encoder.encode(self, from: request)
}
}
| 38.94 | 86 | 0.709296 |
3882191d5c940dbe118a2930dab00851219918af | 1,393 | //
// AppDelegate.swift
// iOSWriter
//
// Created by Reynaldo on 22/7/21.
// Copyright © 2021 Apple. All rights reserved.
//
import UIKit
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
| 36.657895 | 179 | 0.744436 |
8921748773e83a6f9bc551b71923e4c1086f22a1 | 2,270 | //
// ComposeViewController.swift
// TwitZy
//
// Created by Savannah McCoy on 6/29/16.
// Copyright © 2016 Savannah McCoy. All rights reserved.
//
import UIKit
class ComposeViewController: UIViewController, UITextViewDelegate {
@IBOutlet weak var tweetTextView: UITextView!
@IBOutlet weak var countdownLabel: UILabel!
@IBOutlet weak var didPressTweetButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
self.tweetTextView.delegate = self
self.updateCharacterCount()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func composeCancelAction(sender: AnyObject) {
dismissViewControllerAnimated(true, completion: nil)
}
func updateCharacterCount() {
self.countdownLabel.text = "\((140) - self.tweetTextView.text.characters.count)"
}
func textViewDidChange(textView: UITextView) {
self.updateCharacterCount()
}
@IBAction func didPressTweet(sender: UIButton) {
TwitterClient.Post(tweetTextView.text, success: {
print("YAY!!")
self.dismissViewControllerAnimated(true, completion: nil)
}) { (error) in
print(error)
print("An error occured while posting tweet")
}
}
func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
self.updateCharacterCount()
return textView.text.characters.count + (text.characters.count - range.length) <= 140
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 24.148936 | 119 | 0.617181 |
e0479a41b6e24552a55d38993779a601036f6798 | 1,071 | //
// PyMultipeerHelper.swift
// Pyto
//
// Created by Emma Labbé on 21-01-20.
// Copyright © 2018-2021 Emma Labbé. All rights reserved.
//
import MultiPeer
import UIKit
@objc class PyMultipeerHelper: NSObject, MultiPeerDelegate {
static let delegate = PyMultipeerHelper()
@objc static var data: String?
@objc static func autoConnect() {
MultiPeer.instance.initialize(serviceType: "pyto")
MultiPeer.instance.delegate = delegate
MultiPeer.instance.autoConnect()
}
@objc static func disconnect() {
MultiPeer.instance.disconnect()
}
@objc static func send(_ data: String) {
if !MultiPeer.instance.isConnected {
MultiPeer.instance.autoConnect()
}
MultiPeer.instance.send(data: data.data(using: .utf8) ?? Data(), type: 0)
}
func multiPeer(didReceiveData data: Data, ofType type: UInt32) {
PyMultipeerHelper.data = String(data: data, encoding: .utf8)
}
func multiPeer(connectedDevicesChanged devices: [String]) {}
}
| 26.121951 | 81 | 0.647059 |
cc39ebc030f9976746bdd7f61d3d9fd931de0bf5 | 199 | //
// GroceryListItem+CoreDataClass.swift
// GroceryListSwiftUI
//
// Created by JoshRhee on 3/26/22.
//
//
import Foundation
import CoreData
public class GroceryListItem: NSManagedObject {
}
| 12.4375 | 47 | 0.733668 |
75bd2a08fb53289f0df7765348a438a78d180f5e | 1,405 | //
// AppDelegate.swift
// H4X0R News
//
// Created by jigar on 12/08/20.
// Copyright © 2020 jigar. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
| 36.973684 | 179 | 0.745907 |
2061ece6455f582710a554f48104885de6272e75 | 4,106 | //===-- NumpyConversion.swift ---------------------------------*- swift -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file defines the `ConvertibleFromNumpyArray` protocol for bridging
// `numpy.ndarray`.
//
//===----------------------------------------------------------------------===//
/// The `numpy` Python module.
/// Note: Global variables are lazy, so the following declaration won't produce
// a Python import error until it is first used.
private let np = Python.import("numpy")
/// A type that can be initialized from a `numpy.ndarray` instance represented
/// as a `PythonObject`.
public protocol ConvertibleFromNumpyArray {
init?(numpyArray: PythonObject)
}
/// A type that is bitwise compatible with one or more NumPy scalar types.
public protocol NumpyScalarCompatible {
/// The NumPy scalar types that this type is bitwise compatible with. Must
/// be nonempty.
static var numpyScalarTypes: [PythonObject] { get }
}
extension Bool : NumpyScalarCompatible {
public static let numpyScalarTypes = [np.bool_, Python.bool]
}
extension UInt8 : NumpyScalarCompatible {
public static let numpyScalarTypes = [np.uint8]
}
extension Int8 : NumpyScalarCompatible {
public static let numpyScalarTypes = [np.int8]
}
extension UInt16 : NumpyScalarCompatible {
public static let numpyScalarTypes = [np.uint16]
}
extension Int16 : NumpyScalarCompatible {
public static let numpyScalarTypes = [np.int16]
}
extension UInt32 : NumpyScalarCompatible {
public static let numpyScalarTypes = [np.uint32]
}
extension Int32 : NumpyScalarCompatible {
public static let numpyScalarTypes = [np.int32]
}
extension UInt64 : NumpyScalarCompatible {
public static let numpyScalarTypes = [np.uint64]
}
extension Int64 : NumpyScalarCompatible {
public static let numpyScalarTypes = [np.int64]
}
extension Float : NumpyScalarCompatible {
public static let numpyScalarTypes = [np.float32]
}
extension Double : NumpyScalarCompatible {
public static let numpyScalarTypes = [np.float64]
}
extension Array : ConvertibleFromNumpyArray
where Element : NumpyScalarCompatible {
public init?(numpyArray: PythonObject) {
// Check if input is a `numpy.ndarray` instance.
guard Python.isinstance(numpyArray, np.ndarray) == true else {
return nil
}
// Check if the dtype of the `ndarray` is compatible with the `Element`
// type.
guard Element.numpyScalarTypes.contains(numpyArray.dtype) else {
return nil
}
// Only 1-D `ndarray` instances can be converted to `Array`.
let pyShape = numpyArray.__array_interface__["shape"]
guard let shape = Array<Int>(pyShape) else { return nil }
guard shape.count == 1 else {
return nil
}
// Make sure that the array is contiguous in memory. This does a copy if
// the array is not already contiguous in memory.
let contiguousNumpyArray = np.ascontiguousarray(numpyArray)
guard let ptrVal =
UInt(contiguousNumpyArray.__array_interface__["data"].tuple2.0) else {
return nil
}
guard let ptr = UnsafePointer<Element>(bitPattern: ptrVal) else {
fatalError("numpy.ndarray data pointer was nil")
}
// This code avoids constructing and initialize from `UnsafeBufferPointer`
// because that uses the `init<S : Sequence>(_ elements: S)` initializer,
// which performs unnecessary copying.
let dummyPointer = UnsafeMutablePointer<Element>.allocate(capacity: 1)
let scalarCount = shape.reduce(1, *)
self.init(repeating: dummyPointer.move(), count: scalarCount)
dummyPointer.deallocate()
withUnsafeMutableBufferPointer { buffPtr in
buffPtr.baseAddress!.assign(from: ptr, count: scalarCount)
}
}
}
| 33.382114 | 80 | 0.69435 |
cc828b4d1a6c484a3cfd6fe961fec4fd4cab7022 | 12,904 | //
// DocumentController.swift
//
// CotEditor
// https://coteditor.com
//
// Created by nakamuxu on 2004-12-14.
//
// ---------------------------------------------------------------------------
//
// © 2004-2007 nakamuxu
// © 2014-2019 1024jp
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Cocoa
protocol AdditionalDocumentPreparing: NSDocument {
func didMakeDocumentForExisitingFile(url: URL)
}
final class DocumentController: NSDocumentController {
private(set) lazy var autosaveDirectoryURL: URL = try! FileManager.default.url(for: .autosavedInformationDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: true)
private(set) var accessorySelectedEncoding: String.Encoding?
// MARK: Private Properties
private let transientDocumentLock = NSLock()
private var deferredDocuments = [NSDocument]()
// MARK: -
// MARK: Lifecycle
override init() {
super.init()
self.autosavingDelay = UserDefaults.standard[.autosavingDelay]
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Document Controller Methods
/// automatically inserts Share menu
override var allowsAutomaticShareMenu: Bool {
return true
}
/// open document
override func openDocument(withContentsOf url: URL, display displayDocument: Bool, completionHandler: @escaping (NSDocument?, Bool, Error?) -> Void) {
// obtain transient document if exists
self.transientDocumentLock.lock()
let transientDocument = self.transientDocumentToReplace
if let transientDocument = transientDocument {
transientDocument.isTransient = false
self.deferredDocuments = []
}
self.transientDocumentLock.unlock()
super.openDocument(withContentsOf: url, display: false) { [unowned self] (document, documentWasAlreadyOpen, error) in
assert(Thread.isMainThread)
// invalidate encoding that was set in the open panel
self.accessorySelectedEncoding = nil
if let transientDocument = transientDocument, let document = document as? Document {
self.replaceTransientDocument(transientDocument, with: document)
if displayDocument {
document.makeWindowControllers()
document.showWindows()
}
// display all deferred documents since the transient document has been replaced
for deferredDocument in self.deferredDocuments {
deferredDocument.makeWindowControllers()
deferredDocument.showWindows()
}
self.deferredDocuments = []
} else if displayDocument, let document = document {
if self.deferredDocuments.isEmpty {
// display the document immediately, because the transient document has been replaced.
document.makeWindowControllers()
document.showWindows()
} else {
// defer displaying this document, because the transient document has not yet been replaced.
self.deferredDocuments.append(document)
}
}
completionHandler(document, documentWasAlreadyOpen, error)
}
}
/// open untitled document
override func openUntitledDocumentAndDisplay(_ displayDocument: Bool) throws -> NSDocument {
let document = try super.openUntitledDocumentAndDisplay(displayDocument)
// make document transient when it is an open or reopen event
if self.documents.count == 1, NSAppleEventManager.shared().isOpenEvent {
(document as? Document)?.isTransient = true
}
return document
}
/// instantiates a document located by a URL, of a specified type, and returns it if successful
override func makeDocument(withContentsOf url: URL, ofType typeName: String) throws -> NSDocument {
// [caution] This method may be called from a background thread due to concurrent-opening.
do {
try self.checkOpeningSafetyOfDocument(at: url, typeName: typeName)
} catch {
// ask user for opening file
try DispatchQueue.syncOnMain {
guard self.presentError(error) else { throw CocoaError(.userCancelled) }
}
}
// make document
let document = try super.makeDocument(withContentsOf: url, ofType: typeName)
(document as? AdditionalDocumentPreparing)?.didMakeDocumentForExisitingFile(url: url)
return document
}
/// add document to documentController's list
override func addDocument(_ document: NSDocument) {
// clear the first document's transient status when a second document is added
// -> This happens when the user selects "New" when a transient document already exists.
if self.documents.count == 1,
let firstDocument = self.documents.first as? Document,
firstDocument.isTransient {
firstDocument.isTransient = false
}
super.addDocument(document)
}
/// add encoding menu to open panel
override func beginOpenPanel(_ openPanel: NSOpenPanel, forTypes inTypes: [String]?, completionHandler: @escaping (Int) -> Void) {
let accessoryController = OpenPanelAccessoryController.instantiate(storyboard: "OpenDocumentAccessory")
// initialize encoding menu and set the accessory view
accessoryController.openPanel = openPanel
openPanel.accessoryView = accessoryController.view
// force accessory view visible
openPanel.isAccessoryViewDisclosed = true
// run non-modal open panel
super.beginOpenPanel(openPanel, forTypes: inTypes) { [unowned self] (result: Int) in
if result == NSApplication.ModalResponse.OK.rawValue {
self.accessorySelectedEncoding = accessoryController.selectedEncoding
}
completionHandler(result)
}
}
/// return enability of actions
override func validateUserInterfaceItem(_ item: NSValidatedUserInterfaceItem) -> Bool {
if item.action == #selector(newDocumentAsTab) {
return self.currentDocument != nil
}
return super.validateUserInterfaceItem(item)
}
// MARK: Action Messages
/// open a new document as new window
@IBAction func newDocumentAsWindow(_ sender: Any?) {
let document: NSDocument
do {
document = try self.openUntitledDocumentAndDisplay(false)
} catch {
self.presentError(error)
return
}
DocumentWindow.tabbingPreference = .manual
document.makeWindowControllers()
document.showWindows()
DocumentWindow.tabbingPreference = nil
}
/// open a new document as tab in the existing frontmost window
@IBAction func newDocumentAsTab(_ sender: Any?) {
let document: NSDocument
do {
document = try self.openUntitledDocumentAndDisplay(false)
} catch {
self.presentError(error)
return
}
document.makeWindowControllers()
document.windowControllers.first?.window?.tabbingMode = .preferred
document.showWindows()
}
// MARK: Private Methods
/// transient document to be replaced or nil
private var transientDocumentToReplace: Document? {
guard
self.documents.count == 1,
let document = self.documents.first as? Document,
document.isTransient,
document.windowForSheet?.attachedSheet == nil
else { return nil }
return document
}
/// replace window controllers in documents
private func replaceTransientDocument(_ transientDocument: Document, with document: Document) {
assert(Thread.isMainThread)
for controller in transientDocument.windowControllers {
document.addWindowController(controller)
transientDocument.removeWindowController(controller)
}
transientDocument.close()
// notify accessibility clients about the value replacement of the transient document with opened document
document.textStorage.layoutManagers
.flatMap { $0.textContainers }
.compactMap { $0.textView }
.forEach { NSAccessibility.post(element: $0, notification: .valueChanged) }
}
/// Check file before creating a new document instance.
///
/// - Parameters:
/// - url: The location of the new document object.
/// - typeName: The type of the document.
/// - Throws: `DocumentReadError`
private func checkOpeningSafetyOfDocument(at url: URL, typeName: String) throws {
// check if the file is possible binary
let cfTypeName = typeName as CFString
let binaryTypes = [kUTTypeImage,
kUTTypeAudiovisualContent,
kUTTypeGNUZipArchive,
kUTTypeZipArchive,
kUTTypeBzip2Archive]
if binaryTypes.contains(where: { UTTypeConformsTo(cfTypeName, $0) }),
!UTTypeEqual(cfTypeName, kUTTypeScalableVectorGraphics) // SVG is plain-text (except SVGZ)
{
throw DocumentReadError(kind: .binaryFile(type: typeName), url: url)
}
// check if the file is enorm large
let fileSizeThreshold = UserDefaults.standard[.largeFileAlertThreshold]
if fileSizeThreshold > 0,
let fileSize = (try? url.resourceValues(forKeys: [.fileSizeKey]))?.fileSize,
fileSize > fileSizeThreshold
{
throw DocumentReadError(kind: .tooLarge(size: fileSize), url: url)
}
}
}
// MARK: - Error
private struct DocumentReadError: LocalizedError, RecoverableError {
enum ErrorKind {
case binaryFile(type: String)
case tooLarge(size: Int)
}
let kind: ErrorKind
let url: URL
var errorDescription: String? {
switch self.kind {
case .binaryFile:
return String(format: "The file “%@” doesn’t appear to be text data.".localized,
self.url.lastPathComponent)
case .tooLarge(let size):
return String(format: "The file “%@” has a size of %@.".localized,
self.url.lastPathComponent,
ByteCountFormatter.string(fromByteCount: Int64(size), countStyle: .file))
}
}
var recoverySuggestion: String? {
switch self.kind {
case .binaryFile(let type):
let localizedTypeName = (UTTypeCopyDescription(type as CFString)?.takeRetainedValue() as String?) ?? "unknown file type"
return String(format: "The file is %@.\n\nDo you really want to open the file?".localized, localizedTypeName)
case .tooLarge:
return "Opening such a large file can make the application slow or unresponsive.\n\nDo you really want to open the file?".localized
}
}
var recoveryOptions: [String] {
return ["Open".localized,
"Cancel".localized]
}
func attemptRecovery(optionIndex recoveryOptionIndex: Int) -> Bool {
return (recoveryOptionIndex == 0)
}
}
| 34.137566 | 154 | 0.592917 |
fbebe0e766db800ef8d5f30106fb5fcbae557c7e | 3,465 | //
// AlertViewController.swift
// SwiftCase
//
// Created by 伍腾飞 on 2017/4/30.
// Copyright © 2017年 Shepherd. All rights reserved.
//
import UIKit
class AlertViewController: UIViewController {
@IBOutlet weak var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
self.addSourceCodeItem("alertc")
}
// MARK: UIEvents
@IBAction func showAlert(_ sender: UIButton) {
let alertC = UIAlertController(title: "My Title", message: "This is an alert", preferredStyle: .alert)
let cancel = UIAlertAction(title: "Cancel", style: .cancel) { _ in
print("Cancel. No change")
}
alertC.addAction(cancel)
let confirm = UIAlertAction(title: "Confirm", style: .default) { _ in
print("Confirm. To do something")
}
alertC.addAction(confirm)
let delete = UIAlertAction(title: "Delete", style: .destructive) { _ in
print("Delete. Important!")
}
alertC.addAction(delete)
self.present(alertC, animated: true, completion: {
// your code here
})
}
@IBAction func showActionSheet(_ sender: UIButton) {
let alertC = UIAlertController(title: "Options", message: "Please select one", preferredStyle: .actionSheet)
let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler:nil)
alertC.addAction(cancel)
// self的生命周期 > AlertSheet,不会造成循环引用
let cut = UIAlertAction(title: "Cut Off", style: .default) { _ in
UIPasteboard.general.string = self.label.text
self.label.text = ""
}
alertC.addAction(cut)
let copy = UIAlertAction(title: "Copy", style: .default) { _ in
UIPasteboard.general.string = self.label.text
}
alertC.addAction(copy)
let paste = UIAlertAction(title: "Paste", style: .default) { _ in
self.label.text = UIPasteboard.general.string
}
alertC.addAction(paste)
self.present(alertC, animated: true, completion: nil)
}
@IBAction func showAlertWithForm(_ sender: UIButton) {
let alertC = UIAlertController(title: "Login Login", message: "This is an alert", preferredStyle: .alert)
let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler:nil)
alertC.addAction(cancel)
// 点击空白处收起键盘 可以用第三方切面处理
let login = UIAlertAction(title: "Sign In", style: .default) { _ in
let username = alertC.textFields![0].text
let password = alertC.textFields![1].text
self.loginAction(username, password)
}
alertC.addAction(login)
alertC.addTextField { (textField) in
textField.placeholder = "Your name"
}
alertC.addTextField { (textField) in
textField.placeholder = "Your password"
textField.isSecureTextEntry = true
textField.keyboardType = .decimalPad
}
self.present(alertC, animated: true, completion: nil)
}
func loginAction(_ username: String?, _ password: String?) {
print("username:\(username ?? "") password:\(password ?? "")")
}
}
| 30.130435 | 116 | 0.566522 |
5d5216cb5789b9ca264e9ebfd3ce71dc001caf14 | 11,305 | // SPDX-License-Identifier: MIT
// Copyright © 2018-2021 WireGuard LLC. All Rights Reserved.
import Foundation
extension TunnelConfiguration {
enum ParserState {
case inInterfaceSection
case inPeerSection
case notInASection
}
enum ParseError: Error {
case invalidLine(String.SubSequence)
case noInterface
case multipleInterfaces
case interfaceHasNoPrivateKey
case interfaceHasInvalidPrivateKey(String)
case interfaceHasInvalidListenPort(String)
case interfaceHasInvalidAddress(String)
case interfaceHasInvalidDNS(String)
case interfaceHasInvalidMTU(String)
case interfaceHasUnrecognizedKey(String)
case peerHasNoPublicKey
case peerHasInvalidPublicKey(String)
case peerHasInvalidPreSharedKey(String)
case peerHasInvalidAllowedIP(String)
case peerHasInvalidEndpoint(String)
case peerHasInvalidPersistentKeepAlive(String)
case peerHasInvalidTransferBytes(String)
case peerHasInvalidLastHandshakeTime(String)
case peerHasUnrecognizedKey(String)
case multiplePeersWithSamePublicKey
case multipleEntriesForKey(String)
}
convenience init(fromWgQuickConfig wgQuickConfig: String, called name: String? = nil) throws {
var interfaceConfiguration: InterfaceConfiguration?
var peerConfigurations = [PeerConfiguration]()
let lines = wgQuickConfig.split { $0.isNewline }
var parserState = ParserState.notInASection
var attributes = [String: String]()
for (lineIndex, line) in lines.enumerated() {
var trimmedLine: String
if let commentRange = line.range(of: "#") {
trimmedLine = String(line[..<commentRange.lowerBound])
} else {
trimmedLine = String(line)
}
trimmedLine = trimmedLine.trimmingCharacters(in: .whitespacesAndNewlines)
let lowercasedLine = trimmedLine.lowercased()
if !trimmedLine.isEmpty {
if let equalsIndex = trimmedLine.firstIndex(of: "=") {
// Line contains an attribute
let keyWithCase = trimmedLine[..<equalsIndex].trimmingCharacters(in: .whitespacesAndNewlines)
let key = keyWithCase.lowercased()
let value = trimmedLine[trimmedLine.index(equalsIndex, offsetBy: 1)...].trimmingCharacters(in: .whitespacesAndNewlines)
let keysWithMultipleEntriesAllowed: Set<String> = ["address", "allowedips", "dns"]
if let presentValue = attributes[key] {
if keysWithMultipleEntriesAllowed.contains(key) {
attributes[key] = presentValue + "," + value
} else {
throw ParseError.multipleEntriesForKey(keyWithCase)
}
} else {
attributes[key] = value
}
let interfaceSectionKeys: Set<String> = ["privatekey", "listenport", "address", "dns", "mtu"]
let peerSectionKeys: Set<String> = ["publickey", "presharedkey", "allowedips", "endpoint", "persistentkeepalive"]
if parserState == .inInterfaceSection {
guard interfaceSectionKeys.contains(key) else {
throw ParseError.interfaceHasUnrecognizedKey(keyWithCase)
}
} else if parserState == .inPeerSection {
guard peerSectionKeys.contains(key) else {
throw ParseError.peerHasUnrecognizedKey(keyWithCase)
}
}
} else if lowercasedLine != "[interface]" && lowercasedLine != "[peer]" {
throw ParseError.invalidLine(line)
}
}
let isLastLine = lineIndex == lines.count - 1
if isLastLine || lowercasedLine == "[interface]" || lowercasedLine == "[peer]" {
// Previous section has ended; process the attributes collected so far
if parserState == .inInterfaceSection {
let interface = try TunnelConfiguration.collate(interfaceAttributes: attributes)
guard interfaceConfiguration == nil else { throw ParseError.multipleInterfaces }
interfaceConfiguration = interface
} else if parserState == .inPeerSection {
let peer = try TunnelConfiguration.collate(peerAttributes: attributes)
peerConfigurations.append(peer)
}
}
if lowercasedLine == "[interface]" {
parserState = .inInterfaceSection
attributes.removeAll()
} else if lowercasedLine == "[peer]" {
parserState = .inPeerSection
attributes.removeAll()
}
}
let peerPublicKeysArray = peerConfigurations.map { $0.publicKey }
let peerPublicKeysSet = Set<PublicKey>(peerPublicKeysArray)
if peerPublicKeysArray.count != peerPublicKeysSet.count {
throw ParseError.multiplePeersWithSamePublicKey
}
if let interfaceConfiguration = interfaceConfiguration {
self.init(name: name, interface: interfaceConfiguration, peers: peerConfigurations)
} else {
throw ParseError.noInterface
}
}
func asWgQuickConfig() -> String {
var output = "[Interface]\n"
output.append("PrivateKey = \(interface.privateKey.base64Key)\n")
if let listenPort = interface.listenPort {
output.append("ListenPort = \(listenPort)\n")
}
if !interface.addresses.isEmpty {
let addressString = interface.addresses.map { $0.stringRepresentation }.joined(separator: ", ")
output.append("Address = \(addressString)\n")
}
if !interface.dns.isEmpty || !interface.dnsSearch.isEmpty {
var dnsLine = interface.dns.map { $0.stringRepresentation }
dnsLine.append(contentsOf: interface.dnsSearch)
let dnsString = dnsLine.joined(separator: ", ")
output.append("DNS = \(dnsString)\n")
}
if let mtu = interface.mtu {
output.append("MTU = \(mtu)\n")
}
for peer in peers {
output.append("\n[Peer]\n")
output.append("PublicKey = \(peer.publicKey.base64Key)\n")
if let preSharedKey = peer.preSharedKey?.base64Key {
output.append("PresharedKey = \(preSharedKey)\n")
}
if !peer.allowedIPs.isEmpty {
let allowedIPsString = peer.allowedIPs.map { $0.stringRepresentation }.joined(separator: ", ")
output.append("AllowedIPs = \(allowedIPsString)\n")
}
if let endpoint = peer.endpoint {
output.append("Endpoint = \(endpoint.stringRepresentation)\n")
}
if let persistentKeepAlive = peer.persistentKeepAlive {
output.append("PersistentKeepalive = \(persistentKeepAlive)\n")
}
}
return output
}
private static func collate(interfaceAttributes attributes: [String: String]) throws -> InterfaceConfiguration {
guard let privateKeyString = attributes["privatekey"] else {
throw ParseError.interfaceHasNoPrivateKey
}
guard let privateKey = PrivateKey(base64Key: privateKeyString) else {
throw ParseError.interfaceHasInvalidPrivateKey(privateKeyString)
}
var interface = InterfaceConfiguration(privateKey: privateKey)
if let listenPortString = attributes["listenport"] {
guard let listenPort = UInt16(listenPortString) else {
throw ParseError.interfaceHasInvalidListenPort(listenPortString)
}
interface.listenPort = listenPort
}
if let addressesString = attributes["address"] {
var addresses = [IPAddressRange]()
for addressString in addressesString.splitToArray(trimmingCharacters: .whitespacesAndNewlines) {
guard let address = IPAddressRange(from: addressString) else {
throw ParseError.interfaceHasInvalidAddress(addressString)
}
addresses.append(address)
}
interface.addresses = addresses
}
if let dnsString = attributes["dns"] {
var dnsServers = [DNSServer]()
var dnsSearch = [String]()
for dnsServerString in dnsString.splitToArray(trimmingCharacters: .whitespacesAndNewlines) {
if let dnsServer = DNSServer(from: dnsServerString) {
dnsServers.append(dnsServer)
} else {
dnsSearch.append(dnsServerString)
}
}
interface.dns = dnsServers
interface.dnsSearch = dnsSearch
}
if let mtuString = attributes["mtu"] {
guard let mtu = UInt16(mtuString) else {
throw ParseError.interfaceHasInvalidMTU(mtuString)
}
interface.mtu = mtu
}
return interface
}
private static func collate(peerAttributes attributes: [String: String]) throws -> PeerConfiguration {
guard let publicKeyString = attributes["publickey"] else {
throw ParseError.peerHasNoPublicKey
}
guard let publicKey = PublicKey(base64Key: publicKeyString) else {
throw ParseError.peerHasInvalidPublicKey(publicKeyString)
}
var peer = PeerConfiguration(publicKey: publicKey)
if let preSharedKeyString = attributes["presharedkey"] {
guard let preSharedKey = PreSharedKey(base64Key: preSharedKeyString) else {
throw ParseError.peerHasInvalidPreSharedKey(preSharedKeyString)
}
peer.preSharedKey = preSharedKey
}
if let allowedIPsString = attributes["allowedips"] {
var allowedIPs = [IPAddressRange]()
for allowedIPString in allowedIPsString.splitToArray(trimmingCharacters: .whitespacesAndNewlines) {
guard let allowedIP = IPAddressRange(from: allowedIPString) else {
throw ParseError.peerHasInvalidAllowedIP(allowedIPString)
}
allowedIPs.append(allowedIP)
}
peer.allowedIPs = allowedIPs
}
if let endpointString = attributes["endpoint"] {
guard let endpoint = Endpoint(from: endpointString) else {
throw ParseError.peerHasInvalidEndpoint(endpointString)
}
peer.endpoint = endpoint
}
if let persistentKeepAliveString = attributes["persistentkeepalive"] {
guard let persistentKeepAlive = UInt16(persistentKeepAliveString) else {
throw ParseError.peerHasInvalidPersistentKeepAlive(persistentKeepAliveString)
}
peer.persistentKeepAlive = persistentKeepAlive
}
return peer
}
}
| 44.683794 | 139 | 0.602123 |
e6c46492c6247c88638ba88efb14cbd3a8076841 | 892 | //
// TNSFramebufferAttachmentParameter.swift
// CanvasNative
//
// Created by Osei Fortune on 4/18/20.
//
import Foundation
@objcMembers
@objc(TNSFramebufferAttachmentParameter)
public class TNSFramebufferAttachmentParameter: NSObject {
var _isTexture: Bool
var _isRenderbuffer: Bool
var _value: Int32
public var isTexture: Bool{
get {
return _isTexture
}
}
public var isRenderbuffer: Bool {
get {
return _isRenderbuffer
}
}
public var value: Int32{
get {
return _value
}
}
public override init() {
_isTexture = false
_isRenderbuffer = false
_value = 0
}
public init(isTexture: Bool, isRenderbuffer: Bool, value: Int32) {
_isTexture = isTexture
_isRenderbuffer = isRenderbuffer
_value = value
}
}
| 21.238095 | 70 | 0.607623 |
1ef1b8655c3d82e40e28da8d727d3bbb7f889125 | 569 | //
// CEFDragData+Interop.g.swift
// CEF.swift
//
// This file was generated automatically from cef_drag_data.h.
//
import Foundation
extension cef_drag_data_t: CEFObject {}
/// Class used to represent drag data. The methods of this class may be called
/// on any thread.
public class CEFDragData: CEFProxy<cef_drag_data_t> {
override init?(ptr: UnsafeMutablePointer<cef_drag_data_t>) {
super.init(ptr: ptr)
}
static func fromCEF(ptr: UnsafeMutablePointer<cef_drag_data_t>) -> CEFDragData? {
return CEFDragData(ptr: ptr)
}
}
| 23.708333 | 85 | 0.706503 |
5be6c3b79fa3e814f838020b874c00a9d31235ca | 2,264 | /**
* Copyright (c) 2017 Razeware LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* Notwithstanding the foregoing, you may not use, copy, modify, merge, publish,
* distribute, sublicense, create a derivative work, and/or sell copies of the
* Software in any work that is designed, intended, or marketed for pedagogical or
* instructional purposes related to programming, coding, application development,
* or information technology. Permission for such use, copying, modification,
* merger, publication, distribution, sublicensing, creation of derivative works,
* or sale is expressly withheld.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import Foundation
class Bug: Codable {
enum Context: String, Codable {
case toDo
case inProgress
case done
}
enum Priority: String, Codable {
case low
case medium
case high
}
var id: String
var label: String
var context: Context
var priority: Priority
enum CodingKeys: String, CodingKey {
case id
case label = "description"
case context
case priority
}
init(id: String, label: String, context: Context = .toDo, priority: Priority = .high) {
self.id = id
self.label = label
self.context = context
self.priority = priority
}
}
| 34.30303 | 89 | 0.731007 |
28419514a253b9deaf0a05547996848ffbc684b1 | 2,143 | //
// AppDelegate.swift
// Calculator
//
// Created by Dulio Denis on 5/1/16.
// Copyright © 2016 Dulio Denis. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 45.595745 | 285 | 0.753616 |
cc18945f148190f8165735d78cb1369b4369a12f | 1,016 | //
// Styles.swift
// Dash
//
// Created by zw on 2022/3/7.
//
import SwiftUI
struct StrokeStyle: ViewModifier{
var cornerRadius: CGFloat
@Environment(\.colorScheme) var colorScheme
func body(content: Content) -> some View {
content.overlay(RoundedRectangle(cornerRadius: cornerRadius, style: .continuous)
.stroke(
.linearGradient(
colors: [
.white.opacity(colorScheme == .dark ?0.1 :0.3),
.black.opacity(colorScheme == .dark ?0.3 :0.1)
], startPoint: .top, endPoint: .bottom
)
)
.blendMode(.overlay)
)
}
}
extension View{
func strokeStyle(cornerRadius: CGFloat = 30.0) -> some View
{
modifier(StrokeStyle(cornerRadius: cornerRadius))
}
}
| 27.459459 | 88 | 0.457677 |
1dfeea8939fb6f48be299909362ee375ed24d401 | 5,477 | //
// RemoteRedditImageLoader.swift
// Reddit-ShowcaseTests
//
// Created by Gustavo on 10/06/21.
//
import XCTest
import Reddit_Showcase
class RemoteRedditImageLoaderTest: XCTestCase {
func test_init_doesNotPerformAnyURLRequest() {
let (_, client) = makeSUT()
XCTAssertTrue(client.requestedUrls.isEmpty)
}
func test_loadImageDataFromURL_requestsDataFromURL() {
let url = anyURL
let (sut, client) = makeSUT(url: url)
_ = sut.loadImageData(from: url) { _ in }
XCTAssertEqual(client.requestedUrls, [url])
}
func test_loadImageDataFromURLTwice_requestsDataFromURLTwice() {
let url = anyURL
let (sut, client) = makeSUT(url: url)
_ = sut.loadImageData(from: url) { _ in }
_ = sut.loadImageData(from: url) { _ in }
XCTAssertEqual(client.requestedUrls, [url, url])
}
func test_loadImageDataFromURL_deliversConnectivityErrorOnClientError() {
let (sut, client) = makeSUT()
let clientError = NSError(domain: "a client error", code: 0)
expect(sut, toCompleteWith: failure(.connectivity), when: {
client.complete(with: clientError)
})
}
func test_loadImageDataFromURL_deliversInvalidDataErrorOnNon200HTTPResponse() {
let (sut, client) = makeSUT()
let samples = [199, 201, 300, 400, 500]
samples.enumerated().forEach { index, code in
expect(sut, toCompleteWith: failure(.invalidData), when: {
client.complete(statusCode: code, data: anyData, at: index)
})
}
}
func test_loadImageDataFromURL_deliversInvalidDataErrorOn200HTTPResponseWithEmptyData() {
let (sut, client) = makeSUT()
expect(sut, toCompleteWith: failure(.invalidData), when: {
let emptyData = Data()
client.complete(statusCode: 200, data: emptyData)
})
}
func test_loadImageDataFromURL_deliversReceivedNonEmptyDataOn200HTTPResponse() {
let (sut, client) = makeSUT()
let nonEmptyData = Data("non-empty data".utf8)
expect(sut, toCompleteWith: .success(nonEmptyData), when: {
client.complete(statusCode: 200, data: nonEmptyData)
})
}
func test_loadImageDataFromURL_doesNotDeliverResultAfterCancellingTask() {
let (sut, client) = makeSUT()
let nonEmptyData = Data("non-empty data".utf8)
var received = [RemoteImageDataLoader.Result]()
let task = sut.loadImageData(from: anyURL) { received.append($0) }
task.cancel()
client.complete(statusCode: 404, data: anyData)
client.complete(statusCode: 200, data: nonEmptyData)
client.complete(with: anyNSError)
XCTAssertTrue(received.isEmpty, "Expected no received results after cancelling task")
}
func test_loadImageDataFromURL_doesNotDeliverResultAfterSUTInstanceHasBeenDeallocated() {
let client = HTTPClientSpy()
var sut: RemoteImageDataLoader? = RemoteImageDataLoader(client: client)
var capturedResults = [RemoteImageDataLoader.Result]()
_ = sut?.loadImageData(from: anyURL) { capturedResults.append($0) }
sut = nil
client.complete(statusCode: 200, data: anyData)
XCTAssertTrue(capturedResults.isEmpty)
}
// MARK: - Helpers
private func makeSUT(url: URL = anyURL,
file: StaticString = #file,
line: UInt = #line) -> (sut: RemoteImageDataLoader, client: HTTPClientSpy) {
let client = HTTPClientSpy()
let sut = RemoteImageDataLoader(client: client)
trackForMemoryLeaks(sut, file: file, line: line)
trackForMemoryLeaks(client, file: file, line: line)
return (sut, client)
}
private func failure(_ error: RemoteImageDataLoader.Error) -> RemoteImageDataLoader.Result {
return .failure(error)
}
private func expect(_ sut: RemoteImageDataLoader,
toCompleteWith expectedResult: RemoteImageDataLoader.Result,
file: StaticString = #file,
line: UInt = #line,
when action: () -> Void) {
let url = URL(string: "https://a-given-url.com")!
let exp = expectation(description: "Wait for load completion")
_ = sut.loadImageData(from: url) { receivedResult in
switch (receivedResult, expectedResult) {
case let (.success(receivedData), .success(expectedData)):
XCTAssertEqual(receivedData, expectedData, file: file, line: line)
case let (.failure(receivedError as RemoteImageDataLoader.Error), .failure(expectedError as RemoteImageDataLoader.Error)):
XCTAssertEqual(receivedError, expectedError, file: file, line: line)
case let (.failure(receivedError as NSError), .failure(expectedError as NSError)):
XCTAssertEqual(receivedError, expectedError, file: file, line: line)
default:
XCTFail("Expected result \(expectedResult) got \(receivedResult) instead", file: file, line: line)
}
exp.fulfill()
}
action()
wait(for: [exp], timeout: 1.0)
}
}
| 36.032895 | 134 | 0.612014 |
750fdd689326e0c2b7b920b085851f5d8068bfce | 1,561 | protocol View {
associatedtype Body: View
@ViewBuilder var body: Body { get }
}
protocol BuiltinView {
func _buildNodeTree(_ node: Node)
}
extension View {
func observeObjects(_ node: Node) {
let m = Mirror(reflecting: self)
for child in m.children {
guard let observedObject = child.value as? AnyObservedObject else { return }
observedObject.addDependency(node)
}
}
func buildNodeTree(_ node: Node) {
if let b = self as? BuiltinView {
node.view = b
b._buildNodeTree(node)
return
}
if !node.needsRebuild {
for child in node.children {
child.rebuildIfNeeded()
}
return
}
node.view = AnyBuiltinView(self)
self.observeObjects(node)
let b = body
if node.children.isEmpty {
node.children = [Node()]
}
b.buildNodeTree(node.children[0])
node.needsRebuild = false
}
}
extension Never: View {
var body: Never {
fatalError("We should never reach this")
}
}
extension BuiltinView {
var body: Never {
fatalError("This should never happen")
}
}
struct Button: View, BuiltinView {
var title: String
var action: () -> ()
init(_ title: String, action: @escaping () -> ()) {
self.title = title
self.action = action
}
func _buildNodeTree(_ node: Node) {
// todo create a UIButton
}
}
| 22.3 | 88 | 0.545163 |
334e9d587cb5ecaa180bac37e71919e4d1598117 | 1,598 | // Copyright © 2017 Schibsted. All rights reserved.
import XCTest
@testable import Layout
private func url(forXml name: String) throws -> URL {
guard let url = Bundle(for: LayoutViewControllerTests.self)
.url(forResource: name, withExtension: "xml") else {
throw NSError(domain: "Could not locate: \(name).xml", code: 0)
}
return url
}
class LayoutViewControllerTests: XCTestCase {
// Test class which overrides layoutDidLoad(_:)
private class TestLayoutViewController: UIViewController, LayoutLoading {
var layoutDidLoadLayoutNode: LayoutNode?
var layoutDidLoadLayoutNodeCallCount = 0
func layoutDidLoad(_ layoutNode: LayoutNode) {
layoutDidLoadLayoutNodeCallCount += 1
layoutDidLoadLayoutNode = layoutNode
}
}
func testLayoutDidLoadWithValidXML() throws {
let viewController = TestLayoutViewController()
viewController.loadLayout(withContentsOfURL: try url(forXml: "LayoutDidLoad_Valid"))
XCTAssertNotNil(viewController.layoutDidLoadLayoutNode)
XCTAssertEqual(viewController.layoutNode, viewController.layoutDidLoadLayoutNode)
XCTAssertEqual(viewController.layoutDidLoadLayoutNodeCallCount, 1)
}
func testLayoutDidLoadWithInvalidXML() throws {
let viewController = TestLayoutViewController()
viewController.loadLayout(withContentsOfURL: try url(forXml: "LayoutDidLoad_Invalid"))
XCTAssertNil(viewController.layoutDidLoadLayoutNode)
XCTAssertEqual(viewController.layoutDidLoadLayoutNodeCallCount, 0)
}
}
| 37.162791 | 94 | 0.734668 |
5078821daa0416546978026afded49af3b906de7 | 515 | import UIKit
struct FlutterBridgeConst {
// necessary
static let MethodChannel = "com.example.flutter/method"
static let EventChannel = "com.example.flutter/event"
static let BasicMessageChannel = "com.example.flutter/basicMessage"
/// 打开相册
static let OPEN_GALLERY = "OPEN_GALLERY"
/// 拍照
static let TAKE_PHOTO = "TAKE_PHOTO"
/// 导航
static let TO_NAVIGATION = "TO_NAVIGATION"
/// 清除数据
static let REMOVE_DATA = "REMOVE_DATA"
}
| 20.6 | 71 | 0.638835 |
eb69d9a8d041d033aaf54e81165e625e85a2e4f2 | 351 | //
// WindowController.swift
// Youtube-dl-GUI
//
// Created by Kevin De Koninck on 28/01/2017.
// Copyright © 2017 Kevin De Koninck. All rights reserved.
//
import Cocoa
class WindowController: NSWindowController {
override func windowDidLoad() {
super.windowDidLoad()
self.window!.backgroundColor = NSColor.white
}
}
| 18.473684 | 59 | 0.683761 |
9cde332da2c0f6ce6ae7838510c3838520076148 | 2,210 | //
// SceneDelegate.swift
// CountrySelectionPod
//
// Created by Fedor Volchkov on 10/4/19.
// Copyright © 2019 Fedor Volchkov. All rights reserved.
//
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
guard let windowScene = (scene as? UIWindowScene) else { return }
window = UIWindow(frame: UIScreen.main.bounds)
let viewController = ExampleVC()
window?.rootViewController = viewController
window?.makeKeyAndVisible()
window?.windowScene = windowScene
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| 39.464286 | 141 | 0.704977 |
0e297af96c0fa9d1c4ab0e270600c421b0f12fcb | 8,700 | //
// CheckoutViewController.swift
// HippoChat
//
// Created by Vishal on 05/11/19.
// Copyright © 2019 CL-macmini-88. All rights reserved.
//
import UIKit
import WebKit
class PrePaymentViewController: UIViewController {
@IBOutlet weak var navigationBar : NavigationBar!
var webView: WKWebView!
var config: WebViewConfig!
var isComingForPayment = false
var isPrePayment : Bool?
var isPaymentSuccess : ((Bool)->())?
var isPaymentCancelled : ((Bool)->())?
var channelId : Int?
let transparentView = UIView()
override func viewDidLoad() {
super.viewDidLoad()
setTheme()
initalizeWebView()
launchRequest()
navigationBar.title = config.title
navigationBar.leftButton.addTarget(self, action: #selector(backAction(_:)), for: .touchUpInside)
navigationBar.image_back.isHidden = isPrePayment ?? false ? true : false
navigationBar.leftButton.isEnabled = isPrePayment ?? false ? false : true
navigationBar.rightButton.setImage(BumbleConfig.shared.theme.crossBarButtonImage_bumble, for: .normal)
navigationBar.rightButton.addTarget(self, action: #selector(cancelAction(_:)), for: .touchUpInside)
navigationBar.rightButton.isHidden = isPrePayment ?? false ? false : true
navigationBar.rightButton.isEnabled = isPrePayment ?? false ? true : false
navigationBar.rightButton.tintColor = .black
// FayeConnection.shared.subscribeTo(channelId: "\(channelId ?? -1)", completion: {(success) in
// print("channel subscribed", success)
// }) {(messageDict) in
// print(messageDict)
// if messageDict["message_type"] as? Int == 22{
// if (messageDict["custom_action"] as? NSDictionary)?.value(forKey: "selected_id") as? Int == 1{
// self.isPaymentSuccess?(true)
// DispatchQueue.main.asyncAfter(deadline: .now() + 2.0, execute: {
// self.backAction(UIButton())
// })
// FayeConnection.shared.unsubscribe(fromChannelId: "\(self.channelId ?? -1)", completion: nil)
// }
// }
// }
}
private func initalizeWebView() {
let webConfiguration = WKWebViewConfiguration()
if #available(iOS 10.0, *) {
webConfiguration.ignoresViewportScaleLimits = false
}
var height : CGFloat = 0.0
if #available(iOS 11.0, *) {
height = UIApplication.shared.delegate?.window??.safeAreaInsets.top ?? 0.0
}
webView = WKWebView(frame: CGRect(x: 0, y: height + navigationBar.frame.size.height + 10, width: self.view.bounds.width, height: self.view.bounds.height - (height + navigationBar.frame.size.height + 10)), configuration: webConfiguration)
webView.uiDelegate = self
if !config.zoomingEnabled {
webView.scrollView.delegate = self
}
webView.navigationDelegate = self
view.addSubview(webView)
}
private func launchRequest() {
let request = URLRequest(url: config.initalUrl)
webView.load(request)
}
private func setTheme() {
}
class func getNewInstance(config: WebViewConfig) -> PrePaymentViewController {
let storyboard = UIStoryboard(name: "FuguUnique", bundle: BumbleFlowManager.bundle)
let vc = storyboard.instantiateViewController(withIdentifier: "CheckoutViewController") as! PrePaymentViewController
vc.config = config
return vc
}
// handling keys of paytm add money feature
func handleForPaytmAddMoneyStatus(webUrl: String) {
handleForUrlKeys(webUrl: webUrl)
}
//Payfort redirects through several URLs.
func handleForUrlKeys(webUrl: String) {
print(webUrl)
if webUrl.contains("success.html"){
self.isPaymentSuccess?(true)
DispatchQueue.main.asyncAfter(deadline: .now() + 2.0, execute: {
self.backAction(UIButton())
})
}else if webUrl.contains("error.html") || webUrl.contains("error") || webUrl.contains("Error"){
self.isPaymentSuccess?(false)
DispatchQueue.main.asyncAfter(deadline: .now() + 2.0, execute: {
self.backAction(UIButton())
})
}
}
@IBAction func cancelAction(_ sender : UIButton){
addTransparentView()
}
@IBAction func backAction(_ sender: UIButton) {
if self.navigationController?.viewControllers.count ?? 0 > 1 {
_ = self.navigationController?.popViewController(animated: true)
} else {
BumbleConfig.shared.notifiyDeinit()
self.navigationController?.dismiss(animated: true, completion: nil)
}
}
}
extension PrePaymentViewController{
func addTransparentView(){
let window = UIApplication.shared.keyWindow
transparentView.backgroundColor = UIColor.black.withAlphaComponent(0.9)
let screenSize = UIScreen.main.bounds.size
transparentView.frame = CGRect(x: 0, y: 0, width: screenSize.width, height: screenSize.height)
window?.addSubview(transparentView)
transparentView.alpha = 0
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1.0, initialSpringVelocity: 1.0, options: .curveEaseInOut, animations: {
self.transparentView.alpha = 0.5
self.openCancelPopup()
}, completion: nil)
}
func openCancelPopup(){
let bottomPopupController = UIStoryboard(name: "FuguUnique", bundle: BumbleFlowManager.bundle).instantiateViewController(withIdentifier: "BottomPopupController") as! BottomPopupController
bottomPopupController.modalPresentationStyle = .overFullScreen
bottomPopupController.paymentCancelled = {[weak self]() in
DispatchQueue.main.async {
self?.isPaymentCancelled?(false)
self?.onClickTransparentView()
self?.backAction(UIButton())
}
}
bottomPopupController.popupdismissed = {[weak self]() in
DispatchQueue.main.async {
self?.onClickTransparentView()
}
}
self.present(bottomPopupController, animated: true, completion: nil)
}
@objc func onClickTransparentView() {
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1.0, initialSpringVelocity: 1.0, options: .curveEaseInOut, animations: {
self.transparentView.alpha = 0
}, completion: { (status) in
self.transparentView.removeFromSuperview()
})
}
}
extension PrePaymentViewController: WKUIDelegate {
}
extension PrePaymentViewController: UIScrollViewDelegate {
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return nil
}
func scrollViewWillBeginZooming(_ scrollView: UIScrollView, with view: UIView?) {
scrollView.pinchGestureRecognizer?.isEnabled = config.zoomingEnabled
}
}
extension PrePaymentViewController: WKNavigationDelegate {
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
print("======00000\(webView.url?.description ?? "")")
if isComingForPayment == true{
handleForPaytmAddMoneyStatus(webUrl: webView.url?.absoluteString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) ?? "")
}
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
print("======11111\(error)")
}
func webViewWebContentProcessDidTerminate(_ webView: WKWebView) {
print("======22222\(webView)")
}
func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) {
print("======33333\(navigation.debugDescription) \(webView.url?.description ?? "")")
}
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
print("======44444\(error)")
}
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
print("======66666\(navigationAction)")
decisionHandler(.allow)
}
func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
print("======55555\(navigationResponse)")
decisionHandler(.allow)
}
}
| 40.277778 | 246 | 0.647356 |
e647daf5330b315ee19160a1447f9a647070d7d8 | 867 | //
// UIStackView+Extensions.swift
// Extensions
//
// Created by Ayşenur Bakırcı on 16.11.2021.
//
import UIKit
public extension UIStackView {
static func create(arrangedSubViews: [UIView] = [],
axis: NSLayoutConstraint.Axis = .vertical,
alignment: UIStackView.Alignment = .fill,
distribution: UIStackView.Distribution = .fill,
spacing: CGFloat = .leastNormalMagnitude,
tamic: Bool = true
) -> UIStackView {
let stackView = UIStackView(arrangedSubviews: arrangedSubViews)
stackView.axis = axis
stackView.alignment = alignment
stackView.distribution = distribution
stackView.spacing = spacing
stackView.translatesAutoresizingMaskIntoConstraints = tamic
return stackView
}
}
| 30.964286 | 71 | 0.614764 |
d6d55ee6a9970529a69504c16fdeeb4abef278be | 617 | public struct VCSRootEntry {
public let id : String
public let vcsRoot : VCSRootSummary
public let checkoutRules: String?
init?(dictionary: [String: AnyObject]) {
guard let id = dictionary["id"] as? String,
let checkoutRules = dictionary["checkout-rules"] as? String,
let vcsRootDictionary = dictionary["vcs-root"] as? [String: AnyObject],
let vcsRoot = VCSRootSummary(dictionary: vcsRootDictionary) else {
return nil
}
self.id = id
self.vcsRoot = vcsRoot
self.checkoutRules = checkoutRules
}
}
| 29.380952 | 85 | 0.614263 |
f87889dad857f2c6a242bc73c7e7c64bcc7ab634 | 3,685 | //
// AIPlayer.swift
// agario
//
// Created by Ming on 10/12/15.
//
//
import SpriteKit
class AIPlayer : Player {
var confidenceLevel = 0
override init(playerName name : String, parentNode parent : SKNode, initPosition p : CGPoint) {
super.init(playerName: name, parentNode: parent, initPosition: p)
self.children.first!.position = randomPosition()
self.move(randomPosition())
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func randomMove() {
confidenceLevel = 0
if let b = self.children.first as! Ball? {
if b.physicsBody?.velocity == CGVector(dx: 0, dy: 0) {
//print("a")
self.move(randomPosition())
} else if b.position.x + b.radius > 1950 || b.position.x - b.radius < -1950 {
//print("here", b.position.x, b.radius)
self.move(randomPosition())
} else if b.position.y + b.radius > 1950 || b.position.y - b.radius < -1950 {
//print("there")
self.move(randomPosition())
} else {
// Keep moving
let scene : GameScene = self.scene as! GameScene
for food in scene.foodLayer.children as! [Food] {
if distance(food.position, p2: self.centerPosition()) < b.radius * 5 {
self.move(food.position)
return
}
}
}
}
}
func moveAway(player : Player) {
let p = self.centerPosition()
let b = player.children.first! as! Ball
let v : CGVector = self.centerPosition() - (player.centerPosition() + (b.physicsBody?.velocity)! * 0.4)
self.move(CGPoint(x: p.x + v.dx, y: p.y + v.dy))
}
func chase(player : Player) {
let p = self.centerPosition()
let v : CGVector = player.centerPosition() - self.centerPosition()
self.move(CGPoint(x: p.x + v.dx, y: p.y + v.dy))
}
override func refreshState() {
if self.children.count == 0 {
return
}
let scene : GameScene = self.scene as! GameScene
var targetPlayer : Player? = nil
var dist : CGFloat = 100000
for player in scene.playerLayer.children as! [Player] {
if player.name == self.name {
continue
}
let tmpd = distance(player.centerPosition(), p2: self.centerPosition())
if tmpd < dist {
dist = tmpd
targetPlayer = player
}
}
let b = self.children.first! as! Ball
if targetPlayer == nil {
randomMove()
} else if self.children.count > 1 {
if b.mass < targetPlayer!.totalMass() * 0.9 {
self.moveAway(targetPlayer!)
} else {
self.randomMove()
}
} else if dist > 10 * b.radius {
self.randomMove()
} else if self.totalMass() > targetPlayer!.totalMass() * 2.25 {
self.chase(targetPlayer!)
confidenceLevel += 1
if dist < b.radius * 3 && confidenceLevel > 100 {
// EAT THE BASTARD!
self.split()
}
} else if self.totalMass() < targetPlayer!.totalMass() / CGFloat(min(targetPlayer!.children.count, 4)) * 0.90 {
self.moveAway(targetPlayer!)
} else {
self.randomMove()
}
super.refreshState()
}
} | 32.610619 | 119 | 0.503935 |
0abbb110da7ef4a9f134f2a2e6987ba48e9af341 | 1,356 | //
// RDPUIFont+Extension.swift
// Redpos
//
// Created by Jesus Nieves on 16/09/2019.
// Copyright © 2019 Jesus Nieves. All rights reserved.
//
import UIKit
extension UIFont {
private static func customFont(name: String, size: CGFloat) -> UIFont {
let font = UIFont(name: name, size: size)
assert(font != nil, "Can't load font: \(name)")
return font ?? UIFont.systemFont(ofSize: size)
}
static func romanFont(ofSize size: CGFloat) -> UIFont {
return customFont(name: "AvenirLTStd-Roman", size: size)
}
static func obliqueFont(ofSize size: CGFloat) -> UIFont {
return customFont(name: "AvenirLTStd-Oblique", size: size)
}
static func mediumFont(ofSize size: CGFloat) -> UIFont {
return customFont(name: "AvenirLTStd-Medium", size: size)
}
static func heavyFont(ofSize size: CGFloat) -> UIFont {
return customFont(name: "AvenirLTStd-Heavy", size: size)
}
static func bookFont(ofSize size: CGFloat) -> UIFont {
return customFont(name: "AvenirLTStd-Book", size: size)
}
static func lightFont(ofSize size: CGFloat) -> UIFont {
return customFont(name: "AvenirLTStd-Light", size: size)
}
static func blackFont(ofSize size: CGFloat) -> UIFont {
return customFont(name: "AvenirLTStd-Black", size: size)
}
}
| 29.478261 | 75 | 0.648968 |
e5331de1de1fcd64501bab4a93843b4fbc0b9ae1 | 7,614 | //
// EventCell.swift
// SberDiplomaProject
//
// Created by Анна Ереськина on 09.07.2021.
//
import UIKit
/// Ячейка отображения события
final class EventCell: UITableViewCell {
/// Идентификатор переиспользования ячейки
static var reuseID: String { String(describing: EventCell.self) }
/// Нажатие на "Избранное"
var favouriteButtonHandler: ((_ model: EventViewModel) -> Void)?
/// Загрузка картинки
var loadImage: ((_ imageView: UIImageView) -> Void)?
/// Модель отображаемых данных
private var viewModel: EventViewModel?
/// Подложка
private let backView: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = .lightGray
view.layer.cornerRadius = 12
view.clipsToBounds = true
view.backgroundColor = #colorLiteral(red: 0.9761093259, green: 0.952090919, blue: 0.7397835851, alpha: 1)
return view
}()
/// Картинка события
private let eventImageView: UIImageView = {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .scaleAspectFill
imageView.layer.cornerRadius = 12
imageView.clipsToBounds = true
return imageView
}()
/// Дата
private let dateLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.textColor = #colorLiteral(red: 0.6326112747, green: 0.101905562, blue: 0, alpha: 1)
label.textAlignment = .left
label.font = UIFont(name: "ChalkboardSE-Bold", size: 12)
return label
}()
/// Заголовок
private let titleLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.textAlignment = .left
label.font = UIFont(name: "ChalkboardSE-Bold", size: 14)
label.textColor = #colorLiteral(red: 0.02914242074, green: 0.4192609787, blue: 0.03124724142, alpha: 1)
label.numberOfLines = 2
return label
}()
/// Адрес
private let placeLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.textAlignment = .left
label.font = UIFont(name: "ChalkboardSE-Bold", size: 12)
label.numberOfLines = 2
return label
}()
/// Описание события
private let descriptionLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.textColor = .red
label.textAlignment = .left
label.font = UIFont(name: "Chalkboard SE", size: 14)
label.numberOfLines = 2
return label
}()
/// Цена
private let priceLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.numberOfLines = 2
label.textColor = #colorLiteral(red: 0.6326112747, green: 0.101905562, blue: 0, alpha: 1)
label.textAlignment = .left
label.font = UIFont(name: "ChalkboardSE-Bold", size: 12)
return label
}()
/// Кнопка "Избранное"
private lazy var favouriteButton: UIButton = {
let button = UIButton()
button.translatesAutoresizingMaskIntoConstraints = false
button.setImage(UIImage(named: "heart"), for: .normal)
button.addTarget(self, action: #selector(favouriteButtonTapped), for: .touchUpInside)
return button
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupViews()
makeConstraints()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/// Обновить ячейку из модели
/// - Parameter model: модель данных
func configure(with model: EventViewModel) {
viewModel = model
if let image = model.image {
eventImageView.image = UIImage(data: image)
} else {
eventImageView.loadImage(with: model.imageURL)
}
dateLabel.text = model.date
titleLabel.text = model.title
placeLabel.text = model.place
descriptionLabel.attributedText = makeDescription(from: model.description)
priceLabel.text = model.priceText
favouriteButton.setImage(UIImage(named: model.isFavourite ? "filledHeart" : "heart"), for: .normal)
}
}
//MARK: - User methods
extension EventCell {
private func setupViews() {
selectionStyle = .none
contentView.addSubview(backView)
backView.addSubview(eventImageView)
backView.addSubview(dateLabel)
backView.addSubview(titleLabel)
backView.addSubview(placeLabel)
backView.addSubview(descriptionLabel)
backView.addSubview(priceLabel)
backView.addSubview(favouriteButton)
}
private func makeConstraints() {
NSLayoutConstraint.activate([
backView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 8),
backView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -8),
backView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 16),
backView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -16),
eventImageView.topAnchor.constraint(equalTo: backView.topAnchor, constant: 10),
eventImageView.leadingAnchor.constraint(equalTo: backView.leadingAnchor, constant: 16),
eventImageView.bottomAnchor.constraint(equalTo: backView.bottomAnchor, constant: -16),
eventImageView.widthAnchor.constraint(equalToConstant: 100),
eventImageView.heightAnchor.constraint(equalToConstant: 150),
favouriteButton.topAnchor.constraint(equalTo: backView.topAnchor, constant: 10),
favouriteButton.trailingAnchor.constraint(equalTo: backView.trailingAnchor, constant: -16),
favouriteButton.widthAnchor.constraint(equalToConstant: 24),
favouriteButton.heightAnchor.constraint(equalToConstant: 24),
dateLabel.topAnchor.constraint(equalTo: backView.topAnchor, constant: 10),
dateLabel.leadingAnchor.constraint(equalTo: eventImageView.trailingAnchor, constant: 8),
dateLabel.trailingAnchor.constraint(equalTo: favouriteButton.leadingAnchor, constant: -8),
dateLabel.heightAnchor.constraint(equalToConstant: 16),
titleLabel.topAnchor.constraint(equalTo: dateLabel.bottomAnchor, constant: 8),
titleLabel.leadingAnchor.constraint(equalTo: eventImageView.trailingAnchor, constant: 8),
titleLabel.trailingAnchor.constraint(equalTo: favouriteButton.leadingAnchor, constant: -8),
titleLabel.heightAnchor.constraint(equalToConstant: 16),
descriptionLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 4),
descriptionLabel.leadingAnchor.constraint(equalTo: eventImageView.trailingAnchor, constant: 8),
descriptionLabel.trailingAnchor.constraint(equalTo: backView.trailingAnchor, constant: -16),
placeLabel.topAnchor.constraint(equalTo: descriptionLabel.bottomAnchor, constant: 8),
placeLabel.leadingAnchor.constraint(equalTo: eventImageView.trailingAnchor, constant: 8),
placeLabel.trailingAnchor.constraint(equalTo: backView.trailingAnchor, constant: -16),
priceLabel.bottomAnchor.constraint(equalTo: backView.bottomAnchor, constant: -16),
priceLabel.trailingAnchor.constraint(equalTo: backView.trailingAnchor, constant: -16),
priceLabel.topAnchor.constraint(greaterThanOrEqualTo: placeLabel.bottomAnchor, constant: 8)
])
}
private func makeDescription(from text: NSAttributedString?) -> NSAttributedString? {
guard let text = text else { return nil }
let description = NSMutableAttributedString(attributedString: text)
if let font = UIFont(name: "Chalkboard SE", size: 12) {
let fontAttribute = [ NSAttributedString.Key.font: font ]
description.addAttributes(fontAttribute, range: NSRange(location: 0, length: description.string.count))
return description
}
return text
}
@objc private func favouriteButtonTapped() {
guard let model = viewModel else { return }
favouriteButtonHandler?(model)
}
}
| 35.579439 | 107 | 0.764381 |
5b3e230b9901013381b36bcb22840f8b8bfc1137 | 803 | //
// WhatsNewHeaderView.swift
// WhatsNewView
//
// Created by Jonathan Gander
//
// Display WhatsNewView's header with title and subtitle
//
import SwiftUI
struct WhatsNewHeaderView: View {
public var title: String
public var subtitle: String?
var body: some View {
VStack {
Text(title)
.font(.custom("Helvetica Neue", size: 34))
.fontWeight(.bold)
.multilineTextAlignment(.center)
.padding(.top, 20)
.padding(.bottom, 5)
if let subtitle = subtitle {
Text(subtitle)
.font(.body)
.multilineTextAlignment(.center)
}
}
.padding(.bottom, 40)
}
}
| 21.702703 | 58 | 0.496887 |
1ebf43a65690bba5dad9371c899d3bb08fa462df | 139 | /////
//// SaveCenter.swift
/// Copyright © 2020 Dmitriy Borovikov. All rights reserved.
//
import Foundation
protocol SaveCenter {}
| 13.9 | 62 | 0.683453 |
5d8d1294fda9aa5b2ac3b0cbad1c00e113efb30c | 4,049 | //
// SettingVC.swift
// CollectionView
//
// Created by Nick Lin on 2018/7/30.
// Copyright © 2018年 Nick Lin. All rights reserved.
//
import UIKit
enum SectionTitle: String {
case aboutYou = "關於您"
case aboutMe = "關於我"
}
enum SectionItem: String {
case yourFace = "您的臉"
case yourEye = "您的眼睛"
case yourHeart = "您的心"
case myFace = "我的臉"
case myEye = "我的眼睛"
case myHeart = "我的心"
}
struct SettingSection: SectionProtocol {
let title: SectionTitle
var items: [SectionItem]
init(title: SectionTitle, items: [SectionItem]) {
self.items = items
self.title = title
}
}
final class SettingDatas: SettingData<SettingSection> {
override init() {
super.init()
self.sections = [
SettingSection(title: .aboutYou,
items: [.yourEye,
.yourFace,
.yourHeart,
.myEye,
.myHeart
]),
SettingSection(title: .aboutMe,
items: [.myFace
]),
SettingSection(title: .aboutMe, items: [
.yourEye,
.myEye
])
]
}
}
final class SettingVC: UIViewController {
private let tableView: UITableView = UITableView(frame: .zero, style: UITableViewStyle.grouped)
fileprivate lazy var settingData: SettingDatas = SettingDatas()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(tableView)
tableView.mLay(pin: .zero)
tableView.registerCell(type: SettingTableViewCell.self)
tableView.dataSource = self
tableView.delegate = self
tableView.tableFooterView = UIView()
}
}
extension SettingVC: UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return settingData.numberOfSections()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return settingData.numberOfItem(in: section)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let item = settingData.item(for: indexPath)
let cell = tableView.dequeueCell(type: SettingTableViewCell.self)
cell.textLabel?.text = item.rawValue
return cell
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if cell.responds(to: #selector(setter: UITableViewCell.separatorInset)) {
cell.separatorInset = .zero
}
if cell.responds(to: #selector(setter: UITableViewCell.preservesSuperviewLayoutMargins)) {
cell.preservesSuperviewLayoutMargins = false
}
if cell.responds(to: #selector(setter: UITableViewCell.layoutMargins )) {
cell.layoutMargins = .zero
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let item = settingData.item(for: indexPath)
print(indexPath)
print(item.rawValue)
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return settingData.section(for: section).title.rawValue.isEmpty ? 0 : 60
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if settingData.section(for: section).title.rawValue.isEmpty { return nil }
let view = UIView()
view.backgroundColor = UIColor(red: 240/255, green: 240/255, blue: 240/255, alpha: 0.9)
let label = UILabel()
label.text = settingData.section(for: section).title.rawValue
view.addSubview(label)
label.mLay(pin: .init(top: 10, left: 10, bottom: 10, right: 10))
return view
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 60
}
}
| 30.674242 | 112 | 0.617436 |
18f531de8208ea092a0b71a59c97af456c8242e0 | 3,388 | //
// NotificationPreference.swift
// PennMobile
//
// Created by Dominic Holmes on 12/27/19.
// Copyright © 2019 PennLabs. All rights reserved.
//
import Foundation
typealias NotificationPreferences = Dictionary<String, Bool>
/*
Notification preferences are stored in UserDefaults as a String:Bool mapping, where
String is the unique key of the notification option (NotificationOption.rawValue) and
Bool is whether or not the option is enabled.
TO SET NOTIFICATION PREFS: use the
UserDefaults.standard.setNotificationOption() method.
After setting notification options, you should attempt to send the changes to
the server. Do this with UserDBManager.shared.saveUserNotificationSettings()
TO FETCH NOTIFICATION OPTIONS: use UserDBManager.shared.syncUserSettings() to pull
settings from the database. Then use
UserDefaults.standard.getPreference(forOption) to get individual preferences values
for each option.
*/
enum NotificationOption: String, Codable {
case pennMobileUpdateAnnouncement
case upcomingStudyRoomReminder
case diningBalanceSummary
case laundryMachineCycleComplete
case collegeHouseAnnouncement
case universityEventAnnouncement
case dailyMenuNotification
case dailyMenuNotificationBreakfast
case dailyMenuNotificationLunch
case dailyMenuNotificationDinner
case pennCourseAlerts
// Options to be actually shown to the user
static let visibleOptions: [NotificationOption] = [
.upcomingStudyRoomReminder, .diningBalanceSummary, .pennCourseAlerts, .universityEventAnnouncement, .pennMobileUpdateAnnouncement
]
var cellTitle: String? {
switch self {
case .pennCourseAlerts: return "Penn Course Alerts"
case .upcomingStudyRoomReminder: return "GSR booking notifications"
case .diningBalanceSummary: return "Dining balance notifications"
case .laundryMachineCycleComplete: return "Laundry notifications"
case .universityEventAnnouncement: return "University notifications"
case .pennMobileUpdateAnnouncement: return "App update notifications"
default: return nil
}
}
var cellFooterDescription: String? {
switch self {
case .pennCourseAlerts: return "Receive notifications when courses open up."
case .upcomingStudyRoomReminder: return "Notifications about your upcoming GSR bookings, sent 10 minutes from the start of booking. Includes the room and duration. Long press the notification to cancel your booking."
case .laundryMachineCycleComplete:
return "Notifications about laundry cycles. Tap on a laundry machine with time remaining to set the notification."
case .diningBalanceSummary:
return "Receive monthly updates containing a summary of the past month's dining dollar and swipe use."
case .universityEventAnnouncement: return "Notifications about significant university events."
case .pennMobileUpdateAnnouncement: return "Get notified about major updates to Penn Mobile."
default: return nil
}
}
var defaultValue: Bool {
switch self {
case .diningBalanceSummary: return UserDefaults.standard.hasDiningPlan()
case .pennCourseAlerts: return UserDefaults.standard.getPreference(for: .alertsThroughPennMobile)
default: return true
}
}
}
| 41.82716 | 224 | 0.751476 |
338ffba8f323cefe28227c03384097a1d5311b19 | 183,591 | /*
This source file is part of the Swift.org open source project
Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import XCTest
import PackageGraph
import PackageLoading
import PackageModel
import SourceControl
import SPMBuildCore
import TSCBasic
import TSCUtility
import Workspace
import Basics
import SPMTestSupport
final class WorkspaceTests: XCTestCase {
func testBasics() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fs: fs,
roots: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo", dependencies: ["Bar"]),
MockTarget(name: "Bar", dependencies: ["Baz"]),
MockTarget(name: "BarTests", dependencies: ["Bar"], type: .test),
],
products: [
MockProduct(name: "Foo", targets: ["Foo", "Bar"]),
],
dependencies: [
MockDependency(name: "Baz", requirement: .upToNextMajor(from: "1.0.0")),
]
),
],
packages: [
MockPackage(
name: "Baz",
targets: [
MockTarget(name: "Baz"),
],
products: [
MockProduct(name: "Baz", targets: ["Baz"]),
],
versions: ["1.0.0", "1.5.0"]
),
MockPackage(
name: "Quix",
targets: [
MockTarget(name: "Quix"),
],
products: [
MockProduct(name: "Quix", targets: ["Quix"]),
],
versions: ["1.0.0", "1.2.0"]
),
]
)
let deps: [MockDependency] = [
.init(name: "Quix", requirement: .upToNextMajor(from: "1.0.0"), products: .specific(["Quix"])),
.init(name: "Baz", requirement: .exact("1.0.0"), products: .specific(["Baz"])),
]
workspace.checkPackageGraph(roots: ["Foo"], deps: deps) { graph, diagnostics in
PackageGraphTester(graph) { result in
result.check(roots: "Foo")
result.check(packages: "Baz", "Foo", "Quix")
result.check(targets: "Bar", "Baz", "Foo", "Quix")
result.check(testModules: "BarTests")
result.checkTarget("Foo") { result in result.check(dependencies: "Bar") }
result.checkTarget("Bar") { result in result.check(dependencies: "Baz") }
result.checkTarget("BarTests") { result in result.check(dependencies: "Bar") }
}
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkManagedDependencies { result in
result.check(dependency: "baz", at: .checkout(.version("1.0.0")))
result.check(dependency: "quix", at: .checkout(.version("1.2.0")))
}
// Check the load-package callbacks.
XCTAssertTrue(workspace.delegate.events.contains("will load manifest for root package: /tmp/ws/roots/Foo"))
XCTAssertTrue(workspace.delegate.events.contains("did load manifest for root package: /tmp/ws/roots/Foo"))
XCTAssertTrue(workspace.delegate.events.contains("will load manifest for remote package: /tmp/ws/pkgs/Quix"))
XCTAssertTrue(workspace.delegate.events.contains("did load manifest for remote package: /tmp/ws/pkgs/Quix"))
XCTAssertTrue(workspace.delegate.events.contains("will load manifest for remote package: /tmp/ws/pkgs/Baz"))
XCTAssertTrue(workspace.delegate.events.contains("did load manifest for remote package: /tmp/ws/pkgs/Baz"))
// Close and reopen workspace.
workspace.closeWorkspace()
workspace.checkManagedDependencies { result in
result.check(dependency: "baz", at: .checkout(.version("1.0.0")))
result.check(dependency: "quix", at: .checkout(.version("1.2.0")))
}
let stateFile = workspace.createWorkspace().state.path
// Remove state file and check we can get the state back automatically.
try fs.removeFileTree(stateFile)
workspace.checkPackageGraph(roots: ["Foo"], deps: deps) { _, _ in }
XCTAssertTrue(fs.exists(stateFile))
// Remove state file and check we get back to a clean state.
try fs.removeFileTree(workspace.createWorkspace().state.path)
workspace.closeWorkspace()
workspace.checkManagedDependencies { result in
result.checkEmpty()
}
}
func testInterpreterFlags() throws {
let fs = localFileSystem
try testWithTemporaryDirectory { path in
let foo = path.appending(component: "foo")
func createWorkspace(withManifest manifest: (OutputByteStream) -> Void) throws -> Workspace {
try fs.writeFileContents(foo.appending(component: "Package.swift")) {
manifest($0)
}
let manifestLoader = ManifestLoader(manifestResources: Resources.default)
let sandbox = path.appending(component: "ws")
return Workspace(
dataPath: sandbox.appending(component: ".build"),
editablesPath: sandbox.appending(component: "edits"),
pinsFile: sandbox.appending(component: "Package.resolved"),
manifestLoader: manifestLoader,
delegate: MockWorkspaceDelegate(),
cachePath: fs.swiftPMCacheDirectory.appending(component: "repositories")
)
}
do {
let ws = try createWorkspace {
$0 <<<
"""
// swift-tools-version:4.0
import PackageDescription
let package = Package(
name: "foo"
)
"""
}
XCTAssertMatch(ws.interpreterFlags(for: foo), [.equal("-swift-version"), .equal("4")])
}
do {
let ws = try createWorkspace {
$0 <<<
"""
// swift-tools-version:3.1
import PackageDescription
let package = Package(
name: "foo"
)
"""
}
XCTAssertEqual(ws.interpreterFlags(for: foo), [])
}
}
}
func testMultipleRootPackages() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fs: fs,
roots: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo", dependencies: ["Baz"]),
],
products: [],
dependencies: [
MockDependency(name: "Baz", requirement: .upToNextMajor(from: "1.0.0")),
]
),
MockPackage(
name: "Bar",
targets: [
MockTarget(name: "Bar", dependencies: ["Baz"]),
],
products: [],
dependencies: [
MockDependency(name: "Baz", requirement: .exact("1.0.1")),
]
),
],
packages: [
MockPackage(
name: "Baz",
targets: [
MockTarget(name: "Baz"),
],
products: [
MockProduct(name: "Baz", targets: ["Baz"]),
],
versions: ["1.0.0", "1.0.1", "1.0.3", "1.0.5", "1.0.8"]
),
]
)
workspace.checkPackageGraph(roots: ["Foo", "Bar"]) { graph, diagnostics in
PackageGraphTester(graph) { result in
result.check(roots: "Bar", "Foo")
result.check(packages: "Bar", "Baz", "Foo")
result.checkTarget("Foo") { result in result.check(dependencies: "Baz") }
result.checkTarget("Bar") { result in result.check(dependencies: "Baz") }
}
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkManagedDependencies { result in
result.check(dependency: "baz", at: .checkout(.version("1.0.1")))
}
}
func testRootPackagesOverride() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fs: fs,
roots: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo", dependencies: ["Baz"]),
],
products: [],
dependencies: [
MockDependency(name: nil, path: "bazzz", requirement: .upToNextMajor(from: "1.0.0")),
],
toolsVersion: .v5
),
MockPackage(
name: "Bar",
targets: [
MockTarget(name: "Bar"),
],
products: []
),
MockPackage(
name: "Baz",
path: "Overridden/bazzz",
targets: [
MockTarget(name: "Baz"),
],
products: [
MockProduct(name: "Baz", targets: ["Baz"]),
]
),
],
packages: [
MockPackage(
name: "Baz",
path: "bazzz",
targets: [
MockTarget(name: "Baz"),
],
products: [
MockProduct(name: "Baz", targets: ["Baz"]),
],
versions: ["1.0.0", "1.0.1", "1.0.3", "1.0.5", "1.0.8"]
),
]
)
workspace.checkPackageGraph(roots: ["Foo", "Bar", "Overridden/bazzz"]) { graph, diagnostics in
PackageGraphTester(graph) { result in
result.check(roots: "Bar", "Foo", "Baz")
result.check(packages: "Bar", "Baz", "Foo")
result.checkTarget("Foo") { result in result.check(dependencies: "Baz") }
}
XCTAssertNoDiagnostics(diagnostics)
}
}
func testDependencyRefsAreIteratedInStableOrder() throws {
// This graph has two references to Bar, one with .git suffix and one without.
// The test ensures that we use the URL which appears first (i.e. the one with .git suffix).
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fs: fs,
roots: [],
packages: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo", dependencies: ["Bar"]),
],
products: [
MockProduct(name: "Foo", targets: ["Foo"]),
],
dependencies: [
MockDependency(name: "Bar", requirement: .upToNextMajor(from: "1.0.0")),
],
versions: ["1.0.0"]
),
MockPackage(
name: "Bar",
targets: [
MockTarget(name: "Bar"),
],
products: [
MockProduct(name: "Bar", targets: ["Bar"]),
],
versions: ["1.0.0"]
),
]
)
let dependencies: [PackageDependencyDescription] = [
.init(
name: nil,
url: workspace.packagesDir.appending(component: "Foo").pathString,
requirement: .upToNextMajor(from: "1.0.0"),
productFilter: .specific(["Foo"])
),
.init(
name: nil,
url: workspace.packagesDir.appending(component: "Bar").pathString + ".git",
requirement: .upToNextMajor(from: "1.0.0"),
productFilter: .specific(["Bar"])
),
]
// Add entry for the Bar.git package.
do {
let barKey = MockManifestLoader.Key(url: "/tmp/ws/pkgs/Bar", version: "1.0.0")
let barGitKey = MockManifestLoader.Key(url: "/tmp/ws/pkgs/Bar.git", version: "1.0.0")
let manifest = workspace.manifestLoader.manifests[barKey]!
workspace.manifestLoader.manifests[barGitKey] = manifest.with(url: "/tmp/ws/pkgs/Bar.git")
}
workspace.checkPackageGraph(dependencies: dependencies) { graph, diagnostics in
PackageGraphTester(graph) { result in
result.check(packages: "Bar", "Foo")
result.check(targets: "Bar", "Foo")
result.checkTarget("Foo") { result in result.check(dependencies: "Bar") }
}
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkManagedDependencies { result in
result.check(dependency: "foo", at: .checkout(.version("1.0.0")))
result.check(dependency: "bar", at: .checkout(.version("1.0.0")))
}
workspace.checkResolved { result in
result.check(dependency: "foo", at: .checkout(.version("1.0.0")))
result.check(dependency: "bar", at: .checkout(.version("1.0.0")))
result.check(dependency: "bar", url: "/tmp/ws/pkgs/Bar.git")
}
}
func testDuplicateRootPackages() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fs: fs,
roots: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo", dependencies: []),
],
products: [],
dependencies: []
),
MockPackage(
name: "Foo",
path: "Nested/Foo",
targets: [
MockTarget(name: "Foo", dependencies: []),
],
products: [],
dependencies: []
),
],
packages: []
)
workspace.checkPackageGraph(roots: ["Foo", "Nested/Foo"]) { _, diagnostics in
DiagnosticsEngineTester(diagnostics) { result in
result.check(diagnostic: .equal("found multiple top-level packages named 'Foo'"), behavior: .error)
}
}
}
/// Test that the explicit name given to a package is not used as its identity.
func testExplicitPackageNameIsNotUsedAsPackageIdentity() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fs: fs,
roots: [
MockPackage(
name: "FooPackage",
path: "foo-package",
targets: [
MockTarget(name: "FooTarget", dependencies: [.product(name: "BarProduct", package: "BarPackage")]),
],
products: [],
dependencies: [
MockDependency(name: "BarPackage", path: "bar-package", requirement: .upToNextMajor(from: "1.0.0")),
],
toolsVersion: .v5
),
MockPackage(
name: "BarPackage",
path: "bar-package",
targets: [
MockTarget(name: "BarTarget"),
],
products: [
MockProduct(name: "BarProduct", targets: ["BarTarget"]),
],
versions: ["1.0.0", "1.0.1"]
),
],
packages: [
MockPackage(
name: "BarPackage",
path: "bar-package",
targets: [
MockTarget(name: "BarTarget"),
],
products: [
MockProduct(name: "BarProduct", targets: ["BarTarget"]),
],
versions: ["1.0.0", "1.0.1"]
),
]
)
workspace.checkPackageGraph(roots: ["foo-package", "bar-package"], dependencies: [PackageDependencyDescription(url: "/tmp/ws/pkgs/bar-package", requirement: .upToNextMajor(from: "1.0.0"), productFilter: .everything)]) { graph, diagnostics in
PackageGraphTester(graph) { result in
result.check(roots: "FooPackage", "BarPackage")
result.check(packages: "FooPackage", "BarPackage")
result.checkTarget("FooTarget") { result in result.check(dependencies: "BarProduct") }
}
XCTAssertNoDiagnostics(diagnostics)
}
}
/// Test that the remote repository is not resolved when a root package with same name is already present.
func testRootAsDependency1() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fs: fs,
roots: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo", dependencies: ["BazAB"]),
],
products: [],
dependencies: [
MockDependency(name: "Baz", requirement: .upToNextMajor(from: "1.0.0")),
],
toolsVersion: .v5
),
MockPackage(
name: "Baz",
targets: [
MockTarget(name: "BazA"),
MockTarget(name: "BazB"),
],
products: [
MockProduct(name: "BazAB", targets: ["BazA", "BazB"]),
]
),
],
packages: [
MockPackage(
name: "Baz",
targets: [
MockTarget(name: "Baz"),
],
products: [
MockProduct(name: "Baz", targets: ["Baz"]),
],
versions: ["1.0.0"]
),
]
)
workspace.checkPackageGraph(roots: ["Foo", "Baz"]) { graph, diagnostics in
PackageGraphTester(graph) { result in
result.check(roots: "Baz", "Foo")
result.check(packages: "Baz", "Foo")
result.check(targets: "BazA", "BazB", "Foo")
result.checkTarget("Foo") { result in result.check(dependencies: "BazAB") }
}
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkManagedDependencies { result in
result.check(notPresent: "baz")
}
XCTAssertNoMatch(workspace.delegate.events, [.equal("fetching repo: /tmp/ws/pkgs/Baz")])
XCTAssertNoMatch(workspace.delegate.events, [.equal("will resolve dependencies")])
}
/// Test that a root package can be used as a dependency when the remote version was resolved previously.
func testRootAsDependency2() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fs: fs,
roots: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo", dependencies: ["Baz"]),
],
products: [],
dependencies: [
MockDependency(name: "Baz", requirement: .upToNextMajor(from: "1.0.0")),
]
),
MockPackage(
name: "Baz",
targets: [
MockTarget(name: "BazA"),
MockTarget(name: "BazB"),
],
products: [
MockProduct(name: "Baz", targets: ["BazA", "BazB"]),
]
),
],
packages: [
MockPackage(
name: "Baz",
targets: [
MockTarget(name: "Baz"),
],
products: [
MockProduct(name: "Baz", targets: ["Baz"]),
],
versions: ["1.0.0"]
),
]
)
// Load only Foo right now so Baz is loaded from remote.
workspace.checkPackageGraph(roots: ["Foo"]) { graph, diagnostics in
PackageGraphTester(graph) { result in
result.check(roots: "Foo")
result.check(packages: "Baz", "Foo")
result.check(targets: "Baz", "Foo")
result.checkTarget("Foo") { result in result.check(dependencies: "Baz") }
}
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkManagedDependencies { result in
result.check(dependency: "baz", at: .checkout(.version("1.0.0")))
}
XCTAssertMatch(workspace.delegate.events, [.equal("fetching repo: /tmp/ws/pkgs/Baz")])
XCTAssertMatch(workspace.delegate.events, [.equal("will resolve dependencies")])
// Now load with Baz as a root package.
workspace.delegate.clear()
workspace.checkPackageGraph(roots: ["Foo", "Baz"]) { graph, diagnostics in
PackageGraphTester(graph) { result in
result.check(roots: "Baz", "Foo")
result.check(packages: "Baz", "Foo")
result.check(targets: "BazA", "BazB", "Foo")
result.checkTarget("Foo") { result in result.check(dependencies: "Baz") }
}
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkManagedDependencies { result in
result.check(notPresent: "baz")
}
XCTAssertNoMatch(workspace.delegate.events, [.equal("fetching repo: /tmp/ws/pkgs/Baz")])
XCTAssertNoMatch(workspace.delegate.events, [.equal("will resolve dependencies")])
XCTAssertMatch(workspace.delegate.events, [.equal("removing repo: /tmp/ws/pkgs/Baz")])
}
func testGraphRootDependencies() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fs: fs,
roots: [],
packages: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo", dependencies: ["Bar"]),
],
products: [
MockProduct(name: "Foo", targets: ["Foo"]),
],
dependencies: [
MockDependency(name: "Bar", requirement: .upToNextMajor(from: "1.0.0")),
],
versions: ["1.0.0"]
),
MockPackage(
name: "Bar",
targets: [
MockTarget(name: "Bar"),
],
products: [
MockProduct(name: "Bar", targets: ["Bar"]),
],
versions: ["1.0.0"]
),
]
)
let dependencies: [PackageDependencyDescription] = [
.init(
url: workspace.packagesDir.appending(component: "Bar").pathString,
requirement: .upToNextMajor(from: "1.0.0"),
productFilter: .specific(["Bar"])
),
.init(
url: "file://\(workspace.packagesDir.appending(component: "Foo").pathString)/",
requirement: .upToNextMajor(from: "1.0.0"),
productFilter: .specific(["Foo"])
),
]
workspace.checkPackageGraph(dependencies: dependencies) { graph, diagnostics in
PackageGraphTester(graph) { result in
result.check(packages: "Bar", "Foo")
result.check(targets: "Bar", "Foo")
result.checkTarget("Foo") { result in result.check(dependencies: "Bar") }
}
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkManagedDependencies { result in
result.check(dependency: "foo", at: .checkout(.version("1.0.0")))
result.check(dependency: "bar", at: .checkout(.version("1.0.0")))
}
}
func testCanResolveWithIncompatiblePins() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fs: fs,
roots: [],
packages: [
MockPackage(
name: "A",
targets: [
MockTarget(name: "A", dependencies: ["AA"]),
],
products: [
MockProduct(name: "A", targets: ["A"]),
],
dependencies: [
MockDependency(name: "AA", requirement: .exact("1.0.0")),
],
versions: ["1.0.0"]
),
MockPackage(
name: "A",
targets: [
MockTarget(name: "A", dependencies: ["AA"]),
],
products: [
MockProduct(name: "A", targets: ["A"]),
],
dependencies: [
MockDependency(name: "AA", requirement: .exact("2.0.0")),
],
versions: ["1.0.1"]
),
MockPackage(
name: "AA",
targets: [
MockTarget(name: "AA"),
],
products: [
MockProduct(name: "AA", targets: ["AA"]),
],
versions: ["1.0.0", "2.0.0"]
),
]
)
// Resolve when A = 1.0.0.
do {
let deps: [MockDependency] = [
.init(name: "A", requirement: .exact("1.0.0"), products: .specific(["A"])),
]
workspace.checkPackageGraph(deps: deps) { graph, diagnostics in
PackageGraphTester(graph) { result in
result.check(packages: "A", "AA")
result.check(targets: "A", "AA")
result.checkTarget("A") { result in result.check(dependencies: "AA") }
}
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkManagedDependencies { result in
result.check(dependency: "a", at: .checkout(.version("1.0.0")))
result.check(dependency: "aa", at: .checkout(.version("1.0.0")))
}
workspace.checkResolved { result in
result.check(dependency: "a", at: .checkout(.version("1.0.0")))
result.check(dependency: "aa", at: .checkout(.version("1.0.0")))
}
}
// Resolve when A = 1.0.1.
do {
let deps: [MockDependency] = [
.init(name: "A", requirement: .exact("1.0.1"), products: .specific(["A"])),
]
workspace.checkPackageGraph(deps: deps) { graph, diagnostics in
PackageGraphTester(graph) { result in
result.checkTarget("A") { result in result.check(dependencies: "AA") }
}
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkManagedDependencies { result in
result.check(dependency: "a", at: .checkout(.version("1.0.1")))
result.check(dependency: "aa", at: .checkout(.version("2.0.0")))
}
workspace.checkResolved { result in
result.check(dependency: "a", at: .checkout(.version("1.0.1")))
result.check(dependency: "aa", at: .checkout(.version("2.0.0")))
}
XCTAssertMatch(workspace.delegate.events, [.equal("updating repo: /tmp/ws/pkgs/A")])
XCTAssertMatch(workspace.delegate.events, [.equal("updating repo: /tmp/ws/pkgs/AA")])
XCTAssertEqual(workspace.delegate.events.filter { $0.hasPrefix("updating repo") }.count, 2)
}
}
func testResolverCanHaveError() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fs: fs,
roots: [],
packages: [
MockPackage(
name: "A",
targets: [
MockTarget(name: "A", dependencies: ["AA"]),
],
products: [
MockProduct(name: "A", targets: ["A"]),
],
dependencies: [
MockDependency(name: "AA", requirement: .exact("1.0.0")),
],
versions: ["1.0.0"]
),
MockPackage(
name: "B",
targets: [
MockTarget(name: "B", dependencies: ["AA"]),
],
products: [
MockProduct(name: "B", targets: ["B"]),
],
dependencies: [
MockDependency(name: "AA", requirement: .exact("2.0.0")),
],
versions: ["1.0.0"]
),
MockPackage(
name: "AA",
targets: [
MockTarget(name: "AA"),
],
products: [
MockProduct(name: "AA", targets: ["AA"]),
],
versions: ["1.0.0", "2.0.0"]
),
]
)
let deps: [MockDependency] = [
.init(name: "A", requirement: .exact("1.0.0"), products: .specific(["A"])),
.init(name: "B", requirement: .exact("1.0.0"), products: .specific(["B"])),
]
workspace.checkPackageGraph(deps: deps) { _, diagnostics in
DiagnosticsEngineTester(diagnostics) { result in
result.check(diagnostic: .contains("Dependencies could not be resolved"), behavior: .error)
}
}
// There should be no extra fetches.
XCTAssertNoMatch(workspace.delegate.events, [.contains("updating repo")])
}
func testPrecomputeResolution_empty() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let bPath = RelativePath("B")
let v1_5 = CheckoutState(revision: Revision(identifier: "hello"), version: "1.0.5")
let v2 = CheckoutState(revision: Revision(identifier: "hello"), version: "2.0.0")
let workspace = try MockWorkspace(
sandbox: sandbox,
fs: fs,
roots: [
MockPackage(
name: "A",
targets: [MockTarget(name: "A")],
products: []
),
],
packages: []
)
let bRepo = RepositorySpecifier(url: workspace.urlForPackage(withName: "B"))
let cRepo = RepositorySpecifier(url: workspace.urlForPackage(withName: "C"))
let bRef = PackageReference(identity: PackageIdentity(url: bRepo.url), path: bRepo.url)
let cRef = PackageReference(identity: PackageIdentity(url: cRepo.url), path: cRepo.url)
try workspace.set(
pins: [bRef: v1_5, cRef: v2],
managedDependencies: [
ManagedDependency(packageRef: bRef, subpath: bPath, checkoutState: v1_5)
.editedDependency(subpath: bPath, unmanagedPath: nil),
]
)
try workspace.checkPrecomputeResolution { result in
XCTAssertEqual(result.diagnostics.hasErrors, false)
XCTAssertEqual(result.result.isRequired, false)
}
}
func testPrecomputeResolution_newPackages() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let bPath = RelativePath("B")
let v1Requirement: MockDependency.Requirement = .range("1.0.0" ..< "2.0.0")
let v1 = CheckoutState(revision: Revision(identifier: "hello"), version: "1.0.0")
let workspace = try MockWorkspace(
sandbox: sandbox,
fs: fs,
roots: [
MockPackage(
name: "A",
targets: [MockTarget(name: "A")],
products: [],
dependencies: [
MockDependency(name: "B", requirement: v1Requirement),
MockDependency(name: "C", requirement: v1Requirement),
]
),
],
packages: [
MockPackage(
name: "B",
targets: [MockTarget(name: "B")],
products: [MockProduct(name: "B", targets: ["B"])],
versions: ["1.0.0"]
),
MockPackage(
name: "C",
targets: [MockTarget(name: "C")],
products: [MockProduct(name: "C", targets: ["C"])],
versions: ["1.0.0"]
),
]
)
let bRepo = RepositorySpecifier(url: workspace.urlForPackage(withName: "B"))
let cRepo = RepositorySpecifier(url: workspace.urlForPackage(withName: "C"))
let bRef = PackageReference(identity: PackageIdentity(url: bRepo.url), path: bRepo.url)
let cRef = PackageReference(identity: PackageIdentity(url: cRepo.url), path: cRepo.url)
try workspace.set(
pins: [bRef: v1],
managedDependencies: [
ManagedDependency(packageRef: bRef, subpath: bPath, checkoutState: v1),
]
)
try workspace.checkPrecomputeResolution { result in
XCTAssertEqual(result.diagnostics.hasErrors, false)
XCTAssertEqual(result.result, .required(reason: .newPackages(packages: [cRef])))
}
}
func testPrecomputeResolution_requirementChange_versionToBranch() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let bPath = RelativePath("B")
let cPath = RelativePath("C")
let v1Requirement: MockDependency.Requirement = .range("1.0.0" ..< "2.0.0")
let branchRequirement: MockDependency.Requirement = .branch("master")
let v1_5 = CheckoutState(revision: Revision(identifier: "hello"), version: "1.0.5")
let workspace = try MockWorkspace(
sandbox: sandbox,
fs: fs,
roots: [
MockPackage(
name: "A",
targets: [MockTarget(name: "A")],
products: [],
dependencies: [
MockDependency(name: "B", requirement: v1Requirement),
MockDependency(name: "C", requirement: branchRequirement),
]
),
],
packages: [
MockPackage(
name: "B",
targets: [MockTarget(name: "B")],
products: [MockProduct(name: "B", targets: ["B"])],
versions: [nil, "1.0.0", "1.0.5", "2.0.0"]
),
MockPackage(
name: "C",
targets: [MockTarget(name: "C")],
products: [MockProduct(name: "C", targets: ["C"])],
versions: [nil, "1.0.0", "1.0.5", "2.0.0"]
),
]
)
let bRepo = RepositorySpecifier(url: workspace.urlForPackage(withName: "B"))
let cRepo = RepositorySpecifier(url: workspace.urlForPackage(withName: "C"))
let bRef = PackageReference(identity: PackageIdentity(url: bRepo.url), path: bRepo.url)
let cRef = PackageReference(identity: PackageIdentity(url: cRepo.url), path: cRepo.url)
try workspace.set(
pins: [bRef: v1_5, cRef: v1_5],
managedDependencies: [
ManagedDependency(packageRef: bRef, subpath: bPath, checkoutState: v1_5),
ManagedDependency(packageRef: cRef, subpath: cPath, checkoutState: v1_5),
]
)
try workspace.checkPrecomputeResolution { result in
XCTAssertEqual(result.diagnostics.hasErrors, false)
XCTAssertEqual(result.result, .required(reason: .packageRequirementChange(
package: cRef,
state: .checkout(v1_5),
requirement: .revision("master")
)))
}
}
func testPrecomputeResolution_requirementChange_versionToRevision() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let cPath = RelativePath("C")
let v1_5 = CheckoutState(revision: Revision(identifier: "hello"), version: "1.0.5")
let testWorkspace = try MockWorkspace(
sandbox: sandbox,
fs: fs,
roots: [
MockPackage(
name: "A",
targets: [MockTarget(name: "A")],
products: [],
dependencies: [
MockDependency(name: "C", requirement: .revision("hello")),
]
),
],
packages: [
MockPackage(
name: "C",
targets: [MockTarget(name: "C")],
products: [MockProduct(name: "C", targets: ["C"])],
versions: [nil, "1.0.0", "1.0.5", "2.0.0"]
),
]
)
let cRepo = RepositorySpecifier(url: testWorkspace.urlForPackage(withName: "C"))
let cRef = PackageReference(identity: PackageIdentity(url: cRepo.url), path: cRepo.url)
try testWorkspace.set(
pins: [cRef: v1_5],
managedDependencies: [
ManagedDependency(packageRef: cRef, subpath: cPath, checkoutState: v1_5),
]
)
try testWorkspace.checkPrecomputeResolution { result in
XCTAssertEqual(result.diagnostics.hasErrors, false)
XCTAssertEqual(result.result, .required(reason: .packageRequirementChange(
package: cRef,
state: .checkout(v1_5),
requirement: .revision("hello")
)))
}
}
func testPrecomputeResolution_requirementChange_localToBranch() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let bPath = RelativePath("B")
let v1Requirement: MockDependency.Requirement = .range("1.0.0" ..< "2.0.0")
let masterRequirement: MockDependency.Requirement = .branch("master")
let v1_5 = CheckoutState(revision: Revision(identifier: "hello"), version: "1.0.5")
let workspace = try MockWorkspace(
sandbox: sandbox,
fs: fs,
roots: [
MockPackage(
name: "A",
targets: [MockTarget(name: "A")],
products: [],
dependencies: [
MockDependency(name: "B", requirement: v1Requirement),
MockDependency(name: "C", requirement: masterRequirement),
]
),
],
packages: [
MockPackage(
name: "B",
targets: [MockTarget(name: "B")],
products: [MockProduct(name: "B", targets: ["B"])],
versions: [nil, "1.0.0", "1.0.5", "2.0.0"]
),
MockPackage(
name: "C",
targets: [MockTarget(name: "C")],
products: [MockProduct(name: "C", targets: ["C"])],
versions: [nil, "1.0.0", "1.0.5", "2.0.0"]
),
]
)
let bRepo = RepositorySpecifier(url: workspace.urlForPackage(withName: "B"))
let cRepo = RepositorySpecifier(url: workspace.urlForPackage(withName: "C"))
let bRef = PackageReference(identity: PackageIdentity(url: bRepo.url), path: bRepo.url)
let cRef = PackageReference(identity: PackageIdentity(url: cRepo.url), path: cRepo.url)
try workspace.set(
pins: [bRef: v1_5],
managedDependencies: [
ManagedDependency(packageRef: bRef, subpath: bPath, checkoutState: v1_5),
ManagedDependency.local(packageRef: cRef),
]
)
try workspace.checkPrecomputeResolution { result in
XCTAssertEqual(result.diagnostics.hasErrors, false)
XCTAssertEqual(result.result, .required(reason: .packageRequirementChange(
package: cRef,
state: .local,
requirement: .revision("master")
)))
}
}
func testPrecomputeResolution_requirementChange_versionToLocal() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let bPath = RelativePath("B")
let cPath = RelativePath("C")
let v1Requirement: MockDependency.Requirement = .range("1.0.0" ..< "2.0.0")
let localRequirement: MockDependency.Requirement = .localPackage
let v1_5 = CheckoutState(revision: Revision(identifier: "hello"), version: "1.0.5")
let workspace = try MockWorkspace(
sandbox: sandbox,
fs: fs,
roots: [
MockPackage(
name: "A",
targets: [MockTarget(name: "A")],
products: [],
dependencies: [
MockDependency(name: "B", requirement: v1Requirement),
MockDependency(name: "C", requirement: localRequirement),
]
),
],
packages: [
MockPackage(
name: "B",
targets: [MockTarget(name: "B")],
products: [MockProduct(name: "B", targets: ["B"])],
versions: [nil, "1.0.0", "1.0.5", "2.0.0"]
),
MockPackage(
name: "C",
targets: [MockTarget(name: "C")],
products: [MockProduct(name: "C", targets: ["C"])],
versions: [nil, "1.0.0", "1.0.5", "2.0.0"]
),
]
)
let bRepo = RepositorySpecifier(url: workspace.urlForPackage(withName: "B"))
let cRepo = RepositorySpecifier(url: workspace.urlForPackage(withName: "C"))
let bRef = PackageReference(identity: PackageIdentity(url: bRepo.url), path: bRepo.url)
let cRef = PackageReference(identity: PackageIdentity(url: cRepo.url), path: cRepo.url)
try workspace.set(
pins: [bRef: v1_5, cRef: v1_5],
managedDependencies: [
ManagedDependency(packageRef: bRef, subpath: bPath, checkoutState: v1_5),
ManagedDependency(packageRef: cRef, subpath: cPath, checkoutState: v1_5),
]
)
try workspace.checkPrecomputeResolution { result in
XCTAssertEqual(result.diagnostics.hasErrors, false)
XCTAssertEqual(result.result, .required(reason: .packageRequirementChange(
package: cRef,
state: .checkout(v1_5),
requirement: .unversioned
)))
}
}
func testPrecomputeResolution_requirementChange_branchToLocal() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let bPath = RelativePath("B")
let cPath = RelativePath("C")
let v1Requirement: MockDependency.Requirement = .range("1.0.0" ..< "2.0.0")
let localRequirement: MockDependency.Requirement = .localPackage
let v1_5 = CheckoutState(revision: Revision(identifier: "hello"), version: "1.0.5")
let master = CheckoutState(revision: Revision(identifier: "master"), branch: "master")
let workspace = try MockWorkspace(
sandbox: sandbox,
fs: fs,
roots: [
MockPackage(
name: "A",
targets: [MockTarget(name: "A")],
products: [],
dependencies: [
MockDependency(name: "B", requirement: v1Requirement),
MockDependency(name: "C", requirement: localRequirement),
]
),
],
packages: [
MockPackage(
name: "B",
targets: [MockTarget(name: "B")],
products: [MockProduct(name: "B", targets: ["B"])],
versions: [nil, "1.0.0", "1.0.5", "2.0.0"]
),
MockPackage(
name: "C",
targets: [MockTarget(name: "C")],
products: [MockProduct(name: "C", targets: ["C"])],
versions: [nil, "1.0.0", "1.0.5", "2.0.0"]
),
]
)
let bRepo = RepositorySpecifier(url: workspace.urlForPackage(withName: "B"))
let cRepo = RepositorySpecifier(url: workspace.urlForPackage(withName: "C"))
let bRef = PackageReference(identity: PackageIdentity(url: bRepo.url), path: bRepo.url)
let cRef = PackageReference(identity: PackageIdentity(url: cRepo.url), path: cRepo.url)
try workspace.set(
pins: [bRef: v1_5, cRef: master],
managedDependencies: [
ManagedDependency(packageRef: bRef, subpath: bPath, checkoutState: v1_5),
ManagedDependency(packageRef: cRef, subpath: cPath, checkoutState: master),
]
)
try workspace.checkPrecomputeResolution { result in
XCTAssertEqual(result.diagnostics.hasErrors, false)
XCTAssertEqual(result.result, .required(reason: .packageRequirementChange(
package: cRef,
state: .checkout(master),
requirement: .unversioned
)))
}
}
func testPrecomputeResolution_other() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let bPath = RelativePath("B")
let cPath = RelativePath("C")
let v1Requirement: MockDependency.Requirement = .range("1.0.0" ..< "2.0.0")
let v2Requirement: MockDependency.Requirement = .range("2.0.0" ..< "3.0.0")
let v1_5 = CheckoutState(revision: Revision(identifier: "hello"), version: "1.0.5")
let workspace = try MockWorkspace(
sandbox: sandbox,
fs: fs,
roots: [
MockPackage(
name: "A",
targets: [MockTarget(name: "A")],
products: [],
dependencies: [
MockDependency(name: "B", requirement: v1Requirement),
MockDependency(name: "C", requirement: v2Requirement),
]
),
],
packages: [
MockPackage(
name: "B",
targets: [MockTarget(name: "B")],
products: [MockProduct(name: "B", targets: ["B"])],
versions: [nil, "1.0.0", "1.0.5", "2.0.0"]
),
MockPackage(
name: "C",
targets: [MockTarget(name: "C")],
products: [MockProduct(name: "C", targets: ["C"])],
versions: [nil, "1.0.0", "1.0.5", "2.0.0"]
),
]
)
let bRepo = RepositorySpecifier(url: workspace.urlForPackage(withName: "B"))
let cRepo = RepositorySpecifier(url: workspace.urlForPackage(withName: "C"))
let bRef = PackageReference(identity: PackageIdentity(url: bRepo.url), path: bRepo.url)
let cRef = PackageReference(identity: PackageIdentity(url: cRepo.url), path: cRepo.url)
try workspace.set(
pins: [bRef: v1_5, cRef: v1_5],
managedDependencies: [
ManagedDependency(packageRef: bRef, subpath: bPath, checkoutState: v1_5),
ManagedDependency(packageRef: cRef, subpath: cPath, checkoutState: v1_5),
]
)
try workspace.checkPrecomputeResolution { result in
XCTAssertEqual(result.diagnostics.hasErrors, false)
XCTAssertEqual(result.result, .required(reason: .other))
}
}
func testPrecomputeResolution_notRequired() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let bPath = RelativePath("B")
let cPath = RelativePath("C")
let v1Requirement: MockDependency.Requirement = .range("1.0.0" ..< "2.0.0")
let v2Requirement: MockDependency.Requirement = .range("2.0.0" ..< "3.0.0")
let v1_5 = CheckoutState(revision: Revision(identifier: "hello"), version: "1.0.5")
let v2 = CheckoutState(revision: Revision(identifier: "hello"), version: "2.0.0")
let workspace = try MockWorkspace(
sandbox: sandbox,
fs: fs,
roots: [
MockPackage(
name: "A",
targets: [MockTarget(name: "A")],
products: [],
dependencies: [
MockDependency(name: "B", requirement: v1Requirement),
MockDependency(name: "C", requirement: v2Requirement),
]
),
],
packages: [
MockPackage(
name: "B",
targets: [MockTarget(name: "B")],
products: [MockProduct(name: "B", targets: ["B"])],
versions: [nil, "1.0.0", "1.0.5", "2.0.0"]
),
MockPackage(
name: "C",
targets: [MockTarget(name: "C")],
products: [MockProduct(name: "C", targets: ["C"])],
versions: [nil, "1.0.0", "1.0.5", "2.0.0"]
),
]
)
let bRepo = RepositorySpecifier(url: workspace.urlForPackage(withName: "B"))
let cRepo = RepositorySpecifier(url: workspace.urlForPackage(withName: "C"))
let bRef = PackageReference(identity: PackageIdentity(url: bRepo.url), path: bRepo.url)
let cRef = PackageReference(identity: PackageIdentity(url: cRepo.url), path: cRepo.url)
try workspace.set(
pins: [bRef: v1_5, cRef: v2],
managedDependencies: [
ManagedDependency(packageRef: bRef, subpath: bPath, checkoutState: v1_5),
ManagedDependency(packageRef: cRef, subpath: cPath, checkoutState: v2),
]
)
try workspace.checkPrecomputeResolution { result in
XCTAssertEqual(result.diagnostics.hasErrors, false)
XCTAssertEqual(result.result.isRequired, false)
}
}
func testLoadingRootManifests() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fs: fs,
roots: [
.genericPackage1(named: "A"),
.genericPackage1(named: "B"),
.genericPackage1(named: "C"),
],
packages: []
)
workspace.checkPackageGraph(roots: ["A", "B", "C"]) { graph, diagnostics in
PackageGraphTester(graph) { result in
result.check(packages: "A", "B", "C")
result.check(targets: "A", "B", "C")
}
XCTAssertNoDiagnostics(diagnostics)
}
}
func testUpdate() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fs: fs,
roots: [
MockPackage(
name: "Root",
targets: [
MockTarget(name: "Root", dependencies: ["Foo"]),
],
products: [
MockProduct(name: "Root", targets: ["Root"]),
],
dependencies: [
MockDependency(name: "Foo", requirement: .upToNextMajor(from: "1.0.0")),
]
),
],
packages: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo", dependencies: ["Bar"]),
],
products: [
MockProduct(name: "Foo", targets: ["Foo"]),
],
dependencies: [
MockDependency(name: "Bar", requirement: .upToNextMajor(from: "1.0.0")),
],
versions: ["1.0.0"]
),
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo"),
],
products: [
MockProduct(name: "Foo", targets: ["Foo"]),
],
versions: ["1.5.0"]
),
MockPackage(
name: "Bar",
targets: [
MockTarget(name: "Bar"),
],
products: [
MockProduct(name: "Bar", targets: ["Bar"]),
],
versions: ["1.0.0"]
),
]
)
// Do an intial run, capping at Foo at 1.0.0.
let deps: [MockDependency] = [
.init(name: "Foo", requirement: .exact("1.0.0"), products: .specific(["Foo"])),
]
workspace.checkPackageGraph(roots: ["Root"], deps: deps) { graph, diagnostics in
PackageGraphTester(graph) { result in
result.check(roots: "Root")
result.check(packages: "Bar", "Foo", "Root")
}
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkManagedDependencies { result in
result.check(dependency: "foo", at: .checkout(.version("1.0.0")))
result.check(dependency: "bar", at: .checkout(.version("1.0.0")))
}
// Run update.
workspace.checkUpdate(roots: ["Root"]) { diagnostics in
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkPackageGraph(roots: ["Root"]) { graph, diagnostics in
PackageGraphTester(graph) { result in
result.check(roots: "Root")
result.check(packages: "Foo", "Root")
}
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkManagedDependencies { result in
result.check(dependency: "foo", at: .checkout(.version("1.5.0")))
}
XCTAssertMatch(workspace.delegate.events, [.equal("removing repo: /tmp/ws/pkgs/Bar")])
// Run update again.
// Ensure that up-to-date delegate is called when there is nothing to update.
workspace.checkUpdate(roots: ["Root"]) { diagnostics in
XCTAssertNoDiagnostics(diagnostics)
}
XCTAssertMatch(workspace.delegate.events, [.equal("Everything is already up-to-date")])
}
func testUpdateDryRun() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fs: fs,
roots: [
MockPackage(
name: "Root",
targets: [
MockTarget(name: "Root", dependencies: ["Foo"]),
],
products: [
MockProduct(name: "Root", targets: ["Root"]),
],
dependencies: [
MockDependency(name: "Foo", requirement: .upToNextMajor(from: "1.0.0")),
]
),
],
packages: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo"),
],
products: [
MockProduct(name: "Foo", targets: ["Foo"]),
],
versions: ["1.0.0"]
),
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo"),
],
products: [
MockProduct(name: "Foo", targets: ["Foo"]),
],
versions: ["1.5.0"]
),
]
)
// Do an intial run, capping at Foo at 1.0.0.
let deps: [MockDependency] = [
.init(name: "Foo", requirement: .exact("1.0.0"), products: .specific(["Foo"])),
]
workspace.checkPackageGraph(roots: ["Root"], deps: deps) { graph, diagnostics in
PackageGraphTester(graph) { result in
result.check(roots: "Root")
result.check(packages: "Foo", "Root")
}
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkManagedDependencies { result in
result.check(dependency: "foo", at: .checkout(.version("1.0.0")))
}
// Run update.
workspace.checkUpdateDryRun(roots: ["Root"]) { changes, diagnostics in
XCTAssertNoDiagnostics(diagnostics)
#if ENABLE_TARGET_BASED_DEPENDENCY_RESOLUTION
let stateChange = Workspace.PackageStateChange.updated(.init(requirement: .version(Version("1.5.0")), products: .specific(["Foo"])))
#else
let stateChange = Workspace.PackageStateChange.updated(.init(requirement: .version(Version("1.5.0")), products: .everything))
#endif
let path = AbsolutePath("/tmp/ws/pkgs/Foo")
let expectedChange = (
PackageReference(identity: PackageIdentity(path: path), path: path.pathString),
stateChange
)
guard let change = changes?.first, changes?.count == 1 else {
XCTFail()
return
}
XCTAssertEqual(expectedChange, change)
}
workspace.checkPackageGraph(roots: ["Root"]) { graph, diagnostics in
PackageGraphTester(graph) { result in
result.check(roots: "Root")
result.check(packages: "Foo", "Root")
}
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkManagedDependencies { result in
result.check(dependency: "foo", at: .checkout(.version("1.0.0")))
}
}
func testPartialUpdate() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fs: fs,
roots: [
MockPackage(
name: "Root",
targets: [
MockTarget(name: "Root", dependencies: ["Foo"]),
],
products: [
MockProduct(name: "Root", targets: ["Root"]),
],
dependencies: [
MockDependency(name: "Foo", requirement: .upToNextMajor(from: "1.0.0")),
]
),
],
packages: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo", dependencies: ["Bar"]),
],
products: [
MockProduct(name: "Foo", targets: ["Foo"]),
],
dependencies: [
MockDependency(name: "Bar", requirement: .upToNextMajor(from: "1.0.0")),
],
versions: ["1.5.0"]
),
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo", dependencies: ["Bar"]),
],
products: [
MockProduct(name: "Foo", targets: ["Foo"]),
],
dependencies: [
MockDependency(name: "Bar", requirement: .upToNextMinor(from: "1.0.0")),
],
versions: ["1.0.0"]
),
MockPackage(
name: "Bar",
targets: [
MockTarget(name: "Bar"),
],
products: [
MockProduct(name: "Bar", targets: ["Bar"]),
],
versions: ["1.0.0", "1.2.0"]
),
]
)
// Do an intial run, capping at Foo at 1.0.0.
let deps: [MockDependency] = [
.init(name: "Foo", requirement: .exact("1.0.0"), products: .specific(["Foo"])),
]
workspace.checkPackageGraph(roots: ["Root"], deps: deps) { _, diagnostics in
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkManagedDependencies { result in
result.check(dependency: "foo", at: .checkout(.version("1.0.0")))
result.check(dependency: "bar", at: .checkout(.version("1.0.0")))
}
// Run partial updates.
//
// Try to update just Bar. This shouldn't do anything because Bar can't be updated due
// to Foo's requirements.
workspace.checkUpdate(roots: ["Root"], packages: ["Bar"]) { diagnostics in
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkManagedDependencies { result in
result.check(dependency: "foo", at: .checkout(.version("1.0.0")))
result.check(dependency: "bar", at: .checkout(.version("1.0.0")))
}
// Try to update just Foo. This should update Foo but not Bar.
workspace.checkUpdate(roots: ["Root"], packages: ["Foo"]) { diagnostics in
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkManagedDependencies { result in
result.check(dependency: "foo", at: .checkout(.version("1.5.0")))
result.check(dependency: "bar", at: .checkout(.version("1.0.0")))
}
// Run full update.
workspace.checkUpdate(roots: ["Root"]) { diagnostics in
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkManagedDependencies { result in
result.check(dependency: "foo", at: .checkout(.version("1.5.0")))
result.check(dependency: "bar", at: .checkout(.version("1.2.0")))
}
}
func testCleanAndReset() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fs: fs,
roots: [
MockPackage(
name: "Root",
targets: [
MockTarget(name: "Root", dependencies: ["Foo"]),
],
products: [
MockProduct(name: "Root", targets: ["Root"]),
],
dependencies: [
MockDependency(name: "Foo", requirement: .upToNextMajor(from: "1.0.0")),
]
),
],
packages: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo"),
],
products: [
MockProduct(name: "Foo", targets: ["Foo"]),
],
versions: ["1.0.0"]
),
]
)
// Load package graph.
workspace.checkPackageGraph(roots: ["Root"]) { _, diagnostics in
XCTAssertNoDiagnostics(diagnostics)
}
// Drop a build artifact in data directory.
let ws = workspace.createWorkspace()
let buildArtifact = ws.dataPath.appending(component: "test.o")
try fs.writeFileContents(buildArtifact, bytes: "Hi")
// Sanity checks.
XCTAssert(fs.exists(buildArtifact))
XCTAssert(fs.exists(ws.checkoutsPath))
// Check clean.
workspace.checkClean { diagnostics in
// Only the build artifact should be removed.
XCTAssertFalse(fs.exists(buildArtifact))
XCTAssert(fs.exists(ws.checkoutsPath))
XCTAssert(fs.exists(ws.dataPath))
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkManagedDependencies { result in
result.check(dependency: "foo", at: .checkout(.version("1.0.0")))
}
// Add the build artifact again.
try fs.writeFileContents(buildArtifact, bytes: "Hi")
// Check reset.
workspace.checkReset { diagnostics in
// Only the build artifact should be removed.
XCTAssertFalse(fs.exists(buildArtifact))
XCTAssertFalse(fs.exists(ws.checkoutsPath))
XCTAssertFalse(fs.exists(ws.dataPath))
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkManagedDependencies { result in
result.checkEmpty()
}
}
func testDependencyManifestLoading() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fs: fs,
roots: [
MockPackage(
name: "Root1",
targets: [
MockTarget(name: "Root1", dependencies: ["Foo"]),
],
products: [],
dependencies: [
MockDependency(name: "Foo", requirement: .upToNextMajor(from: "1.0.0")),
]
),
MockPackage(
name: "Root2",
targets: [
MockTarget(name: "Root2", dependencies: ["Bar"]),
],
products: [],
dependencies: [
MockDependency(name: "Bar", requirement: .upToNextMajor(from: "1.0.0")),
]
),
],
packages: [
.genericPackage1(named: "Foo"),
.genericPackage1(named: "Bar"),
]
)
// Check that we can compute missing dependencies.
try workspace.loadDependencyManifests(roots: ["Root1", "Root2"]) { manifests, diagnostics in
XCTAssertEqual(manifests.missingPackageURLs().map { $0.path }.sorted(), ["/tmp/ws/pkgs/Bar", "/tmp/ws/pkgs/Foo"])
XCTAssertNoDiagnostics(diagnostics)
}
// Load the graph with one root.
workspace.checkPackageGraph(roots: ["Root1"]) { graph, diagnostics in
PackageGraphTester(graph) { result in
result.check(packages: "Foo", "Root1")
}
XCTAssertNoDiagnostics(diagnostics)
}
// Check that we compute the correct missing dependencies.
try workspace.loadDependencyManifests(roots: ["Root1", "Root2"]) { manifests, diagnostics in
XCTAssertEqual(manifests.missingPackageURLs().map { $0.path }.sorted(), ["/tmp/ws/pkgs/Bar"])
XCTAssertNoDiagnostics(diagnostics)
}
// Load the graph with both roots.
workspace.checkPackageGraph(roots: ["Root1", "Root2"]) { graph, diagnostics in
PackageGraphTester(graph) { result in
result.check(packages: "Bar", "Foo", "Root1", "Root2")
}
XCTAssertNoDiagnostics(diagnostics)
}
// Check that we compute the correct missing dependencies.
try workspace.loadDependencyManifests(roots: ["Root1", "Root2"]) { manifests, diagnostics in
XCTAssertEqual(manifests.missingPackageURLs().map { $0.path }.sorted(), [])
XCTAssertNoDiagnostics(diagnostics)
}
}
func testDependencyManifestsOrder() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fs: fs,
roots: [
MockPackage(
name: "Root1",
targets: [
MockTarget(name: "Root1", dependencies: ["Foo", "Bar", "Baz", "Bam"]),
],
products: [],
dependencies: [
MockDependency(name: "Foo", requirement: .upToNextMajor(from: "1.0.0")),
MockDependency(name: "Bar", requirement: .upToNextMajor(from: "1.0.0")),
MockDependency(name: "Baz", requirement: .upToNextMajor(from: "1.0.0")),
MockDependency(name: "Bam", requirement: .upToNextMajor(from: "1.0.0")),
]
),
],
packages: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo", dependencies: ["Bar", "Baz"]),
],
products: [
MockProduct(name: "Foo", targets: ["Foo"]),
],
dependencies: [
MockDependency(name: "Bar", requirement: .upToNextMajor(from: "1.0.0")),
MockDependency(name: "Baz", requirement: .upToNextMajor(from: "1.0.0")),
],
versions: ["1.0.0"]
),
.genericPackage1(named: "Bar"),
MockPackage(
name: "Baz",
targets: [
MockTarget(name: "Baz", dependencies: ["Bam"]),
],
products: [
MockProduct(name: "Baz", targets: ["Baz"]),
],
dependencies: [
MockDependency(name: "Bam", requirement: .upToNextMajor(from: "1.0.0")),
],
versions: ["1.0.0"]
),
.genericPackage1(named: "Bam"),
]
)
workspace.checkPackageGraph(roots: ["Root1"]) { _, diagnostics in
XCTAssertNoDiagnostics(diagnostics)
}
try workspace.loadDependencyManifests(roots: ["Root1"]) { manifests, diagnostics in
// Ensure that the order of the manifests is stable.
XCTAssertEqual(manifests.allDependencyManifests().map { $0.name }, ["Foo", "Baz", "Bam", "Bar"])
XCTAssertNoDiagnostics(diagnostics)
}
}
func testBranchAndRevision() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fs: fs,
roots: [
MockPackage(
name: "Root",
targets: [
MockTarget(name: "Root", dependencies: ["Foo"]),
],
products: [],
dependencies: [
MockDependency(name: "Foo", requirement: .branch("develop")),
]
),
],
packages: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo"),
],
products: [
MockProduct(name: "Foo", targets: ["Foo"]),
],
versions: ["develop"]
),
MockPackage(
name: "Bar",
targets: [
MockTarget(name: "Bar"),
],
products: [
MockProduct(name: "Bar", targets: ["Bar"]),
],
versions: ["boo"]
),
]
)
// Get some revision identifier of Bar.
let bar = RepositorySpecifier(url: "/tmp/ws/pkgs/Bar")
let barRevision = workspace.repoProvider.specifierMap[bar]!.revisions[0]
// We request Bar via revision.
let deps: [MockDependency] = [
.init(name: "Bar", requirement: .revision(barRevision), products: .specific(["Bar"])),
]
workspace.checkPackageGraph(roots: ["Root"], deps: deps) { graph, diagnostics in
PackageGraphTester(graph) { result in
result.check(roots: "Root")
result.check(packages: "Bar", "Foo", "Root")
}
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkManagedDependencies { result in
result.check(dependency: "foo", at: .checkout(.branch("develop")))
result.check(dependency: "bar", at: .checkout(.revision(barRevision)))
}
}
func testResolve() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fs: fs,
roots: [
MockPackage(
name: "Root",
targets: [
MockTarget(name: "Root", dependencies: ["Foo"]),
],
products: [],
dependencies: [
MockDependency(name: "Foo", requirement: .upToNextMajor(from: "1.0.0")),
]
),
],
packages: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo"),
],
products: [
MockProduct(name: "Foo", targets: ["Foo"]),
],
versions: ["1.0.0", "1.2.3"]
),
]
)
// Load initial version.
workspace.checkPackageGraph(roots: ["Root"]) { graph, diagnostics in
PackageGraphTester(graph) { result in
result.check(roots: "Root")
result.check(packages: "Foo", "Root")
}
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkManagedDependencies { result in
result.check(dependency: "foo", at: .checkout(.version("1.2.3")))
}
workspace.checkResolved { result in
result.check(dependency: "foo", at: .checkout(.version("1.2.3")))
}
// Resolve to an older version.
workspace.checkResolve(pkg: "Foo", roots: ["Root"], version: "1.0.0") { diagnostics in
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkManagedDependencies { result in
result.check(dependency: "foo", at: .checkout(.version("1.0.0")))
}
workspace.checkResolved { result in
result.check(dependency: "foo", at: .checkout(.version("1.0.0")))
}
// Check failure.
workspace.checkResolve(pkg: "Foo", roots: ["Root"], version: "1.3.0") { diagnostics in
DiagnosticsEngineTester(diagnostics) { result in
result.check(diagnostic: .contains("'Foo' 1.3.0"), behavior: .error)
}
}
workspace.checkManagedDependencies { result in
result.check(dependency: "foo", at: .checkout(.version("1.0.0")))
}
workspace.checkResolved { result in
result.check(dependency: "foo", at: .checkout(.version("1.0.0")))
}
}
func testDeletedCheckoutDirectory() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fs: fs,
roots: [
MockPackage(
name: "Root",
targets: [
MockTarget(name: "Root", dependencies: ["Foo"]),
],
products: [],
dependencies: [
MockDependency(name: "Foo", requirement: .upToNextMajor(from: "1.0.0")),
]
),
],
packages: [
.genericPackage1(named: "Foo"),
]
)
// Load the graph.
workspace.checkPackageGraph(roots: ["Root"]) { graph, diagnostics in
PackageGraphTester(graph) { result in
result.check(roots: "Root")
result.check(packages: "Foo", "Root")
}
XCTAssertNoDiagnostics(diagnostics)
}
try fs.removeFileTree(workspace.createWorkspace().checkoutsPath)
workspace.checkPackageGraph(roots: ["Root"]) { graph, diagnostics in
PackageGraphTester(graph) { result in
result.check(roots: "Root")
result.check(packages: "Foo", "Root")
}
DiagnosticsEngineTester(diagnostics) { result in
result.check(diagnostic: .contains("dependency 'Foo' is missing; cloning again"), behavior: .warning)
}
}
}
func testMinimumRequiredToolsVersionInDependencyResolution() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fs: fs,
roots: [
MockPackage(
name: "Root",
targets: [
MockTarget(name: "Root", dependencies: ["Foo"]),
],
products: [],
dependencies: [
MockDependency(name: "Foo", requirement: .upToNextMajor(from: "1.0.0")),
]
),
],
packages: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo"),
],
products: [
MockProduct(name: "Foo", targets: ["Foo"]),
],
versions: ["1.0.0"],
toolsVersion: .v3
),
]
)
#if ENABLE_TARGET_BASED_DEPENDENCY_RESOLUTION
workspace.checkPackageGraph(roots: ["Root"]) { _, diagnostics in
DiagnosticsEngineTester(diagnostics) { result in
result.check(diagnostic: .contains("Foo[Foo] 1.0.0..<2.0.0"), behavior: .error)
}
}
#endif
}
func testToolsVersionRootPackages() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fs: fs,
roots: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo"),
],
products: []
),
MockPackage(
name: "Bar",
targets: [
MockTarget(name: "Bar"),
],
products: []
),
MockPackage(
name: "Baz",
targets: [
MockTarget(name: "Baz"),
],
products: []
),
],
packages: [],
toolsVersion: .v4
)
let roots = workspace.rootPaths(for: ["Foo", "Bar", "Baz"]).map { $0.appending(component: "Package.swift") }
try fs.writeFileContents(roots[0], bytes: "// swift-tools-version:4.0")
try fs.writeFileContents(roots[1], bytes: "// swift-tools-version:4.1.0")
try fs.writeFileContents(roots[2], bytes: "// swift-tools-version:3.1")
workspace.checkPackageGraph(roots: ["Foo"]) { _, diagnostics in
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkPackageGraph(roots: ["Bar"]) { _, diagnostics in
DiagnosticsEngineTester(diagnostics) { result in
result.check(diagnostic: .equal("package at '/tmp/ws/roots/Bar' is using Swift tools version 4.1.0 but the installed version is 4.0.0"), behavior: .error, location: "/tmp/ws/roots/Bar")
}
}
workspace.checkPackageGraph(roots: ["Foo", "Bar"]) { _, diagnostics in
DiagnosticsEngineTester(diagnostics) { result in
result.check(diagnostic: .equal("package at '/tmp/ws/roots/Bar' is using Swift tools version 4.1.0 but the installed version is 4.0.0"), behavior: .error, location: "/tmp/ws/roots/Bar")
}
}
workspace.checkPackageGraph(roots: ["Baz"]) { _, diagnostics in
DiagnosticsEngineTester(diagnostics) { result in
result.check(diagnostic: .equal("package at '/tmp/ws/roots/Baz' is using Swift tools version 3.1.0 which is no longer supported; consider using '// swift-tools-version:4.0' to specify the current tools version"), behavior: .error, location: "/tmp/ws/roots/Baz")
}
}
}
func testEditDependency() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fs: fs,
roots: [
MockPackage(
name: "Root",
targets: [
MockTarget(name: "Root", dependencies: ["Foo", "Bar"]),
],
products: [],
dependencies: [
MockDependency(name: "Foo", requirement: .upToNextMajor(from: "1.0.0")),
MockDependency(name: "Bar", requirement: .upToNextMajor(from: "1.0.0")),
]
),
],
packages: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo"),
],
products: [
MockProduct(name: "Foo", targets: ["Foo"]),
],
versions: ["1.0.0", nil]
),
MockPackage(
name: "Bar",
targets: [
MockTarget(name: "Bar"),
],
products: [
MockProduct(name: "Bar", targets: ["Bar"]),
],
versions: ["1.0.0", nil]
),
]
)
// Load the graph.
workspace.checkPackageGraph(roots: ["Root"]) { graph, diagnostics in
PackageGraphTester(graph) { result in
result.check(roots: "Root")
result.check(packages: "Bar", "Foo", "Root")
}
XCTAssertNoDiagnostics(diagnostics)
}
// Edit foo.
let fooPath = workspace.createWorkspace().editablesPath.appending(component: "Foo")
workspace.checkEdit(packageName: "Foo") { diagnostics in
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkManagedDependencies { result in
result.check(dependency: "foo", at: .edited(nil))
}
XCTAssertTrue(fs.exists(fooPath))
try workspace.loadDependencyManifests(roots: ["Root"]) { manifests, diagnostics in
let editedPackages = manifests.editedPackagesConstraints()
XCTAssertEqual(editedPackages.map { $0.identifier.path }, [fooPath.pathString])
XCTAssertNoDiagnostics(diagnostics)
}
// Try re-editing foo.
workspace.checkEdit(packageName: "Foo") { diagnostics in
DiagnosticsEngineTester(diagnostics) { result in
result.check(diagnostic: .equal("dependency 'Foo' already in edit mode"), behavior: .error)
}
}
workspace.checkManagedDependencies { result in
result.check(dependency: "foo", at: .edited(nil))
}
// Try editing bar at bad revision.
workspace.checkEdit(packageName: "Bar", revision: Revision(identifier: "dev")) { diagnostics in
DiagnosticsEngineTester(diagnostics) { result in
result.check(diagnostic: .equal("revision 'dev' does not exist"), behavior: .error)
}
}
// Edit bar at a custom path and branch (ToT).
let barPath = AbsolutePath("/tmp/ws/custom/bar")
workspace.checkEdit(packageName: "Bar", path: barPath, checkoutBranch: "dev") { diagnostics in
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkManagedDependencies { result in
result.check(dependency: "bar", at: .edited(barPath))
}
let barRepo = try workspace.repoProvider.openCheckout(at: barPath) as! InMemoryGitRepository
XCTAssert(barRepo.revisions.contains("dev"))
// Test unediting.
workspace.checkUnedit(packageName: "Foo", roots: ["Root"]) { diagnostics in
XCTAssertFalse(fs.exists(fooPath))
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkUnedit(packageName: "Bar", roots: ["Root"]) { diagnostics in
XCTAssert(fs.exists(barPath))
XCTAssertNoDiagnostics(diagnostics)
}
}
func testMissingEditCanRestoreOriginalCheckout() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fs: fs,
roots: [
MockPackage(
name: "Root",
targets: [
MockTarget(name: "Root", dependencies: ["Foo"]),
],
products: [],
dependencies: [
MockDependency(name: "Foo", requirement: .upToNextMajor(from: "1.0.0")),
]
),
],
packages: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo"),
],
products: [
MockProduct(name: "Foo", targets: ["Foo"]),
],
versions: ["1.0.0", nil]
),
]
)
// Load the graph.
workspace.checkPackageGraph(roots: ["Root"]) { _, _ in }
// Edit foo.
let fooPath = workspace.createWorkspace().editablesPath.appending(component: "Foo")
workspace.checkEdit(packageName: "Foo") { diagnostics in
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkManagedDependencies { result in
result.check(dependency: "foo", at: .edited(nil))
}
XCTAssertTrue(fs.exists(fooPath))
// Remove the edited package.
try fs.removeFileTree(fooPath)
workspace.checkPackageGraph(roots: ["Root"]) { _, diagnostics in
DiagnosticsEngineTester(diagnostics) { result in
result.check(diagnostic: .equal("dependency 'Foo' was being edited but is missing; falling back to original checkout"), behavior: .warning)
}
}
workspace.checkManagedDependencies { result in
result.check(dependency: "foo", at: .checkout(.version("1.0.0")))
}
}
func testCanUneditRemovedDependencies() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fs: fs,
roots: [],
packages: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo"),
],
products: [
MockProduct(name: "Foo", targets: ["Foo"]),
],
versions: ["1.0.0", nil]
),
]
)
let deps: [MockDependency] = [
.init(name: "Foo", requirement: .upToNextMajor(from: "1.0.0"), products: .specific(["Foo"])),
]
let ws = workspace.createWorkspace()
// Load the graph and edit foo.
workspace.checkPackageGraph(deps: deps) { graph, diagnostics in
PackageGraphTester(graph) { result in
result.check(packages: "Foo")
}
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkEdit(packageName: "Foo") { diagnostics in
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkManagedDependencies { result in
result.check(dependency: "foo", at: .edited(nil))
}
// Remove foo.
workspace.checkUpdate { diagnostics in
XCTAssertNoDiagnostics(diagnostics)
}
XCTAssertMatch(workspace.delegate.events, [.equal("removing repo: /tmp/ws/pkgs/Foo")])
workspace.checkPackageGraph(deps: []) { _, diagnostics in
XCTAssertNoDiagnostics(diagnostics)
}
// There should still be an entry for `foo`, which we can unedit.
let editedDependency = ws.state.dependencies[forNameOrIdentity: "foo"]!
XCTAssertNil(editedDependency.basedOn)
workspace.checkManagedDependencies { result in
result.check(dependency: "foo", at: .edited(nil))
}
// Unedit foo.
workspace.checkUnedit(packageName: "Foo", roots: []) { diagnostics in
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkManagedDependencies { result in
result.checkEmpty()
}
}
func testDependencyResolutionWithEdit() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fs: fs,
roots: [
MockPackage(
name: "Root",
targets: [
MockTarget(name: "Root", dependencies: ["Foo", "Bar"]),
],
products: [],
dependencies: [
MockDependency(name: "Foo", requirement: .upToNextMajor(from: "1.0.0")),
MockDependency(name: "Bar", requirement: .upToNextMajor(from: "1.0.0")),
]
),
],
packages: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo"),
],
products: [
MockProduct(name: "Foo", targets: ["Foo"]),
],
versions: ["1.0.0", "1.2.0", "1.3.2"]
),
MockPackage(
name: "Bar",
targets: [
MockTarget(name: "Bar"),
],
products: [
MockProduct(name: "Bar", targets: ["Bar"]),
],
versions: ["1.0.0", nil]
),
]
)
let deps: [MockDependency] = [
.init(name: "Foo", requirement: .exact("1.0.0"), products: .specific(["Foo"])),
]
// Load the graph.
workspace.checkPackageGraph(roots: ["Root"], deps: deps) { graph, diagnostics in
PackageGraphTester(graph) { result in
result.check(roots: "Root")
result.check(packages: "Bar", "Foo", "Root")
}
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkManagedDependencies { result in
result.check(dependency: "foo", at: .checkout(.version("1.0.0")))
result.check(dependency: "bar", at: .checkout(.version("1.0.0")))
}
// Edit bar.
workspace.checkEdit(packageName: "Bar") { diagnostics in
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkManagedDependencies { result in
result.check(dependency: "foo", at: .checkout(.version("1.0.0")))
result.check(dependency: "bar", at: .edited(nil))
}
workspace.checkResolved { result in
result.check(dependency: "foo", at: .checkout(.version("1.0.0")))
result.check(dependency: "bar", at: .checkout(.version("1.0.0")))
}
// Add entry for the edited package.
do {
let barKey = MockManifestLoader.Key(url: "/tmp/ws/pkgs/Bar")
let editedBarKey = MockManifestLoader.Key(url: "/tmp/ws/edits/Bar")
let manifest = workspace.manifestLoader.manifests[barKey]!
workspace.manifestLoader.manifests[editedBarKey] = manifest
}
// Now, resolve foo at a different version.
workspace.checkResolve(pkg: "Foo", roots: ["Root"], version: "1.2.0") { diagnostics in
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkManagedDependencies { result in
result.check(dependency: "foo", at: .checkout(.version("1.2.0")))
result.check(dependency: "bar", at: .edited(nil))
}
workspace.checkResolved { result in
result.check(dependency: "foo", at: .checkout(.version("1.2.0")))
result.check(notPresent: "bar")
}
// Try package update.
workspace.checkUpdate(roots: ["Root"]) { diagnostics in
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkManagedDependencies { result in
result.check(dependency: "foo", at: .checkout(.version("1.3.2")))
result.check(dependency: "bar", at: .edited(nil))
}
workspace.checkResolved { result in
result.check(dependency: "foo", at: .checkout(.version("1.3.2")))
result.check(notPresent: "bar")
}
// Unedit should get the Package.resolved entry back.
workspace.checkUnedit(packageName: "bar", roots: ["Root"]) { diagnostics in
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkManagedDependencies { result in
result.check(dependency: "foo", at: .checkout(.version("1.3.2")))
result.check(dependency: "bar", at: .checkout(.version("1.0.0")))
}
workspace.checkResolved { result in
result.check(dependency: "foo", at: .checkout(.version("1.3.2")))
result.check(dependency: "bar", at: .checkout(.version("1.0.0")))
}
}
func testPrefetchingWithOverridenPackage() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fs: fs,
roots: [
MockPackage(
name: "Root",
targets: [
MockTarget(name: "Root", dependencies: ["Foo"]),
],
products: [],
dependencies: [
MockDependency(name: "Foo", requirement: .upToNextMajor(from: "1.0.0")),
]
),
],
packages: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo"),
],
products: [
MockProduct(name: "Foo", targets: ["Foo"]),
],
versions: ["1.0.0"]
),
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo", dependencies: ["Bar"]),
],
products: [
MockProduct(name: "Foo", targets: ["Foo"]),
],
dependencies: [
MockDependency(name: "Bar", requirement: .upToNextMajor(from: "1.0.0")),
],
versions: [nil]
),
MockPackage(
name: "Bar",
targets: [
MockTarget(name: "Bar"),
],
products: [
MockProduct(name: "Bar", targets: ["Bar"]),
],
versions: ["1.0.0"]
),
]
)
// Load the graph.
workspace.checkPackageGraph(roots: ["Root"]) { graph, diagnostics in
PackageGraphTester(graph) { result in
result.check(roots: "Root")
result.check(packages: "Foo", "Root")
}
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkManagedDependencies { result in
result.check(dependency: "foo", at: .checkout(.version("1.0.0")))
}
let deps: [MockDependency] = [
.init(name: "Foo", requirement: .localPackage, products: .specific(["Foo"])),
]
workspace.checkPackageGraph(roots: ["Root"], deps: deps) { graph, diagnostics in
PackageGraphTester(graph) { result in
result.check(roots: "Root")
result.check(packages: "Foo", "Bar", "Root")
}
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkManagedDependencies { result in
result.check(dependency: "foo", at: .local)
result.check(dependency: "bar", at: .checkout(.version("1.0.0")))
}
}
// Test that changing a particular dependency re-resolves the graph.
func testChangeOneDependency() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fs: fs,
roots: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo", dependencies: ["Bar"]),
],
products: [
MockProduct(name: "Foo", targets: ["Foo"]),
],
dependencies: [
MockDependency(name: "Bar", requirement: .exact("1.0.0")),
]
),
],
packages: [
MockPackage(
name: "Bar",
targets: [
MockTarget(name: "Bar"),
],
products: [
MockProduct(name: "Bar", targets: ["Bar"]),
],
versions: ["1.0.0", "1.5.0"]
),
]
)
// Initial resolution.
workspace.checkPackageGraph(roots: ["Foo"]) { graph, diagnostics in
PackageGraphTester(graph) { result in
result.check(roots: "Foo")
result.check(packages: "Bar", "Foo")
}
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkManagedDependencies { result in
result.check(dependency: "bar", at: .checkout(.version("1.0.0")))
}
// Check that changing the requirement to 1.5.0 triggers re-resolution.
//
// FIXME: Find a cleaner way to change a dependency requirement.
let fooKey = MockManifestLoader.Key(url: "/tmp/ws/roots/Foo")
let manifest = workspace.manifestLoader.manifests[fooKey]!
workspace.manifestLoader.manifests[fooKey] = Manifest(
name: manifest.name,
platforms: [],
path: manifest.path,
url: manifest.url,
version: manifest.version,
toolsVersion: manifest.toolsVersion,
packageKind: .root,
dependencies: [PackageDependencyDescription(url: manifest.dependencies[0].url, requirement: .exact("1.5.0"))],
targets: manifest.targets
)
workspace.checkPackageGraph(roots: ["Foo"]) { _, diagnostics in
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkManagedDependencies { result in
result.check(dependency: "bar", at: .checkout(.version("1.5.0")))
}
}
func testResolutionFailureWithEditedDependency() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fs: fs,
roots: [
MockPackage(
name: "Root",
targets: [
MockTarget(name: "Root", dependencies: ["Foo"]),
],
products: [],
dependencies: [
MockDependency(name: "Foo", requirement: .upToNextMajor(from: "1.0.0")),
]
),
],
packages: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo"),
],
products: [
MockProduct(name: "Foo", targets: ["Foo"]),
],
versions: ["1.0.0", nil]
),
MockPackage(
name: "Bar",
targets: [
MockTarget(name: "Bar"),
],
products: [
MockProduct(name: "Bar", targets: ["Bar"]),
],
versions: ["1.0.0", nil]
),
]
)
// Load the graph.
workspace.checkPackageGraph(roots: ["Root"]) { graph, diagnostics in
PackageGraphTester(graph) { result in
result.check(roots: "Root")
result.check(packages: "Foo", "Root")
}
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkEdit(packageName: "Foo") { diagnostics in
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkManagedDependencies { result in
result.check(dependency: "foo", at: .edited(nil))
}
workspace.checkResolved { result in
result.check(dependency: "foo", at: .checkout(.version("1.0.0")))
}
// Add entry for the edited package.
do {
let fooKey = MockManifestLoader.Key(url: "/tmp/ws/pkgs/Foo")
let editedFooKey = MockManifestLoader.Key(url: "/tmp/ws/edits/Foo")
let manifest = workspace.manifestLoader.manifests[fooKey]!
workspace.manifestLoader.manifests[editedFooKey] = manifest
}
// Try resolving a bad graph.
let deps: [MockDependency] = [
.init(name: "Bar", requirement: .exact("1.1.0"), products: .specific(["Bar"])),
]
workspace.checkPackageGraph(roots: ["Root"], deps: deps) { _, diagnostics in
DiagnosticsEngineTester(diagnostics) { result in
result.check(diagnostic: .contains("'Bar' 1.1.0"), behavior: .error)
}
}
}
func testSkipUpdate() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fs: fs,
roots: [
MockPackage(
name: "Root",
targets: [
MockTarget(name: "Root", dependencies: ["Foo"]),
],
products: [
MockProduct(name: "Root", targets: ["Root"]),
],
dependencies: [
MockDependency(name: "Foo", requirement: .upToNextMajor(from: "1.0.0")),
]
),
],
packages: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo"),
],
products: [
MockProduct(name: "Foo", targets: ["Foo"]),
],
versions: ["1.5.0"]
),
],
skipUpdate: true
)
// Run update and remove all events.
workspace.checkUpdate(roots: ["Root"]) { diagnostics in
XCTAssertNoDiagnostics(diagnostics)
}
workspace.delegate.clear()
// Check we don't have updating Foo event.
workspace.checkUpdate(roots: ["Root"]) { diagnostics in
XCTAssertNoDiagnostics(diagnostics)
XCTAssertMatch(workspace.delegate.events, ["Everything is already up-to-date"])
}
}
func testLocalDependencyBasics() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fs: fs,
roots: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo", dependencies: ["Bar", "Baz"]),
MockTarget(name: "FooTests", dependencies: ["Foo"], type: .test),
],
products: [],
dependencies: [
MockDependency(name: "Bar", requirement: .localPackage),
MockDependency(name: "Baz", requirement: .upToNextMajor(from: "1.0.0")),
]
),
],
packages: [
MockPackage(
name: "Bar",
targets: [
MockTarget(name: "Bar"),
],
products: [
MockProduct(name: "Bar", targets: ["Bar"]),
],
versions: ["1.0.0", "1.5.0", nil]
),
MockPackage(
name: "Baz",
targets: [
MockTarget(name: "Baz", dependencies: ["Bar"]),
],
products: [
MockProduct(name: "Baz", targets: ["Baz"]),
],
dependencies: [
MockDependency(name: "Bar", requirement: .upToNextMajor(from: "1.0.0")),
],
versions: ["1.0.0", "1.5.0"]
),
]
)
workspace.checkPackageGraph(roots: ["Foo"]) { graph, diagnostics in
PackageGraphTester(graph) { result in
result.check(roots: "Foo")
result.check(packages: "Bar", "Baz", "Foo")
result.check(targets: "Bar", "Baz", "Foo")
result.check(testModules: "FooTests")
result.checkTarget("Baz") { result in result.check(dependencies: "Bar") }
result.checkTarget("Foo") { result in result.check(dependencies: "Baz", "Bar") }
result.checkTarget("FooTests") { result in result.check(dependencies: "Foo") }
}
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkManagedDependencies { result in
result.check(dependency: "baz", at: .checkout(.version("1.5.0")))
result.check(dependency: "bar", at: .local)
}
// Test that its not possible to edit or resolve this package.
workspace.checkEdit(packageName: "Bar") { diagnostics in
DiagnosticsEngineTester(diagnostics) { result in
result.check(diagnostic: .contains("local dependency 'Bar' can't be edited"), behavior: .error)
}
}
workspace.checkResolve(pkg: "Bar", roots: ["Foo"], version: "1.0.0") { diagnostics in
DiagnosticsEngineTester(diagnostics) { result in
result.check(diagnostic: .contains("local dependency 'Bar' can't be edited"), behavior: .error)
}
}
}
func testLocalDependencyTransitive() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fs: fs,
roots: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo", dependencies: ["Bar"]),
MockTarget(name: "FooTests", dependencies: ["Foo"], type: .test),
],
products: [],
dependencies: [
MockDependency(name: "Bar", requirement: .upToNextMajor(from: "1.0.0")),
]
),
],
packages: [
MockPackage(
name: "Bar",
targets: [
MockTarget(name: "Bar", dependencies: ["Baz"]),
],
products: [
MockProduct(name: "Bar", targets: ["Bar"]),
],
dependencies: [
MockDependency(name: "Baz", requirement: .localPackage),
],
versions: ["1.0.0", "1.5.0", nil]
),
MockPackage(
name: "Baz",
targets: [
MockTarget(name: "Baz"),
],
products: [
MockProduct(name: "Baz", targets: ["Baz"]),
],
versions: ["1.0.0", "1.5.0", nil]
),
]
)
workspace.checkPackageGraph(roots: ["Foo"]) { graph, diagnostics in
PackageGraphTester(graph) { result in
result.check(roots: "Foo")
result.check(packages: "Foo")
result.check(targets: "Foo")
}
#if ENABLE_TARGET_BASED_DEPENDENCY_RESOLUTION
DiagnosticsEngineTester(diagnostics) { result in
result.check(diagnostic: .contains("Bar[Bar] {1.0.0..<1.5.0, 1.5.1..<2.0.0} is forbidden"), behavior: .error)
}
#endif
}
}
func testLocalDependencyWithPackageUpdate() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fs: fs,
roots: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo", dependencies: ["Bar"]),
],
products: [],
dependencies: [
MockDependency(name: "Bar", requirement: .upToNextMajor(from: "1.0.0")),
]
),
],
packages: [
MockPackage(
name: "Bar",
targets: [
MockTarget(name: "Bar"),
],
products: [
MockProduct(name: "Bar", targets: ["Bar"]),
],
versions: ["1.0.0", "1.5.0", nil]
),
]
)
workspace.checkPackageGraph(roots: ["Foo"]) { graph, diagnostics in
PackageGraphTester(graph) { result in
result.check(roots: "Foo")
result.check(packages: "Bar", "Foo")
}
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkManagedDependencies { result in
result.check(dependency: "bar", at: .checkout(.version("1.5.0")))
}
// Override with local package and run update.
let deps: [MockDependency] = [
.init(name: "Bar", requirement: .localPackage, products: .specific(["Bar"])),
]
workspace.checkUpdate(roots: ["Foo"], deps: deps) { diagnostics in
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkManagedDependencies { result in
result.check(dependency: "bar", at: .local)
}
// Go back to the versioned state.
workspace.checkUpdate(roots: ["Foo"]) { diagnostics in
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkManagedDependencies { result in
result.check(dependency: "bar", at: .checkout(.version("1.5.0")))
}
}
func testMissingLocalDependencyDiagnostic() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fs: fs,
roots: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo", dependencies: []),
],
products: [],
dependencies: [
MockDependency(name: nil, path: "Bar", requirement: .localPackage),
]
),
],
packages: [
]
)
workspace.checkPackageGraph(roots: ["Foo"]) { graph, diagnostics in
PackageGraphTester(graph) { result in
result.check(roots: "Foo")
result.check(packages: "Foo")
result.check(targets: "Foo")
}
DiagnosticsEngineTester(diagnostics) { result in
result.check(diagnostic: .contains("the package at '/tmp/ws/pkgs/Bar' cannot be accessed (/tmp/ws/pkgs/Bar doesn't exist in file system"), behavior: .error)
}
}
}
func testRevisionVersionSwitch() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fs: fs,
roots: [
MockPackage(
name: "Root",
targets: [
MockTarget(name: "Root", dependencies: []),
],
products: [],
dependencies: []
),
],
packages: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo"),
],
products: [
MockProduct(name: "Foo", targets: ["Foo"]),
],
versions: ["develop", "1.0.0"]
),
]
)
// Test that switching between revision and version requirement works
// without running swift package update.
var deps: [MockDependency] = [
.init(name: "Foo", requirement: .branch("develop"), products: .specific(["Foo"])),
]
workspace.checkPackageGraph(roots: ["Root"], deps: deps) { graph, diagnostics in
PackageGraphTester(graph) { result in
result.check(roots: "Root")
result.check(packages: "Foo", "Root")
}
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkManagedDependencies { result in
result.check(dependency: "foo", at: .checkout(.branch("develop")))
}
deps = [
.init(name: "Foo", requirement: .upToNextMajor(from: "1.0.0"), products: .specific(["Foo"])),
]
workspace.checkPackageGraph(roots: ["Root"], deps: deps) { _, diagnostics in
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkManagedDependencies { result in
result.check(dependency: "foo", at: .checkout(.version("1.0.0")))
}
deps = [
.init(name: "Foo", requirement: .branch("develop"), products: .specific(["Foo"])),
]
workspace.checkPackageGraph(roots: ["Root"], deps: deps) { _, diagnostics in
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkManagedDependencies { result in
result.check(dependency: "foo", at: .checkout(.branch("develop")))
}
}
func testLocalVersionSwitch() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fs: fs,
roots: [
MockPackage(
name: "Root",
targets: [
MockTarget(name: "Root", dependencies: []),
],
products: [],
dependencies: []
),
],
packages: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo"),
],
products: [
MockProduct(name: "Foo", targets: ["Foo"]),
],
versions: ["develop", "1.0.0", nil]
),
]
)
// Test that switching between local and version requirement works
// without running swift package update.
var deps: [MockDependency] = [
.init(name: "Foo", requirement: .localPackage, products: .specific(["Foo"])),
]
workspace.checkPackageGraph(roots: ["Root"], deps: deps) { graph, diagnostics in
PackageGraphTester(graph) { result in
result.check(roots: "Root")
result.check(packages: "Foo", "Root")
}
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkManagedDependencies { result in
result.check(dependency: "foo", at: .local)
}
deps = [
.init(name: "Foo", requirement: .upToNextMajor(from: "1.0.0"), products: .specific(["Foo"])),
]
workspace.checkPackageGraph(roots: ["Root"], deps: deps) { _, diagnostics in
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkManagedDependencies { result in
result.check(dependency: "foo", at: .checkout(.version("1.0.0")))
}
deps = [
.init(name: "Foo", requirement: .localPackage, products: .specific(["Foo"])),
]
workspace.checkPackageGraph(roots: ["Root"], deps: deps) { _, diagnostics in
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkManagedDependencies { result in
result.check(dependency: "foo", at: .local)
}
}
func testLocalLocalSwitch() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fs: fs,
roots: [
MockPackage(
name: "Root",
targets: [
MockTarget(name: "Root", dependencies: []),
],
products: [],
dependencies: []
),
],
packages: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo"),
],
products: [
MockProduct(name: "Foo", targets: ["Foo"]),
],
versions: [nil]
),
MockPackage(
name: "Foo",
path: "Foo2",
targets: [
MockTarget(name: "Foo"),
],
products: [
MockProduct(name: "Foo", targets: ["Foo"]),
],
versions: [nil]
),
]
)
// Test that switching between two same local packages placed at
// different locations works correctly.
var deps: [MockDependency] = [
.init(name: "Foo", requirement: .localPackage, products: .specific(["Foo"])),
]
workspace.checkPackageGraph(roots: ["Root"], deps: deps) { graph, diagnostics in
PackageGraphTester(graph) { result in
result.check(roots: "Root")
result.check(packages: "Foo", "Root")
}
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkManagedDependencies { result in
result.check(dependency: "foo", at: .local)
}
deps = [
.init(name: "Foo2", requirement: .localPackage, products: .specific(["Foo"])),
]
workspace.checkPackageGraph(roots: ["Root"], deps: deps) { _, diagnostics in
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkManagedDependencies { result in
result.check(dependency: "foo2", at: .local)
}
}
func testDependencySwitchWithSameIdentity() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fs: fs,
roots: [
MockPackage(
name: "Root",
targets: [
MockTarget(name: "Root", dependencies: []),
],
products: [],
dependencies: []
),
],
packages: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo"),
],
products: [
MockProduct(name: "Foo", targets: ["Foo"]),
],
versions: [nil]
),
MockPackage(
name: "Foo",
path: "Nested/Foo",
targets: [
MockTarget(name: "Foo"),
],
products: [
MockProduct(name: "Foo", targets: ["Foo"]),
],
versions: [nil]
),
]
)
// Test that switching between two same local packages placed at
// different locations works correctly.
var deps: [MockDependency] = [
.init(name: "Foo", requirement: .localPackage, products: .specific(["Foo"])),
]
workspace.checkPackageGraph(roots: ["Root"], deps: deps) { graph, diagnostics in
PackageGraphTester(graph) { result in
result.check(roots: "Root")
result.check(packages: "Foo", "Root")
}
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkManagedDependencies { result in
result.check(dependency: "foo", at: .local)
}
do {
let ws = workspace.createWorkspace()
XCTAssertNotNil(ws.state.dependencies[forURL: "/tmp/ws/pkgs/Foo"])
}
deps = [
.init(name: "Nested/Foo", requirement: .localPackage, products: .specific(["Foo"])),
]
workspace.checkPackageGraph(roots: ["Root"], deps: deps) { _, diagnostics in
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkManagedDependencies { result in
result.check(dependency: "foo", at: .local)
}
do {
let ws = workspace.createWorkspace()
XCTAssertNotNil(ws.state.dependencies[forURL: "/tmp/ws/pkgs/Nested/Foo"])
}
}
func testResolvedFileUpdate() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fs: fs,
roots: [
MockPackage(
name: "Root",
targets: [
MockTarget(name: "Root", dependencies: []),
],
products: [],
dependencies: []
),
],
packages: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo"),
],
products: [
MockProduct(name: "Foo", targets: ["Foo"]),
],
versions: ["1.0.0"]
),
]
)
let deps: [MockDependency] = [
.init(name: "Foo", requirement: .upToNextMajor(from: "1.0.0"), products: .specific(["Foo"])),
]
workspace.checkPackageGraph(roots: ["Root"], deps: deps) { _, diagnostics in
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkManagedDependencies { result in
result.check(dependency: "foo", at: .checkout(.version("1.0.0")))
}
workspace.checkResolved { result in
result.check(dependency: "foo", at: .checkout(.version("1.0.0")))
}
workspace.checkPackageGraph(roots: ["Root"], deps: []) { _, diagnostics in
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkManagedDependencies { result in
result.check(dependency: "foo", at: .checkout(.version("1.0.0")))
}
workspace.checkResolved { result in
result.check(notPresent: "foo")
}
}
func testPackageMirror() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fs: fs,
roots: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo", dependencies: ["Dep"]),
],
products: [
MockProduct(name: "Foo", targets: ["Foo"]),
],
dependencies: [
MockDependency(name: "Dep", requirement: .upToNextMajor(from: "1.0.0")),
],
toolsVersion: .v5
),
],
packages: [
MockPackage(
name: "Dep",
targets: [
MockTarget(name: "Dep", dependencies: ["Bar"]),
],
products: [
MockProduct(name: "Dep", targets: ["Dep"]),
],
dependencies: [
MockDependency(name: nil, path: "Bar", requirement: .upToNextMajor(from: "1.0.0")),
],
versions: ["1.0.0", "1.5.0"],
toolsVersion: .v5
),
MockPackage(
name: "Bar",
targets: [
MockTarget(name: "Bar"),
],
products: [
MockProduct(name: "Bar", targets: ["Bar"]),
],
versions: ["1.0.0", "1.5.0"]
),
MockPackage(
name: "Baz",
targets: [
MockTarget(name: "Baz"),
],
products: [
MockProduct(name: "Bar", targets: ["Baz"]),
],
versions: ["1.0.0", "1.4.0"]
),
MockPackage(
name: "Bam",
targets: [
MockTarget(name: "Bam"),
],
products: [
MockProduct(name: "Bar", targets: ["Bam"]),
],
versions: ["1.0.0", "1.5.0"]
),
]
)
workspace.checkPackageGraph(roots: ["Foo"]) { graph, diagnostics in
PackageGraphTester(graph) { result in
result.check(roots: "Foo")
result.check(packages: "Foo", "Dep", "Bar")
result.check(targets: "Foo", "Dep", "Bar")
}
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkManagedDependencies { result in
result.check(dependency: "Dep", at: .checkout(.version("1.5.0")))
result.check(dependency: "Bar", at: .checkout(.version("1.5.0")))
result.check(notPresent: "Baz")
}
workspace.config.mirrors.set(mirrorURL: workspace.packagesDir.appending(component: "Baz").pathString, forURL: workspace.packagesDir.appending(component: "Bar").pathString)
workspace.config.mirrors.set(mirrorURL: workspace.packagesDir.appending(component: "Baz").pathString, forURL: workspace.packagesDir.appending(component: "Bam").pathString)
try workspace.config.saveState()
let deps: [MockDependency] = [
.init(name: "Bam", requirement: .upToNextMajor(from: "1.0.0"), products: .specific(["Bar"])),
]
workspace.checkPackageGraph(roots: ["Foo"], deps: deps) { graph, diagnostics in
PackageGraphTester(graph) { result in
result.check(roots: "Foo")
result.check(packages: "Foo", "Dep", "Baz")
result.check(targets: "Foo", "Dep", "Baz")
}
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkManagedDependencies { result in
result.check(dependency: "Dep", at: .checkout(.version("1.5.0")))
result.check(dependency: "Baz", at: .checkout(.version("1.4.0")))
result.check(notPresent: "Bar")
result.check(notPresent: "Bam")
}
}
func testTransitiveDependencySwitchWithSameIdentity() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fs: fs,
roots: [
MockPackage(
name: "Root",
targets: [
MockTarget(name: "Root", dependencies: ["Bar"]),
],
products: [],
dependencies: [
MockDependency(name: "Bar", requirement: .upToNextMajor(from: "1.0.0")),
]
),
],
packages: [
MockPackage(
name: "Bar",
targets: [
MockTarget(name: "Bar", dependencies: ["Foo"]),
],
products: [
MockProduct(name: "Bar", targets: ["Bar"]),
],
dependencies: [
MockDependency(name: "Foo", requirement: .upToNextMajor(from: "1.0.0")),
],
versions: ["1.0.0"]
),
MockPackage(
name: "Bar",
targets: [
MockTarget(name: "Bar", dependencies: ["Nested/Foo"]),
],
products: [
MockProduct(name: "Bar", targets: ["Bar"]),
],
dependencies: [
MockDependency(name: nil, path: "Nested/Foo", requirement: .upToNextMajor(from: "1.0.0")),
],
versions: ["1.1.0"],
toolsVersion: .v5
),
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo"),
],
products: [
MockProduct(name: "Foo", targets: ["Foo"]),
],
versions: ["1.0.0"]
),
MockPackage(
name: "Foo",
path: "Nested/Foo",
targets: [
MockTarget(name: "Foo"),
],
products: [
MockProduct(name: "Nested/Foo", targets: ["Foo"]),
],
versions: ["1.0.0"]
),
]
)
// In this test, we get into a state where add an entry in the resolved
// file for a transitive dependency whose URL is later changed to
// something else, while keeping the same package identity.
//
// This is normally detected during pins validation before the
// dependency resolution process even begins but if we're starting with
// a clean slate, we don't even know about the correct urls of the
// transitive dependencies. We will end up fetching the wrong
// dependency as we prefetch the pins. If we get into this case, it
// should kick off another dependency resolution operation which will
// have enough information to remove the invalid pins of transitive
// dependencies.
var deps: [MockDependency] = [
.init(name: "Bar", requirement: .exact("1.0.0"), products: .specific(["Bar"])),
]
workspace.checkPackageGraph(roots: ["Root"], deps: deps) { graph, diagnostics in
PackageGraphTester(graph) { result in
result.check(roots: "Root")
result.check(packages: "Bar", "Foo", "Root")
}
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkManagedDependencies { result in
result.check(dependency: "foo", at: .checkout(.version("1.0.0")))
result.check(dependency: "bar", at: .checkout(.version("1.0.0")))
}
do {
let ws = workspace.createWorkspace()
XCTAssertNotNil(ws.state.dependencies[forURL: "/tmp/ws/pkgs/Foo"])
}
workspace.checkReset { diagnostics in
XCTAssertNoDiagnostics(diagnostics)
}
deps = [
.init(name: "Bar", requirement: .exact("1.1.0"), products: .specific(["Bar"])),
]
workspace.checkPackageGraph(roots: ["Root"], deps: deps) { graph, diagnostics in
PackageGraphTester(graph) { result in
result.check(roots: "Root")
result.check(packages: "Bar", "Foo", "Root")
}
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkManagedDependencies { result in
result.check(dependency: "foo", at: .checkout(.version("1.0.0")))
result.check(dependency: "bar", at: .checkout(.version("1.1.0")))
}
do {
let ws = workspace.createWorkspace()
XCTAssertNotNil(ws.state.dependencies[forURL: "/tmp/ws/pkgs/Nested/Foo"])
}
}
func testForceResolveToResolvedVersions() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fs: fs,
roots: [
MockPackage(
name: "Root",
targets: [
MockTarget(name: "Root", dependencies: ["Foo", "Bar"]),
],
products: [],
dependencies: [
MockDependency(name: "Foo", requirement: .upToNextMajor(from: "1.0.0")),
MockDependency(name: "Bar", requirement: .upToNextMajor(from: "1.0.0")),
]
),
],
packages: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo"),
],
products: [
MockProduct(name: "Foo", targets: ["Foo"]),
],
versions: ["1.0.0", "1.2.0", "1.3.2"]
),
MockPackage(
name: "Bar",
targets: [
MockTarget(name: "Bar"),
],
products: [
MockProduct(name: "Bar", targets: ["Bar"]),
],
versions: ["1.0.0", "develop"]
),
]
)
// Load the initial graph.
let deps: [MockDependency] = [
.init(name: "Bar", requirement: .revision("develop"), products: .specific(["Bar"])),
]
workspace.checkPackageGraph(roots: ["Root"], deps: deps) { _, diagnostics in
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkManagedDependencies { result in
result.check(dependency: "foo", at: .checkout(.version("1.3.2")))
result.check(dependency: "bar", at: .checkout(.branch("develop")))
}
workspace.checkResolved { result in
result.check(dependency: "foo", at: .checkout(.version("1.3.2")))
result.check(dependency: "bar", at: .checkout(.branch("develop")))
}
// Change pin of foo to something else.
do {
let ws = workspace.createWorkspace()
let pinsStore = try ws.pinsStore.load()
let fooPin = pinsStore.pins.first(where: { $0.packageRef.identity.description == "foo" })!
let fooRepo = workspace.repoProvider.specifierMap[RepositorySpecifier(url: fooPin.packageRef.path)]!
let revision = try fooRepo.resolveRevision(tag: "1.0.0")
let newState = CheckoutState(revision: revision, version: "1.0.0")
pinsStore.pin(packageRef: fooPin.packageRef, state: newState)
try pinsStore.saveState()
}
// Check force resolve. This should produce an error because the resolved file is out-of-date.
workspace.checkPackageGraph(roots: ["Root"], forceResolvedVersions: true) { _, diagnostics in
DiagnosticsEngineTester(diagnostics) { result in
result.check(diagnostic: "cannot update Package.resolved file because automatic resolution is disabled", checkContains: true, behavior: .error)
}
}
workspace.checkManagedDependencies { result in
result.check(dependency: "foo", at: .checkout(.version("1.0.0")))
result.check(dependency: "bar", at: .checkout(.branch("develop")))
}
workspace.checkResolved { result in
result.check(dependency: "foo", at: .checkout(.version("1.0.0")))
result.check(dependency: "bar", at: .checkout(.branch("develop")))
}
// A normal resolution.
workspace.checkPackageGraph(roots: ["Root"]) { _, diagnostics in
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkManagedDependencies { result in
result.check(dependency: "foo", at: .checkout(.version("1.0.0")))
result.check(dependency: "bar", at: .checkout(.version("1.0.0")))
}
workspace.checkResolved { result in
result.check(dependency: "foo", at: .checkout(.version("1.0.0")))
result.check(dependency: "bar", at: .checkout(.version("1.0.0")))
}
// This force resolution should succeed.
workspace.checkPackageGraph(roots: ["Root"], forceResolvedVersions: true) { _, diagnostics in
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkManagedDependencies { result in
result.check(dependency: "foo", at: .checkout(.version("1.0.0")))
result.check(dependency: "bar", at: .checkout(.version("1.0.0")))
}
workspace.checkResolved { result in
result.check(dependency: "foo", at: .checkout(.version("1.0.0")))
result.check(dependency: "bar", at: .checkout(.version("1.0.0")))
}
}
func testForceResolveToResolvedVersionsLocalPackage() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fs: fs,
roots: [
MockPackage(
name: "Root",
targets: [
MockTarget(name: "Root", dependencies: ["Foo"]),
],
products: [],
dependencies: [
MockDependency(name: "Foo", requirement: .localPackage),
]
),
],
packages: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo"),
],
products: [
MockProduct(name: "Foo", targets: ["Foo"]),
],
versions: [nil]
),
]
)
workspace.checkPackageGraph(roots: ["Root"], forceResolvedVersions: true) { _, diagnostics in
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkManagedDependencies { result in
result.check(dependency: "foo", at: .local)
}
}
func testSimpleAPI() throws {
guard Resources.havePD4Runtime else { return }
// This verifies that the simplest possible loading APIs are available for package clients.
// This checkout of the SwiftPM package.
let package = AbsolutePath(#file).parentDirectory.parentDirectory.parentDirectory
// Clients must locate the corresponding “swiftc” exectuable themselves for now.
// (This just uses the same one used by all the other tests.)
let swiftCompiler = Resources.default.swiftCompiler
// From here the API should be simple and straightforward:
let diagnostics = DiagnosticsEngine()
let manifest = try tsc_await {
ManifestLoader.loadManifest(packagePath: package, swiftCompiler: swiftCompiler, swiftCompilerFlags: [], packageKind: .local, on: .global(), completion: $0)
}
let loadedPackage = try tsc_await {
PackageBuilder.loadPackage(packagePath: package, swiftCompiler: swiftCompiler, swiftCompilerFlags: [], xcTestMinimumDeploymentTargets: [:], diagnostics: diagnostics, on: .global(), completion: $0)
}
let graph = try Workspace.loadGraph(
packagePath: package, swiftCompiler: swiftCompiler, swiftCompilerFlags: [], diagnostics: diagnostics
)
XCTAssertEqual(manifest.name, "SwiftPM")
XCTAssertEqual(loadedPackage.name, "SwiftPM")
XCTAssert(graph.reachableProducts.contains(where: { $0.name == "SwiftPM" }))
}
func testRevisionDepOnLocal() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fs: fs,
roots: [
MockPackage(
name: "Root",
targets: [
MockTarget(name: "Root", dependencies: ["Foo"]),
],
products: [],
dependencies: [
MockDependency(name: "Foo", requirement: .branch("develop")),
]
),
],
packages: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo", dependencies: ["Local"]),
],
products: [
MockProduct(name: "Foo", targets: ["Foo"]),
],
dependencies: [
MockDependency(name: "Local", requirement: .localPackage),
],
versions: ["develop"]
),
MockPackage(
name: "Local",
targets: [
MockTarget(name: "Local"),
],
products: [
MockProduct(name: "Local", targets: ["Local"]),
],
versions: [nil]
),
]
)
workspace.checkPackageGraph(roots: ["Root"]) { _, diagnostics in
DiagnosticsEngineTester(diagnostics) { result in
result.check(diagnostic: .equal("package 'Foo' is required using a revision-based requirement and it depends on local package 'Local', which is not supported"), behavior: .error)
}
}
}
func testRootPackagesOverrideBasenameMismatch() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fs: fs,
roots: [
MockPackage(
name: "Baz",
path: "Overridden/bazzz-master",
targets: [
MockTarget(name: "Baz"),
],
products: [
MockProduct(name: "Baz", targets: ["Baz"]),
]
),
],
packages: [
MockPackage(
name: "Baz",
path: "bazzz",
targets: [
MockTarget(name: "Baz"),
],
products: [
MockProduct(name: "Baz", targets: ["Baz"]),
],
versions: ["1.0.0"]
),
]
)
let deps: [MockDependency] = [
.init(name: "bazzz", requirement: .exact("1.0.0"), products: .specific(["Baz"])),
]
workspace.checkPackageGraph(roots: ["Overridden/bazzz-master"], deps: deps) { _, diagnostics in
DiagnosticsEngineTester(diagnostics, ignoreNotes: true) { result in
result.check(diagnostic: .equal("unable to override package 'Baz' because its basename 'bazzz' doesn't match directory name 'bazzz-master'"), behavior: .error)
}
}
}
func testUnsafeFlags() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fs: fs,
roots: [
MockPackage(
name: "Bar",
targets: [
MockTarget(name: "Bar", settings: [.init(tool: .swift, name: .unsafeFlags, value: ["-F", "/tmp"])]),
],
products: [
MockProduct(name: "Bar", targets: ["Bar"]),
],
versions: ["1.0.0", nil]
),
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo", dependencies: ["Bar", "Baz"]),
],
products: [],
dependencies: [
MockDependency(name: "Bar", requirement: .localPackage),
MockDependency(name: "Baz", requirement: .upToNextMajor(from: "1.0.0")),
]
),
],
packages: [
MockPackage(
name: "Bar",
targets: [
MockTarget(name: "Bar", settings: [.init(tool: .swift, name: .unsafeFlags, value: ["-F", "/tmp"])]),
],
products: [
MockProduct(name: "Bar", targets: ["Bar"]),
],
versions: ["1.0.0", nil]
),
MockPackage(
name: "Baz",
targets: [
MockTarget(name: "Baz", dependencies: ["Bar"], settings: [.init(tool: .swift, name: .unsafeFlags, value: ["-F", "/tmp"])]),
],
products: [
MockProduct(name: "Baz", targets: ["Baz"]),
],
dependencies: [
MockDependency(name: "Bar", requirement: .upToNextMajor(from: "1.0.0")),
],
versions: ["1.0.0", "1.5.0"]
),
]
)
// We should only see errors about use of unsafe flag in the version-based dependency.
workspace.checkPackageGraph(roots: ["Foo", "Bar"]) { _, diagnostics in
DiagnosticsEngineTester(diagnostics, ignoreNotes: true) { result in
result.checkUnordered(diagnostic: .equal("the target 'Baz' in product 'Baz' contains unsafe build flags"), behavior: .error)
result.checkUnordered(diagnostic: .equal("the target 'Bar' in product 'Baz' contains unsafe build flags"), behavior: .error)
}
}
}
func testEditDependencyHadOverridableConstraints() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fs: fs,
roots: [
MockPackage(
name: "Root",
targets: [
MockTarget(name: "Root", dependencies: ["Foo", "Baz"]),
],
products: [],
dependencies: [
MockDependency(name: "Foo", requirement: .branch("master")),
MockDependency(name: "Baz", requirement: .upToNextMajor(from: "1.0.0")),
]
),
],
packages: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo", dependencies: ["Bar"]),
],
products: [
MockProduct(name: "Foo", targets: ["Foo"]),
],
dependencies: [
MockDependency(name: "Bar", requirement: .branch("master")),
],
versions: ["master", nil]
),
MockPackage(
name: "Bar",
targets: [
MockTarget(name: "Bar"),
],
products: [
MockProduct(name: "Bar", targets: ["Bar"]),
],
versions: ["master", "1.0.0", nil]
),
MockPackage(
name: "Baz",
targets: [
MockTarget(name: "Baz", dependencies: ["Bar"]),
],
products: [
MockProduct(name: "Baz", targets: ["Baz"]),
],
dependencies: [
MockDependency(name: "Bar", requirement: .upToNextMajor(from: "1.0.0")),
],
versions: ["1.0.0", nil]
),
]
)
// Load the graph.
workspace.checkPackageGraph(roots: ["Root"]) { _, diagnostics in
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkManagedDependencies { result in
result.check(dependency: "foo", at: .checkout(.branch("master")))
result.check(dependency: "bar", at: .checkout(.branch("master")))
result.check(dependency: "baz", at: .checkout(.version("1.0.0")))
}
// Edit foo.
let fooPath = workspace.createWorkspace().editablesPath.appending(component: "Foo")
workspace.checkEdit(packageName: "Foo") { diagnostics in
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkManagedDependencies { result in
result.check(dependency: "foo", at: .edited(nil))
}
XCTAssertTrue(fs.exists(fooPath))
// Add entry for the edited package.
do {
let fooKey = MockManifestLoader.Key(url: "/tmp/ws/pkgs/Foo")
let editedFooKey = MockManifestLoader.Key(url: "/tmp/ws/edits/Foo")
let manifest = workspace.manifestLoader.manifests[fooKey]!
workspace.manifestLoader.manifests[editedFooKey] = manifest
}
XCTAssertMatch(workspace.delegate.events, [.equal("will resolve dependencies")])
workspace.delegate.clear()
workspace.checkPackageGraph(roots: ["Root"]) { _, diagnostics in
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkManagedDependencies { result in
result.check(dependency: "foo", at: .edited(nil))
result.check(dependency: "bar", at: .checkout(.branch("master")))
result.check(dependency: "baz", at: .checkout(.version("1.0.0")))
}
XCTAssertNoMatch(workspace.delegate.events, [.equal("will resolve dependencies")])
}
func testTargetBasedDependency() throws {
#if ENABLE_TARGET_BASED_DEPENDENCY_RESOLUTION
#else
try XCTSkipIf(true)
#endif
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fs: fs,
roots: [
MockPackage(
name: "Root",
targets: [
MockTarget(name: "Root", dependencies: ["Foo", "Bar"]),
MockTarget(name: "RootTests", dependencies: ["TestHelper1"], type: .test),
],
products: [],
dependencies: [
MockDependency(name: "Foo", requirement: .upToNextMajor(from: "1.0.0")),
MockDependency(name: "Bar", requirement: .upToNextMajor(from: "1.0.0")),
MockDependency(name: "TestHelper1", requirement: .upToNextMajor(from: "1.0.0")),
],
toolsVersion: .v5_2
),
],
packages: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo1", dependencies: ["Foo2"]),
MockTarget(name: "Foo2", dependencies: ["Baz"]),
MockTarget(name: "FooTests", dependencies: ["TestHelper2"], type: .test),
],
products: [
MockProduct(name: "Foo", targets: ["Foo1"]),
],
dependencies: [
MockDependency(name: "TestHelper2", requirement: .upToNextMajor(from: "1.0.0")),
MockDependency(name: "Baz", requirement: .upToNextMajor(from: "1.0.0")),
],
versions: ["1.0.0"],
toolsVersion: .v5_2
),
MockPackage(
name: "Bar",
targets: [
MockTarget(name: "Bar"),
MockTarget(name: "BarUnused", dependencies: ["Biz"]),
MockTarget(name: "BarTests", dependencies: ["TestHelper2"], type: .test),
],
products: [
MockProduct(name: "Bar", targets: ["Bar"]),
MockProduct(name: "BarUnused", targets: ["BarUnused"]),
],
dependencies: [
MockDependency(name: "TestHelper2", requirement: .upToNextMajor(from: "1.0.0")),
MockDependency(name: "Biz", requirement: .upToNextMajor(from: "1.0.0")),
],
versions: ["1.0.0"],
toolsVersion: .v5_2
),
MockPackage(
name: "Baz",
targets: [
MockTarget(name: "Baz"),
],
products: [
MockProduct(name: "Baz", targets: ["Baz"]),
],
versions: ["1.0.0"],
toolsVersion: .v5_2
),
MockPackage(
name: "TestHelper1",
targets: [
MockTarget(name: "TestHelper1"),
],
products: [
MockProduct(name: "TestHelper1", targets: ["TestHelper1"]),
],
versions: ["1.0.0"],
toolsVersion: .v5_2
),
],
toolsVersion: .v5_2,
enablePubGrub: true
)
// Load the graph.
workspace.checkPackageGraph(roots: ["Root"]) { _, diagnostics in
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkManagedDependencies { result in
result.check(dependency: "Foo", at: .checkout(.version("1.0.0")))
result.check(dependency: "Bar", at: .checkout(.version("1.0.0")))
result.check(dependency: "Baz", at: .checkout(.version("1.0.0")))
result.check(dependency: "TestHelper1", at: .checkout(.version("1.0.0")))
result.check(notPresent: "Biz")
result.check(notPresent: "TestHelper2")
}
}
func testChecksumForBinaryArtifact() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fs: fs,
roots: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo", dependencies: ["Foo"]),
],
products: []
),
],
packages: []
)
let ws = workspace.createWorkspace()
// Checks the valid case.
do {
let binaryPath = sandbox.appending(component: "binary.zip")
try fs.writeFileContents(binaryPath, bytes: ByteString([0xAA, 0xBB, 0xCC]))
let diagnostics = DiagnosticsEngine()
let checksum = ws.checksum(forBinaryArtifactAt: binaryPath, diagnostics: diagnostics)
XCTAssertTrue(!diagnostics.hasErrors)
XCTAssertEqual(workspace.checksumAlgorithm.hashes.map { $0.contents }, [[0xAA, 0xBB, 0xCC]])
XCTAssertEqual(checksum, "ccbbaa")
}
// Checks an unsupported extension.
do {
let unknownPath = sandbox.appending(component: "unknown")
let diagnostics = DiagnosticsEngine()
let checksum = ws.checksum(forBinaryArtifactAt: unknownPath, diagnostics: diagnostics)
XCTAssertEqual(checksum, "")
DiagnosticsEngineTester(diagnostics) { result in
let expectedDiagnostic = "unexpected file type; supported extensions are: zip"
result.check(diagnostic: .contains(expectedDiagnostic), behavior: .error)
}
}
// Checks a supported extension that is not a file (does not exist).
do {
let unknownPath = sandbox.appending(component: "missingFile.zip")
let diagnostics = DiagnosticsEngine()
let checksum = ws.checksum(forBinaryArtifactAt: unknownPath, diagnostics: diagnostics)
XCTAssertEqual(checksum, "")
DiagnosticsEngineTester(diagnostics) { result in
result.check(diagnostic: .contains("file not found at path: /tmp/ws/missingFile.zip"),
behavior: .error)
}
}
// Checks a supported extension that is a directory instead of a file.
do {
let unknownPath = sandbox.appending(component: "aDirectory.zip")
try fs.createDirectory(unknownPath)
let diagnostics = DiagnosticsEngine()
let checksum = ws.checksum(forBinaryArtifactAt: unknownPath, diagnostics: diagnostics)
XCTAssertEqual(checksum, "")
DiagnosticsEngineTester(diagnostics) { result in
result.check(diagnostic: .contains("file not found at path: /tmp/ws/aDirectory.zip"),
behavior: .error)
}
}
}
func testArtifactDownload() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
var downloads: [MockDownloader.Download] = []
let workspace = try MockWorkspace(
sandbox: sandbox,
fs: fs,
downloader: MockDownloader(fileSystem: fs, downloadFile: { url, destination, _, completion in
let contents: [UInt8]
switch url.lastPathComponent {
case "a1.zip": contents = [0xA1]
case "a2.zip": contents = [0xA2]
case "a3.zip": contents = [0xA3]
case "b.zip": contents = [0xB0]
default:
XCTFail("unexpected url")
contents = []
}
try! fs.writeFileContents(
destination,
bytes: ByteString(contents),
atomically: true
)
downloads.append(MockDownloader.Download(url: url, destinationPath: destination))
completion(.success(()))
}),
roots: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo", dependencies: [
"B",
.product(name: "A1", package: "A"),
.product(name: "A2", package: "A"),
.product(name: "A3", package: "A"),
.product(name: "A4", package: "A"),
]),
],
products: [],
dependencies: [
MockDependency(name: "A", requirement: .exact("1.0.0")),
MockDependency(name: "B", requirement: .exact("1.0.0")),
]
),
],
packages: [
MockPackage(
name: "A",
targets: [
MockTarget(
name: "A1",
type: .binary,
url: "https://a.com/a1.zip",
checksum: "a1"
),
MockTarget(
name: "A2",
type: .binary,
url: "https://a.com/a2.zip",
checksum: "a2"
),
MockTarget(
name: "A3",
type: .binary,
url: "https://a.com/a3.zip",
checksum: "a3"
),
MockTarget(
name: "A4",
type: .binary,
path: "A4.xcframework"
),
],
products: [
MockProduct(name: "A1", targets: ["A1"]),
MockProduct(name: "A2", targets: ["A2"]),
MockProduct(name: "A3", targets: ["A3"]),
MockProduct(name: "A4", targets: ["A4"]),
],
versions: ["1.0.0"]
),
MockPackage(
name: "B",
targets: [
MockTarget(
name: "B",
type: .binary,
url: "https://b.com/b.zip",
checksum: "b0"
),
],
products: [
MockProduct(name: "B", targets: ["B"]),
],
versions: ["1.0.0"]
),
]
)
let a4FrameworkPath = workspace.packagesDir.appending(components: "A", "A4.xcframework")
try fs.createDirectory(a4FrameworkPath, recursive: true)
try [("A", "A1.xcframework"), ("A", "A2.xcframework"), ("B", "B.xcframework")].forEach {
let frameworkPath = workspace.artifactsDir.appending(components: $0.0, $0.1)
try fs.createDirectory(frameworkPath, recursive: true)
}
// Pin A to 1.0.0, Checkout B to 1.0.0
let aURL = workspace.urlForPackage(withName: "A")
let aRef = PackageReference(identity: PackageIdentity(url: aURL), path: aURL)
let aRepo = workspace.repoProvider.specifierMap[RepositorySpecifier(url: aURL)]!
let aRevision = try aRepo.resolveRevision(tag: "1.0.0")
let aState = CheckoutState(revision: aRevision, version: "1.0.0")
try workspace.set(
pins: [aRef: aState],
managedDependencies: [],
managedArtifacts: [
ManagedArtifact(
packageRef: aRef,
targetName: "A1",
source: .remote(
url: "https://a.com/a1.zip",
checksum: "a1",
subpath: RelativePath("A/A1.xcframework")
)
),
ManagedArtifact(
packageRef: aRef,
targetName: "A3",
source: .remote(
url: "https://a.com/old/a3.zip",
checksum: "a3-old-checksum",
subpath: RelativePath("A/A3.xcframework")
)
),
ManagedArtifact(
packageRef: aRef,
targetName: "A4",
source: .remote(
url: "https://a.com/a4.zip",
checksum: "a4",
subpath: RelativePath("A/A4.xcframework")
)
),
ManagedArtifact(
packageRef: aRef,
targetName: "A5",
source: .remote(
url: "https://a.com/a5.zip",
checksum: "a5",
subpath: RelativePath("A/A5.xcframework")
)
),
ManagedArtifact(
packageRef: aRef,
targetName: "A6",
source: .local(path: "A6.xcframework")
),
]
)
workspace.checkPackageGraph(roots: ["Foo"]) { graph, diagnostics in
XCTAssertEqual(diagnostics.diagnostics.map { $0.message.text }, ["downloaded archive of binary target 'A3' does not contain expected binary artifact 'A3.xcframework'"])
XCTAssert(fs.isDirectory(AbsolutePath("/tmp/ws/.build/artifacts/B")))
XCTAssert(!fs.exists(AbsolutePath("/tmp/ws/.build/artifacts/A/A3.xcframework")))
XCTAssert(!fs.exists(AbsolutePath("/tmp/ws/.build/artifacts/A/A4.xcframework")))
XCTAssert(!fs.exists(AbsolutePath("/tmp/ws/.build/artifacts/A/A5.xcframework")))
XCTAssert(!fs.exists(AbsolutePath("/tmp/ws/.build/artifacts/Foo")))
XCTAssertEqual(downloads.map { $0.url }, [
URL(string: "https://b.com/b.zip")!,
URL(string: "https://a.com/a2.zip")!,
URL(string: "https://a.com/a3.zip")!,
])
XCTAssertEqual(workspace.checksumAlgorithm.hashes, [
ByteString([0xB0]),
ByteString([0xA2]),
ByteString([0xA3]),
])
XCTAssertEqual(workspace.archiver.extractions.map { $0.destinationPath }, [
AbsolutePath("/tmp/ws/.build/artifacts/B"),
AbsolutePath("/tmp/ws/.build/artifacts/A"),
AbsolutePath("/tmp/ws/.build/artifacts/A"),
])
XCTAssertEqual(
downloads.map { $0.destinationPath },
workspace.archiver.extractions.map { $0.archivePath }
)
PackageGraphTester(graph) { graph in
if let a1 = graph.find(target: "A1")?.underlyingTarget as? BinaryTarget {
XCTAssertEqual(a1.artifactPath, AbsolutePath("/tmp/ws/.build/artifacts/A/A1.xcframework"))
XCTAssertEqual(a1.artifactSource, .remote(url: "https://a.com/a1.zip"))
} else {
XCTFail("expected binary target")
}
if let a2 = graph.find(target: "A2")?.underlyingTarget as? BinaryTarget {
XCTAssertEqual(a2.artifactPath, AbsolutePath("/tmp/ws/.build/artifacts/A/A2.xcframework"))
XCTAssertEqual(a2.artifactSource, .remote(url: "https://a.com/a2.zip"))
} else {
XCTFail("expected binary target")
}
if let a3 = graph.find(target: "A3")?.underlyingTarget as? BinaryTarget {
XCTAssertEqual(a3.artifactPath, AbsolutePath("/tmp/ws/.build/artifacts/A/A3.xcframework"))
XCTAssertEqual(a3.artifactSource, .remote(url: "https://a.com/a3.zip"))
} else {
XCTFail("expected binary target")
}
if let a4 = graph.find(target: "A4")?.underlyingTarget as? BinaryTarget {
XCTAssertEqual(a4.artifactPath, a4FrameworkPath)
XCTAssertEqual(a4.artifactSource, .local)
} else {
XCTFail("expected binary target")
}
if let b = graph.find(target: "B")?.underlyingTarget as? BinaryTarget {
XCTAssertEqual(b.artifactPath, AbsolutePath("/tmp/ws/.build/artifacts/B/B.xcframework"))
XCTAssertEqual(b.artifactSource, .remote(url: "https://b.com/b.zip"))
} else {
XCTFail("expected binary target")
}
}
}
workspace.checkManagedArtifacts { result in
result.check(packageName: "A", targetName: "A1", source: .remote(
url: "https://a.com/a1.zip",
checksum: "a1",
subpath: RelativePath("A/A1.xcframework")
))
result.check(packageName: "A", targetName: "A2", source: .remote(
url: "https://a.com/a2.zip",
checksum: "a2",
subpath: RelativePath("A/A2.xcframework")
))
result.check(packageName: "A", targetName: "A3", source: .remote(
url: "https://a.com/a3.zip",
checksum: "a3",
subpath: RelativePath("A/A3.xcframework")
))
result.check(packageName: "A", targetName: "A4", source: .local(path: "A4.xcframework"))
result.checkNotPresent(packageName: "A", targetName: "A5")
result.check(packageName: "B", targetName: "B", source: .remote(
url: "https://b.com/b.zip",
checksum: "b0",
subpath: RelativePath("B/B.xcframework")
))
}
}
func testArtifactDownloaderOrArchiverError() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fs: fs,
downloader: MockDownloader(fileSystem: fs, downloadFile: { url, destination, _, completion in
switch url {
case URL(string: "https://a.com/a1.zip")!:
completion(.failure(.serverError(statusCode: 500)))
case URL(string: "https://a.com/a2.zip")!:
try! fs.writeFileContents(destination, bytes: ByteString([0xA2]))
completion(.success(()))
case URL(string: "https://a.com/a3.zip")!:
try! fs.writeFileContents(destination, bytes: "different contents = different checksum")
completion(.success(()))
default:
XCTFail("unexpected url")
completion(.success(()))
}
}),
archiver: MockArchiver(extract: { _, destinationPath, completion in
XCTAssertEqual(destinationPath, AbsolutePath("/tmp/ws/.build/artifacts/A"))
completion(.failure(DummyError()))
}),
roots: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo", dependencies: [
.product(name: "A1", package: "A"),
.product(name: "A2", package: "A"),
]),
],
products: [],
dependencies: [
MockDependency(name: "A", requirement: .exact("1.0.0")),
]
),
],
packages: [
MockPackage(
name: "A",
targets: [
MockTarget(
name: "A1",
type: .binary,
url: "https://a.com/a1.zip",
checksum: "a1"
),
MockTarget(
name: "A2",
type: .binary,
url: "https://a.com/a2.zip",
checksum: "a2"
),
MockTarget(
name: "A3",
type: .binary,
url: "https://a.com/a3.zip",
checksum: "a3"
),
],
products: [
MockProduct(name: "A1", targets: ["A1"]),
MockProduct(name: "A2", targets: ["A2"]),
MockProduct(name: "A3", targets: ["A3"]),
],
versions: ["1.0.0"]
),
]
)
workspace.checkPackageGraph(roots: ["Foo"]) { result, diagnostics in
print(diagnostics.diagnostics)
DiagnosticsEngineTester(diagnostics) { result in
result.check(diagnostic: .contains("artifact of binary target 'A1' failed download: invalid status code 500"), behavior: .error)
result.check(diagnostic: .contains("artifact of binary target 'A2' failed extraction: dummy error"), behavior: .error)
result.check(diagnostic: .contains("checksum of downloaded artifact of binary target 'A3' (6d75736b6365686320746e65726566666964203d2073746e65746e6f6320746e65726566666964) does not match checksum specified by the manifest (a3)"), behavior: .error)
}
}
}
func testArtifactChecksumChange() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fs: fs,
roots: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo", dependencies: ["A"]),
],
products: [],
dependencies: [
MockDependency(name: "A", requirement: .exact("1.0.0")),
]
),
],
packages: [
MockPackage(
name: "A",
targets: [
MockTarget(name: "A", type: .binary, url: "https://a.com/a.zip", checksum: "a"),
],
products: [
MockProduct(name: "A", targets: ["A"]),
],
versions: ["0.9.0", "1.0.0"]
),
]
)
// Pin A to 1.0.0, Checkout A to 1.0.0
let aURL = workspace.urlForPackage(withName: "A")
let aRef = PackageReference(identity: PackageIdentity(url: aURL), path: aURL)
let aRepo = workspace.repoProvider.specifierMap[RepositorySpecifier(url: aURL)]!
let aRevision = try aRepo.resolveRevision(tag: "1.0.0")
let aState = CheckoutState(revision: aRevision, version: "1.0.0")
let aDependency = ManagedDependency(packageRef: aRef, subpath: RelativePath("A"), checkoutState: aState)
try workspace.set(
pins: [aRef: aState],
managedDependencies: [aDependency],
managedArtifacts: [
ManagedArtifact(
packageRef: aRef,
targetName: "A",
source: .remote(
url: "https://a.com/a.zip",
checksum: "old-checksum",
subpath: RelativePath("A/A.xcframework")
)
),
]
)
workspace.checkPackageGraph(roots: ["Foo"]) { result, diagnostics in
XCTAssertEqual(workspace.downloader.downloads, [])
DiagnosticsEngineTester(diagnostics) { result in
result.check(diagnostic: .contains("artifact of binary target 'A' has changed checksum"), behavior: .error)
}
}
}
func testAndroidCompilerFlags() throws {
let target = try Triple("x86_64-unknown-linux-android")
let sdk = AbsolutePath("/some/path/to/an/SDK.sdk")
let toolchainPath = AbsolutePath("/some/path/to/a/toolchain.xctoolchain")
let destination = Destination(
target: target,
sdk: sdk,
binDir: toolchainPath.appending(components: "usr", "bin")
)
XCTAssertEqual(UserToolchain.deriveSwiftCFlags(triple: target, destination: destination), [
// Needed when cross‐compiling for Android. 2020‐03‐01
"-sdk", sdk.pathString,
])
}
}
extension PackageGraph {
/// Finds the package matching the given name.
func lookup(_ name: String) -> ResolvedPackage {
return packages.first { $0.name == name }!
}
}
struct DummyError: LocalizedError, Equatable {
public var errorDescription: String? { "dummy error" }
}
| 39.245618 | 277 | 0.470432 |
9c186b441be3db8e3f57d35a5456f6db26bb19c6 | 1,874 | //
// PriceCalendarResultCell.swift
// AviasalesSDKTemplate
//
// Created by Dim on 20.02.2018.
// Copyright © 2018 Go Travel Un Limited. All rights reserved.
//
import UIKit
class PriceCalendarResultCell: UITableViewCell {
@IBOutlet weak var containerView: UIView!
@IBOutlet weak var cheapestContainerView: UIView!
@IBOutlet weak var cheapestLabel: UILabel!
@IBOutlet weak var priceLabel: UILabel!
@IBOutlet weak var datesLabel: UILabel!
@IBOutlet weak var cheapestContainerViewHeightConstraint: NSLayoutConstraint!
override func awakeFromNib() {
super.awakeFromNib()
selectionStyle = .none
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
updateBackground(animated: animated)
}
override func setHighlighted(_ highlighted: Bool, animated: Bool) {
super.setHighlighted(highlighted, animated: animated)
updateBackground(animated: animated)
}
func setup(_ cellModel: PriceCalendarResultCellModel) {
cheapestContainerViewHeightConstraint.constant = cellModel.cheapest == nil ? 0 : 40
cheapestContainerView.isHidden = cellModel.cheapest == nil
cheapestLabel.text = cellModel.cheapest?.uppercased()
priceLabel.text = cellModel.price
datesLabel.text = cellModel.dates?.arabicDigits()
}
}
private extension PriceCalendarResultCell {
func updateBackground(animated: Bool) {
let color = isSelected || isHighlighted ? JRColorScheme.itemsSelectedBackgroundColor() : JRColorScheme.itemsBackgroundColor()
let duration = animated ? 0.3 : 0
UIView.animate(withDuration: duration) { [weak self] in
self?.containerView.backgroundColor = color
self?.cheapestContainerView.backgroundColor = color
}
}
}
| 32.877193 | 133 | 0.707577 |
e567c91aee63156a1574964f67f7dfcc8b8e2711 | 1,156 | //
// main.swift
// SierpinskiSwift
//
// Runs the main sierpinski algorithm.
import SVGLibrary
// YOUR CODE HERE
func draw_triangle(_ p1: Point, _ p2:Point, _ p3: Point, _ figure: SVG){
figure.draw_line(p1, p2)
figure.draw_line(p2, p3)
figure.draw_line(p3, p1)
}
// Draw a triangle between the three points and then recursively draw
// three more triangles in each of the three corners of the first triangle.
func sierpinski(_ p1: Point, _ p2: Point, _ p3: Point, _ level: Int, _ figure: SVG) {
if (level <= 0){
return
}
draw_triangle(p1,p2,p3, figure)
sierpinski(p1, midpoint(p1,p2), midpoint(p1,p3),level-1, figure)
sierpinski(p2, midpoint(p1,p2), midpoint(p2,p3),level-1, figure)
sierpinski(p3, midpoint(p1,p3), midpoint(p2,p3),level-1, figure)
}
// Start the algorithm off using a 300x300 canvas and its largest triangle
// going across that canvas
func main() {
let figure: SVG = SVG(width: 300, height: 300)
let p1: Point = (0, 300)
let p2: Point = (150, 0)
let p3: Point = (300, 300)
sierpinski(p1, p2, p3, 5, figure)
figure.write(filePath: "sierpinski.svg")
}
main()
| 26.272727 | 85 | 0.665225 |
e0fc2cd3cc626cbe450b6ecc5da05c647a49475c | 1,404 | //
// KeyPadButtonView.swift
// Brieftasche
//
// Created by Lloyd on 2/21/22.
//
import SwiftUI
struct KeyPadButtonView: View {
var key: String
var body: some View {
Button(action: { self.action(self.key) }) {
Color.clear
// .overlay(RoundedRectangle(cornerRadius: 12)
// .stroke(Color.accentColor))
.overlay(
Text(key)
.foregroundColor(UIConfig.primaryFontColor)
.font(UIConfig.xLargeFont)
)
}
}
// Create an environment key
enum ActionKey: EnvironmentKey {
static var defaultValue: (String) -> Void { { _ in } }
}
// Let `keyPadButtonAction` be accessible globally
@Environment(\.keyPadButtonAction) var action: (String) -> Void
}
// Extend the environment - to provide a getter/setter that we can use
extension EnvironmentValues {
var keyPadButtonAction: (String) -> Void {
get { self[KeyPadButtonView.ActionKey.self] }
set { self[KeyPadButtonView.ActionKey.self] = newValue }
}
}
struct KeyPadButtonView_Previews: PreviewProvider {
static var previews: some View {
KeyPadButtonView(key: "9")
.padding()
.frame(width: 80, height: 80)
.previewLayout(.sizeThatFits)
}
}
| 27.529412 | 73 | 0.568376 |
46881e4831bbd8981bb17ed4303f67980947769e | 852 | import Foundation
private class PrivateToken {}
extension Decodable {
static func decodingResource(byName resourceName: String) -> Self {
guard let resourceURL = Bundle(for: PrivateToken.self).url(forResource: resourceName, withExtension: "json") else {
fatalError("Could not find resource '\(resourceName)'")
}
guard let resourceData = try? Data(contentsOf: resourceURL) else {
fatalError("Could not load resource '\(resourceURL)'")
}
do {
return try Self.decodeJson(resourceData)
} catch {
fatalError("Could not decode resource '\(resourceURL)': \(error)")
}
}
public static func decodeJson(_ jsonData: Data) throws -> Self {
let decoder = JSONDecoder()
return try decoder.decode(Self.self, from: jsonData)
}
}
| 34.08 | 123 | 0.633803 |
76a881cd28826c4c7581ac3bb32579fb11b88de7 | 118 | import XCTest
import NvimViewTests
var tests = [XCTestCaseEntry]()
tests += NvimViewTests.allTests()
XCTMain(tests)
| 14.75 | 33 | 0.779661 |
fb538e7ceb093723fe3cbe79814bb7db09da2fa0 | 339 | //
// File.swift
// AdzerkSDK
//
// Created by Ben Scheirman on 10/4/20.
//
import Foundation
@testable import AdzerkSDK
class FakeKeyStore: UserKeyStore {
var currentUserKey: String?
func save(userKey: String) {
currentUserKey = userKey
}
func removeUserKey() {
currentUserKey = nil
}
}
| 15.409091 | 40 | 0.628319 |
7130397e000d5c9972199e72880d34b7f2a84dd2 | 2,493 | // RUN: rm -rf %t && mkdir -p %t/before && mkdir -p %t/after
// RUN: %target-build-swift -emit-library -Xfrontend -enable-resilience -D BEFORE -c %S/Inputs/struct_add_remove_conformances.swift -o %t/before/struct_add_remove_conformances.o
// RUN: %target-build-swift -emit-module -Xfrontend -enable-resilience -D BEFORE -c %S/Inputs/struct_add_remove_conformances.swift -o %t/before/struct_add_remove_conformances.o
// RUN: %target-build-swift -emit-library -Xfrontend -enable-resilience -D AFTER -c %S/Inputs/struct_add_remove_conformances.swift -o %t/after/struct_add_remove_conformances.o
// RUN: %target-build-swift -emit-module -Xfrontend -enable-resilience -D AFTER -c %S/Inputs/struct_add_remove_conformances.swift -o %t/after/struct_add_remove_conformances.o
// RUN: %target-build-swift -D BEFORE -c %s -I %t/before -o %t/before/main.o
// RUN: %target-build-swift -D AFTER -c %s -I %t/after -o %t/after/main.o
// RUN: %target-build-swift %t/before/struct_add_remove_conformances.o %t/before/main.o -o %t/before_before
// RUN: %target-build-swift %t/before/struct_add_remove_conformances.o %t/after/main.o -o %t/before_after
// RUN: %target-build-swift %t/after/struct_add_remove_conformances.o %t/before/main.o -o %t/after_before
// RUN: %target-build-swift %t/after/struct_add_remove_conformances.o %t/after/main.o -o %t/after_after
// RUN: %target-run %t/before_before
// RUN: %target-run %t/before_after
// RUN: %target-run %t/after_before
// RUN: %target-run %t/after_after
// Requires fixes to @_transparent attribute
// XFAIL: *
import StdlibUnittest
import struct_add_remove_conformances
var StructAddRemoveConformancesTest = TestSuite("StructAddRemoveConformances")
StructAddRemoveConformancesTest.test("AddRemoveConformance") {
var t = AddRemoveConformance()
do {
t.x = 10
t.y = 20
expectEqual(t.x, 10)
expectEqual(t.y, 20)
}
if getVersion() > 0 {
var p = t as! PointLike
p.x = 30
p.y = 40
expectEqual(p.x, 30)
expectEqual(p.y, 40)
} else {
expectEqual(t is PointLike, false)
}
}
#if AFTER
protocol MyPointLike {
var x: Int { get set }
var y: Int { get set }
}
protocol MyPoint3DLike {
var z: Int { get set }
}
extension AddRemoveConformance : MyPointLike {}
extension AddRemoveConformance : MyPoint3DLike {}
StructAddRemoveConformancesTest.test("MyPointLike") {
var p: MyPointLike = AddRemoveConformance()
p.x = 50
p.y = 60
expectEqual(p.x, 50)
expectEqual(p.y, 60)
}
#endif
runAllTests()
| 32.802632 | 177 | 0.727637 |
7663e3d4c67dc250ca62de76784e154f648539f2 | 466 | //
// OctopusCard.swift
// TRETJapanNFCReader
//
// Created by treastrain on 2019/09/20.
// Copyright © 2019 treastrain / Tanaka Ryoga. All rights reserved.
//
import Foundation
/// Octopus Card (八達通)
@available(iOS 13.0, *)
public struct OctopusCard: FeliCaCard {
public let tag: OctopusCardTag
public var data: OctopusCardData
public init(tag: OctopusCardTag, data: OctopusCardData) {
self.tag = tag
self.data = data
}
}
| 21.181818 | 68 | 0.67382 |
20035f18a8fa532aa9dfcebd64623443ab2fa903 | 9,869 | //
// APNetIndicatorClientTests.swift
// ApplepieTests
//
// Created by 山天大畜 on 2018/11/8.
// Copyright © 2018 山天大畜. All rights reserved.
//
import XCTest
import Applepie
import Alamofire
import ReactiveCocoa
extension String {
/// User info dictionary key representing the `Request` associated with the notification.
fileprivate static let requestKey = "org.alamofire.notification.key.request"
}
class APNetIndicatorClientTests: BaseTestCase {
func mockRequest() -> Request {
return Session().request(URLRequest(url: URL(string: "https://www.baidu.com")!))
}
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
class TestRequestHandler: APRequestHandler {
weak var testApi: APNetApi!
}
func testNetIndicator() {
let expectation = XCTestExpectation(description: "Complete")
let api = TestNetApi()
api.baseUrlString = Constant.urlString
api.baseHeaders = Constant.baseHeaders
api.headers = HTTPHeaders(Constant.headers)
api.baseParams = Constant.baseParams
api.url = "get"
api.params = Constant.params
let handler = TestRequestHandler()
handler.testApi = api
api.requestHandler = handler
let indicator = APIndicator()
let view = UIView()
let text = "Loading"
api.setIndicator(indicator, view: view, text: text).signal(format: .json).on(started: {
let model = APNetIndicatorClient.getIndicatorModel(identifier: api.identifier)
assert(model != nil)
assert(model!.api === api)
assert(model!.indicator === indicator)
assert(model!.view == view)
assert(model!.text == text)
assert(model!.request != nil)
assert(indicator.showing == true)
}, failed: { error in
assertionFailure()
expectation.fulfill()
}, completed: {
let model = APNetIndicatorClient.getIndicatorModel(identifier: api.identifier)
assert(model == nil)
let api2 = TestNetApi()
api2.baseUrlString = Constant.urlString
api2.baseHeaders = Constant.baseHeaders
api2.headers = HTTPHeaders(Constant.headers)
api2.baseParams = Constant.baseParams
api2.url = "get"
api2.params = Constant.params
let handler2 = TestRequestHandler()
handler2.testApi = api2
api2.requestHandler = handler2
let indicator2 = APIndicator()
let view2 = UIView()
let text2 = "Loading"
api2.setIndicator(indicator2, view: view2, text: text2).signal(format: .json).on(started: {
let model = APNetIndicatorClient.getIndicatorModel(identifier: api2.identifier)
assert(model != nil)
assert(model!.api === api2)
assert(model!.indicator === indicator2)
assert(model!.view == view2)
assert(model!.text == text2)
assert(model!.request != nil)
assert(indicator2.showing == true)
}, failed: { error in
assertionFailure()
expectation.fulfill()
}, completed: {
let model = APNetIndicatorClient.getIndicatorModel(identifier: api2.identifier)
assert(model == nil)
expectation.fulfill()
}, value: { data in
}).start()
}, value: { data in
}).start()
wait(for: [expectation], timeout: 10)
}
func testRemoveIndicator() {
let expectation = XCTestExpectation(description: "Complete")
let api = TestNetApi()
api.baseUrlString = Constant.urlString
api.baseHeaders = Constant.baseHeaders
api.headers = HTTPHeaders(Constant.headers)
api.baseParams = Constant.baseParams
api.url = "get"
api.params = Constant.params
let handler = TestRequestHandler()
handler.testApi = api
api.requestHandler = handler
let indicator = APIndicator()
let view = UIView()
let text = "Loading"
api.setIndicator(indicator, view: view, text: text).signal(format: .json).on(started: {
APNetIndicatorClient.remove(indicator: indicator)
}, failed: { error in
assertionFailure()
expectation.fulfill()
}, completed: {
assertionFailure()
expectation.fulfill()
}, interrupted: {
let model = APNetIndicatorClient.getIndicatorModel(identifier: api.identifier)
assert(model == nil)
expectation.fulfill()
}, value: { data in
}).start()
wait(for: [expectation], timeout: 10)
}
func testCancelTask() {
let expectation = XCTestExpectation(description: "Complete")
let api = TestNetApi()
api.baseUrlString = Constant.urlString
api.baseHeaders = Constant.baseHeaders
api.headers = HTTPHeaders(Constant.headers)
api.baseParams = Constant.baseParams
api.url = "get"
api.params = Constant.params
let handler = TestRequestHandler()
handler.testApi = api
api.requestHandler = handler
let indicator = APIndicator()
let view = UIView()
let text = "Loading"
api.setIndicator(indicator, view: view, text: text).signal(format: .json).on(started: {
let model = APNetIndicatorClient.getIndicatorModel(identifier: api.identifier)
assert(model != nil)
assert(model!.indicator!.showing == true)
model!.request!.cancel()
}, failed: { error in
assertionFailure()
expectation.fulfill()
}, completed: {
assertionFailure()
expectation.fulfill()
}, interrupted: {
let model = APNetIndicatorClient.getIndicatorModel(identifier: api.identifier)
assert(model == nil)
assert(indicator.showing == false)
expectation.fulfill()
}, value: { data in
}).start()
wait(for: [expectation], timeout: 10)
}
func testMockCancel() {
let api = TestNetApi()
api.baseUrlString = Constant.urlString
api.baseHeaders = Constant.baseHeaders
api.headers = HTTPHeaders(Constant.headers)
api.baseParams = Constant.baseParams
api.url = "get"
api.params = Constant.params
let handler = TestRequestHandler()
handler.testApi = api
api.requestHandler = handler
let indicator = APIndicator()
let view = UIView()
let text = "Loading"
let request = mockRequest()
_ = api.setIndicator(indicator, view: view, text: text)
APNetIndicatorClient.bind(api: api, request: request)
var model = APNetIndicatorClient.getIndicatorModel(identifier: api.identifier)
assert(model != nil)
NotificationCenter.default.post(name: Request.didResumeNotification, object: nil, userInfo: [String.requestKey: request])
model = APNetIndicatorClient.getIndicatorModel(identifier: api.identifier)
assert(model != nil)
assert(model?.indicator?.showing == true)
NotificationCenter.default.post(name: Request.didCancelNotification, object: nil, userInfo: [String.requestKey: request])
model = APNetIndicatorClient.getIndicatorModel(identifier: api.identifier)
assert(model == nil)
}
func testMockSuspend() {
let api = TestNetApi()
api.baseUrlString = Constant.urlString
api.baseHeaders = Constant.baseHeaders as [String: Any]
api.headers = HTTPHeaders(Constant.headers)
api.baseParams = Constant.baseParams
api.url = "get"
api.params = Constant.params
let handler = TestRequestHandler()
handler.testApi = api
api.requestHandler = handler
let indicator = APIndicator()
let view = UIView()
let text = "Loading"
let request = mockRequest()
_ = api.setIndicator(indicator, view: view, text: text)
APNetIndicatorClient.bind(api: api, request: request)
var model = APNetIndicatorClient.getIndicatorModel(identifier: api.identifier)
assert(model != nil)
NotificationCenter.default.post(name: Request.didResumeNotification, object: nil, userInfo: [String.requestKey: request])
model = APNetIndicatorClient.getIndicatorModel(identifier: api.identifier)
assert(model != nil)
assert(model?.indicator?.showing == true)
NotificationCenter.default.post(name: Request.didSuspendNotification, object: nil, userInfo: [String.requestKey: request])
model = APNetIndicatorClient.getIndicatorModel(identifier: api.identifier)
assert(model != nil)
assert(model?.indicator?.showing == false)
NotificationCenter.default.post(name: Request.didResumeNotification, object: nil, userInfo: [String.requestKey: request])
model = APNetIndicatorClient.getIndicatorModel(identifier: api.identifier)
assert(model != nil)
assert(model?.indicator?.showing == true)
NotificationCenter.default.post(name: Request.didCompleteTaskNotification, object: nil, userInfo: [String.requestKey: request])
model = APNetIndicatorClient.getIndicatorModel(identifier: api.identifier)
assert(model == nil)
}
}
| 39.794355 | 135 | 0.617286 |
e47e91cdc796d91e64661204d4a5bbd8e2d0cf69 | 236 | import XCTest
public final class AutomaticCurrentTestCaseProvider: CurrentTestCaseProvider {
public init() {
}
public func currentTestCase() -> XCTestCase? {
return _XCTCurrentTestCase() as? XCTestCase
}
}
| 21.454545 | 78 | 0.699153 |
9bb0ea0508765931dbdbde097a47168a0b85f50e | 11,485 | //
// BRELocationManager.swift
// BeaconRangingExample
//
// Created by Sam Piggott on 05/04/2017.
// Copyright © 2017 Sam Piggott. All rights reserved.
//
import UIKit
import CoreLocation
import UserNotifications
enum BRELocationManagerError:Error {
case bluetoothIsDisabled
case locationServicesAreDisabled
case rangingUnavailable
case unknownError
var description:String {
switch self {
case .bluetoothIsDisabled: return "Bluetooth is currently disabled. Enable it on your device and try again!"
case .locationServicesAreDisabled: return "Location services are currently disabled for Rumblr. Head over to Settings and enable it in Location Services, then try again."
case .rangingUnavailable: return "Beacon ranging for this device is unavailable, sorry!"
case .unknownError: return "An unknown error occured whilst searching for beacons."
}
}
}
protocol BRELocationManagerDelegate:class {
func beaconDiscoveredNewBeacon(beacon:BREBeacon)
func beaconScanningFailed(error:BRELocationManagerError)
func beaconOutOfRange(beacon:BREBeacon)
}
class BRELocationManager: NSObject {
weak var delegate:BRELocationManagerDelegate?
fileprivate var regionsArray:[BREBeaconRegion]?
fileprivate var beaconsInRange:[BREBeacon] = []
fileprivate lazy var bluetoothController:BREBluetoothController = {
let controller = BREBluetoothController()
return controller
}()
lazy fileprivate var locationManager:CLLocationManager = {
let locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.allowsBackgroundLocationUpdates = true
return locationManager
}()
override init() {
guard
let url = Bundle.main.url(forResource: "beacons", withExtension: "json"),
let data = try? Data(contentsOf: url),
let _dictionary = try? JSONSerialization.jsonObject(with: data, options: []),
let dictionary = _dictionary as? [String:Any],
let regionsArray = dictionary["regions"] as? [[String:Any]] else {
print("Error occured: Beacons.json couldn't be parsed correctly. Make sure it's valid and try again.")
return
}
self.regionsArray = regionsArray.flatMap { return BREBeaconRegion(dictionary: $0) }
}
func beginMonitoring() {
// Right, before we actually start, we need to check that bluetooth is available and the required permissions have been given to the application. Let's do that before going any further...
bluetoothController.checkIfBluetoothIsEnabled { [weak self] (isEnabled:Bool) in
if isEnabled {
// It is, we're golden. Let's request authorization!
self?.locationManager.requestAlwaysAuthorization()
return
}
else {
// Bluetooth is disabled! Let's tell the user...
self?.delegate?.beaconScanningFailed(error: BRELocationManagerError.bluetoothIsDisabled)
return
}
}
}
func stopMonitoring() {
regionsArray?.forEach({ (region:BREBeaconRegion) in
locationManager.stopRangingBeacons(in: region.region)
locationManager.stopMonitoring(for: region.region)
})
}
fileprivate func monitorRegions() {
regionsArray?.forEach({ (region:BREBeaconRegion) in
locationManager.startRangingBeacons(in: region.region)
locationManager.startMonitoring(for: region.region)
})
}
}
extension BRELocationManager: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if status == .notDetermined {
// Not determined, but we can assume the user has been prompted.
return
}
guard status == .authorizedAlways else {
// The status has been determined (i.e. the user has allowed/not allowed the
delegate?.beaconScanningFailed(error: .locationServicesAreDisabled)
return
}
monitorRegions()
}
func locationManager(_ manager: CLLocationManager, rangingBeaconsDidFailFor region: CLBeaconRegion, withError error: Error) {
delegate?.beaconScanningFailed(error: BRELocationManagerError.unknownError)
}
func locationManager(_ manager: CLLocationManager, didRangeBeacons beacons: [CLBeacon], in region: CLBeaconRegion) {
guard let regionsArray = regionsArray else { return }
// First, we range.
// When you range multiple beacons at a time, this function is called once a second for _every beacon_ you range. That means if you're ranging four beacon regions at once, this will call four times. If you're in range of one of them, ONE of those callbacks will have a discovered beacon. The other three will return empty arrays.
// The way we've handled this is by dividing our beacons into regions. Each region shares the same UUID, they just have different Minor values to help us identify them. You can head over to beacons.json if you're confused by this - the structure over there should make things fairly clear.
// The clue for what this does is in the name - it helps us understand how close each of the beacon is from the device, and comes back to us periodically to let us know which beacons it's found in the surrounding area in the form of this delegate method. Neat, right?
// We're going to use the ranging system to identify how close we are to the beacons in our list. If we're close enough to one that's set up to trigger (see the shouldTrigger property in the BREBeacon model), and we're ready to make our entrance, it'll tell the user that they're ready to go!
// Find region first
let idx = regionsArray.index { region.proximityUUID.uuidString == $0.uuid.uuidString }
let region = regionsArray[idx!]
guard let beaconsArray = region.beacons else { return }
beacons.forEach { (beacon:CLBeacon) in
let signalStrength = beacon.rssi
// Check that we actually have a decent RSSI - iBeacons have a weird tendency of just sending an RSSI of 0 whenever the signal isn't strong enough.
guard signalStrength < 0 else { return }
// Identify which beacon has been ranged by the device. Doing this will help us understand whether we should or shouldn't trigger starting the music (again, see the shouldTrigger property).
let beaconObj:BREBeacon = {
let idx = beaconsArray.index { beacon.minor.intValue == $0.minor }
return beaconsArray[idx!]
}()
// Right, bit of a confusing step here. We're going to measure the strength of the signal offered by the beacon (.rssi), and ignore it until it's strong enough.
let inRangeIdx = beaconsInRange.index { $0.minor == beaconObj.minor }
// Right, so we've found a beacon! Is it within the programmed range we've specified for it to trigger?
if beaconObj.isInRange(rssi: signalStrength) {
// ...it bloody is! But wait - is it already in the array already? Have we found this beacon already?
if inRangeIdx == nil {
// It isn't. Let's add it to the array and start monitoring it!
beaconsInRange.append(beaconObj)
delegate?.beaconDiscoveredNewBeacon(beacon: beaconObj)
}
else {
// Ah, looks like it was already in the array. This method gets called over and over until it's told to stop ranging, so we can just ignore this. This time, we've stayed within range.
// Keep calm, carry on.
}
}
else {
// Beacon isn't in range. We can ignore this - unless, of course, it was already in the beacons array? If it was, that means we've just moved out of signal, so let's check if it's in range using that handy index we calculated earlier...
if inRangeIdx != nil {
// Yup, we've just stepped out of range. Let's remove it and alert the delegate.
beaconsInRange.remove(at: inRangeIdx!)
delegate?.beaconOutOfRange(beacon: beaconObj)
}
}
}
}
func locationManager(_ manager: CLLocationManager, didDetermineState state: CLRegionState, for region: CLRegion) {
// Right, didDetermineState is a bit of a pinging mechanism.
// For example, if you entered a region, closed the application, then re-opened it, you wouldn't expect to "enter" the region again - because you didn't enter, you just stayed in the same place. didDetermineState will trigger during every "transition" period (i.e. left/re-entered a zone).
// It's also worth mentioning that didDetermineState will be called whilst the app isn't even in memory if the region's notifyEntryOnDisplay is enabled. By default, this is false - but for this demonstration, I've enabled it for every monitored region.
// When notifyEntryOnDisplay is enabled for a monitored region, when the device WAKES (not even unlocked!), the device will do a quick pass for any beacons in range. If it finds one, it'll wake the app and fire this method. Using this, we can fire off a push notification when the user's within range of one of our beacons to get them to make their entrance!
// Final note - didDetermineState can be "forced" by using the locationManager.requestStateFor() method. That means you can request an update and run whatever logic's in here at (roughly) any given time (it's async), which is pretty gnarly.
// Check if the user's INSIDE the region, not outside...
guard state == CLRegionState.inside else { print("Not inside."); return }
// Alright, we're in range. Time to get the user to open the app and make their entrance.
BREPushNotificationController.createPushNotification(message: "Ready to make your big entrance?")
}
}
| 41.763636 | 366 | 0.604963 |
e68acb57673228b02b283e0c525ac7152eb99770 | 4,112 | //
// NativeAdViewController.swift
// AotterGoogleMediationAdSwift
//
// Created by JustinTsou on 2021/4/23.
//
import UIKit
import GoogleMobileAds
class NativeAdViewController: UIViewController {
@IBOutlet weak var nativeAdTableView: UITableView!
private let TestNativeAdUnit: String = "Your Native ad unit"
private let googleMediationNativeAdPosition: Int = 11
private var refreshControl: UIRefreshControl?
private var adLoader: GADAdLoader?
private var gADUnifiedNativeAd: GADNativeAd?
override func viewDidLoad() {
super.viewDidLoad()
self.setupTableView()
self.setupRefreshControl()
self.setupGADAdloader()
}
}
// MARK: Setup UI
extension NativeAdViewController {
private func setupTableView() {
nativeAdTableView.delegate = self
nativeAdTableView.dataSource = self
nativeAdTableView.register(UINib(nibName: "TrekNativeAdTableViewCell", bundle: nil), forCellReuseIdentifier: "TrekNativeAdTableViewCell")
nativeAdTableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
}
private func setupRefreshControl() {
refreshControl = UIRefreshControl()
refreshControl?.addTarget(self, action: #selector(self.onRefreshTable), for: .valueChanged)
nativeAdTableView.addSubview(refreshControl!)
}
@objc func onRefreshTable(_: UIRefreshControl) {
refreshControl?.beginRefreshing()
if gADUnifiedNativeAd != nil {
gADUnifiedNativeAd = nil;
}
self.adLoaderLoadRequest()
refreshControl?.endRefreshing()
}
}
// MARK: Setup GADAdLoader
extension NativeAdViewController {
private func setupGADAdloader() {
adLoader = GADAdLoader.init(adUnitID: TestNativeAdUnit, rootViewController: self, adTypes: [.native], options: [])
adLoader?.delegate = self
adLoaderLoadRequest()
}
private func adLoaderLoadRequest() {
adLoader?.load(GADRequest())
}
}
// MARK: UITableViewDataSource
extension NativeAdViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 30
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = UITableViewCell()
if indexPath.row == googleMediationNativeAdPosition {
let trekNativeAdTableViewCell = tableView.dequeueReusableCell(withIdentifier: "TrekNativeAdTableViewCell", for: indexPath) as! TrekNativeAdTableViewCell
guard let gADUnifiedNativeAd = gADUnifiedNativeAd else { return cell }
trekNativeAdTableViewCell.setGADNativeAdData(nativeAd: gADUnifiedNativeAd )
cell = trekNativeAdTableViewCell
}
cell.textLabel?.text = "index:\(indexPath.row)"
cell.selectionStyle = .none
return cell
}
}
// MARK: UITableViewDelegate
extension NativeAdViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.row == googleMediationNativeAdPosition {
return gADUnifiedNativeAd == nil ? 0:80
}
return 80
}
}
// MARK: GADNativeAdLoaderDelegate
extension NativeAdViewController: GADNativeAdLoaderDelegate {
func adLoader(_ adLoader: GADAdLoader, didReceive nativeAd: GADNativeAd) {
guard let extraAssets = nativeAd.extraAssets else { return }
if extraAssets.keys.contains("trekAd") {
let adType = extraAssets["trekAd"] as! String
if adType == "nativeAd" {
gADUnifiedNativeAd = nativeAd
}
}
nativeAdTableView.reloadData()
}
func adLoader(_ adLoader: GADAdLoader, didFailToReceiveAdWithError error: Error) {
print("Error Message:\(error.localizedDescription)")
}
}
| 27.413333 | 164 | 0.66537 |
9b6a49ca3b0f743212e40f288085f5c86e6c024c | 3,270 | //
// Recoverable.swift
// SkeletonView
//
// Created by Juanpe Catalán on 13/05/2018.
// Copyright © 2018 SkeletonView. All rights reserved.
//
import UIKit
protocol Recoverable {
func saveViewState()
func recoverViewState(forced: Bool)
}
extension UIView: Recoverable {
var viewState: RecoverableViewState? {
get { return ao_get(pkey: &ViewAssociatedKeys.viewState) as? RecoverableViewState }
set { ao_setOptional(newValue, pkey: &ViewAssociatedKeys.viewState) }
}
@objc func saveViewState() {
viewState = RecoverableViewState(view: self)
}
@objc func recoverViewState(forced: Bool) {
guard let safeViewState = viewState else { return }
startTransition { [weak self] in
self?.layer.cornerRadius = safeViewState.cornerRadius
self?.layer.masksToBounds = safeViewState.clipToBounds
if safeViewState.backgroundColor != self?.backgroundColor || forced {
self?.backgroundColor = safeViewState.backgroundColor
}
}
}
}
extension UILabel{
var labelState: RecoverableTextViewState? {
get { return ao_get(pkey: &ViewAssociatedKeys.labelViewState) as? RecoverableTextViewState }
set { ao_setOptional(newValue, pkey: &ViewAssociatedKeys.labelViewState) }
}
override func saveViewState() {
super.saveViewState()
labelState = RecoverableTextViewState(view: self)
}
override func recoverViewState(forced: Bool) {
super.recoverViewState(forced: forced)
startTransition { [weak self] in
self?.textColor = self?.labelState?.textColor
self?.text = self?.labelState?.text
self?.isUserInteractionEnabled = self?.labelState?.isUserInteractionsEnabled ?? false
}
}
}
extension UITextView{
var textState: RecoverableTextViewState? {
get { return ao_get(pkey: &ViewAssociatedKeys.labelViewState) as? RecoverableTextViewState }
set { ao_setOptional(newValue, pkey: &ViewAssociatedKeys.labelViewState) }
}
override func saveViewState() {
super.saveViewState()
textState = RecoverableTextViewState(view: self)
}
override func recoverViewState(forced: Bool) {
super.recoverViewState(forced: forced)
startTransition { [weak self] in
self?.textColor = self?.textState?.textColor
self?.text = self?.textState?.text
self?.isUserInteractionEnabled = self?.textState?.isUserInteractionsEnabled ?? false
}
}
}
extension UIImageView {
var imageState: RecoverableImageViewState? {
get { return ao_get(pkey: &ViewAssociatedKeys.imageViewState) as? RecoverableImageViewState }
set { ao_setOptional(newValue, pkey: &ViewAssociatedKeys.imageViewState) }
}
override func saveViewState() {
super.saveViewState()
imageState = RecoverableImageViewState(view: self)
}
override func recoverViewState(forced: Bool) {
super.recoverViewState(forced: forced)
startTransition { [weak self] in
self?.image = self?.image == nil || forced ? self?.imageState?.image : self?.image
}
}
}
| 32.7 | 101 | 0.659633 |