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
|
---|---|---|---|---|---|
d98ddb56a7d4751ddc863dfe5642abdc96c8cf43 | 3,453 | //
// StringTests.swift
// SwiftExtensionsTests
//
// Created by Tatsuya Tanaka on 20171217.
// Copyright © 2017年 tattn. All rights reserved.
//
import XCTest
import BTSwiftExtensions
class StringTests: XCTestCase {
func testLocalized() {
XCTAssertEqual("hello".localized, "hello")
// UserDefaults.standard.set(["ja"], forKey: "AppleLanguages")
// UserDefaults.standard.synchronize()
// XCTAssertEqual("hello".localized, "こんにちは")
}
}
extension StringTests {
func testUrl() {
let string = "https://example.com"
XCTAssertEqual(string.url, URL(string: "https://example.com")!)
}
func testUrlNil() {
let string = "🐱"
XCTAssertNil(string.url)
}
}
extension StringTests {
func testRangeSubscript() {
let string = "0123456789"
XCTAssertEqual(string[0...5], "012345")
XCTAssertEqual(string[1...3], "123")
XCTAssertEqual(string[3..<7], "3456")
XCTAssertEqual(string[...4], "01234")
XCTAssertEqual(string[..<4], "0123")
XCTAssertEqual(string[4...], "456789")
}
}
extension StringTests {
func testHalfWidthFullNumberToHalf() {
let target = "123"
let expected = "123"
XCTAssertEqual(expected, target.halfWidth)
}
func testHalfWidthHalfNumberToHalf() {
let target = "12345"
let expected = "12345"
XCTAssertEqual(expected, target.halfWidth)
}
func testHalfWidthFullAlphabetToHalf() {
let target = "ABCD"
let expected = "ABCD"
XCTAssertEqual(expected, target.halfWidth)
}
func testHalfWidthHalfAlphabetToHalf() {
let target = "ABCD"
let answer = "ABCD"
XCTAssertEqual(answer, target.halfWidth, "半角英字が半角英字になることを確認")
}
func testHalfWidthFullAlphabetAndNumberToHalf() {
let target = "12AB"
let expected = "12AB"
XCTAssertEqual(expected, target.halfWidth)
}
func testHalfWidthHalfOrFullAlphabetAndNumberToHalf() {
let target = "123ABcde"
let expected = "123ABcde"
XCTAssertEqual(expected, target.halfWidth)
}
func testHalfWidthひらがなToひらがな() {
let target = "あいうえお"
let expected = "あいうえお"
XCTAssertEqual(expected, target.halfWidth)
}
func testFullWidthHalfNumberToFull() {
let target = "123"
let expected = "123"
XCTAssertEqual(expected, target.fullWidth)
}
func testFullWidthFullNumberToFull() {
let target = "12345"
let expected = "12345"
XCTAssertEqual(expected, target.fullWidth)
}
func testFullWidthHalfAlphabetToFull() {
let target = "ABCD"
let expected = "ABCD"
XCTAssertEqual(expected, target.fullWidth)
}
func testFullWidthFullAlphabetToFull() {
let target = "ABCD"
let expected = "ABCD"
XCTAssertEqual(expected, target.fullWidth)
}
func testFullWidthHalfAlphabetAndNumberToFull() {
let target = "12AB"
let expected = "12AB"
XCTAssertEqual(expected, target.fullWidth)
}
func testFullWidthFullOrHalfAlphabetAndNumberToFull() {
let target = "123ABcde"
let expected = "123ABcde"
XCTAssertEqual(expected, target.fullWidth)
}
func testFullWidthひらがなToひらがな() {
let target = "あいうえお"
let expected = "あいうえお"
XCTAssertEqual(expected, target.fullWidth)
}
}
| 26.358779 | 71 | 0.626991 |
e2af4695e6bb4f31019bb2bc954653edcb064c1f | 2,292 | //
// SceneDelegate.swift
// Task9
//
// Created by Егор Зайнуллин on 27.05.2021.
//
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.245283 | 147 | 0.712914 |
ebb63de61509729b734f313023175443cd6a1a07 | 906 | //
// ValueFormatter.swift
// VFCounter
//
// Created by Sunmi on 2020/10/02.
// Copyright © 2020 creativeSun. All rights reserved.
//
import Foundation
import Charts
public class ValueFormatter: NSObject, IValueFormatter, IAxisValueFormatter {
/// Suffix to be appended after the values
public var appendix: String?
public init(appendix: String? = nil) {
self.appendix = appendix
}
fileprivate func format(value: Double) -> String {
var newValue = value
var r = String(format: "%.0f", newValue)
return r
}
public func stringForValue(_ value: Double, axis: AxisBase?) -> String {
return format(value: value)
}
public func stringForValue(_ value: Double, entry: ChartDataEntry,
dataSetIndex: Int, viewPortHandler: ViewPortHandler?) -> String {
return format(value: value)
}
}
| 24.486486 | 96 | 0.64128 |
eb1bb26e2505afa3399de907ada96c5c77d1c805 | 203 | //
// Developer+CoreDataClass.swift
// StudyHall v2
//
// Created by Kathryn Jerez on 12/21/21.
//
//
import Foundation
import CoreData
@objc(Developer)
public class Developer: NSManagedObject {
}
| 12.6875 | 41 | 0.714286 |
0123546e120437e758deea421b6d061cfcbd77fa | 3,042 | //
// DetailsViewController.swift
// Parsetagram
//
// Created by Ming Horn on 6/22/16.
// Copyright © 2016 Ming Horn. All rights reserved.
//
import UIKit
import Parse
import ParseUI
class DetailsViewController: UIViewController {
@IBOutlet weak var profImage: PFImageView!
@IBOutlet weak var userLabel: UILabel!
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var postImage: PFImageView!
@IBOutlet weak var captionLabel: UILabel!
@IBOutlet weak var likeHeart: UIImageView!
@IBOutlet weak var likesLabel: UILabel!
var post: PFObject?
override func viewDidLoad() {
super.viewDidLoad()
userLabel.text = post?["author"].username
//dateLabel.text = post?["createdAt"]
postImage.file = post?["media"] as? PFFile
// Do any additional setup after loading the view.
let dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = .MediumStyle
dateFormatter.timeStyle = .NoStyle
dateLabel.text = dateFormatter.stringFromDate(post!.createdAt!)
if(post!["caption"] != nil) {
captionLabel.text = post!["caption"] as? String
} else {
captionLabel.frame = CGRect(x: 0, y: 0, width: 0, height: 0)
}
let gesture = UITapGestureRecognizer(target: self, action:#selector(PhotoPostCell.onDoubleTap(_:)))
gesture.numberOfTapsRequired = 2
view.addGestureRecognizer(gesture)
likeHeart?.hidden = true
likesLabel.text = "\(String(post!["likesCount"])) likes"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func backPressed(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion: nil)
}
func onDoubleTap(sender:AnyObject) {
if(post != nil) {
if var likes:Int? = post!.objectForKey("likesCount") as? Int {
likes! += 1
post!.setObject(likes!, forKey: "likesCount");
post!.saveInBackground();
likesLabel?.text = "\(likes!) likes";
}
}
likeHeart?.hidden = false
likeHeart?.alpha = 1.0
UIView.animateWithDuration(1.0, delay: 1.0, options: [], animations: {
self.likeHeart?.alpha = 0
}, completion: {
(value:Bool) in
self.likeHeart?.hidden = true
})
}
/*
// 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.
}
*/
}
| 30.118812 | 107 | 0.59073 |
16a8be51f06e30652c6956900e946b52e4bc6d3e | 1,162 | //
// RelationshipListing.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
public class RelationshipListing: Codable {
public var entities: [Relationship]?
public var pageSize: Int?
public var pageNumber: Int?
public var total: Int64?
public var firstUri: String?
public var selfUri: String?
public var nextUri: String?
public var previousUri: String?
public var lastUri: String?
public var pageCount: Int?
public init(entities: [Relationship]?, pageSize: Int?, pageNumber: Int?, total: Int64?, firstUri: String?, selfUri: String?, nextUri: String?, previousUri: String?, lastUri: String?, pageCount: Int?) {
self.entities = entities
self.pageSize = pageSize
self.pageNumber = pageNumber
self.total = total
self.firstUri = firstUri
self.selfUri = selfUri
self.nextUri = nextUri
self.previousUri = previousUri
self.lastUri = lastUri
self.pageCount = pageCount
}
}
| 22.346154 | 205 | 0.612737 |
3974a3df553e937a13426c2e971c706f82c55c00 | 420 | //
// ConnectionView.swift
// Connections
//
// Created by Luan Nguyen on 06/12/2020.
//
import SwiftUI
struct ConnectionView: View {
// MARK: - PROPERTIES
let imageName: String
// MARK: - BODY
var body: some View {
Image(imageName)
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width: 80, height: 80)
.clipShape(Circle())
}
}
| 18.26087 | 44 | 0.559524 |
dd77a6fdfb680016341c270fe75fbc7cc90e20d2 | 7,700 | //
// StatisticsLoaderTests.swift
// DuckDuckGo
//
// Copyright © 2017 DuckDuckGo. All rights reserved.
//
// 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
import OHHTTPStubs
import OHHTTPStubsSwift
@testable import Core
class StatisticsLoaderTests: XCTestCase {
let appUrls = AppUrls()
var mockStatisticsStore: StatisticsStore!
var testee: StatisticsLoader!
override func setUp() {
super.setUp()
mockStatisticsStore = MockStatisticsStore()
testee = StatisticsLoader(statisticsStore: mockStatisticsStore)
}
override func tearDown() {
HTTPStubs.removeAllStubs()
super.tearDown()
}
func testWhenSearchRefreshHasSuccessfulUpdateAtbRequestThenSearchRetentionAtbUpdated() {
mockStatisticsStore.atb = "atb"
mockStatisticsStore.searchRetentionAtb = "retentionatb"
loadSuccessfulUpdateAtbStub()
let expect = expectation(description: "Successful atb updates retention store")
testee.refreshSearchRetentionAtb {
XCTAssertEqual(self.mockStatisticsStore.atb, "v20-1")
XCTAssertEqual(self.mockStatisticsStore.searchRetentionAtb, "v77-5")
expect.fulfill()
}
waitForExpectations(timeout: 1, handler: nil)
}
func testWhenAppRefreshHasSuccessfulUpdateAtbRequestThenAppRetentionAtbUpdated() {
mockStatisticsStore.atb = "atb"
mockStatisticsStore.appRetentionAtb = "retentionatb"
loadSuccessfulUpdateAtbStub()
let expect = expectation(description: "Successful atb updates retention store")
testee.refreshAppRetentionAtb {
XCTAssertEqual(self.mockStatisticsStore.atb, "v20-1")
XCTAssertEqual(self.mockStatisticsStore.appRetentionAtb, "v77-5")
expect.fulfill()
}
waitForExpectations(timeout: 1, handler: nil)
}
func testWhenLoadHasSuccessfulAtbAndExtiRequestsThenStoreUpdatedWithVariant() {
loadSuccessfulAtbStub()
loadSuccessfulExiStub()
let expect = expectation(description: "Successfult atb and exti updates store")
testee.load {
XCTAssertTrue(self.mockStatisticsStore.hasInstallStatistics)
XCTAssertEqual(self.mockStatisticsStore.atb, "v77-5")
expect.fulfill()
}
waitForExpectations(timeout: 1, handler: nil)
}
func testWhenLoadHasUnsuccessfulAtbThenStoreNotUpdated() {
loadUnsuccessfulAtbStub()
loadSuccessfulExiStub()
let expect = expectation(description: "Unsuccessfult atb does not update store")
testee.load {
XCTAssertFalse(self.mockStatisticsStore.hasInstallStatistics)
XCTAssertNil(self.mockStatisticsStore.atb)
expect.fulfill()
}
waitForExpectations(timeout: 1, handler: nil)
}
func testWhenLoadHasUnsuccessfulExtiThenStoreNotUpdated() {
loadSuccessfulAtbStub()
loadUnsuccessfulExiStub()
let expect = expectation(description: "Unsuccessful exti does not update store")
testee.load {
XCTAssertFalse(self.mockStatisticsStore.hasInstallStatistics)
XCTAssertNil(self.mockStatisticsStore.atb)
expect.fulfill()
}
waitForExpectations(timeout: 1, handler: nil)
}
func testWhenSearchRefreshHasSuccessfulAtbRequestThenSearchRetentionAtbUpdated() {
mockStatisticsStore.atb = "atb"
mockStatisticsStore.searchRetentionAtb = "retentionatb"
loadSuccessfulAtbStub()
let expect = expectation(description: "Successful atb updates retention store")
testee.refreshSearchRetentionAtb {
XCTAssertEqual(self.mockStatisticsStore.atb, "atb")
XCTAssertEqual(self.mockStatisticsStore.searchRetentionAtb, "v77-5")
expect.fulfill()
}
waitForExpectations(timeout: 1, handler: nil)
}
func testWhenAppRefreshHasSuccessfulAtbRequestThenAppRetentionAtbUpdated() {
mockStatisticsStore.atb = "atb"
mockStatisticsStore.appRetentionAtb = "retentionatb"
loadSuccessfulAtbStub()
let expect = expectation(description: "Successful atb updates retention store")
testee.refreshAppRetentionAtb {
XCTAssertEqual(self.mockStatisticsStore.atb, "atb")
XCTAssertEqual(self.mockStatisticsStore.appRetentionAtb, "v77-5")
expect.fulfill()
}
waitForExpectations(timeout: 1, handler: nil)
}
func testWhenSearchRefreshHasUnsuccessfulAtbRequestThenSearchRetentionAtbNotUpdated() {
mockStatisticsStore.atb = "atb"
mockStatisticsStore.searchRetentionAtb = "retentionAtb"
loadUnsuccessfulAtbStub()
let expect = expectation(description: "Unsuccessful atb does not update store")
testee.refreshSearchRetentionAtb {
XCTAssertEqual(self.mockStatisticsStore.atb, "atb")
XCTAssertEqual(self.mockStatisticsStore.searchRetentionAtb, "retentionAtb")
expect.fulfill()
}
waitForExpectations(timeout: 1, handler: nil)
}
func testWhenAppRefreshHasUnsuccessfulAtbRequestThenSearchRetentionAtbNotUpdated() {
mockStatisticsStore.atb = "atb"
mockStatisticsStore.appRetentionAtb = "retentionAtb"
loadUnsuccessfulAtbStub()
let expect = expectation(description: "Unsuccessful atb does not update store")
testee.refreshAppRetentionAtb {
XCTAssertEqual(self.mockStatisticsStore.atb, "atb")
XCTAssertEqual(self.mockStatisticsStore.appRetentionAtb, "retentionAtb")
expect.fulfill()
}
waitForExpectations(timeout: 1, handler: nil)
}
func loadSuccessfulAtbStub() {
stub(condition: isHost(appUrls.initialAtb.host!)) { _ in
let path = OHPathForFile("MockFiles/atb.json", type(of: self))!
return fixture(filePath: path, status: 200, headers: nil)
}
}
func loadSuccessfulUpdateAtbStub() {
stub(condition: isHost(appUrls.initialAtb.host!)) { _ in
let path = OHPathForFile("MockFiles/atb-with-update.json", type(of: self))!
return fixture(filePath: path, status: 200, headers: nil)
}
}
func loadUnsuccessfulAtbStub() {
stub(condition: isHost(appUrls.initialAtb.host!)) { _ in
let path = OHPathForFile("MockFiles/invalid.json", type(of: self))!
return fixture(filePath: path, status: 400, headers: nil)
}
}
func loadSuccessfulExiStub() {
stub(condition: isPath(appUrls.exti(forAtb: "").path)) { _ -> HTTPStubsResponse in
let path = OHPathForFile("MockFiles/empty", type(of: self))!
return fixture(filePath: path, status: 200, headers: nil)
}
}
func loadUnsuccessfulExiStub() {
stub(condition: isPath(appUrls.exti(forAtb: "").path)) { _ -> HTTPStubsResponse in
let path = OHPathForFile("MockFiles/empty", type(of: self))!
return fixture(filePath: path, status: 400, headers: nil)
}
}
}
| 35.321101 | 92 | 0.675844 |
e08bec417ea56834f5bd507fc3d7c02e918ce75e | 5,434 | //
// AddressListController.swift
// Carte
//
// Created by Wrappers Zhang on 2018/5/6.
// Copyright © 2018 Wrappers. All rights reserved.
//
import Foundation
import Then
import SnapKit
class AddressListController: BaseViewController {
enum `Type` {
case modify
case select
}
let addButton = UIButton()
let tableView = UITableView()
var source = [AddressCellRequired]()
var addressSource = [Address]()
var type: Type
init(type: Type = .modify) {
self.type = type
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
fetch()
}
private func setupUI() {
view.backgroundColor = .white
setNavigation()
//tableView
tableView.tableFooterView = UIView()
tableView.delegate = self
tableView.dataSource = self
tableView.registerNib(AddressCell.self)
tableView.separatorInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
//addButton
addButton.setTitle("+新地址", for: .normal)
addButton.setTitleColor(UIColor(r: 252, g: 18, b: 36), for: .normal)
addButton.backgroundColor = .white
addButton.addTarget(self, action: #selector(addAddress), for: .touchUpInside)
let line = SeparatorLine(position: SeparatorLine.Position.top, margin: (0,0), height: 0.5)
line.work(with: addButton)
}
private func setNavigation() {
title = "地址管理"
navigationController?.navigationBar.isHidden = false
}
override func addConstraints() {
view.addSubview(addButton)
addButton.snp.makeConstraints { (make) in
make.leading.trailing.equalToSuperview()
make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom)
make.height.equalTo(50)
}
view.addSubview(tableView)
tableView.snp.makeConstraints { (make) in
make.top.leading.trailing.equalToSuperview()
make.bottom.equalTo(addButton.snp.top)
}
}
@objc
private func addAddress() {
navigationController?.pushViewController(AddAddressController.initFromStoryboard(name: .mine), animated: true)
}
}
extension AddressListController {
fileprivate func fetch() {
HUD.wait()
AddressAPI
.fetchUserAddress(userId: Default.Account.integer(forKey: .userId))
.always {
HUD.clear()
}
.then { [weak self] (addresses) -> Void in
self?.addressSource = addresses
self?.source = addresses.map { DataFactory.viewRequired.matchAddressCellRequired($0) }
self?.tableView.reloadData()
}
.catch { (_) in
HUD.showError("发生错误")
}
}
}
extension AddressListController: UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return source.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 75
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: AddressCell = tableView.dequeueReusableCell(withIdentifier: AddressCell.reuseIdentifier) as! AddressCell
cell.model = source[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
switch type {
case .modify:
let controller = AddAddressController.initFromStoryboard(name: .mine)
controller.operate = .modify(addressSource[indexPath.row])
navigationController?.pushViewController(controller, animated: true)
case .select:
NotificationCenter.postNotification(name: .selectAddress, userInfo: ["address": addressSource[indexPath.row]])
navigationController?.popViewController(animated: true)
}
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
switch type {
case .modify:
return true
case .select:
return false
}
}
func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? {
return "删除"
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
HUD.wait()
AddressAPI
.deleteAddress(addressId: addressSource[indexPath.row].id ?? 0)
.always {
HUD.clear()
}
.then { [weak self] (_) -> Void in
self?.tableView.deleteRows(at: [indexPath], with: .automatic)
}
.catch { (_) in
HUD.showError("发生错误")
}
}
}
| 31.593023 | 127 | 0.611888 |
611776ed78308c9e96136c62a01caa5ae33b015a | 2,862 | //
// Generals.swift
// HasbroSTransformers
//
// Created by Amir on 2018-09-22.
// Copyright © 2018 Amir. All rights reserved.
//
import Foundation
import UIKit
// welcome message in case of empty list to give initial idea to user
let welcomeMsgText : String = "Welcome to\nHasbro’s Transformers\n GAME \nto enter your\nFirst Transfromer\nTAP ON TOP Right\n ADD Button"
// get token from UserDefaults.standard
// for the first time generate token over firebase api
func getToken(getNew : Bool, api : API) {
let defaultssettings = DefaultsSettings()
var apiToken = defaultssettings.loadSettings(keyName: "token")
if (apiToken == "" && getNew ) {
apiToken = "Bearer " + api.getOneToken()
defaultssettings.saveSettings(keyName: "token", keyValue: apiToken)
}
//print(apiToken)
api.apiToken = apiToken
}
// find list of images and pre load them to speed up app interface
func getURLImagesListAndPreLoadThem(transformersList : [Transformer]) -> [String : UIImage] {
let imagesList = findImageList(transformers: transformersList)
var preloadedImage : [String : UIImage] = [:]
for oneImage in imagesList {
preloadedImage[oneImage.key] = preLoadImage(imagePath: oneImage.value)
}
return preloadedImage
}
// pre-load one image from url and keep it on memory
func preLoadImage(imagePath : String) -> UIImage {
var image : UIImage = UIImage(named: "questionMark") ?? #imageLiteral(resourceName: "questionMark")
let url = URL(string: imagePath)
let data = try? Data(contentsOf: url!)
if let imageData = data {
image = UIImage(data: imageData)!
} else {
//keep image init Value
}
return image
}
// find list of images inside an array of Transformer
func findImageList(transformers : [Transformer]) -> [String : String] {
var imagesList : [String : String] = [:]
for oneTransformer in transformers {
var shouldAdd = true
for oneImage in imagesList {
if (oneTransformer.team_icon == oneImage.value) {
shouldAdd = false
}
}
if shouldAdd {
imagesList[oneTransformer.team] = oneTransformer.team_icon
}
}
return imagesList
}
// find battle Winner and creat a message for alert popup
func battleWinner(numA : Int, numD : Int) -> String {
var winner : String = ""
if (numA > numD ){
winner = "Decepticons is winner with \(numA) Win"
} else if (numA < numD ) {
winner = "Autobots is Winner with \(numD) Win"
} else {
winner = "Tie No Winner"
}
return winner
}
// send error source information to console
func locateQuickErr(myLine: Int , inputStr : String = "" ) {
print("===> Guard Error \(inputStr) :\n file:\(#file)\n line:\(myLine)\n function:\(#function) ")
}
| 29.8125 | 138 | 0.65269 |
2964b45b5c8cbb1b2b162650c9c39116e32743be | 3,604 | //
// ViewState+Diffable.swift
// FitnessTrackerReSwift
//
// Created by Swain Molster on 7/23/18.
// Copyright © 2018 Swain Molster. All rights reserved.
//
import Foundation
import FitnessTrackerKit
extension ViewState: Diffable {
internal enum Change {
// Tab Switching
/// The user switched `fromTab`, `toTab`
case switched(fromTab: Tab, toTab: Tab)
// View controller states changed.
case tabStacksChanged([(Tab, [ViewController])])
// Modals
case presentedModal(viewController: ViewController, onTab: Tab)
case presentedModalInNavigationController(viewController: ViewController, onTab: Tab)
case dismissedModal(onTab: Tab)
case modalStackChanged([ViewController])
/// Smaller number means MORE important
var renderingImportance: Int {
switch self {
case .dismissedModal: return 0
case .switched: return 1
case .modalStackChanged: return 2
case .presentedModal, .presentedModalInNavigationController: return 3
case .tabStacksChanged: return 4
}
}
}
internal func differences(to other: ViewState) -> [ViewState.Change] {
guard self != other else { return [] }
var changes: [ViewState.Change] = []
if self.selectedTab != other.selectedTab {
changes.append(.switched(fromTab: self.selectedTab, toTab: other.selectedTab))
}
let selectedTab = other.selectedTab
if self.modal != other.modal {
// Change in the modals
if self.modal == nil && other.modal != nil {
// Presented a modal, where there wasn't one previously.
switch other.modal! {
case .single(let viewController):
changes.append(.presentedModal(viewController: viewController, onTab: selectedTab))
case .stack(let viewControllers):
changes.append(.presentedModalInNavigationController(viewController: viewControllers.first!, onTab: selectedTab))
}
} else if self.modal != nil && other.modal == nil {
// Dismissed a modal
changes.append(.dismissedModal(onTab: selectedTab))
} else {
// Both non-nil, has to be a push/pop on modal navigation stack.
let oldModal = self.modal!
let newModal = other.modal!
guard case .stack(let oldViewControllers) = oldModal, case .stack(let newViewControllers) = newModal else {
fatalError("Invalid state! You tried to push/pop a view controller on a presented modal without presenting that modal in a UINavigationController.")
}
if oldViewControllers.differences(to: newViewControllers).isNotEmpty {
changes.append(.modalStackChanged(newViewControllers))
}
}
}
var tabsWithNewVCs: [Tab: [ViewController]] = [:]
for tab in Tab.allCases {
// Compare old.tabStacks
if self.tabStacks[tab].differences(to: other.tabStacks[tab]).isNotEmpty {
tabsWithNewVCs[tab] = other.tabStacks[tab]
}
}
if !tabsWithNewVCs.isEmpty {
changes.append(.tabStacksChanged(tabsWithNewVCs.map { ($0.key, $0.value) }))
}
return changes
}
}
| 37.936842 | 168 | 0.577969 |
1aab74cf9f0d3ac3e36506baed27c5399588f172 | 377 | //
// dateCollectionViewCell.swift
// CalendarTexting
//
// Created by Jairo Millan on 8/20/19.
// Copyright © 2019 Jairo Millan. All rights reserved.
//
import UIKit
class dateCollectionViewCell: UICollectionViewCell {
var date:Date?
@IBOutlet weak var dateLabel: UILabel! {
didSet {
self.dateLabel.textAlignment = .center
}
}
}
| 18.85 | 55 | 0.657825 |
ff6f169594af2c7b6a73f845468c7ff69f8f3705 | 2,126 | //
// RouteAPITest.swift
// StravaZpot
//
// Created by Tomás Ruiz López on 7/11/16.
// Copyright © 2016 SweetZpot AS. All rights reserved.
//
import XCTest
import Nimble
@testable import StravaZpot
class RouteAPITest: XCTestCase {
func testShouldRetrieveARoute() {
let client = MockHTTPClient(respondWithJSON: ROUTE_JSON)
let api = RouteAPI(client: client)
var result : StravaResult<Route>?
api.retrieveRoute(withID: 1263727).execute{ result = $0 }
expect(result).toEventually(beSuccessful())
expect(client.lastUrl).to(contain("routes/1263727"))
expect(client.getCalled).to(equal(true))
}
func testShoudlListAthleteRoutes() {
let client = MockHTTPClient(respondWithJSON: "[]")
let api = RouteAPI(client: client)
var result : StravaResult<EquatableArray<Route>>?
api.listAthleteRoutes(withID: 1234).execute{ result = $0 }
expect(result).toEventually(beSuccessful())
expect(client.lastUrl).to(contain("athletes/1234/routes"))
expect(client.getCalled).to(equal(true))
}
let ROUTE_JSON = "{" +
" \"athlete\": {" +
" \"id\": 265720," +
" \"resource_state\": 2" +
" }," +
" \"description\": \"\"," +
" \"distance\": 173625.6," +
" \"elevation_gain\": 2964.6," +
" \"id\": 1263727," +
" \"map\": {" +
" \"id\": \"r1263727\"," +
" \"summary_polyline\": \"qyrFxswgV|\"," +
" \"resource_state\": 3" +
" }," +
" \"name\": \"New Years Resolution - Santa Cruz Century Edition\"," +
" \"private\": false," +
" \"resource_state\": 3," +
" \"starred\": false," +
" \"timestamp\": 1419669292," +
" \"type\": 1," +
" \"sub_type\": 2," +
" \"segments\": [" +
" {" +
" \"id\": 3799," +
" \"resource_state\": 2," +
" \"name\": \"Highway 9 - HWY236 to Skyline\"" +
" }" +
" ]" +
"}"
}
| 30.811594 | 78 | 0.502822 |
f78783f4cc73228da78b786f6348227ba26de27d | 4,441 | //
// LogHeadView.swift
// exampleWindow
//
// Created by Remi Robert on 20/01/2017.
// Copyright © 2017 Remi Robert. All rights reserved.
//
import UIKit
protocol LogHeadViewDelegate: class {
func didTapButton()
}
class LogHeadView: UIView {
weak var delegate: LogHeadViewDelegate?
private var obsLog: NotificationObserver<LogLevel>!
private var obsNetwork: NotificationObserver<Void>!
private var badge: LogBadgeView!
private lazy var imageView: UIImageView! = {
let frame = CGRect(origin: CGPoint(x: 20, y: 20), size: CGSize(width: 40, height: 40))
let imageView = UIImageView(frame: frame)
imageView.contentMode = .scaleAspectFit
let image = UIImage(named: "logo", in: Bundle(for: LogHeadView.self), compatibleWith: nil)
imageView.image = image?.withRenderingMode(.alwaysTemplate)
imageView.tintColor = Color.mainGreen
imageView.layer.cornerRadius = 40
return imageView
}()
static var originalPosition: CGPoint {
return CGPoint(x: -10, y: UIScreen.main.bounds.size.height / 2)
}
static var size: CGSize {return CGSize(width: 80, height: 80)}
fileprivate func initBadgeView() {
clipsToBounds = false
badge = LogBadgeView(frame: CGRect(x: 60, y: 0, width: 30, height: 20))
addSubview(badge)
}
fileprivate func initLabelEvent(content: String) {
let view = UILabel()
view.frame = CGRect(x: self.frame.size.width / 2 - 12.5,
y: self.frame.size.height / 2 - 25, width: 25, height: 25)
view.text = content
self.addSubview(view)
UIView.animate(withDuration: 0.8, animations: {
view.frame.origin.y = -100
view.alpha = 0
}, completion: { _ in
view.removeFromSuperview()
})
}
fileprivate func initLayer() {
backgroundColor = UIColor.black
layer.shadowColor = UIColor.black.cgColor
layer.shadowRadius = 5
layer.shadowOpacity = 0.8
layer.cornerRadius = 40
layer.shadowOffset = CGSize.zero
sizeToFit()
layer.masksToBounds = true
let gradientLayer = CAGradientLayer()
gradientLayer.frame = bounds
gradientLayer.cornerRadius = 40
gradientLayer.colors = Color.colorGradientHead
layer.addSublayer(gradientLayer)
addSubview(imageView)
initBadgeView()
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(LogHeadView.tap))
addGestureRecognizer(tapGesture)
self.obsLog = NotificationObserver(notification: LogNotificationApp.newLog, block: { level in
guard let level = level as? LogLevel, level == .warning || level == .error else {return}
DispatchQueue.main.async {
self.initLabelEvent(content: level.notificationText)
}
})
self.obsNetwork = NotificationObserver(notification: LogNotificationApp.newRequest, block: { _ in
DispatchQueue.main.async {
self.initLabelEvent(content: "🚀")
}
})
}
@objc func tap() {
delegate?.didTapButton()
}
override init(frame: CGRect) {
super.init(frame: frame)
initLayer()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func changeSideDisplay(left: Bool) {
if left {
UIView.animate(withDuration: 0.5, delay: 0.1, usingSpringWithDamping: 0.5,
initialSpringVelocity: 5, options: .curveEaseInOut, animations: {
self.badge.frame.origin.x = 60
}, completion: nil)
} else {
UIView.animate(withDuration: 0.5, delay: 0.1, usingSpringWithDamping: 0.5,
initialSpringVelocity: 5, options: .curveEaseInOut, animations: {
self.badge.frame.origin.x = 20 - self.badge.frame.size.width
}, completion: nil)
}
}
func updateOrientation(newSize: CGSize) {
let oldSize = CGSize(width: newSize.height, height: newSize.width)
let percent = center.y / oldSize.height * 100
let newOrigin = newSize.height * percent / 100
let originX = frame.origin.x < newSize.height / 2 ? 30 : newSize.width - 30
self.center = CGPoint(x: originX, y: newOrigin)
}
}
| 34.695313 | 105 | 0.619905 |
726718315b348e8b5931f31d87d6500465c69685 | 1,169 | //
// FundingSourceSelectorInteractor.swift
// AptoSDK
//
// Created by Takeichi Kanzaki on 18/12/2018.
//
import AptoSDK
import Foundation
class FundingSourceSelectorInteractor: FundingSourceSelectorInteractorProtocol {
private let card: Card
private let platform: AptoPlatformProtocol
init(card: Card, platform: AptoPlatformProtocol) {
self.card = card
self.platform = platform
}
func loadFundingSources(forceRefresh: Bool, callback: @escaping Result<[FundingSource], NSError>.Callback) {
platform.fetchCardFundingSources(card.accountId, page: 0, rows: Int.max, forceRefresh: forceRefresh,
callback: callback)
}
func activeCardFundingSource(forceRefresh: Bool, callback: @escaping Result<FundingSource?, NSError>.Callback) {
platform.fetchCardFundingSource(card.accountId, forceRefresh: forceRefresh, callback: callback)
}
func setActive(fundingSource: FundingSource, callback: @escaping Result<FundingSource, NSError>.Callback) {
platform.setCardFundingSource(fundingSource.fundingSourceId, cardId: card.accountId, callback: callback)
}
}
| 35.424242 | 116 | 0.728828 |
decd2f0959894addcac229438a6da724f8043326 | 3,349 | //
// Presprciption.swift
// ePills
//
// Created by Javier Calatrava on 25/04/2020.
// Copyright © 2020 Javier Calatrava. All rights reserved.
//
import Foundation
enum PrescriptionState {
case notStarted
case ongoing
case ongoingReady
case ongoingEllapsed
case finished
}
class Prescription: Identifiable {
struct Constants {
static let ongoingReadyOffset: Int = 5
}
let id: UUID = UUID()
var name: String
var unitsBox: Int
var interval: Interval
var unitsDose: Int
var unitsConsumed: Int = 0
var nextDose: Int?
var creation: Int = Int(Date().timeIntervalSince1970)
init(name: String, unitsBox: Int, interval: Interval, unitsDose: Int) {
self.name = name
self.unitsBox = unitsBox
self.interval = interval
self.unitsDose = unitsDose
}
func getState(timeManager: TimeManagerProtocol = TimeManager()) -> PrescriptionState {
guard let nextDose = self.nextDose else {
return unitsConsumed >= unitsBox ? .finished : .notStarted
}
if unitsConsumed >= unitsBox {
return .finished
} else {
if timeManager.timeIntervalSince1970() > nextDose {
return .ongoingEllapsed
} else {
return timeManager.timeIntervalSince1970() > nextDose - Prescription.Constants.ongoingReadyOffset ? . ongoingReady: .ongoing
}
}
}
func takeDose(timeManager: TimeManagerProtocol = TimeManager()) {
let state = getState()
if (state == .notStarted ||
state == .ongoingReady ||
state == .ongoingEllapsed) {
self.unitsConsumed += self.unitsDose
guard unitsConsumed < unitsBox else {
nextDose = nil
return
}
self.nextDose = timeManager.timeIntervalSince1970() + self.interval.secs
}
}
func isFirst() -> Bool {
return unitsConsumed == 0
}
func isLast() -> Bool {
return unitsConsumed + unitsDose >= unitsBox
}
func getRemaining(timeManager: TimeManagerProtocol = TimeManager()) -> Int? {
guard let nextDose = self.nextDose else { return nil }
return Int(timeManager.timeIntervalSince1970()) - nextDose
}
func getRemainingMins(timeManager: TimeManagerProtocol = TimeManager()) -> Int? {
guard let remainigSecs = getRemaining(timeManager: timeManager) else { return nil }
return Int(floor(Double(remainigSecs / 60)))
}
func getRemainingHours(timeManager: TimeManagerProtocol = TimeManager()) -> Int? {
guard let remainigMins = getRemainingMins(timeManager: timeManager) else { return nil }
return Int(floor(Double(remainigMins / 60)))
}
func getRemainingDays(timeManager: TimeManagerProtocol = TimeManager()) -> Int? {
guard let remainigHours = getRemainingHours(timeManager: timeManager) else { return nil }
return Int(floor(Double(remainigHours / 24)))
}
}
extension Prescription: Equatable {
static func == (lhs: Prescription, rhs: Prescription) -> Bool {
return lhs.name == rhs.name &&
lhs.unitsBox == rhs.unitsBox &&
lhs.interval == rhs.interval &&
lhs.unitsDose == rhs.unitsDose
}
}
| 30.724771 | 140 | 0.623171 |
e53a8bab54e425d01289209d7d3d34757dc9b814 | 1,250 | //
// LCNibBridgeDemoUITests.swift
// LCNibBridgeDemoUITests
//
// Created by 刘通超 on 16/5/27.
// Copyright © 2016年 刘通超. All rights reserved.
//
import XCTest
class LCNibBridgeDemoUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| 33.783784 | 182 | 0.6656 |
e88fff19258132f68764b9ced0a5c50d920f8f13 | 10,284 | //
// Entwine
// https://github.com/tcldr/Entwine
//
// Copyright © 2019 Tristan Celder. All rights reserved.
//
// 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 XCTest
import OpenCombine
@testable import Entwine
@testable import EntwineTest
final class ShareReplayTests: XCTestCase {
// MARK: - Properties
private var scheduler: TestScheduler!
// MARK: - Per test set-up and tear-down
override func setUp() {
scheduler = TestScheduler(initialClock: 0)
}
// MARK: - Tests
func testPassesThroughValueWithBufferOfZero() {
let subject = PassthroughSubject<Int, Never>()
let results1 = scheduler.createTestableSubscriber(Int.self, Never.self)
let results2 = scheduler.createTestableSubscriber(Int.self, Never.self)
let sut = subject.share(replay: 0)
scheduler.schedule(after: 100) { sut.subscribe(results1) }
scheduler.schedule(after: 200) { subject.send(0) }
scheduler.schedule(after: 300) { sut.subscribe(results2) }
scheduler.schedule(after: 400) { subject.send(1) }
scheduler.resume()
let expected1: TestSequence<Int, Never> = [
(100, .subscription),
(200, .input(0)),
(400, .input(1)),
]
XCTAssertEqual(expected1, results1.recordedOutput)
let expected2: TestSequence<Int, Never> = [
(300, .subscription),
(400, .input(1)),
]
XCTAssertEqual(expected2, results2.recordedOutput)
}
func testPassesThroughValueWithBufferOfOne() {
let subject = PassthroughSubject<Int, Never>()
let results1 = scheduler.createTestableSubscriber(Int.self, Never.self)
let results2 = scheduler.createTestableSubscriber(Int.self, Never.self)
let sut = subject.share(replay: 1)
scheduler.schedule(after: 100) { sut.subscribe(results1) }
scheduler.schedule(after: 200) { subject.send(0) }
scheduler.schedule(after: 300) { sut.subscribe(results2) }
scheduler.schedule(after: 400) { subject.send(1) }
scheduler.resume()
let expected1: TestSequence<Int, Never> = [
(100, .subscription),
(200, .input(0)),
(400, .input(1)),
]
XCTAssertEqual(expected1, results1.recordedOutput)
let expected2: TestSequence<Int, Never> = [
(300, .subscription),
(300, .input(0)),
(400, .input(1)),
]
XCTAssertEqual(expected2, results2.recordedOutput)
}
func testPassesThroughLatestValueWithBufferOfOne() {
let subject = PassthroughSubject<Int, Never>()
let results1 = scheduler.createTestableSubscriber(Int.self, Never.self)
let results2 = scheduler.createTestableSubscriber(Int.self, Never.self)
let sut = subject.share(replay: 1)
scheduler.schedule(after: 100) { sut.subscribe(results1) }
scheduler.schedule(after: 200) { subject.send(0) }
scheduler.schedule(after: 250) { subject.send(1) }
scheduler.schedule(after: 300) { sut.subscribe(results2) }
scheduler.schedule(after: 400) { subject.send(2) }
scheduler.resume()
let expected1: TestSequence<Int, Never> = [
(100, .subscription),
(200, .input(0)),
(250, .input(1)),
(400, .input(2)),
]
XCTAssertEqual(expected1, results1.recordedOutput)
let expected2: TestSequence<Int, Never> = [
(300, .subscription),
(300, .input(1)),
(400, .input(2)),
]
XCTAssertEqual(expected2, results2.recordedOutput)
}
func testPassesThroughCompletionIssuedPreSubscribe() {
let subject = PassthroughSubject<Int, Never>()
let results1 = scheduler.createTestableSubscriber(Int.self, Never.self)
let sut = subject.share(replay: 0)
scheduler.schedule(after: 100) { subject.send(completion: .finished) }
scheduler.schedule(after: 200) { sut.subscribe(results1) }
scheduler.resume()
let expected: TestSequence<Int, Never> = [
(200, .subscription),
(200, .completion(.finished)),
]
XCTAssertEqual(expected, results1.recordedOutput)
}
func testPassesThroughCompletionIssuedPostSubscribe() {
let subject = PassthroughSubject<Int, Never>()
let results1 = scheduler.createTestableSubscriber(Int.self, Never.self)
let sut = subject.share(replay: 0)
scheduler.schedule(after: 200) { sut.subscribe(results1) }
scheduler.schedule(after: 300) { subject.send(completion: .finished) }
scheduler.resume()
let expected: TestSequence<Int, Never> = [
(200, .subscription),
(300, .completion(.finished)),
]
XCTAssertEqual(expected, results1.recordedOutput)
}
func testStopsForwardingToSubscribersPostCompletion() {
let subject = PassthroughSubject<Int, Never>()
let results1 = scheduler.createTestableSubscriber(Int.self, Never.self)
let sut = subject.share(replay: 0)
scheduler.schedule(after: 200) { sut.subscribe(results1) }
scheduler.schedule(after: 300) { subject.send(completion: .finished) }
scheduler.schedule(after: 400) { subject.send(0) }
scheduler.resume()
let expected1: TestSequence<Int, Never> = [
(200, .subscription),
(300, .completion(.finished)),
]
XCTAssertEqual(expected1, results1.recordedOutput)
}
func testImmediatelyCompletesForNewSubscribersPostPreviousCompletion() {
let subject = PassthroughSubject<Int, Never>()
let results1 = scheduler.createTestableSubscriber(Int.self, Never.self)
let results2 = scheduler.createTestableSubscriber(Int.self, Never.self)
let sut = subject.share(replay: 0)
scheduler.schedule(after: 200) { sut.subscribe(results1) }
scheduler.schedule(after: 300) { subject.send(0) }
scheduler.schedule(after: 400) { subject.send(completion: .finished) }
scheduler.schedule(after: 500) { sut.subscribe(results2) }
scheduler.schedule(after: 600) { subject.send(0) }
scheduler.schedule(after: 700) { subject.send(completion: .finished) }
scheduler.resume()
let expected1: TestSequence<Int, Never> = [
(200, .subscription),
(300, .input(0)),
(400, .completion(.finished)),
]
XCTAssertEqual(expected1, results1.recordedOutput)
let expected2: TestSequence<Int, Never> = [
(500, .subscription),
(500, .completion(.finished)),
]
XCTAssertEqual(expected2, results2.recordedOutput)
}
func testPassesThroughInitialValueToFirstSubscriberOnly() {
let passthrough = PassthroughSubject<Int, Never>()
let subject = passthrough.prepend(-1).share()
let results1 = scheduler.createTestableSubscriber(Int.self, Never.self)
let results2 = scheduler.createTestableSubscriber(Int.self, Never.self)
scheduler.schedule(after: 100) { subject.subscribe(results1) }
scheduler.schedule(after: 110) { subject.subscribe(results2) }
scheduler.schedule(after: 200) { passthrough.send(0) }
scheduler.schedule(after: 210) { passthrough.send(1) }
scheduler.resume()
let expected2: TestSequence<Int, Never> = [
(110, .subscription),
(200, .input( 0)),
(210, .input( 1)),
]
XCTAssertEqual(expected2, results2.recordedOutput)
}
func testResetsWhenReferenceCountReachesZero() {
let passthrough = PassthroughSubject<Int, Never>()
let subject = passthrough.prepend(-1).share(replay: 2)
let results1 = scheduler.createTestableSubscriber(Int.self, Never.self)
let results2 = scheduler.createTestableSubscriber(Int.self, Never.self)
scheduler.schedule(after: 100) { subject.subscribe(results1) }
scheduler.schedule(after: 110) { passthrough.send(0) }
scheduler.schedule(after: 200) { results1.cancel() }
scheduler.schedule(after: 200) { subject.subscribe(results2) }
scheduler.schedule(after: 300) { passthrough.send(5) }
scheduler.schedule(after: 310) { passthrough.send(6) }
scheduler.resume()
let expected1: TestSequence<Int, Never> = [
(100, .subscription),
(100, .input(-1)),
(110, .input( 0)),
]
let expected2: TestSequence<Int, Never> = [
(200, .subscription),
(200, .input(-1)),
(300, .input( 5)),
(310, .input( 6)),
]
XCTAssertEqual(expected1, results1.recordedOutput)
XCTAssertEqual(expected2, results2.recordedOutput)
}
}
| 35.340206 | 81 | 0.617561 |
5bc8a20e6bb8a8910e7b98007720284e54a7d66c | 197 | //
// Enviroment.swift
// MVVM_FIPE
//
// Created by Daniel Nascimento on 07/12/20.
//
import Foundation
enum Enviroment {
static let apiBaseUrl = "https://parallelum.com.br/fipe/api/v1"
}
| 16.416667 | 67 | 0.685279 |
7516e0ebe6112f04240f969cc097344f83ece30c | 1,582 | //
// LibraryEntryStartedAtHandler.swift
// Ookami
//
// Created by Maka on 26/6/17.
// Copyright © 2017 Mikunj Varsani. All rights reserved.
//
import UIKit
import OokamiKit
import ActionSheetPicker_3_0
class LibraryEntryStartedAtHandler: LibraryEntryDataHandler {
var heading: LibraryEntryViewData.Heading {
return .startedAt
}
//The table data
func tableData(for entry: LibraryEntry) -> LibraryEntryViewData.TableData {
//Format the date to dd/MM/YYYY
let formatter = DateFormatter()
formatter.dateFormat = "dd/MM/YYYY"
formatter.timeZone = TimeZone(abbreviation: "UTC")
var date = "-"
if let start = entry.startedAt {
date = formatter.string(from: start)
}
return LibraryEntryViewData.TableData(type: .string, value: date, heading: heading)
}
//The handling of tap
func didSelect(updater: LibraryEntryUpdater, cell: UITableViewCell, controller: LibraryEntryViewController) {
let selected = updater.entry.startedAt ?? Date()
let picker = ActionSheetDatePicker(title: "Started At:", datePickerMode: .date, selectedDate: selected, doneBlock: { _, value, _ in
updater.update(startedAt: value as? Date)
controller.reloadData()
}, cancel: { _ in }, origin: cell)
picker?.minimumDate = Date(timeIntervalSince1970: 0)
picker?.maximumDate = Date()
picker?.timeZone = TimeZone(abbreviation: "UTC")
picker?.show()
}
}
| 31.019608 | 139 | 0.637168 |
4697859c41c5afaac5ab4d77ec602d3662b316c4 | 1,629 | //
// PhysicsComponent.swift
// ZeroG BattleRoom
//
// Created by Rudy Gomez on 4/4/20.
// Copyright © 2020 JRudy Gaming. All rights reserved.
//
import Foundation
import SpriteKit
import GameplayKit
struct PhysicsCategoryMask {
static var ghost : UInt32 = 0x1 << 0
static var hero : UInt32 = 0x1 << 1
static var base : UInt32 = 0x1 << 2
static var wall : UInt32 = 0x1 << 3
static var tractor : UInt32 = 0x1 << 4
static var field : UInt32 = 0x1 << 5
static var payload : UInt32 = 0x1 << 6
static var package : UInt32 = 0x1 << 7
static var deposit : UInt32 = 0x1 << 8
static var pod : UInt32 = 0x1 << 9
}
class PhysicsComponent: GKComponent {
var physicsBody: SKPhysicsBody
var isEffectedByPhysics = true {
didSet {
if self.isEffectedByPhysics {
physicsBody.isDynamic = true
physicsBody.allowsRotation = true
} else {
physicsBody.isDynamic = false
physicsBody.velocity = CGVector.zero
physicsBody.angularVelocity = 0.0
physicsBody.allowsRotation = false
}
}
}
init(physicsBody: SKPhysicsBody) {
self.physicsBody = physicsBody
super.init()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension PhysicsComponent {
func randomImpulse(x: Double? = nil, y: Double? = nil) {
let randomX = (Bool.random() ? -1 : 1) * (Double.random(in: 1...2))
let randomY = (Bool.random() ? -1 : 1) * (Double.random(in: 1...2))
self.physicsBody.applyImpulse(CGVector(dx: x ?? randomX, dy: y ?? randomY))
}
}
| 24.313433 | 80 | 0.628607 |
abbc9727db68dc1f4ee6647bc5aafce709a5acc8 | 121 | import Foundation
@testable import Alicerce
struct MockReusableViewModelView: Equatable {
let testProperty = "😎"
}
| 15.125 | 45 | 0.768595 |
4a2750b3cb5b43c29d7d98086c575a7d35f88449 | 14,438 | //
// AddEditDocumentViewController.swift
// TeamHome
//
// Created by Andrew Dhan on 2/14/19.
// Copyright © 2019 Lambda School under the MIT license. All rights reserved.
//
import UIKit
import Apollo
import Cloudinary
import Photos
import Material
import Motion
import GrowingTextView
typealias Document = FindDocumentInputQuery.Data.FindDocument // FindDocumentsByTeamQuery.Data.FindDocumentsByTeam
class AddEditDocumentViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UITextFieldDelegate {
override func viewDidLoad() {
super.viewDidLoad()
collectionView.dataSource = self
collectionView.delegate = self
documentTitleTextField.delegate = self
documentLinkTextField.delegate = self
tagsTextField.delegate = self
documentNotesTextView.keyboardAppearance = .dark
documentNotesTextView.addDoneButtonOnKeyboard()
// documentNotesTextView
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification , object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification , object: nil)
setupViews()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if let document = document {
updateViewsForEdit(document: document)
} else {
updateViewsForAdd()
}
guard let apollo = apollo,
let team = team,
let teamId = team.id else { return }
fetchAllTags(with: apollo, for: teamId)
}
//MARK: - IBActions
@IBAction func submitDocument(_ sender: Any) {
guard let title = documentTitleTextField.text,
let link = documentLinkTextField.text
// ,
// let tagID = findSelectedTag()
else { return}
let note = documentNotesTextView.text ?? ""
if let document = document {
performEditMutation(document: document, title: title, doc_url: link, textContent: note, tagID: findSelectedTag())
} else {
performAddMutation(title: title, doc_url: link, team: team.id!, textContent: note, tagID: findSelectedTag())
}
watcher?.refetch()
navigationController?.popToRootViewController(animated: true)
// navigationController?.popViewController(animated: true)
}
@IBAction func cancelNewMessage(_ sender: Any) {
navigationController?.popViewController(animated: true)
}
@IBAction func createTag(_ sender: Any) {
guard let apollo = apollo,
let team = team,
let teamId = team.id,
let tag = processTagText(tag: tagsTextField.text) else { return }
apollo.perform(mutation: CreateNewTagMutation(name: tag, teamId: teamId), queue: DispatchQueue.global()) { (result, error) in
if let error = error {
print("\(error)")
return
}
guard let result = result,
let data = result.data,
let tag = data.addTag else { return }
print(tag)
self.tagsWatcher?.refetch()
self.tagButtonWasClicked = true
DispatchQueue.main.async {
self.tagsTextField.text = ""
self.tagsTextField.resignFirstResponder()
}
}
}
@IBAction func addToFolder(_ sender: Any) {
}
// MARK: - UITextFieldDelegate
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
switch textField {
case documentTitleTextField:
_ = documentLinkTextField.becomeFirstResponder()
case documentLinkTextField:
_ = documentNotesTextView.becomeFirstResponder()
default:
textField.resignFirstResponder()
}
return true
}
// MARK: - UICollectionViewDataSource for tags
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return tags?.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "TagCell", for: indexPath) as! TagCollectionViewCell
guard let tag = tags?[indexPath.row] else { return UICollectionViewCell() }
cell.tagLabel.text = DocumentHelper.displayTagText(tag: tag.name)
cell.backgroundColor = Appearance.darkMauveColor
cell.layer.cornerRadius = cell.frame.height / 2
if let document = self.document {
if let documentTag = document.tag {
let this = documentTag.name
if tag.name == this {
self.tagSelected = documentTag.name
cell.backgroundColor = Appearance.mauveColor
self.tagCellSelected = cell
}
}
}
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath:
IndexPath) {
guard let tag = tags?[indexPath.row] else { return }
self.tagSelected = tag.name
let cell = collectionView.cellForItem(at: indexPath) as! TagCollectionViewCell
if cell == tagCellSelected {
//user is unselecting a tag so remove selection
cell.backgroundColor = Appearance.darkMauveColor
tagCellSelected = nil
tagSelected = nil
} else {
// user is selecting a new tag
if tagCellSelected != nil {
tagCellSelected?.backgroundColor = Appearance.darkMauveColor
}
cell.backgroundColor = Appearance.mauveColor
tagCellSelected = cell
}
//
// cell?.backgroundColor = Appearance.mauveColor
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "ChooseFolder" {
let destVC = segue.destination as! FolderManagementViewController
destVC.apollo = apollo
destVC.team = team
destVC.document = document
}
}
//MARK: - Private Properties
@objc private func keyboardWillShow(notification:NSNotification){
guard let userInfo = notification.userInfo,
let keyboardFrame = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect else {return}
let contentInset = UIEdgeInsets(top: 0.0, left: 0.0, bottom: keyboardFrame.height, right: 0.0)
scrollView.contentInset = contentInset
scrollView.scrollIndicatorInsets = contentInset
}
@objc private func keyboardWillHide(notification:NSNotification){
let contentInset = UIEdgeInsets(top: 0.0, left: 0.0, bottom: 0.0, right: 0.0)
scrollView.contentInset = contentInset
scrollView.scrollIndicatorInsets = contentInset
}
private func processTagText(tag: String?) -> String? {
guard let tag = tag,
let first = tag.first else {return nil}
if first == "#"{
return tag
} else {
return "#\(tag)"
}
}
private func setupViews(){
setUpViewAppearance()
// hideKeyboardWhenTappedAround()
newDocumentView.backgroundColor = Appearance.plumColor
cancelButton.tintColor = Appearance.yellowColor
submitButton.backgroundColor = Appearance.darkMauveColor
documentLinkTextField.placeholderNormalColor = .white
documentLinkTextField.textColor = .white
documentLinkTextField.placeholder = "Add a link"
documentLinkTextField.placeholderActiveColor = Appearance.yellowColor
documentLinkTextField.dividerActiveColor = Appearance.yellowColor
documentNotesTextView.textColor = .white
documentNotesTextView.placeholder = "Add a note"
documentTitleTextField.textColor = .white
documentTitleTextField.placeholderNormalColor = .white
documentTitleTextField.placeholderActiveColor = Appearance.yellowColor
documentTitleTextField.dividerActiveColor = Appearance.yellowColor
tagsTextField.textColor = .white
documentTitleTextField.placeholderAnimation = .hidden
documentLinkTextField.placeholderAnimation = .hidden
tagsTextField.placeholderAnimation = .hidden
titleLabel.font = Appearance.setTitleFont(with: .title2, pointSize: 20)
collectionView.backgroundColor = .clear
}
private func updateViewsForEdit(document: Document){
titleLabel.text = "Edit Document"
documentTitleTextField.text = document.title
documentLinkTextField.text = document.docUrl
documentNotesTextView.text = document.textContent
}
private func updateViewsForAdd(){
titleLabel.text = "Add Document"
documentTitleTextField.text = ""
documentLinkTextField.text = ""
documentNotesTextView.text = ""
}
private func performEditMutation(document: Document, title: String, doc_url: String, textContent: String, tagID: String?){
if let tagID = tagID {
apollo.perform(mutation: UpdateDocumentMutation(id: document.id!, title: title, doc_url: doc_url, textContent: textContent, tag: tagID))
} else {
apollo.perform(mutation: UpdateDocumentMutation(id: document.id!, title: title, doc_url: doc_url, textContent: textContent))
}
}
private func performAddMutation(title: String, doc_url: String, team: String, textContent: String, tagID: String?){
if let tagID = tagID {
apollo.perform(mutation: AddNewDocumentMutation(title: title, doc_url: doc_url, team: team, textContent: textContent, tag: tagID))
} else {
apollo.perform(mutation: AddNewDocumentMutation(title: title, doc_url: doc_url, team: team, textContent: textContent))
}
}
private func fetchAllTags(with apollo: ApolloClient, for teamId: GraphQLID) {
// Find all tags by current team
tagsWatcher = apollo.watch(query: FindTagsByTeamQuery(teamId: teamId)) { (result, error) in
if let error = error {
NSLog("\(error)")
return
}
guard let result = result,
let data = result.data,
let tags = data.findTagsByTeam else { return }
// Save tags and populate collection view
print(tags)
self.tags = tags
self.collectionView.reloadData()
if self.tagButtonWasClicked{
self.collectionView.scrollToBottom(animated: true)
self.tagButtonWasClicked = false
}
}
}
private func findSelectedTag() -> GraphQLID? {
// Unwrap tag selection or recently created tag.
guard let selectedTag = self.tagSelected,
let tags = tags else {
if let tagId = tagSelectedId {
return tagId
}
return nil
}
for tag in tags {
if let tag = tag {
if tag.name == selectedTag {
return tag.id
}
}
}
return nil
}
@objc func hideKeyboard() {
view.endEditing(true)
}
func hideKeyboardWhenTappedAround() {
let tapGesture = UITapGestureRecognizer(target: self,
action: #selector(hideKeyboard))
view.addGestureRecognizer(tapGesture)
}
//MARK: - Properties
var apollo: ApolloClient!
var team: FindTeamsByUserQuery.Data.FindTeamsByUser!
var document: Document?
private var tagButtonWasClicked = false
private var tagSelected: String?
private var tagSelectedId: GraphQLID?
private var tagCellSelected: TagCollectionViewCell?
private var tags: [FindTagsByTeamQuery.Data.FindTagsByTeam?]?
private var tagsWatcher: GraphQLQueryWatcher<FindTagsByTeamQuery>?
private var firstResponder: UIView?
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var folderButton: UIBarButtonItem!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var cancelButton: FlatButton!
@IBOutlet weak var submitButton: RaisedButton!
@IBOutlet weak var newDocumentView: UIView!
@IBOutlet weak var documentTitleTextField: TextField!
@IBOutlet weak var documentLinkTextField: TextField!
@IBOutlet weak var documentNotesTextView: GrowingTextView!
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var tagsTextField: TextField!
}
extension UITextView{
@IBInspectable var doneAccessory: Bool{
get{
return self.doneAccessory
}
set (hasDone) {
if hasDone{
addDoneButtonOnKeyboard()
}
}
}
func addDoneButtonOnKeyboard()
{
let doneToolbar: UIToolbar = UIToolbar(frame: CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 50))
doneToolbar.barStyle = .black
// doneToolbar.barTintColor = UIColor.darkGray
let flexSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let done: UIBarButtonItem = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(self.doneButtonAction))
let items = [flexSpace, done]
doneToolbar.items = items
doneToolbar.sizeToFit()
self.inputAccessoryView = doneToolbar
}
@objc func doneButtonAction()
{
self.resignFirstResponder()
}
}
| 36.551899 | 168 | 0.621693 |
3874b3e3847148073d570dadb8f5ea0371c1ea63 | 10,039 | //
// Generated by SwagGen
// https://github.com/yonaskolb/SwagGen
//
import Foundation
extension Rocket.Account {
/**
Get the video files associated with an item given maximum resolution, device type
and one or more delivery types.
This endpoint is identical to the `/account/items/{id}/videos` however it expects
an Account Playback token. This token, and in association this endpoint, is specifically
for use when playback files are classification restricted and require an account
level pin to access them.
Returns an array of video file objects which each include a url to a video.
The first entry in the array contains what is predicted to be the best match.
The remainder of the entries, if any, may contain resolutions below what was
requests. For example if you request HD-720 the response may also contain
SD entries.
If you specify multiple delivery types, then the response array will insert
types in the order you specify them in the query. For example `stream,progressive`
would return an array with 0 or more stream files followed by 0 or more progressive files.
If no files are found a 404 is returned.
*/
public enum GetItemMediaFilesGuarded {
public static let service = APIService<Response>(id: "getItemMediaFilesGuarded", tag: "account", method: "GET", path: "/account/items/{id}/videos-guarded", hasBody: false, securityRequirement: SecurityRequirement(type: "accountAuth", scope: "Playback"))
public final class Request: APIRequest<Response> {
public struct Options {
/** The identifier of the item whose video files to load. */
public var id: String
/** The video delivery type you require. */
public var delivery: [MediaFileDelivery]
/** The maximum resolution the device to playback the media can present. */
public var resolution: MediaFileResolution
/** The type of device the content is targeting. */
public var device: String?
/** The active subscription code. */
public var sub: String?
/** The list of segments to filter the response by. */
public var segments: [String]?
/** The set of opt in feature flags which cause breaking changes to responses.
While Rocket APIs look to avoid breaking changes under the active major version, the formats of responses
may need to evolve over this time.
These feature flags allow clients to select which response formats they expect and avoid breaking
clients as these formats evolve under the current major version.
### Flags
- `all` - Enable all flags. Useful for testing. _Don't use in production_.
- `idp` - Dynamic item detail pages with schedulable rows.
- `ldp` - Dynamic list detail pages with schedulable rows.
See the `feature-flags.md` for available flag details.
*/
public var ff: [FeatureFlags]?
public init(id: String, delivery: [MediaFileDelivery], resolution: MediaFileResolution, device: String? = nil, sub: String? = nil, segments: [String]? = nil, ff: [FeatureFlags]? = nil) {
self.id = id
self.delivery = delivery
self.resolution = resolution
self.device = device
self.sub = sub
self.segments = segments
self.ff = ff
}
}
public var options: Options
public init(options: Options) {
self.options = options
super.init(service: GetItemMediaFilesGuarded.service)
}
/// convenience initialiser so an Option doesn't have to be created
public convenience init(id: String, delivery: [MediaFileDelivery], resolution: MediaFileResolution, device: String? = nil, sub: String? = nil, segments: [String]? = nil, ff: [FeatureFlags]? = nil) {
let options = Options(id: id, delivery: delivery, resolution: resolution, device: device, sub: sub, segments: segments, ff: ff)
self.init(options: options)
}
public override var path: String {
return super.path.replacingOccurrences(of: "{" + "id" + "}", with: "\(self.options.id)")
}
public override var parameters: [String: Any] {
var params: [String: Any] = [:]
params["delivery"] = options.delivery.encode().map({ String(describing: $0) }).joined(separator: ",")
params["resolution"] = options.resolution.encode()
if let device = options.device {
params["device"] = device
}
if let sub = options.sub {
params["sub"] = sub
}
if let segments = options.segments?.joined(separator: ",") {
params["segments"] = segments
}
if let ff = options.ff?.encode().map({ String(describing: $0) }).joined(separator: ",") {
params["ff"] = ff
}
return params
}
}
public enum Response: APIResponseValue, CustomStringConvertible, CustomDebugStringConvertible {
public typealias SuccessType = [MediaFile]
/** The list of video files available.
The first entry containing what is predicted to be the best match.
*/
case status200([MediaFile])
/** Bad request. */
case status400(ServiceError)
/** Invalid access token. */
case status401(ServiceError)
/** Forbidden. */
case status403(ServiceError)
/** Not found. */
case status404(ServiceError)
/** Internal server error. */
case status500(ServiceError)
/** Service error. */
case defaultResponse(statusCode: Int, ServiceError)
public var success: [MediaFile]? {
switch self {
case .status200(let response): return response
default: return nil
}
}
public var failure: ServiceError? {
switch self {
case .status400(let response): return response
case .status401(let response): return response
case .status403(let response): return response
case .status404(let response): return response
case .status500(let response): return response
case .defaultResponse(_, let response): return response
default: return nil
}
}
/// either success or failure value. Success is anything in the 200..<300 status code range
public var responseResult: APIResponseResult<[MediaFile], ServiceError> {
if let successValue = success {
return .success(successValue)
} else if let failureValue = failure {
return .failure(failureValue)
} else {
fatalError("Response does not have success or failure response")
}
}
public var response: Any {
switch self {
case .status200(let response): return response
case .status400(let response): return response
case .status401(let response): return response
case .status403(let response): return response
case .status404(let response): return response
case .status500(let response): return response
case .defaultResponse(_, let response): return response
}
}
public var statusCode: Int {
switch self {
case .status200: return 200
case .status400: return 400
case .status401: return 401
case .status403: return 403
case .status404: return 404
case .status500: return 500
case .defaultResponse(let statusCode, _): return statusCode
}
}
public var successful: Bool {
switch self {
case .status200: return true
case .status400: return false
case .status401: return false
case .status403: return false
case .status404: return false
case .status500: return false
case .defaultResponse: return false
}
}
public init(statusCode: Int, data: Data, decoder: ResponseDecoder) throws {
switch statusCode {
case 200: self = try .status200(decoder.decode([MediaFile].self, from: data))
case 400: self = try .status400(decoder.decode(ServiceError.self, from: data))
case 401: self = try .status401(decoder.decode(ServiceError.self, from: data))
case 403: self = try .status403(decoder.decode(ServiceError.self, from: data))
case 404: self = try .status404(decoder.decode(ServiceError.self, from: data))
case 500: self = try .status500(decoder.decode(ServiceError.self, from: data))
default: self = try .defaultResponse(statusCode: statusCode, decoder.decode(ServiceError.self, from: data))
}
}
public var description: String {
return "\(statusCode) \(successful ? "success" : "failure")"
}
public var debugDescription: String {
var string = description
let responseString = "\(response)"
if responseString != "()" {
string += "\n\(responseString)"
}
return string
}
}
}
}
| 41.143443 | 261 | 0.575755 |
ac78c8102214fd87b58c741280efa170c1472bc5 | 758 | import App
import Vapor
import PostgreSQLProvider
/// We have isolated all of our App's logic into
/// the App module because it makes our app
/// more testable.
///
/// In general, the executable portion of our App
/// shouldn't include much more code than is presented
/// here.
///
/// We simply initialize our Droplet, optionally
/// passing in values if necessary
/// Then, we pass it to our App's setup function
/// this should setup all the routes and special
/// features of our app
///
/// .run() runs the Droplet's commands,
/// if no command is given, it will default to "serve"
let config = try Config()
try config.addProvider(PostgreSQLProvider.Provider.self)
try config.setup()
let drop = try Droplet(config)
try drop.setup()
try drop.run()
| 27.071429 | 56 | 0.722955 |
dec680bc9a0dff22d6264aa28aca9de9332b1d23 | 13,446 | //
// DetailsViewController.swift
// App
//
// Created by Joao Flores on 21/05/20.
// Copyright © 2020 Joao Flores. All rights reserved.
//
import UIKit
import os.log
class DetaisHabitsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate {
// MARK: - Constants
let constraintViewInsertIdentifier = "Height"
let viewInsertWeightHeight: CGFloat = 53
let timeAnimation = 0.5
let cornerRadiusViews: CGFloat = 10
let tagLabelValueWater = 1000
let tagLabelValueFruits = 2000
let tagLabelValueExercise = 3000
let tagLabelDateWeigh = 1001
let tagViewInsertWeigh = 100
// MARK: - Variables
let pickerData = ["✗", "✓"]
var habitsDates = [String]()
var weightValues = [Int]()
var dataCells = [DataCell]()
struct DataCell {
var water: Int
var fruits: Int
var exercise: Int
var date: String
}
// MARK: - IBOutlet
@IBOutlet weak var detailsTableview: UITableView!
@IBOutlet weak var detaisNavigation: UINavigationItem!
@IBOutlet weak var exerciseTextField: UITextField!
@IBOutlet weak var waterLabel: UILabel!
@IBOutlet weak var fruitsLabel: UILabel!
@IBOutlet weak var weightDateLabel: UILabel!
@IBOutlet weak var viewInsertHabits: UIView!
@IBOutlet weak var cellViewInsertHabits: UIView!
// MARK: - IBOutlet
@IBAction func closeView(_ sender: Any) {
self.dismiss(animated: true, completion: nil)
}
@IBAction func showInsertWeightView(_ sender: Any) {
showCellInsert()
}
// MARK: - Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
loadData()
setupTableView()
setupPickerView()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if let presenter = self.presentingViewController?.children[0] as? ProfileViewController {
presenter.setupGraphic()
presenter.setupDataProfile()
presenter.updateHeaderInformations()
}
}
// MARK: - TableView
func setupTableView() {
detailsTableview.delegate = self
detailsTableview.dataSource = self
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataCells.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return cellCreator(indexPath: indexPath)
}
func cellCreator(indexPath: IndexPath) -> UITableViewCell {
let cell = detailsTableview.dequeueReusableCell(withIdentifier: "cellId", for: indexPath)
let valueWaterLabel = cell.viewWithTag(tagLabelValueWater) as! UILabel
valueWaterLabel.text = pickerData[dataCells[dataCells.count - 1 - indexPath[1]].water]
let valueFruitsLabel = cell.viewWithTag(tagLabelValueFruits) as! UILabel
valueFruitsLabel.text = pickerData[dataCells[dataCells.count - 1 - indexPath[1]].fruits]
let valueExerciseLabel = cell.viewWithTag(tagLabelValueExercise) as! UILabel
valueExerciseLabel.text = pickerData[dataCells[dataCells.count - 1 - indexPath[1]].exercise]
let dateLabel = cell.viewWithTag(tagLabelDateWeigh) as! UILabel
dateLabel.text = dataCells[dataCells.count - 1 - indexPath[1]].date
let cellViewWithe = cell.viewWithTag(tagViewInsertWeigh)!
cellViewWithe.layer.cornerRadius = cornerRadiusViews
return cell
}
// Delete Item
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
deleteValue(indexPath)
}
}
// MARK: - Data Management
func loadData() {
do {
let plotter = try PlotGraphicClass()
let months = plotter.getMonths()
// Getting the current days last two months
let dates: NSMutableArray = plotter.getFullDates(months)
// Starting to populate and draw the charts...
let numbersArray: [[Int]] = plotter.getHabitsValuesDetails(months)
var datesArray = [String]()
for x in 0...(dates.count - 1) {
let aString = dates[x]
datesArray.append(aString as! String)
}
habitsDates = datesArray
weightValues = numbersArray[0]
dataCells.removeAll()
for i in 0...weightValues.count - 1 {
let dataCell = DataCell(water: numbersArray[0][i], fruits: numbersArray[1][i], exercise: numbersArray[2][i], date: habitsDates[i])
dataCells.append(dataCell)
}
}
catch {
os_log("[ERROR] Couldn't communicate with the operating system's internal calendar/time system or memory is too low!")
}
}
func convertStringToDate(dateString: String) -> Date? {
let fullDateArray = dateString.components(separatedBy: "/")
let formatter = DateFormatter()
formatter.dateFormat = "yyyy/MM/dd"
let someDateTime = formatter.date(from: fullDateArray[2]+"/"+fullDateArray[1]+"/"+fullDateArray[0])
return someDateTime
}
func insertNewWeight(waterValue: Bool, fruitsValue: Bool, exerciseValue: Bool, date: Date?) {
do {
let dataHandler = try DataHandler.getShared()
try dataHandler.createDailyDiaryInDate(quality: 1, didDrinkWater: waterValue, didPracticeExercise: exerciseValue, didEatFruit: fruitsValue, date: date!)
alertInsert(titleAlert: "Concluido", messageAlert: "Seus dados foram atualizados")
}
catch DateError.calendarNotFound {
os_log("[ERROR] Couldn't get the iOS calendar system!")
alertInsert(titleAlert: "Erro", messageAlert: "Couldn't get the iOS calendar system!")
}
catch PersistenceError.cantSave {
os_log("[ERROR] Couldn't save into local storage due to low memory!")
alertInsert(titleAlert: "Erro", messageAlert: "Couldn't save into local storage due to low memory!")
}
catch {
os_log("[ERROR] Unknown error occurred while registering the weight inside local storage!")
alertInsert(titleAlert: "Erro", messageAlert: "Unknown error occurred while registering the weight inside local storage!")
}
}
func deleteValue(_ indexPath: IndexPath) {
insertNewWeight(waterValue: false, fruitsValue: false, exerciseValue: false, date: convertStringToDate(dateString: dataCells[dataCells.count - 1 - indexPath.row].date))
loadData()
detailsTableview.reloadData()
}
// MARK: - UI Insert Weight
func showCellInsert() {
let filteredConstraints = viewInsertHabits.constraints.filter { $0.identifier == constraintViewInsertIdentifier }
if let yourConstraint = filteredConstraints.first {
UIView.animate(withDuration: timeAnimation) {
yourConstraint.constant = self.viewInsertWeightHeight
self.view.layoutIfNeeded()
}
}
exerciseTextField.becomeFirstResponder()
}
func hideCellInsertWeight() {
let filteredConstraints = viewInsertHabits.constraints.filter { $0.identifier == constraintViewInsertIdentifier }
if let yourConstraint = filteredConstraints.first {
UIView.animate(withDuration: 0.5) {
yourConstraint.constant = 0
self.view.layoutIfNeeded()
}
}
}
// MARK: - Picker View
func setupPickerView() {
let pickerInsertWeight = UIPickerView()
pickerInsertWeight.delegate = self
exerciseTextField.delegate = self
exerciseTextField.inputView = pickerInsertWeight
exerciseTextField.inputAccessoryView = inputAccessoryViewPicker
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "dismissKeyboard")
view.addGestureRecognizer(tap)
selectInitialRowPickerView(pickerInsertWeight)
hideCellInsertWeight()
cellViewInsertHabits.layer.cornerRadius = cornerRadiusViews
weightDateLabel.text = habitsDates.last
exerciseTextField.text = pickerData[1]
waterLabel.text = pickerData[1]
fruitsLabel.text = pickerData[1]
}
@objc func cancelDatePicker() {
dismissKeyboard()
}
@objc func doneDatePicker() {
dismissKeyboard()
let exerciseValue = self.exerciseTextField.text! == "✗" ? false : true
let waterValue = self.waterLabel.text == "✗" ? false : true
let fruitsValue = self.fruitsLabel.text == "✗" ? false : true
insertNewWeight(waterValue: waterValue, fruitsValue: fruitsValue, exerciseValue: exerciseValue, date: convertStringToDate(dateString: weightDateLabel.text!))
loadData()
detailsTableview.reloadData()
}
@objc func dismissKeyboard() {
view.endEditing(true)
hideCellInsertWeight()
}
var inputAccessoryViewPicker: UIView? {
let toolbar = UIToolbar()
toolbar.sizeToFit()
let cancelButton = UIBarButtonItem(title: "Cancelar", style: UIBarButtonItem.Style.plain, target: self, action: #selector(self.cancelDatePicker))
let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: nil, action: nil)
let doneButton = UIBarButtonItem(title: "Adicionar", style: UIBarButtonItem.Style.done, target: self, action: #selector(self.doneDatePicker))
toolbar.setItems([cancelButton, spaceButton, doneButton], animated: false)
return toolbar
}
func selectInitialRowPickerView(_ pickerData: UIPickerView) {
pickerData.selectRow(Int(habitsDates.count - 1), inComponent: 3, animated: true)
pickerData.selectRow(1, inComponent: 0, animated: true)
pickerData.selectRow(1, inComponent: 1, animated: true)
pickerData.selectRow(1, inComponent: 2, animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 4
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
var sizeValue: Int = 1
switch component {
case 3:
sizeValue = habitsDates.count
default:
sizeValue = pickerData.count
}
return sizeValue
}
func pickerView( _ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
var dataValue: String!
switch component {
case 3:
dataValue = habitsDates[row]
default:
dataValue = pickerData[row]
}
return dataValue
}
func pickerView( _ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
let rowWater = pickerView.selectedRow(inComponent: 0)
let rowFruits = pickerView.selectedRow(inComponent: 1)
let rowExercise = pickerView.selectedRow(inComponent: 2)
let rowDate = pickerView.selectedRow(inComponent: 3)
exerciseTextField.text = pickerData[rowExercise]
waterLabel.text = pickerData[rowWater]
fruitsLabel.text = pickerData[rowFruits]
weightDateLabel.text = habitsDates[rowDate]
}
func pickerView(_ pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat {
var sizeValue: CGFloat!
switch component {
case 0:
sizeValue = 60
case 1:
sizeValue = 60
case 2:
sizeValue = 60
default:
sizeValue = 200
}
return sizeValue
}
// MARK: - ALERTS
func alertInsert(titleAlert: String, messageAlert: String) {
let alert = UIAlertController(title: titleAlert, message: messageAlert, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default))
self.present(alert, animated: true, completion: nil)
}
// MARK: - CONVERTIONS
func convertWeightStringToFloat() -> Float {
let valueArray = self.exerciseTextField.text!.split(separator: ",")
var convertedValue: Float = 0
if let integer = Float(valueArray[0]) {
convertedValue = integer
}
let decimalString = valueArray[1]
let decimalStringReplace = decimalString.replacingOccurrences(of: " %", with: "")
if let decimal = Float(decimalStringReplace) {
convertedValue = convertedValue + decimal/100
}
return convertedValue
}
}
| 36.637602 | 176 | 0.633794 |
e00a31e68bbceb07a25c5b1d1d39a03948285ef7 | 7,506 | //
// 🦠 Corona-Warn-App
//
import XCTest
@testable import ENA
final class StoreTests: XCTestCase {
private var store: SecureStore!
override func setUpWithError() throws {
XCTAssertNoThrow(try SecureStore(at: URL(staticString: ":memory:"), key: "123456", serverEnvironment: ServerEnvironment()))
store = try SecureStore(at: URL(staticString: ":memory:"), key: "123456", serverEnvironment: ServerEnvironment())
}
func testResultReceivedTimeStamp_Success() {
XCTAssertNil(store.testResultReceivedTimeStamp)
store.testResultReceivedTimeStamp = Int64.max
XCTAssertEqual(store.testResultReceivedTimeStamp, Int64.max)
store.testResultReceivedTimeStamp = Int64.min
XCTAssertEqual(store.testResultReceivedTimeStamp, Int64.min)
}
func testLastSuccessfulSubmitDiagnosisKeyTimestamp_Success() {
XCTAssertNil(store.lastSuccessfulSubmitDiagnosisKeyTimestamp)
store.lastSuccessfulSubmitDiagnosisKeyTimestamp = Int64.max
XCTAssertEqual(store.lastSuccessfulSubmitDiagnosisKeyTimestamp, Int64.max)
store.lastSuccessfulSubmitDiagnosisKeyTimestamp = Int64.min
XCTAssertEqual(store.lastSuccessfulSubmitDiagnosisKeyTimestamp, Int64.min)
}
func testNumberOfSuccesfulSubmissions_Success() {
XCTAssertEqual(store.numberOfSuccesfulSubmissions, 0)
store.numberOfSuccesfulSubmissions = Int64.max
XCTAssertEqual(store.numberOfSuccesfulSubmissions, Int64.max)
store.numberOfSuccesfulSubmissions = Int64.min
XCTAssertEqual(store.numberOfSuccesfulSubmissions, Int64.min)
}
func testInitialSubmitCompleted_Success() {
XCTAssertFalse(store.initialSubmitCompleted)
store.initialSubmitCompleted = true
XCTAssertTrue(store.initialSubmitCompleted)
store.initialSubmitCompleted = false
XCTAssertFalse(store.initialSubmitCompleted)
}
func testRegistrationToken_Success() {
XCTAssertNil(store.registrationToken)
let token = UUID().description
store.registrationToken = token
XCTAssertEqual(store.registrationToken, token)
}
/// Reads a statically created db from version 1.0.0 into the app container and checks, whether all values from that version are still readable
func testBackwardsCompatibility() throws {
// swiftlint:disable:next force_unwrapping
let testStoreSourceURL = Bundle(for: StoreTests.self).url(forResource: "testStore", withExtension: "sqlite")!
let fileManager = FileManager.default
let directoryURL = fileManager
.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true)
.appendingPathComponent("testDatabase")
try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true)
let testStoreTargetURL = directoryURL.appendingPathComponent("secureStore.sqlite")
XCTAssertTrue(fileManager.fileExists(atPath: testStoreSourceURL.path))
XCTAssertFalse(fileManager.fileExists(atPath: testStoreTargetURL.path))
try fileManager.copyItem(at: testStoreSourceURL, to: testStoreTargetURL)
let tmpStore: Store = try SecureStore(at: directoryURL, key: "12345678", serverEnvironment: ServerEnvironment())
// Prepare data
let testTimeStamp: Int64 = 1466467200 // 21.06.2016
let testDate1 = Date(timeIntervalSince1970: Double(testTimeStamp))
XCTAssertTrue(tmpStore.isOnboarded)
XCTAssertEqual(tmpStore.dateOfAcceptedPrivacyNotice?.description, testDate1.description)
XCTAssertEqual(tmpStore.teleTan, "97RR2D5644")
XCTAssertEqual(tmpStore.tan, "97RR2D5644")
XCTAssertEqual(tmpStore.testGUID, "00000000-0000-4000-8000-000000000000")
XCTAssertTrue(tmpStore.devicePairingConsentAccept)
XCTAssertEqual(tmpStore.devicePairingConsentAcceptTimestamp, testTimeStamp)
XCTAssertEqual(tmpStore.devicePairingSuccessfulTimestamp, testTimeStamp)
XCTAssertTrue(tmpStore.allowRiskChangesNotification)
XCTAssertTrue(tmpStore.allowTestsStatusNotification)
XCTAssertEqual(tmpStore.registrationToken, "")
XCTAssertTrue(tmpStore.hasSeenSubmissionExposureTutorial)
XCTAssertEqual(tmpStore.testResultReceivedTimeStamp, testTimeStamp)
XCTAssertEqual(tmpStore.lastSuccessfulSubmitDiagnosisKeyTimestamp, testTimeStamp)
XCTAssertEqual(tmpStore.numberOfSuccesfulSubmissions, 1)
XCTAssertTrue(tmpStore.initialSubmitCompleted)
XCTAssertEqual(tmpStore.exposureActivationConsentAcceptTimestamp, testTimeStamp)
XCTAssertTrue(tmpStore.exposureActivationConsentAccept)
}
func testDeviceTimeSettings_initalAfterInitialization() {
XCTAssertEqual(store.deviceTimeCheckResult, .correct)
XCTAssertFalse(store.wasDeviceTimeErrorShown)
store.deviceTimeCheckResult = .incorrect
store.wasDeviceTimeErrorShown = true
XCTAssertEqual(store.deviceTimeCheckResult, .incorrect)
XCTAssertTrue(store.wasDeviceTimeErrorShown)
}
func testValueToggles() throws {
let store = try SecureStore(at: URL(staticString: ":memory:"), key: "123456", serverEnvironment: ServerEnvironment())
let isOnboarded = store.isOnboarded
store.isOnboarded.toggle()
XCTAssertNotEqual(isOnboarded, store.isOnboarded)
let allowRiskChangesNotification = store.allowRiskChangesNotification
store.allowRiskChangesNotification.toggle()
XCTAssertNotEqual(allowRiskChangesNotification, store.allowRiskChangesNotification)
// etc.
}
func testBackupRestoration() throws {
// prerequisite: clean state
let keychain = try KeychainHelper()
try keychain.clearInKeychain(key: SecureStore.keychainDatabaseKey)
// 1. create store and store db key in keychain
let store = SecureStore(subDirectory: "test", serverEnvironment: ServerEnvironment())
XCTAssertFalse(store.isOnboarded)
// user finished onboarding and used the app…
store.isOnboarded.toggle()
store.testGUID = UUID().uuidString
guard let databaseKey = keychain.loadFromKeychain(key: SecureStore.keychainDatabaseKey) else {
XCTFail("expected a key!")
return
}
// 2. restored with db key in keychain
// This simulates iCloud keychain
let restore = SecureStore(subDirectory: "test", serverEnvironment: ServerEnvironment())
XCTAssertTrue(restore.isOnboarded)
XCTAssertEqual(restore.testGUID, store.testGUID)
// still the same key?
XCTAssertEqual(databaseKey, keychain.loadFromKeychain(key: SecureStore.keychainDatabaseKey))
// 3. db key in keychain 'changed' for some reason
// swiftlint:disable:next force_unwrapping
try keychain.saveToKeychain(key: SecureStore.keychainDatabaseKey, data: "corrupted".data(using: .utf8)!)
let restore2 = SecureStore(subDirectory: "test", serverEnvironment: ServerEnvironment())
// database reset?
XCTAssertFalse(restore2.isOnboarded)
XCTAssertEqual(restore2.testGUID, "") // init values…
XCTAssertNotEqual(databaseKey, keychain.loadFromKeychain(key: SecureStore.keychainDatabaseKey))
// cleanup
store.clearAll(key: nil)
}
func testConfigCaching() throws {
let store = SecureStore(subDirectory: "test", serverEnvironment: ServerEnvironment())
store.appConfigMetadata = nil
XCTAssertNil(store.appConfigMetadata)
let tag = "fake_\(Int.random(in: 100...999))"
let config = CachingHTTPClientMock.staticAppConfig
let appConfigMetadata = AppConfigMetadata(lastAppConfigETag: tag, lastAppConfigFetch: Date(), appConfig: config)
store.appConfigMetadata = appConfigMetadata
XCTAssertEqual(store.appConfigMetadata, appConfigMetadata)
}
func testConsentForAutomaticSharingTestResults_initial() throws {
let store = SecureStore(subDirectory: "test", serverEnvironment: ServerEnvironment())
XCTAssertFalse(store.isSubmissionConsentGiven, "isAllowedToAutomaticallyShareTestResults should be 'false' after initialization")
}
}
| 41.7 | 144 | 0.810285 |
1625a36f0e4bbfd318a7e3c92fbd0158116fcaa9 | 410,275 | /*
This source file is part of the Swift.org open source project
Copyright (c) 2014 - 2021 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 Basics
import PackageFingerprint
import PackageGraph
import PackageLoading
import PackageModel
import PackageRegistry
import SourceControl
import SPMBuildCore
import SPMTestSupport
import TSCBasic
import TSCUtility
@testable import Workspace
import XCTest
final class WorkspaceTests: XCTestCase {
func testBasics() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: 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: [
.sourceControl(path: "./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] = [
.sourceControl(path: "./Quix", requirement: .upToNextMajor(from: "1.0.0"), products: .specific(["Quix"])),
.sourceControl(path: "./Baz", requirement: .exact("1.0.0"), products: .specific(["Baz"])),
]
try 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.
XCTAssertMatch(workspace.delegate.events, ["will load manifest for root package: /tmp/ws/roots/Foo"])
XCTAssertMatch(workspace.delegate.events, ["did load manifest for root package: /tmp/ws/roots/Foo"])
XCTAssertMatch(workspace.delegate.events, ["will load manifest for localSourceControl package: /tmp/ws/pkgs/Quix"])
XCTAssertMatch(workspace.delegate.events, ["did load manifest for localSourceControl package: /tmp/ws/pkgs/Quix"])
XCTAssertMatch(workspace.delegate.events, ["will load manifest for localSourceControl package: /tmp/ws/pkgs/Baz"])
XCTAssertMatch(workspace.delegate.events, ["did load manifest for localSourceControl 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 = try workspace.getOrCreateWorkspace().state.storagePath
// Remove state file and check we can get the state back automatically.
try fs.removeFileTree(stateFile)
try workspace.checkPackageGraph(roots: ["Foo"], deps: deps) { _, _ in }
XCTAssertTrue(fs.exists(stateFile), "workspace state file should exist")
// Remove state file and check we get back to a clean state.
try fs.removeFileTree(workspace.getOrCreateWorkspace().state.storagePath)
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(toolchain: ToolchainConfiguration.default)
let sandbox = path.appending(component: "ws")
return try Workspace(
fileSystem: fs,
location: .init(forRootPackage: sandbox, fileSystem: fs),
customManifestLoader: manifestLoader,
delegate: MockWorkspaceDelegate()
)
}
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 testManifestParseError() throws {
let observability = ObservabilitySystem.makeForTesting()
try testWithTemporaryDirectory { path in
let pkgDir = path.appending(component: "MyPkg")
try localFileSystem.writeFileContents(pkgDir.appending(component: "Package.swift")) {
$0 <<<
"""
// swift-tools-version:4.0
import PackageDescription
#error("An error in MyPkg")
let package = Package(
name: "MyPkg"
)
"""
}
let workspace = try Workspace(
fileSystem: localFileSystem,
location: .init(forRootPackage: pkgDir, fileSystem: localFileSystem),
customManifestLoader: ManifestLoader(toolchain: ToolchainConfiguration.default),
delegate: MockWorkspaceDelegate()
)
let rootInput = PackageGraphRootInput(packages: [pkgDir], dependencies: [])
let rootManifests = try tsc_await {
workspace.loadRootManifests(
packages: rootInput.packages,
observabilityScope: observability.topScope,
completion: $0
)
}
XCTAssert(rootManifests.count == 0, "\(rootManifests)")
testDiagnostics(observability.diagnostics) { result in
let diagnostic = result.check(diagnostic: .contains("An error in MyPkg"), severity: .error)
XCTAssertEqual(diagnostic?.metadata?.packageIdentity, .init(path: pkgDir))
XCTAssertEqual(diagnostic?.metadata?.packageKind, .root(pkgDir))
}
}
}
func testMultipleRootPackages() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo", dependencies: ["Baz"]),
],
products: [],
dependencies: [
.sourceControl(path: "./Baz", requirement: .upToNextMajor(from: "1.0.0")),
]
),
MockPackage(
name: "Bar",
targets: [
MockTarget(name: "Bar", dependencies: ["Baz"]),
],
products: [],
dependencies: [
.sourceControl(path: "./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"]
),
]
)
try 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,
fileSystem: fs,
roots: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo", dependencies: ["Baz"]),
],
products: [],
dependencies: [
.sourceControl(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"]
),
]
)
try 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 testDuplicateRootPackages() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: 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.checkPackageGraphFailure(roots: ["Foo", "Nested/Foo"]) { diagnostics in
testDiagnostics(diagnostics) { result in
result.check(diagnostic: .equal("found multiple top-level packages named 'Foo'"), severity: .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,
fileSystem: fs,
roots: [
MockPackage(
name: "FooPackage",
path: "foo-package",
targets: [
MockTarget(name: "FooTarget", dependencies: [.product(name: "BarProduct", package: "BarPackage")]),
],
products: [],
dependencies: [
.sourceControlWithDeprecatedName(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"]
),
]
)
try workspace.checkPackageGraph(
roots: ["foo-package", "bar-package"],
dependencies: [
.localSourceControl(path: .init("/tmp/ws/pkgs/bar-package"), requirement: .upToNextMajor(from: "1.0.0"))
]
) { 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,
fileSystem: fs,
roots: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo", dependencies: ["BazAB"]),
],
products: [],
dependencies: [
.sourceControl(path: "./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"]
),
]
)
try 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,
fileSystem: fs,
roots: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo", dependencies: ["Baz"]),
],
products: [],
dependencies: [
.sourceControl(path: "./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.
try 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()
try 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,
fileSystem: fs,
roots: [],
packages: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo", dependencies: ["Bar"]),
],
products: [
MockProduct(name: "Foo", targets: ["Foo"]),
],
dependencies: [
.sourceControl(path: "./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: [PackageDependency] = [
.localSourceControl(
path: workspace.packagesDir.appending(component: "Bar"),
requirement: .upToNextMajor(from: "1.0.0"),
productFilter: .specific(["Bar"])
),
.localSourceControl(
path: workspace.packagesDir.appending(component: "Foo"),
requirement: .upToNextMajor(from: "1.0.0"),
productFilter: .specific(["Foo"])
),
]
try 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,
fileSystem: fs,
roots: [],
packages: [
MockPackage(
name: "A",
targets: [
MockTarget(name: "A", dependencies: ["AA"]),
],
products: [
MockProduct(name: "A", targets: ["A"]),
],
dependencies: [
.sourceControl(path: "./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: [
.sourceControl(path: "./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] = [
.sourceControl(path: "./A", requirement: .exact("1.0.0"), products: .specific(["A"])),
]
try 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] = [
.sourceControl(path: "./A", requirement: .exact("1.0.1"), products: .specific(["A"])),
]
try 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,
fileSystem: fs,
roots: [],
packages: [
MockPackage(
name: "A",
targets: [
MockTarget(name: "A", dependencies: ["AA"]),
],
products: [
MockProduct(name: "A", targets: ["A"]),
],
dependencies: [
.sourceControl(path: "./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: [
.sourceControl(path: "./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] = [
.sourceControl(path: "./A", requirement: .exact("1.0.0"), products: .specific(["A"])),
.sourceControl(path: "./B", requirement: .exact("1.0.0"), products: .specific(["B"])),
]
try workspace.checkPackageGraph(deps: deps) { _, diagnostics in
testDiagnostics(diagnostics) { result in
result.check(diagnostic: .contains("Dependencies could not be resolved"), severity: .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.version("1.0.5", revision: Revision(identifier: "hello"))
let v2 = CheckoutState.version("2.0.0", revision: Revision(identifier: "hello"))
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "A",
targets: [MockTarget(name: "A")],
products: []
),
],
packages: []
)
let bPackagePath = workspace.pathToPackage(withName: "B")
let cPackagePath = workspace.pathToPackage(withName: "C")
let bRef = PackageReference.localSourceControl(identity: PackageIdentity(path: bPackagePath), path: bPackagePath)
let cRef = PackageReference.localSourceControl(identity: PackageIdentity(path: cPackagePath), path: cPackagePath)
try workspace.set(
pins: [bRef: v1_5, cRef: v2],
managedDependencies: [
.sourceControlCheckout(packageRef: bRef, state: v1_5, subpath: bPath)
.edited(subpath: bPath, unmanagedPath: .none),
]
)
try workspace.checkPrecomputeResolution { result in
XCTAssertEqual(result.diagnostics.hasErrors, false, result.diagnostics.description)
XCTAssertEqual(result.result.isRequired, false)
}
}
func testPrecomputeResolution_newPackages() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let bPath = RelativePath("B")
let v1Requirement: SourceControlRequirement = .range("1.0.0" ..< "2.0.0")
let v1 = CheckoutState.version("1.0.0", revision: Revision(identifier: "hello"))
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "A",
targets: [MockTarget(name: "A")],
products: [],
dependencies: [
.sourceControl(path: "./B", requirement: v1Requirement),
.sourceControl(path: "./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 bPackagePath = workspace.pathToPackage(withName: "B")
let cPackagePath = workspace.pathToPackage(withName: "C")
let bRef = PackageReference.localSourceControl(identity: PackageIdentity(path: bPackagePath), path: bPackagePath)
let cRef = PackageReference.localSourceControl(identity: PackageIdentity(path: cPackagePath), path: cPackagePath)
try workspace.set(
pins: [bRef: v1],
managedDependencies: [
.sourceControlCheckout(packageRef: bRef, state: v1, subpath: bPath),
]
)
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: SourceControlRequirement = .range("1.0.0" ..< "2.0.0")
let branchRequirement: SourceControlRequirement = .branch("master")
let v1_5 = CheckoutState.version("1.0.5", revision: Revision(identifier: "hello"))
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "A",
targets: [MockTarget(name: "A")],
products: [],
dependencies: [
.sourceControl(path: "./B", requirement: v1Requirement),
.sourceControl(path: "./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 bPackagePath = workspace.pathToPackage(withName: "B")
let cPackagePath = workspace.pathToPackage(withName: "C")
let bRef = PackageReference.localSourceControl(identity: PackageIdentity(path: bPackagePath), path: bPackagePath)
let cRef = PackageReference.localSourceControl(identity: PackageIdentity(path: cPackagePath), path: cPackagePath)
try workspace.set(
pins: [bRef: v1_5, cRef: v1_5],
managedDependencies: [
.sourceControlCheckout(packageRef: bRef, state: v1_5, subpath: bPath),
.sourceControlCheckout(packageRef: cRef, state: v1_5, subpath: cPath),
]
)
try workspace.checkPrecomputeResolution { result in
XCTAssertEqual(result.diagnostics.hasErrors, false)
XCTAssertEqual(result.result, .required(reason: .packageRequirementChange(
package: cRef,
state: .sourceControlCheckout(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.version("1.0.5", revision: Revision(identifier: "hello"))
let testWorkspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "A",
targets: [MockTarget(name: "A")],
products: [],
dependencies: [
.sourceControl(path: "./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 cPackagePath = testWorkspace.pathToPackage(withName: "C")
let cRef = PackageReference.localSourceControl(identity: PackageIdentity(path: cPackagePath), path: cPackagePath)
try testWorkspace.set(
pins: [cRef: v1_5],
managedDependencies: [
.sourceControlCheckout(packageRef: cRef, state: v1_5, subpath: cPath),
]
)
try testWorkspace.checkPrecomputeResolution { result in
XCTAssertEqual(result.diagnostics.hasErrors, false)
XCTAssertEqual(result.result, .required(reason: .packageRequirementChange(
package: cRef,
state: .sourceControlCheckout(v1_5),
requirement: .revision("hello")
)))
}
}
func testPrecomputeResolution_requirementChange_localToBranch() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let bPath = RelativePath("B")
let v1Requirement: SourceControlRequirement = .range("1.0.0" ..< "2.0.0")
let masterRequirement: SourceControlRequirement = .branch("master")
let v1_5 = CheckoutState.version("1.0.5", revision: Revision(identifier: "hello"))
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "A",
targets: [MockTarget(name: "A")],
products: [],
dependencies: [
.sourceControl(path: "./B", requirement: v1Requirement),
.sourceControl(path: "./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 bPackagePath = workspace.pathToPackage(withName: "B")
let cPackagePath = workspace.pathToPackage(withName: "C")
let bRef = PackageReference.localSourceControl(identity: PackageIdentity(path: bPackagePath), path: bPackagePath)
let cRef = PackageReference.localSourceControl(identity: PackageIdentity(path: cPackagePath), path: cPackagePath)
try workspace.set(
pins: [bRef: v1_5],
managedDependencies: [
.sourceControlCheckout(packageRef: bRef, state: v1_5, subpath: bPath),
.fileSystem(packageRef: cRef),
]
)
try workspace.checkPrecomputeResolution { result in
XCTAssertEqual(result.diagnostics.hasErrors, false)
XCTAssertEqual(result.result, .required(reason: .packageRequirementChange(
package: cRef,
state: .fileSystem(cPackagePath),
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: SourceControlRequirement = .range("1.0.0" ..< "2.0.0")
let v1_5 = CheckoutState.version("1.0.5", revision: Revision(identifier: "hello"))
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "A",
targets: [MockTarget(name: "A")],
products: [],
dependencies: [
.sourceControl(path: "./B", requirement: v1Requirement),
.fileSystem(path: "./C"),
]
),
],
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 bPackagePath = workspace.pathToPackage(withName: "B")
let cPackagePath = workspace.pathToPackage(withName: "C")
let bRef = PackageReference.localSourceControl(identity: PackageIdentity(path: bPackagePath), path: bPackagePath)
let cRef = PackageReference.localSourceControl(identity: PackageIdentity(path: cPackagePath), path: cPackagePath)
try workspace.set(
pins: [bRef: v1_5, cRef: v1_5],
managedDependencies: [
.sourceControlCheckout(packageRef: bRef, state: v1_5, subpath: bPath),
.sourceControlCheckout(packageRef: cRef, state: v1_5, subpath: cPath),
]
)
try workspace.checkPrecomputeResolution { result in
XCTAssertEqual(result.diagnostics.hasErrors, false)
XCTAssertEqual(result.result, .required(reason: .packageRequirementChange(
package: cRef,
state: .sourceControlCheckout(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: SourceControlRequirement = .range("1.0.0" ..< "2.0.0")
let v1_5 = CheckoutState.version("1.0.5", revision: Revision(identifier: "hello"))
let master = CheckoutState.branch(name: "master", revision: Revision(identifier: "master"))
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "A",
targets: [MockTarget(name: "A")],
products: [],
dependencies: [
.sourceControl(path: "./B", requirement: v1Requirement),
.fileSystem(path: "./C"),
]
),
],
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 bPackagePath = workspace.pathToPackage(withName: "B")
let cPackagePath = workspace.pathToPackage(withName: "C")
let bRef = PackageReference.localSourceControl(identity: PackageIdentity(path: bPackagePath), path: bPackagePath)
let cRef = PackageReference.localSourceControl(identity: PackageIdentity(path: cPackagePath), path: cPackagePath)
try workspace.set(
pins: [bRef: v1_5, cRef: master],
managedDependencies: [
.sourceControlCheckout(packageRef: bRef, state: v1_5, subpath: bPath),
.sourceControlCheckout(packageRef: cRef, state: master, subpath: cPath),
]
)
try workspace.checkPrecomputeResolution { result in
XCTAssertEqual(result.diagnostics.hasErrors, false)
XCTAssertEqual(result.result, .required(reason: .packageRequirementChange(
package: cRef,
state: .sourceControlCheckout(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: SourceControlRequirement = .range("1.0.0" ..< "2.0.0")
let v2Requirement: SourceControlRequirement = .range("2.0.0" ..< "3.0.0")
let v1_5 = CheckoutState.version("1.0.5", revision: Revision(identifier: "hello"))
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "A",
targets: [MockTarget(name: "A")],
products: [],
dependencies: [
.sourceControl(path: "./B", requirement: v1Requirement),
.sourceControl(path: "./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 bPackagePath = workspace.pathToPackage(withName: "B")
let cPackagePath = workspace.pathToPackage(withName: "C")
let bRef = PackageReference.localSourceControl(identity: PackageIdentity(path: bPackagePath), path: bPackagePath)
let cRef = PackageReference.localSourceControl(identity: PackageIdentity(path: cPackagePath), path: cPackagePath)
try workspace.set(
pins: [bRef: v1_5, cRef: v1_5],
managedDependencies: [
.sourceControlCheckout(packageRef: bRef, state: v1_5, subpath: bPath),
.sourceControlCheckout(packageRef: cRef, state: v1_5, subpath: cPath),
]
)
try workspace.checkPrecomputeResolution { result in
XCTAssertEqual(result.diagnostics.hasErrors, false)
XCTAssertEqual(
result.result,
.required(reason: .other("Dependencies could not be resolved because no versions of \'c\' match the requirement 2.0.0..<3.0.0 and root depends on \'c\' 2.0.0..<3.0.0."))
)
}
}
func testPrecomputeResolution_notRequired() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let bPath = RelativePath("B")
let cPath = RelativePath("C")
let v1Requirement: SourceControlRequirement = .range("1.0.0" ..< "2.0.0")
let v2Requirement: SourceControlRequirement = .range("2.0.0" ..< "3.0.0")
let v1_5 = CheckoutState.version("1.0.5", revision: Revision(identifier: "hello"))
let v2 = CheckoutState.version("2.0.0", revision: Revision(identifier: "hello"))
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "A",
targets: [MockTarget(name: "A")],
products: [],
dependencies: [
.sourceControl(path: "./B", requirement: v1Requirement),
.sourceControl(path: "./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 bPackagePath = workspace.pathToPackage(withName: "B")
let cPackagePath = workspace.pathToPackage(withName: "C")
let bRef = PackageReference.localSourceControl(identity: PackageIdentity(path: bPackagePath), path: bPackagePath)
let cRef = PackageReference.localSourceControl(identity: PackageIdentity(path: cPackagePath), path: cPackagePath)
try workspace.set(
pins: [bRef: v1_5, cRef: v2],
managedDependencies: [
.sourceControlCheckout(packageRef: bRef, state: v1_5, subpath: bPath),
.sourceControlCheckout(packageRef: cRef, state: v2, subpath: cPath),
]
)
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,
fileSystem: fs,
roots: [
.genericPackage1(named: "A"),
.genericPackage1(named: "B"),
.genericPackage1(named: "C"),
],
packages: []
)
try 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,
fileSystem: fs,
roots: [
MockPackage(
name: "Root",
targets: [
MockTarget(name: "Root", dependencies: ["Foo"]),
],
products: [
MockProduct(name: "Root", targets: ["Root"]),
],
dependencies: [
.sourceControl(path: "./Foo", requirement: .upToNextMajor(from: "1.0.0")),
]
),
],
packages: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo", dependencies: ["Bar"]),
],
products: [
MockProduct(name: "Foo", targets: ["Foo"]),
],
dependencies: [
.sourceControl(path: "./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] = [
.sourceControl(path: "./Foo", requirement: .exact("1.0.0"), products: .specific(["Foo"])),
]
try 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.
try workspace.checkUpdate(roots: ["Root"]) { diagnostics in
XCTAssertNoDiagnostics(diagnostics)
}
try 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.
try 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,
fileSystem: fs,
roots: [
MockPackage(
name: "Root",
targets: [
MockTarget(name: "Root", dependencies: ["Foo"]),
],
products: [
MockProduct(name: "Root", targets: ["Root"]),
],
dependencies: [
.sourceControl(path: "./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] = [
.sourceControl(path: "./Foo", requirement: .exact("1.0.0"), products: .specific(["Foo"])),
]
try 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.
try 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.localSourceControl(identity: PackageIdentity(path: path), path: path),
stateChange
)
guard let change = changes?.first, changes?.count == 1 else {
XCTFail()
return
}
XCTAssertEqual(expectedChange, change)
}
try 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,
fileSystem: fs,
roots: [
MockPackage(
name: "Root",
targets: [
MockTarget(name: "Root", dependencies: ["Foo"]),
],
products: [
MockProduct(name: "Root", targets: ["Root"]),
],
dependencies: [
.sourceControl(path: "./Foo", requirement: .upToNextMajor(from: "1.0.0")),
]
),
],
packages: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo", dependencies: ["Bar"]),
],
products: [
MockProduct(name: "Foo", targets: ["Foo"]),
],
dependencies: [
.sourceControl(path: "./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: [
.sourceControl(path: "./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] = [
.sourceControl(path: "./Foo", requirement: .exact("1.0.0"), products: .specific(["Foo"])),
]
try 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.
try 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.
try 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.
try 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,
fileSystem: fs,
roots: [
MockPackage(
name: "Root",
targets: [
MockTarget(name: "Root", dependencies: ["Foo"]),
],
products: [
MockProduct(name: "Root", targets: ["Root"]),
],
dependencies: [
.sourceControl(path: "./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.
try workspace.checkPackageGraph(roots: ["Root"]) { _, diagnostics in
XCTAssertNoDiagnostics(diagnostics)
}
// Drop a build artifact in data directory.
let ws = try workspace.getOrCreateWorkspace()
let buildArtifact = ws.location.workingDirectory.appending(component: "test.o")
try fs.writeFileContents(buildArtifact, bytes: "Hi")
// Sanity checks.
XCTAssert(fs.exists(buildArtifact))
XCTAssert(fs.exists(ws.location.repositoriesCheckoutsDirectory))
// Check clean.
workspace.checkClean { diagnostics in
// Only the build artifact should be removed.
XCTAssertFalse(fs.exists(buildArtifact))
XCTAssert(fs.exists(ws.location.repositoriesCheckoutsDirectory))
XCTAssert(fs.exists(ws.location.workingDirectory))
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.location.repositoriesCheckoutsDirectory))
XCTAssertFalse(fs.exists(ws.location.workingDirectory))
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,
fileSystem: fs,
roots: [
MockPackage(
name: "Root1",
targets: [
MockTarget(name: "Root1", dependencies: ["Foo"]),
],
products: [],
dependencies: [
.sourceControl(path: "./Foo", requirement: .upToNextMajor(from: "1.0.0")),
]
),
MockPackage(
name: "Root2",
targets: [
MockTarget(name: "Root2", dependencies: ["Bar"]),
],
products: [],
dependencies: [
.sourceControl(path: "./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.missingPackages().map { $0.locationString }.sorted(), ["/tmp/ws/pkgs/Bar", "/tmp/ws/pkgs/Foo"])
XCTAssertNoDiagnostics(diagnostics)
}
// Load the graph with one root.
try 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.missingPackages().map { $0.locationString }.sorted(), ["/tmp/ws/pkgs/Bar"])
XCTAssertNoDiagnostics(diagnostics)
}
// Load the graph with both roots.
try 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.missingPackages().map { $0.locationString }.sorted(), [])
XCTAssertNoDiagnostics(diagnostics)
}
}
func testDependencyManifestsOrder() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "Root1",
targets: [
MockTarget(name: "Root1", dependencies: ["Foo", "Bar", "Baz", "Bam"]),
],
products: [],
dependencies: [
.sourceControl(path: "./Foo", requirement: .upToNextMajor(from: "1.0.0")),
.sourceControl(path: "./Bar", requirement: .upToNextMajor(from: "1.0.0")),
.sourceControl(path: "./Baz", requirement: .upToNextMajor(from: "1.0.0")),
.sourceControl(path: "./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: [
.sourceControl(path: "./Bar", requirement: .upToNextMajor(from: "1.0.0")),
.sourceControl(path: "./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: [
.sourceControl(path: "./Bam", requirement: .upToNextMajor(from: "1.0.0")),
],
versions: ["1.0.0"]
),
.genericPackage1(named: "Bam"),
]
)
try 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.value.manifest.displayName }, ["Foo", "Baz", "Bam", "Bar"])
XCTAssertNoDiagnostics(diagnostics)
}
}
func testBranchAndRevision() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "Root",
targets: [
MockTarget(name: "Root", dependencies: ["Foo"]),
],
products: [],
dependencies: [
.sourceControl(path: "./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(path: .init("/tmp/ws/pkgs/Bar"))
let barRevision = workspace.repositoryProvider.specifierMap[bar]!.revisions[0]
// We request Bar via revision.
let deps: [MockDependency] = [
.sourceControl(path: "./Bar", requirement: .revision(barRevision), products: .specific(["Bar"])),
]
try 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,
fileSystem: fs,
roots: [
MockPackage(
name: "Root",
targets: [
MockTarget(name: "Root", dependencies: ["Foo"]),
],
products: [],
dependencies: [
.sourceControl(path: "./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.
try 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
testDiagnostics(diagnostics) { result in
result.check(diagnostic: .contains("'foo' 1.3.0"), severity: .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,
fileSystem: fs,
roots: [
MockPackage(
name: "Root",
targets: [
MockTarget(name: "Root", dependencies: ["Foo"]),
],
products: [],
dependencies: [
.sourceControl(path: "./Foo", requirement: .upToNextMajor(from: "1.0.0")),
]
),
],
packages: [
.genericPackage1(named: "Foo"),
]
)
// Load the graph.
try 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.getOrCreateWorkspace().location.repositoriesCheckoutsDirectory)
try workspace.checkPackageGraph(roots: ["Root"]) { graph, diagnostics in
PackageGraphTester(graph) { result in
result.check(roots: "Root")
result.check(packages: "Foo", "Root")
}
testDiagnostics(diagnostics) { result in
result.check(diagnostic: .contains("dependency 'foo' is missing; cloning again"), severity: .warning)
}
}
}
func testMinimumRequiredToolsVersionInDependencyResolution() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "Root",
targets: [
MockTarget(name: "Root", dependencies: ["Foo"]),
],
products: [],
dependencies: [
.sourceControl(path: "./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
),
]
)
try workspace.checkPackageGraph(roots: ["Root"]) { _, diagnostics in
testDiagnostics(diagnostics) { result in
result.check(diagnostic: .contains("'foo' 1.0.0..<2.0.0"), severity: .error)
}
}
}
func testToolsVersionRootPackages() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: 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")
try workspace.checkPackageGraph(roots: ["Foo"]) { _, diagnostics in
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkPackageGraphFailure(roots: ["Bar"]) { diagnostics in
testDiagnostics(diagnostics) { result in
let diagnostic = result.check(
diagnostic: .equal("package 'bar' is using Swift tools version 4.1.0 but the installed version is 4.0.0"),
severity: .error
)
XCTAssertEqual(diagnostic?.metadata?.packageIdentity, .plain("bar"))
}
}
workspace.checkPackageGraphFailure(roots: ["Foo", "Bar"]) { diagnostics in
testDiagnostics(diagnostics) { result in
let diagnostic = result.check(
diagnostic: .equal("package 'bar' is using Swift tools version 4.1.0 but the installed version is 4.0.0"),
severity: .error
)
XCTAssertEqual(diagnostic?.metadata?.packageIdentity, .plain("bar"))
}
}
workspace.checkPackageGraphFailure(roots: ["Baz"]) { diagnostics in
testDiagnostics(diagnostics) { result in
let diagnostic = result.check(
diagnostic: .equal("package '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"),
severity: .error
)
XCTAssertEqual(diagnostic?.metadata?.packageIdentity, .plain("baz"))
}
}
}
func testEditDependency() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "Root",
targets: [
MockTarget(name: "Root", dependencies: ["Foo", "Bar"]),
],
products: [],
dependencies: [
.sourceControl(path: "./Foo", requirement: .upToNextMajor(from: "1.0.0")),
.sourceControl(path: "./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.
try 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 = try workspace.getOrCreateWorkspace().location.editsDirectory.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.package.locationString }, [fooPath.pathString])
XCTAssertNoDiagnostics(diagnostics)
}
// Try re-editing foo.
workspace.checkEdit(packageName: "Foo") { diagnostics in
testDiagnostics(diagnostics) { result in
result.check(diagnostic: .equal("dependency 'foo' already in edit mode"), severity: .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
testDiagnostics(diagnostics) { result in
result.check(diagnostic: .equal("revision 'dev' does not exist"), severity: .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.repositoryProvider.openWorkingCopy(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,
fileSystem: fs,
roots: [
MockPackage(
name: "Root",
targets: [
MockTarget(name: "Root", dependencies: ["Foo"]),
],
products: [],
dependencies: [
.sourceControl(path: "./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.
try workspace.checkPackageGraph(roots: ["Root"]) { _, _ in }
// Edit foo.
let fooPath = try workspace.getOrCreateWorkspace().location.editsDirectory.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)
try workspace.checkPackageGraph(roots: ["Root"]) { _, diagnostics in
testDiagnostics(diagnostics) { result in
result.check(diagnostic: .equal("dependency 'foo' was being edited but is missing; falling back to original checkout"), severity: .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,
fileSystem: fs,
roots: [],
packages: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo"),
],
products: [
MockProduct(name: "Foo", targets: ["Foo"]),
],
versions: ["1.0.0", nil]
),
]
)
let deps: [MockDependency] = [
.sourceControl(path: "./Foo", requirement: .upToNextMajor(from: "1.0.0"), products: .specific(["Foo"])),
]
let ws = try workspace.getOrCreateWorkspace()
// Load the graph and edit foo.
try 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.
try workspace.checkUpdate { diagnostics in
XCTAssertNoDiagnostics(diagnostics)
}
XCTAssertMatch(workspace.delegate.events, [.equal("removing repo: /tmp/ws/pkgs/Foo")])
try workspace.checkPackageGraph(deps: []) { _, diagnostics in
XCTAssertNoDiagnostics(diagnostics)
}
// There should still be an entry for `foo`, which we can unedit.
let editedDependency = ws.state.dependencies[.plain("foo")]
if case .edited(let basedOn, _) = editedDependency?.state {
XCTAssertNil(basedOn)
} else {
XCTFail("expected edited depedency")
}
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,
fileSystem: fs,
roots: [
MockPackage(
name: "Root",
targets: [
MockTarget(name: "Root", dependencies: ["Foo", "Bar"]),
],
products: [],
dependencies: [
.sourceControl(path: "./Foo", requirement: .upToNextMajor(from: "1.0.0")),
.sourceControl(path: "./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] = [
.sourceControl(path: "./Foo", requirement: .exact("1.0.0"), products: .specific(["Foo"])),
]
// Load the graph.
try 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.
try 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,
fileSystem: fs,
roots: [
MockPackage(
name: "Root",
targets: [
MockTarget(name: "Root", dependencies: ["Foo"]),
],
products: [],
dependencies: [
.sourceControl(path: "./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: [
.sourceControl(path: "./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.
try 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] = [
.fileSystem(path: "./Foo", products: .specific(["Foo"])),
]
try 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,
fileSystem: fs,
roots: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo", dependencies: ["Bar"]),
],
products: [
MockProduct(name: "Foo", targets: ["Foo"]),
],
dependencies: [
.sourceControl(path: "./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.
try 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.
let fooKey = MockManifestLoader.Key(url: "/tmp/ws/roots/Foo")
let manifest = workspace.manifestLoader.manifests[fooKey]!
let dependency = manifest.dependencies[0]
switch dependency {
case .sourceControl(let settings):
let updatedDependency: PackageDependency = .sourceControl(
identity: settings.identity,
nameForTargetDependencyResolutionOnly: settings.nameForTargetDependencyResolutionOnly,
location: settings.location,
requirement: .exact("1.5.0"),
productFilter: settings.productFilter
)
workspace.manifestLoader.manifests[fooKey] = Manifest(
displayName: manifest.displayName,
path: manifest.path,
packageKind: manifest.packageKind,
packageLocation: manifest.packageLocation,
platforms: [],
version: manifest.version,
toolsVersion: manifest.toolsVersion,
dependencies: [updatedDependency],
targets: manifest.targets
)
default:
XCTFail("unexpected dependency type")
}
try 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,
fileSystem: fs,
roots: [
MockPackage(
name: "Root",
targets: [
MockTarget(name: "Root", dependencies: ["Foo"]),
],
products: [],
dependencies: [
.sourceControl(path: "./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.
try 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] = [
.sourceControl(path: "./Bar", requirement: .exact("1.1.0"), products: .specific(["Bar"])),
]
try workspace.checkPackageGraph(roots: ["Root"], deps: deps) { _, diagnostics in
testDiagnostics(diagnostics) { result in
result.check(diagnostic: .contains("'bar' 1.1.0"), severity: .error)
}
}
}
func testSkipUpdate() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "Root",
targets: [
MockTarget(name: "Root", dependencies: ["Foo"]),
],
products: [
MockProduct(name: "Root", targets: ["Root"]),
],
dependencies: [
.sourceControl(path: "./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"]
),
],
resolverUpdateEnabled: false
)
// Run update and remove all events.
try workspace.checkUpdate(roots: ["Root"]) { diagnostics in
XCTAssertNoDiagnostics(diagnostics)
}
workspace.delegate.clear()
// Check we don't have updating Foo event.
try 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,
fileSystem: fs,
roots: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo", dependencies: ["Bar", "Baz"]),
MockTarget(name: "FooTests", dependencies: ["Foo"], type: .test),
],
products: [],
dependencies: [
.fileSystem(path: "./Bar"),
.sourceControl(path: "./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: [
.sourceControl(path: "./Bar", requirement: .upToNextMajor(from: "1.0.0")),
],
versions: ["1.0.0", "1.5.0"]
),
]
)
try 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
testDiagnostics(diagnostics) { result in
result.check(diagnostic: .contains("local dependency 'bar' can't be edited"), severity: .error)
}
}
workspace.checkResolve(pkg: "Bar", roots: ["Foo"], version: "1.0.0") { diagnostics in
testDiagnostics(diagnostics) { result in
result.check(diagnostic: .contains("local dependency 'bar' can't be resolved"), severity: .error)
}
}
}
func testLocalDependencyTransitive() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo", dependencies: ["Bar"]),
MockTarget(name: "FooTests", dependencies: ["Foo"], type: .test),
],
products: [],
dependencies: [
.sourceControl(path: "./Bar", requirement: .upToNextMajor(from: "1.0.0")),
]
),
],
packages: [
MockPackage(
name: "Bar",
targets: [
MockTarget(name: "Bar", dependencies: ["Baz"]),
],
products: [
MockProduct(name: "Bar", targets: ["Bar"]),
],
dependencies: [
.fileSystem(path: "./Baz"),
],
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]
),
]
)
try workspace.checkPackageGraph(roots: ["Foo"]) { graph, diagnostics in
PackageGraphTester(graph) { result in
result.check(roots: "Foo")
result.check(packages: "Foo")
result.check(targets: "Foo")
}
testDiagnostics(diagnostics) { result in
result.check(diagnostic: .contains("'bar' {1.0.0..<1.5.0, 1.5.1..<2.0.0} cannot be used"), severity: .error)
}
}
}
func testLocalDependencyWithPackageUpdate() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo", dependencies: ["Bar"]),
],
products: [],
dependencies: [
.sourceControl(path: "./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]
),
]
)
try 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] = [
.fileSystem(path: "./Bar", products: .specific(["Bar"])),
]
try 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.
try 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,
fileSystem: fs,
roots: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo", dependencies: []),
],
products: [],
dependencies: [
.fileSystem(path: "Bar"),
]
),
],
packages: [
]
)
try workspace.checkPackageGraph(roots: ["Foo"]) { graph, diagnostics in
PackageGraphTester(graph) { result in
result.check(roots: "Foo")
result.check(packages: "Foo")
result.check(targets: "Foo")
}
testDiagnostics(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"), severity: .error)
}
}
}
func testRevisionVersionSwitch() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: 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] = [
.sourceControl(path: "./Foo", requirement: .branch("develop"), products: .specific(["Foo"])),
]
try 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 = [
.sourceControl(path: "./Foo", requirement: .upToNextMajor(from: "1.0.0"), products: .specific(["Foo"])),
]
try 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 = [
.sourceControl(path: "./Foo", requirement: .branch("develop"), products: .specific(["Foo"])),
]
try 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,
fileSystem: 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] = [
.fileSystem(path: "./Foo", products: .specific(["Foo"])),
]
try 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 = [
.sourceControl(path: "./Foo", requirement: .upToNextMajor(from: "1.0.0"), products: .specific(["Foo"])),
]
try 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 = [
.fileSystem(path: "./Foo", products: .specific(["Foo"])),
]
try 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,
fileSystem: 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] = [
.fileSystem(path: "./Foo", products: .specific(["Foo"])),
]
try 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 = [
.fileSystem(path: "./Foo2", products: .specific(["Foo"])),
]
try workspace.checkPackageGraph(roots: ["Root"], deps: deps) { _, diagnostics in
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkManagedDependencies { result in
result.check(dependency: "foo2", at: .local)
}
}
// Test that switching between two same local packages placed at
// different locations works correctly.
func testDependencySwitchLocalWithSameIdentity() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: 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]
),
]
)
var deps: [MockDependency] = [
.fileSystem(path: "./Foo", products: .specific(["Foo"])),
]
try 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)
XCTAssertEqual(result.managedDependencies[.plain("foo")]?.packageRef.locationString, "/tmp/ws/pkgs/Foo")
}
deps = [
.fileSystem(path: "./Nested/Foo", products: .specific(["Foo"])),
]
try workspace.checkPackageGraph(roots: ["Root"], deps: deps) { _, diagnostics in
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkManagedDependencies { result in
result.check(dependency: "foo", at: .local)
XCTAssertEqual(result.managedDependencies[.plain("foo")]?.packageRef.locationString, "/tmp/ws/pkgs/Nested/Foo")
}
}
// Test that switching between two remote packages at
// different locations works correctly.
func testDependencySwitchRemoteWithSameIdentity() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "Root",
targets: [
MockTarget(name: "Root", dependencies: []),
],
products: [],
dependencies: []
),
],
packages: [
MockPackage(
name: "Foo",
url: "https://scm.com/org/foo",
targets: [
MockTarget(name: "Foo"),
],
products: [
MockProduct(name: "Foo", targets: ["Foo"]),
],
versions: ["1.0.0"]
),
MockPackage(
name: "Foo",
url: "https://scm.com/other/foo",
targets: [
MockTarget(name: "OtherFoo"),
],
products: [
MockProduct(name: "OtherFoo", targets: ["OtherFoo"]),
],
versions: ["1.1.0"]
),
]
)
var deps: [MockDependency] = [
.sourceControl(url: "https://scm.com/org/foo", requirement: .exact("1.0.0")),
]
try workspace.checkPackageGraph(roots: ["Root"], deps: deps) { graph, diagnostics in
XCTAssertNoDiagnostics(diagnostics)
PackageGraphTester(graph) { result in
result.check(roots: "Root")
result.check(packages: "Foo", "Root")
}
}
workspace.checkManagedDependencies { result in
result.check(dependency: "foo", at: .checkout(.version("1.0.0")))
}
do {
let ws = try workspace.getOrCreateWorkspace()
XCTAssertEqual(ws.state.dependencies[.plain("foo")]?.packageRef.locationString, "https://scm.com/org/foo")
}
deps = [
.sourceControl(url: "https://scm.com/other/foo", requirement: .exact("1.1.0"))
]
try workspace.checkPackageGraph(roots: ["Root"], deps: deps) { _, diagnostics in
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkManagedDependencies { result in
result.check(dependency: "foo", at: .checkout(.version("1.1.0")))
}
do {
let ws = try workspace.getOrCreateWorkspace()
XCTAssertEqual(ws.state.dependencies[.plain("foo")]?.packageRef.locationString, "https://scm.com/other/foo")
}
}
func testResolvedFileUpdate() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: 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] = [
.sourceControl(path: "./Foo", requirement: .upToNextMajor(from: "1.0.0"), products: .specific(["Foo"])),
]
try 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")))
}
try 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 testResolvedFileSchemeToolsVersion() throws {
let fs = InMemoryFileSystem()
for pair in [(ToolsVersion.v5_2, ToolsVersion.v5_2), (ToolsVersion.v5_6, ToolsVersion.v5_6), (ToolsVersion.v5_2, ToolsVersion.v5_6)] {
let sandbox = AbsolutePath("/tmp/ws/")
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "Root1",
targets: [
MockTarget(name: "Root1", dependencies: ["Foo"]),
],
products: [],
dependencies: [
.sourceControl(path: "./Foo", requirement: .upToNextMajor(from: "1.0.0"), products: .specific(["Foo"])),
],
toolsVersion: pair.0
),
MockPackage(
name: "Root2",
targets: [
MockTarget(name: "Root2", dependencies: []),
],
products: [],
dependencies: [],
toolsVersion: pair.1
),
],
packages: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo"),
],
products: [
MockProduct(name: "Foo", targets: ["Foo"]),
],
versions: ["1.0.0"]
),
]
)
try workspace.checkPackageGraph(roots: ["Root1", "Root2"]) { _, 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")))
}
let minToolsVersion = [pair.0, pair.1].min()!
let expectedSchemeVersion = minToolsVersion >= .v5_6 ? 2 : 1
XCTAssertEqual(try workspace.getOrCreateWorkspace().pinsStore.load().schemeVersion(), expectedSchemeVersion)
}
}
func testResolvedFileStableCanonicalLocation() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "Root",
targets: [
MockTarget(name: "Root", dependencies: []),
],
products: [],
dependencies: []
),
],
packages: [
MockPackage(
name: "Foo",
url: "https://localhost/org/foo",
targets: [
MockTarget(name: "Foo"),
],
products: [
MockProduct(name: "Foo", targets: ["Foo"]),
],
versions: ["1.0.0"],
revisionProvider: { version in version } // stable revisions
),
MockPackage(
name: "Bar",
url: "https://localhost/org/bar",
targets: [
MockTarget(name: "Bar"),
],
products: [
MockProduct(name: "Bar", targets: ["Bar"]),
],
versions: ["1.0.0"],
revisionProvider: { version in version } // stable revisions
),
MockPackage(
name: "Foo",
url: "https://localhost/ORG/FOO", // diff: case
targets: [
MockTarget(name: "Foo"),
],
products: [
MockProduct(name: "Foo", targets: ["Foo"]),
],
versions: ["1.0.0", "1.1.0"],
revisionProvider: { version in version } // stable revisions
),
MockPackage(
name: "Foo",
url: "https://localhost/org/foo.git", // diff: .git extension
targets: [
MockTarget(name: "Foo"),
],
products: [
MockProduct(name: "Foo", targets: ["Foo"]),
],
versions: ["1.0.0", "1.1.0"],
revisionProvider: { version in version } // stable revisions
),
MockPackage(
name: "Bar",
url: "https://localhost/org/bar.git", // diff: .git extension
targets: [
MockTarget(name: "Bar"),
],
products: [
MockProduct(name: "Bar", targets: ["Bar"]),
],
versions: ["1.0.0", "1.1.0"],
revisionProvider: { version in version } // stable revisions
),
]
)
// case 1: initial loading
var deps: [MockDependency] = [
.sourceControl(url: "https://localhost/org/foo", requirement: .exact("1.0.0")),
.sourceControl(url: "https://localhost/org/bar", requirement: .exact("1.0.0")),
]
try workspace.checkPackageGraph(roots: ["Root"], deps: deps) { graph, 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")))
XCTAssertEqual(result.managedDependencies[.plain("foo")]?.packageRef.locationString, "https://localhost/org/foo")
XCTAssertEqual(result.managedDependencies[.plain("bar")]?.packageRef.locationString, "https://localhost/org/bar")
}
workspace.checkResolved { result in
result.check(dependency: "foo", at: .checkout(.version("1.0.0")))
result.check(dependency: "bar", at: .checkout(.version("1.0.0")))
XCTAssertEqual(result.store.pinsMap[.plain("foo")]?.packageRef.locationString, "https://localhost/org/foo")
XCTAssertEqual(result.store.pinsMap[.plain("bar")]?.packageRef.locationString, "https://localhost/org/bar")
}
// case 2: set state with slightly different URLs that are canonically the same
deps = [
.sourceControl(url: "https://localhost/ORG/FOO", requirement: .exact("1.0.0")),
.sourceControl(url: "https://localhost/org/bar.git", requirement: .exact("1.0.0")),
]
// reset state, excluding the resolved file
workspace.checkReset { XCTAssertNoDiagnostics($0) }
workspace.closeWorkspace()
XCTAssertTrue(fs.exists(sandbox.appending(component: "Package.resolved")))
// run update
try workspace.checkUpdate(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")))
// URLs should reflect the actual dependencies
XCTAssertEqual(result.managedDependencies[.plain("foo")]?.packageRef.locationString, "https://localhost/ORG/FOO")
XCTAssertEqual(result.managedDependencies[.plain("bar")]?.packageRef.locationString, "https://localhost/org/bar.git")
}
workspace.checkResolved { result in
result.check(dependency: "foo", at: .checkout(.version("1.0.0")))
result.check(dependency: "bar", at: .checkout(.version("1.0.0")))
// URLs should be stable since URLs are canonically the same and we kept the resolved file between the two iterations
XCTAssertEqual(result.store.pinsMap[.plain("foo")]?.packageRef.locationString, "https://localhost/org/foo")
XCTAssertEqual(result.store.pinsMap[.plain("bar")]?.packageRef.locationString, "https://localhost/org/bar")
}
// case 2: set state with slightly different URLs that are canonically the same but request different versions
deps = [
.sourceControl(url: "https://localhost/ORG/FOO", requirement: .exact("1.1.0")),
.sourceControl(url: "https://localhost/org/bar.git", requirement: .exact("1.1.0")),
]
// reset state, excluding the resolved file
workspace.checkReset { XCTAssertNoDiagnostics($0) }
workspace.closeWorkspace()
XCTAssertTrue(fs.exists(sandbox.appending(component: "Package.resolved")))
// run update
try workspace.checkUpdate(roots: ["Root"], deps: deps) { diagnostics in
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkManagedDependencies { result in
result.check(dependency: "foo", at: .checkout(.version("1.1.0")))
result.check(dependency: "bar", at: .checkout(.version("1.1.0")))
// URLs should reflect the actual dependencies
XCTAssertEqual(result.managedDependencies[.plain("foo")]?.packageRef.locationString, "https://localhost/ORG/FOO")
XCTAssertEqual(result.managedDependencies[.plain("bar")]?.packageRef.locationString, "https://localhost/org/bar.git")
}
workspace.checkResolved { result in
result.check(dependency: "foo", at: .checkout(.version("1.1.0")))
result.check(dependency: "bar", at: .checkout(.version("1.1.0")))
// URLs should reflect the actual dependencies since the new version forces rewrite of the resolved file
XCTAssertEqual(result.store.pinsMap[.plain("foo")]?.packageRef.locationString, "https://localhost/ORG/FOO")
XCTAssertEqual(result.store.pinsMap[.plain("bar")]?.packageRef.locationString, "https://localhost/org/bar.git")
}
// case 3: set state with slightly different URLs that are canonically the same but remove resolved file
deps = [
.sourceControl(url: "https://localhost/org/foo.git", requirement: .exact("1.0.0")),
.sourceControl(url: "https://localhost/org/bar.git", requirement: .exact("1.0.0")),
]
// reset state, including the resolved file
workspace.checkReset { XCTAssertNoDiagnostics($0) }
try fs.removeFileTree(sandbox.appending(component: "Package.resolved"))
XCTAssertFalse(fs.exists(sandbox.appending(component: "Package.resolved")))
// run update
try workspace.checkUpdate(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")))
// URLs should reflect the actual dependencies
XCTAssertEqual(result.managedDependencies[.plain("foo")]?.packageRef.locationString, "https://localhost/org/foo.git")
XCTAssertEqual(result.managedDependencies[.plain("bar")]?.packageRef.locationString, "https://localhost/org/bar.git")
}
workspace.checkResolved { result in
result.check(dependency: "foo", at: .checkout(.version("1.0.0")))
result.check(dependency: "bar", at: .checkout(.version("1.0.0")))
// URLs should reflect the actual dependencies since we deleted the resolved file
XCTAssertEqual(result.store.pinsMap[.plain("foo")]?.packageRef.locationString, "https://localhost/org/foo.git")
XCTAssertEqual(result.store.pinsMap[.plain("bar")]?.packageRef.locationString, "https://localhost/org/bar.git")
}
}
func testPackageMirror() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let mirrors = DependencyMirrors()
mirrors.set(mirrorURL: sandbox.appending(components: "pkgs", "Baz").pathString, forURL: sandbox.appending(components: "pkgs", "Bar").pathString)
mirrors.set(mirrorURL: sandbox.appending(components: "pkgs", "Baz").pathString, forURL: sandbox.appending(components: "pkgs", "Bam").pathString)
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
mirrors: mirrors,
roots: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo", dependencies: ["Dep"]),
],
products: [
MockProduct(name: "Foo", targets: ["Foo"]),
],
dependencies: [
.sourceControl(path: "./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: [
.sourceControl(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"]
),
]
)
let deps: [MockDependency] = [
.sourceControl(path: "./Bam", requirement: .upToNextMajor(from: "1.0.0"), products: .specific(["Bar"])),
]
try 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")
}
}
// In this test, we get into a state where an entry in the resolved
// file for a transitive dependency whose URL is later changed to
// something else, while keeping the same package identity.
func testTransitiveDependencySwitchWithSameIdentity() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
// Use the same revision (hash) for "foo" to indicate they are the same
// package despite having different URLs.
let fooRevision = String((UUID().uuidString + UUID().uuidString).prefix(40))
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "Root",
targets: [
MockTarget(
name: "Root",
dependencies: [
.product(name: "Bar", package: "bar")
]),
],
products: [],
dependencies: [
.sourceControl(url: "https://scm.com/org/bar", requirement: .upToNextMajor(from: "1.0.0")),
]
),
],
packages: [
MockPackage(
name: "Bar",
url: "https://scm.com/org/bar",
targets: [
MockTarget(
name: "Bar",
dependencies: [
.product(name: "Foo", package: "foo")
]),
],
products: [
MockProduct(name: "Bar", targets: ["Bar"]),
],
dependencies: [
.sourceControl(url: "https://scm.com/org/foo", requirement: .upToNextMajor(from: "1.0.0")),
],
versions: ["1.0.0"]
),
MockPackage(
name: "Bar",
url: "https://scm.com/org/bar",
targets: [
MockTarget(
name: "Bar",
dependencies: [
.product(name: "OtherFoo", package: "foo")
]),
],
products: [
MockProduct(name: "Bar", targets: ["Bar"]),
],
dependencies: [
.sourceControl(url: "https://scm.com/other/foo", requirement: .upToNextMajor(from: "1.0.0")),
],
versions: ["1.1.0"],
toolsVersion: .v5
),
MockPackage(
name: "Foo",
url: "https://scm.com/org/foo",
targets: [
MockTarget(name: "Foo"),
],
products: [
MockProduct(name: "Foo", targets: ["Foo"]),
],
versions: ["1.0.0"],
revisionProvider: { _ in fooRevision }
),
MockPackage(
name: "Foo",
url: "https://scm.com/other/foo",
targets: [
MockTarget(name: "OtherFoo"),
],
products: [
MockProduct(name: "OtherFoo", targets: ["OtherFoo"]),
],
versions: ["1.0.0"],
revisionProvider: { _ in fooRevision }
),
]
)
var deps: [MockDependency] = [
.sourceControl(url: "https://scm.com/org/bar", requirement: .exact("1.0.0")),
]
try workspace.checkPackageGraph(roots: ["Root"], deps: deps) { graph, diagnostics in
XCTAssertNoDiagnostics(diagnostics)
PackageGraphTester(graph) { result in
result.check(roots: "Root")
result.check(packages: "Bar", "Foo", "Root")
}
}
workspace.checkManagedDependencies { result in
result.check(dependency: "foo", at: .checkout(.version("1.0.0")))
result.check(dependency: "bar", at: .checkout(.version("1.0.0")))
XCTAssertEqual(result.managedDependencies[.plain("foo")]?.packageRef.locationString, "https://scm.com/org/foo")
}
workspace.checkResolved { result in
result.check(dependency: "foo", at: .checkout(.version("1.0.0")))
result.check(dependency: "bar", at: .checkout(.version("1.0.0")))
XCTAssertEqual(result.store.pinsMap[.plain("foo")]?.packageRef.locationString, "https://scm.com/org/foo")
}
// reset state
workspace.checkReset { XCTAssertNoDiagnostics($0) }
deps = [
.sourceControl(url: "https://scm.com/org/bar", requirement: .exact("1.1.0")),
]
try workspace.checkPackageGraph(roots: ["Root"], deps: deps) { graph, diagnostics in
XCTAssertNoDiagnostics(diagnostics)
PackageGraphTester(graph) { result in
result.check(roots: "Root")
result.check(packages: "Bar", "Foo", "Root")
}
}
workspace.checkManagedDependencies { result in
result.check(dependency: "foo", at: .checkout(.version("1.0.0")))
result.check(dependency: "bar", at: .checkout(.version("1.1.0")))
XCTAssertEqual(result.managedDependencies[.plain("foo")]?.packageRef.locationString, "https://scm.com/other/foo")
}
workspace.checkResolved { result in
result.check(dependency: "foo", at: .checkout(.version("1.0.0")))
result.check(dependency: "bar", at: .checkout(.version("1.1.0")))
XCTAssertEqual(result.store.pinsMap[.plain("foo")]?.packageRef.locationString, "https://scm.com/other/foo")
}
}
func testForceResolveToResolvedVersions() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "Root",
targets: [
MockTarget(name: "Root", dependencies: ["Foo", "Bar"]),
],
products: [],
dependencies: [
.sourceControl(path: "./Foo", requirement: .upToNextMajor(from: "1.0.0")),
.sourceControl(path: "./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] = [
.sourceControl(path: "./Bar", requirement: .revision("develop"), products: .specific(["Bar"])),
]
try 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 = try workspace.getOrCreateWorkspace()
let pinsStore = try ws.pinsStore.load()
let fooPin = pinsStore.pins.first(where: { $0.packageRef.identity.description == "foo" })!
let fooRepo = workspace.repositoryProvider.specifierMap[RepositorySpecifier(path: AbsolutePath(fooPin.packageRef.locationString))]!
let revision = try fooRepo.resolveRevision(tag: "1.0.0")
let newState = PinsStore.PinState.version("1.0.0", revision: revision.identifier)
pinsStore.pin(packageRef: fooPin.packageRef, state: newState)
try pinsStore.saveState(toolsVersion: ToolsVersion.currentToolsVersion)
}
// Check force resolve. This should produce an error because the resolved file is out-of-date.
workspace.checkPackageGraphFailure(roots: ["Root"], forceResolvedVersions: true) { diagnostics in
testDiagnostics(diagnostics) { result in
result.check(diagnostic: "an out-of-date resolved file was detected at /tmp/ws/Package.resolved, which is not allowed when automatic dependency resolution is disabled; please make sure to update the file to reflect the changes in dependencies. Running resolver because requirements have changed.", severity: .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.
try 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.
try 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 testForceResolveWithNoResolvedFile() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "Root",
targets: [
MockTarget(name: "Root", dependencies: ["Foo", "Bar"]),
],
products: [],
dependencies: [
.sourceControl(path: "./Foo", requirement: .upToNextMajor(from: "1.0.0")),
.sourceControl(path: "./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"]
),
]
)
workspace.checkPackageGraphFailure(roots: ["Root"], forceResolvedVersions: true) { diagnostics in
guard let diagnostic = diagnostics.first else { return XCTFail("unexpectedly got no diagnostics") }
// rdar://82544922 (`WorkspaceResolveReason` is non-deterministic)
XCTAssertTrue(diagnostic.message.hasPrefix("a resolved file is required when automatic dependency resolution is disabled and should be placed at /tmp/ws/Package.resolved. Running resolver because the following dependencies were added:"), "unexpected diagnostic message")
}
}
func testForceResolveToResolvedVersionsLocalPackage() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "Root",
targets: [
MockTarget(name: "Root", dependencies: ["Foo"]),
],
products: [],
dependencies: [
.fileSystem(path: "./Foo"),
]
),
],
packages: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo"),
],
products: [
MockProduct(name: "Foo", targets: ["Foo"]),
],
versions: [nil]
),
]
)
try workspace.checkPackageGraph(roots: ["Root"], forceResolvedVersions: true) { _, diagnostics in
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkManagedDependencies { result in
result.check(dependency: "foo", at: .local)
}
}
// This verifies that the simplest possible loading APIs are available for package clients.
func testSimpleAPI() throws {
try testWithTemporaryDirectory { path in
// Create a temporary package as a test case.
let packagePath = path.appending(component: "MyPkg")
let initPackage = try InitPackage(name: packagePath.basename, destinationPath: packagePath, packageType: .executable)
try initPackage.writePackageStructure()
// Load the workspace.
let observability = ObservabilitySystem.makeForTesting()
let workspace = try Workspace(forRootPackage: packagePath, customToolchain: UserToolchain.default)
// From here the API should be simple and straightforward:
let manifest = try tsc_await {
workspace.loadRootManifest(
at: packagePath,
observabilityScope: observability.topScope,
completion: $0
)
}
XCTAssertFalse(observability.hasWarningDiagnostics, observability.diagnostics.description)
XCTAssertFalse(observability.hasErrorDiagnostics, observability.diagnostics.description)
let package = try tsc_await {
workspace.loadRootPackage(
at: packagePath,
observabilityScope: observability.topScope,
completion: $0
)
}
XCTAssertFalse(observability.hasWarningDiagnostics, observability.diagnostics.description)
XCTAssertFalse(observability.hasErrorDiagnostics, observability.diagnostics.description)
let graph = try workspace.loadPackageGraph(
rootPath: packagePath,
observabilityScope: observability.topScope
)
XCTAssertFalse(observability.hasWarningDiagnostics, observability.diagnostics.description)
XCTAssertFalse(observability.hasErrorDiagnostics, observability.diagnostics.description)
XCTAssertEqual(manifest.displayName, "MyPkg")
XCTAssertEqual(package.identity, .plain(manifest.displayName))
XCTAssert(graph.reachableProducts.contains(where: { $0.name == "MyPkg" }))
}
}
func testRevisionDepOnLocal() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "Root",
targets: [
MockTarget(name: "Root", dependencies: ["Foo"]),
],
products: [],
dependencies: [
.sourceControl(path: "./Foo", requirement: .branch("develop")),
]
),
],
packages: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo", dependencies: ["Local"]),
],
products: [
MockProduct(name: "Foo", targets: ["Foo"]),
],
dependencies: [
.fileSystem(path: "./Local"),
],
versions: ["develop"]
),
MockPackage(
name: "Local",
targets: [
MockTarget(name: "Local"),
],
products: [
MockProduct(name: "Local", targets: ["Local"]),
],
versions: [nil]
),
]
)
try workspace.checkPackageGraph(roots: ["Root"]) { _, diagnostics in
testDiagnostics(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"), severity: .error)
}
}
}
func testRootPackagesOverrideBasenameMismatch() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: 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] = [
.sourceControl(path: "./bazzz", requirement: .exact("1.0.0"), products: .specific(["Baz"])),
]
try workspace.checkPackageGraphFailure(roots: ["Overridden/bazzz-master"], deps: deps) { diagnostics in
testDiagnostics(diagnostics) { result in
result.check(diagnostic: .equal("unable to override package 'Baz' because its identity 'bazzz' doesn't match override's identity (directory name) 'bazzz-master'"), severity: .error)
}
}
}
func testManagedDependenciesNotCaseSensitive() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo", dependencies: [
.product(name: "Bar", package: "bar"),
.product(name: "Baz", package: "baz")
])
],
products: [],
dependencies: [
.sourceControl(url: "https://localhost/org/bar", requirement: .upToNextMajor(from: "1.0.0")),
.sourceControl(url: "https://localhost/org/baz", requirement: .upToNextMajor(from: "1.0.0"))
]
),
],
packages: [
MockPackage(
name: "Bar",
url: "https://localhost/org/bar",
targets: [
MockTarget(name: "Bar", dependencies: [
.product(name: "Baz", package: "Baz")
]),
],
products: [
MockProduct(name: "Bar", targets: ["Bar"])
],
dependencies: [
.sourceControl(url: "https://localhost/org/Baz", requirement: .upToNextMajor(from: "1.0.0"))
],
versions: ["1.0.0"]
),
MockPackage(
name: "Baz",
url: "https://localhost/org/baz",
targets: [
MockTarget(name: "Baz"),
],
products: [
MockProduct(name: "Baz", targets: ["Baz"])
],
versions: ["1.0.0"]
),
MockPackage(
name: "Baz",
url: "https://localhost/org/Baz",
targets: [
MockTarget(name: "Baz"),
],
products: [
MockProduct(name: "Baz", targets: ["Baz"])
],
versions: ["1.0.0"]
),
]
)
try workspace.checkPackageGraph(roots: ["Foo"]) { graph, diagnostics in
PackageGraphTester(graph) { result in
result.check(roots: "Foo")
result.check(packages: "Bar", "Baz", "Foo")
result.checkTarget("Foo") { result in result.check(dependencies: "Bar", "Baz") }
result.checkTarget("Bar") { result in result.check(dependencies: "Baz") }
}
testDiagnostics(diagnostics, minSeverity: .info) { result in
result.checkUnordered(
diagnostic: "dependency on 'baz' is represented by similar locations ('https://localhost/org/baz' and 'https://localhost/org/Baz') which are treated as the same canonical location 'localhost/org/baz'.",
severity: .info
)
}
}
workspace.checkManagedDependencies { result in
result.check(dependency: "bar", at: .checkout(.version("1.0.0")))
result.check(dependency: "baz", at: .checkout(.version("1.0.0")))
XCTAssertEqual(result.managedDependencies[.plain("bar")]?.packageRef.locationString, "https://localhost/org/bar")
// root casing should win, so testing for lower case
XCTAssertEqual(result.managedDependencies[.plain("baz")]?.packageRef.locationString, "https://localhost/org/baz")
}
}
func testUnsafeFlags() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: 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: [
.fileSystem(path: "./Bar"),
.sourceControl(path: "./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: [
.sourceControl(path: "./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.
try workspace.checkPackageGraph(roots: ["Foo", "Bar"]) { _, diagnostics in
testDiagnostics(diagnostics) { result in
let diagnostic1 = result.checkUnordered(
diagnostic: .equal("the target 'Baz' in product 'Baz' contains unsafe build flags"),
severity: .error
)
XCTAssertEqual(diagnostic1?.metadata?.targetName, "Foo")
let diagnostic2 = result.checkUnordered(
diagnostic: .equal("the target 'Bar' in product 'Baz' contains unsafe build flags"),
severity: .error
)
XCTAssertEqual(diagnostic2?.metadata?.targetName, "Foo")
}
}
}
func testEditDependencyHadOverridableConstraints() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "Root",
targets: [
MockTarget(name: "Root", dependencies: ["Foo", "Baz"]),
],
products: [],
dependencies: [
.sourceControl(path: "./Foo", requirement: .branch("master")),
.sourceControl(path: "./Baz", requirement: .upToNextMajor(from: "1.0.0")),
]
),
],
packages: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo", dependencies: ["Bar"]),
],
products: [
MockProduct(name: "Foo", targets: ["Foo"]),
],
dependencies: [
.sourceControl(path: "./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: [
.sourceControl(path: "./Bar", requirement: .upToNextMajor(from: "1.0.0")),
],
versions: ["1.0.0", nil]
),
]
)
// Load the graph.
try 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 = try workspace.getOrCreateWorkspace().location.editsDirectory.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()
try 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 {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let barProducts: [MockProduct]
#if ENABLE_TARGET_BASED_DEPENDENCY_RESOLUTION
barProducts = [MockProduct(name: "Bar", targets: ["Bar"]), MockProduct(name: "BarUnused", targets: ["BarUnused"])]
#else
// Whether a product is being used does not affect dependency resolution in this case, so we omit the unused product.
barProducts = [MockProduct(name: "Bar", targets: ["Bar"])]
#endif
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "Root",
targets: [
MockTarget(name: "Root", dependencies: ["Foo", "Bar"]),
MockTarget(name: "RootTests", dependencies: ["TestHelper1"], type: .test),
],
products: [],
dependencies: [
.sourceControl(path: "./Foo", requirement: .upToNextMajor(from: "1.0.0")),
.sourceControl(path: "./Bar", requirement: .upToNextMajor(from: "1.0.0")),
.sourceControl(path: "./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: [
.sourceControl(path: "./TestHelper2", requirement: .upToNextMajor(from: "1.0.0")),
.sourceControl(path: "./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: barProducts,
dependencies: [
.sourceControl(path: "./TestHelper2", requirement: .upToNextMajor(from: "1.0.0")),
.sourceControl(path: "./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
)
// Load the graph.
try 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 testLocalArchivedArtifactExtractionHappyPath() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
// create dummy xcframework and artifactbundle directories from the request archive
let archiver = MockArchiver(handler: { archiver, archivePath, destinationPath, completion in
do {
let name: String
switch archivePath.basename {
case "A1.zip":
name = "A1.xcframework"
case "A2.zip":
name = "A2.artifactbundle"
case "B.zip":
name = "B.xcframework"
default:
throw StringError("unexpected archivePath \(archivePath)")
}
try fs.createDirectory(destinationPath.appending(component: name), recursive: false)
archiver.extractions.append(MockArchiver.Extraction(archivePath: archivePath, destinationPath: destinationPath))
completion(.success(()))
} catch {
completion(.failure(error))
}
})
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo", dependencies: [
.product(name: "A1", package: "A"),
.product(name: "A2", package: "A"),
.product(name: "B", package: "B"),
])
],
products: [],
dependencies: [
.sourceControl(path: "./A", requirement: .exact("1.0.0")),
.sourceControl(path: "./B", requirement: .exact("1.0.0")),
]
),
],
packages: [
MockPackage(
name: "A",
targets: [
MockTarget(
name: "A1",
type: .binary,
path: "XCFrameworks/A1.zip"
),
MockTarget(
name: "A2",
type: .binary,
path: "ArtifactBundles/A2.zip"
),
],
products: [
MockProduct(name: "A1", targets: ["A1"]),
MockProduct(name: "A2", targets: ["A2"]),
],
versions: ["1.0.0"]
),
MockPackage(
name: "B",
targets: [
MockTarget(
name: "B",
type: .binary,
path: "XCFrameworks/B.zip"
)
],
products: [
MockProduct(name: "B", targets: ["B"])
],
versions: ["1.0.0"]
)
],
customBinaryArchiver: archiver
)
// Create dummy xcframework/artifactbundle zip files
let aPath = workspace.packagesDir.appending(components: "A")
let aFrameworksPath = aPath.appending(component: "XCFrameworks")
let a1FrameworkArchivePath = aFrameworksPath.appending(component: "A1.zip")
try fs.createDirectory(aFrameworksPath, recursive: true)
try fs.writeFileContents(a1FrameworkArchivePath, bytes: ByteString([0xA1]))
let aArtifactBundlesPath = aPath.appending(component: "ArtifactBundles")
let a2ArtifactBundleArchivePath = aArtifactBundlesPath.appending(component: "A2.zip")
try fs.createDirectory(aArtifactBundlesPath, recursive: true)
try fs.writeFileContents(a2ArtifactBundleArchivePath, bytes: ByteString([0xA2]))
let bPath = workspace.packagesDir.appending(components: "B")
let bFrameworksPath = bPath.appending(component: "XCFrameworks")
let bFrameworkArchivePath = bFrameworksPath.appending(component: "B.zip")
try fs.createDirectory(bFrameworksPath, recursive: true)
try fs.writeFileContents(bFrameworkArchivePath, bytes: ByteString([0xB0]))
// Ensure that the artifacts do not exist yet
XCTAssertFalse(fs.isDirectory(AbsolutePath("/tmp/ws/.build/artifacts/A/A1.xcframework")))
XCTAssertFalse(fs.isDirectory(AbsolutePath("/tmp/ws/.build/artifacts/A/A2.artifactbundle")))
XCTAssertFalse(fs.isDirectory(AbsolutePath("/tmp/ws/.build/artifacts/B/B.xcframework")))
try workspace.checkPackageGraph(roots: ["Foo"]) { graph, diagnostics in
XCTAssertNoDiagnostics(diagnostics)
// Ensure that the artifacts have been properly extracted
XCTAssertTrue(fs.isDirectory(AbsolutePath("/tmp/ws/.build/artifacts/a/A1.xcframework")))
XCTAssertTrue(fs.isDirectory(AbsolutePath("/tmp/ws/.build/artifacts/a/A2.artifactbundle")))
XCTAssertTrue(fs.isDirectory(AbsolutePath("/tmp/ws/.build/artifacts/b/B.xcframework")))
// Ensure that the original archives have been untouched
XCTAssertTrue(fs.exists(a1FrameworkArchivePath))
XCTAssertTrue(fs.exists(a2ArtifactBundleArchivePath))
XCTAssertTrue(fs.exists(bFrameworkArchivePath))
// Ensure that the temporary folders have been properly created
XCTAssertEqual(workspace.archiver.extractions.map { $0.destinationPath.parentDirectory }.sorted(), [
AbsolutePath("/tmp/ws/.build/artifacts/extract/a/A1"),
AbsolutePath("/tmp/ws/.build/artifacts/extract/a/A2"),
AbsolutePath("/tmp/ws/.build/artifacts/extract/b/B")
])
// Ensure that the temporary directories have been removed
XCTAssertTrue(try! fs.getDirectoryContents(AbsolutePath("/tmp/ws/.build/artifacts/extract/a/A1")).isEmpty)
XCTAssertTrue(try! fs.getDirectoryContents(AbsolutePath("/tmp/ws/.build/artifacts/extract/a/A2")).isEmpty)
XCTAssertTrue(try! fs.getDirectoryContents(AbsolutePath("/tmp/ws/.build/artifacts/extract/b/B")).isEmpty)
}
workspace.checkManagedArtifacts { result in
result.check(packageIdentity: .plain("a"),
targetName: "A1",
source: .local(checksum: "a1"),
path: workspace.artifactsDir.appending(components: "a", "A1.xcframework")
)
result.check(packageIdentity: .plain("a"),
targetName: "A2",
source: .local(checksum: "a2"),
path: workspace.artifactsDir.appending(components: "a", "A2.artifactbundle")
)
result.check(packageIdentity: .plain("b"),
targetName: "B",
source: .local(checksum: "b0"),
path: workspace.artifactsDir.appending(components: "b", "B.xcframework")
)
}
}
// There are 6 possible transition permutations of the artifact source set
// {local, local-archived, and remote}, namely:
//
// (remote -> local)
// (local -> remote)
// (local -> local-archived)
// (local-archived -> local)
// (remote -> local-archived)
// (local-archived -> remote)
//
// This test covers the last 4 permutations where the `local-archived` source is involved.
// It ensures that all the appropriate clean-up operations are executed, and the workspace
// contains the correct set of managed artifacts after the transition.
func testLocalArchivedArtifactSourceTransitionPermutations() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let a1FrameworkName = "A1.xcframework"
let a2FrameworkName = "A2.xcframework"
let a3FrameworkName = "A3.xcframework"
let a4FrameworkName = "A4.xcframework"
let a5FrameworkName = "A5.xcframework"
// returns a dummy zipfile for the requested artifact
let httpClient = HTTPClient(handler: { request, _, completion in
do {
guard case .download(let fileSystem, let destination) = request.kind else {
throw StringError("invalid request \(request.kind)")
}
let contents: [UInt8]
switch request.url.lastPathComponent {
case "a4.zip":
contents = [0xA4]
default:
throw StringError("unexpected url \(request.url)")
}
try fileSystem.writeFileContents(
destination,
bytes: ByteString(contents),
atomically: true
)
completion(.success(.okay()))
} catch {
completion(.failure(error))
}
})
// create a dummy xcframework directory (with a marker subdirectory) from the request archive
let archiver = MockArchiver(handler: { archiver, archivePath, destinationPath, completion in
do {
let name: String
var subdirectoryName: String?
switch archivePath.basename {
case "A1.zip":
name = a1FrameworkName
case "A2.zip":
name = a2FrameworkName
case "A3.zip":
name = a3FrameworkName
subdirectoryName = "local-archived"
case "a4.zip":
name = a4FrameworkName
subdirectoryName = "remote"
default:
throw StringError("unexpected archivePath \(archivePath)")
}
try fs.createDirectory(destinationPath.appending(component: name), recursive: false)
if let subdirectoryName = subdirectoryName {
try fs.createDirectory(destinationPath.appending(components: name, subdirectoryName), recursive: false)
}
archiver.extractions.append(MockArchiver.Extraction(archivePath: archivePath, destinationPath: destinationPath))
completion(.success(()))
} catch {
completion(.failure(error))
}
})
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo", dependencies: [
.product(name: "A1", package: "A"),
.product(name: "A2", package: "A"),
.product(name: "A3", package: "A"),
.product(name: "A4", package: "A")
]),
],
products: [],
dependencies: [
.sourceControl(path: "./A", requirement: .exact("1.0.0"))
]
),
],
packages: [
MockPackage(
name: "A",
targets: [
MockTarget(
name: "A1",
type: .binary,
path: "XCFrameworks/A1.zip"
),
MockTarget(
name: "A2",
type: .binary,
path: "XCFrameworks/\(a2FrameworkName)"
),
MockTarget(
name: "A3",
type: .binary,
path: "XCFrameworks/A3.zip"
),
MockTarget(
name: "A4",
type: .binary,
url: "https://a.com/a4.zip",
checksum: "a4"
)
],
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"]
)
],
customHttpClient: httpClient,
customBinaryArchiver: archiver
)
// Create dummy xcframework directories and zip files
let aFrameworksPath = workspace.packagesDir.appending(components: "A", "XCFrameworks")
try fs.createDirectory(aFrameworksPath, recursive: true)
let a1FrameworkPath = aFrameworksPath.appending(component: a1FrameworkName)
let a1FrameworkArchivePath = aFrameworksPath.appending(component: "A1.zip")
try fs.createDirectory(a1FrameworkPath, recursive: true)
try fs.writeFileContents(a1FrameworkArchivePath, bytes: ByteString([0xA1]))
let a2FrameworkPath = aFrameworksPath.appending(component: a2FrameworkName)
let a2FrameworkArchivePath = aFrameworksPath.appending(component: "A2.zip")
try fs.createDirectory(a2FrameworkPath, recursive: true)
try fs.writeFileContents(a2FrameworkArchivePath, bytes: ByteString([0xA2]))
let a3FrameworkArchivePath = aFrameworksPath.appending(component: "A3.zip")
try fs.writeFileContents(a3FrameworkArchivePath, bytes: ByteString([0xA3]))
let a4FrameworkArchivePath = aFrameworksPath.appending(component: "A4.zip")
try fs.writeFileContents(a4FrameworkArchivePath, bytes: ByteString([0xA4]))
// Pin A to 1.0.0, Checkout B to 1.0.0
let aPath = workspace.pathToPackage(withName: "A")
let aRef = PackageReference.localSourceControl(identity: PackageIdentity(path: aPath), path: aPath)
let aRepo = workspace.repositoryProvider.specifierMap[RepositorySpecifier(path: aPath)]!
let aRevision = try aRepo.resolveRevision(tag: "1.0.0")
let aState = CheckoutState.version("1.0.0", revision: aRevision)
// Set an initial workspace state
try workspace.set(
pins: [aRef: aState],
managedDependencies: [],
managedArtifacts: [
.init(
packageRef: aRef,
targetName: "A1",
source: .local(),
path: a1FrameworkPath
),
.init(
packageRef: aRef,
targetName: "A2",
source: .local(checksum: "a2"),
path: workspace.artifactsDir.appending(components: "A", a2FrameworkName)
),
.init(
packageRef: aRef,
targetName: "A3",
source: .remote(url: "https://a.com/a3.zip", checksum: "a3"),
path: workspace.artifactsDir.appending(components: "A", a3FrameworkName)
),
.init(
packageRef: aRef,
targetName: "A4",
source: .local(checksum: "a4"),
path: workspace.artifactsDir.appending(components: "A", a4FrameworkName)
),
.init(
packageRef: aRef,
targetName: "A5",
source: .local(checksum: "a5"),
path: workspace.artifactsDir.appending(components: "A", a5FrameworkName)
)
]
)
// Create marker folders to later check that the frameworks' content is properly overwritten
try fs.createDirectory(workspace.artifactsDir.appending(components: "A", a3FrameworkName, "remote"), recursive: true)
try fs.createDirectory(workspace.artifactsDir.appending(components: "A", a4FrameworkName, "local-archived"), recursive: true)
try workspace.checkPackageGraph(roots: ["Foo"]) { graph, diagnostics in
XCTAssertNoDiagnostics(diagnostics)
// Ensure that the original archives have been untouched
XCTAssertTrue(fs.exists(a1FrameworkArchivePath))
XCTAssertTrue(fs.exists(a2FrameworkArchivePath))
XCTAssertTrue(fs.exists(a3FrameworkArchivePath))
XCTAssertTrue(fs.exists(a4FrameworkArchivePath))
// Ensure that the new artifacts have been properly extracted
XCTAssertTrue(fs.exists(AbsolutePath("/tmp/ws/.build/artifacts/a/\(a1FrameworkName)")))
XCTAssertTrue(fs.exists(AbsolutePath("/tmp/ws/.build/artifacts/a/\(a3FrameworkName)/local-archived")))
XCTAssertTrue(fs.exists(AbsolutePath("/tmp/ws/.build/artifacts/a/\(a4FrameworkName)/remote")))
// Ensure that the old artifacts have been removed
XCTAssertFalse(fs.exists(AbsolutePath("/tmp/ws/.build/artifacts/a/\(a2FrameworkName)")))
XCTAssertFalse(fs.exists(AbsolutePath("/tmp/ws/.build/artifacts/a/\(a3FrameworkName)/remote")))
XCTAssertFalse(fs.exists(AbsolutePath("/tmp/ws/.build/artifacts/a/\(a4FrameworkName)/local-archived")))
XCTAssertFalse(fs.exists(AbsolutePath("/tmp/ws/.build/artifacts/a/\(a5FrameworkName)")))
}
workspace.checkManagedArtifacts { result in
result.check(packageIdentity: .plain("a"),
targetName: "A1",
source: .local(checksum: "a1"),
path: workspace.artifactsDir.appending(components: "a", a1FrameworkName)
)
result.check(packageIdentity: .plain("a"),
targetName: "A2",
source: .local(),
path: a2FrameworkPath
)
result.check(packageIdentity: .plain("a"),
targetName: "A3",
source: .local(checksum: "a3"),
path: workspace.artifactsDir.appending(components: "a", a3FrameworkName)
)
result.check(packageIdentity: .plain("a"),
targetName: "A4",
source: .remote(url: "https://a.com/a4.zip", checksum: "a4"),
path: workspace.artifactsDir.appending(components: "a", a4FrameworkName)
)
}
}
func testLocalArchivedArtifactNameDoesNotMatchTargetName() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
// create a dummy xcframework directory from the request archive
let archiver = MockArchiver(handler: { archiver, archivePath, destinationPath, completion in
do {
let name: String
switch archivePath.basename {
case "archived-artifact-does-not-match-target-name.zip":
name = "A1.xcframework"
default:
throw StringError("unexpected archivePath \(archivePath)")
}
try fs.createDirectory(destinationPath.appending(component: name), recursive: false)
archiver.extractions.append(MockArchiver.Extraction(archivePath: archivePath, destinationPath: destinationPath))
completion(.success(()))
} catch {
completion(.failure(error))
}
})
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo", dependencies: [
.product(name: "A1", package: "A")
]),
],
products: [],
dependencies: [
.sourceControl(path: "./A", requirement: .exact("1.0.0"))
]
),
],
packages: [
MockPackage(
name: "A",
targets: [
MockTarget(
name: "A1",
type: .binary,
path: "XCFrameworks/archived-artifact-does-not-match-target-name.zip"
)
],
products: [
MockProduct(name: "A1", targets: ["A1"])
],
versions: ["1.0.0"]
),
],
customBinaryArchiver: archiver
)
// Create dummy zip files
let aFrameworksPath = workspace.packagesDir.appending(components: "A", "XCFrameworks")
try fs.createDirectory(aFrameworksPath, recursive: true)
try fs.writeFileContents(aFrameworksPath.appending(component: "archived-artifact-does-not-match-target-name.zip"), bytes: ByteString([0xA1]))
workspace.checkPackageGraphFailure(roots: ["Foo"]) { diagnostics in
XCTAssertNoDiagnostics(diagnostics)
}
}
func testLocalArchivedArtifactExtractionError() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let archiver = MockArchiver(handler: { _, _, destinationPath, completion in
completion(.failure(DummyError()))
})
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo", dependencies: [
.product(name: "A1", package: "A")
]),
],
products: [],
dependencies: [
.sourceControl(path: "./A", requirement: .exact("1.0.0"))
]
),
],
packages: [
MockPackage(
name: "A",
targets: [
MockTarget(
name: "A1",
type: .binary,
path: "XCFrameworks/A1.zip"
),
MockTarget(
name: "A2",
type: .binary,
path: "ArtifactBundles/A2.zip"
)
],
products: [
MockProduct(name: "A1", targets: ["A1"]),
MockProduct(name: "A2", targets: ["A2"])
],
versions: ["1.0.0"]
),
],
customBinaryArchiver: archiver
)
workspace.checkPackageGraphFailure(roots: ["Foo"]) { diagnostics in
testDiagnostics(diagnostics) { result in
result.checkUnordered(diagnostic: .contains("failed extracting '/tmp/ws/pkgs/A/XCFrameworks/A1.zip' which is required by binary target 'A1': dummy error"), severity: .error)
result.checkUnordered(diagnostic: .contains("failed extracting '/tmp/ws/pkgs/A/ArtifactBundles/A2.zip' which is required by binary target 'A2': dummy error"), severity: .error)
}
}
}
func testLocalArchiveContainsArtifactWithIncorrectName() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
// create dummy xcframework and artifactbundle directories from the request archive
let archiver = MockArchiver(handler: { archiver, archivePath, destinationPath, completion in
do {
let name: String
switch archivePath.basename {
case "A1.zip":
name = "incorrect-name.xcframework"
case "A2.zip":
name = "incorrect-name.artifactbundle"
default:
throw StringError("unexpected archivePath \(archivePath)")
}
try fs.createDirectory(destinationPath.appending(component: name), recursive: false)
archiver.extractions.append(MockArchiver.Extraction(archivePath: archivePath, destinationPath: destinationPath))
completion(.success(()))
} catch {
completion(.failure(error))
}
})
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo", dependencies: [
.product(name: "A1", package: "A"),
.product(name: "A2", package: "A"),
]),
],
products: [],
dependencies: [
.sourceControl(path: "./A", requirement: .exact("1.0.0"))
]
),
],
packages: [
MockPackage(
name: "A",
targets: [
MockTarget(
name: "A1",
type: .binary,
path: "XCFrameworks/A1.zip"
),
MockTarget(
name: "A2",
type: .binary,
path: "ArtifactBundles/A2.zip"
),
],
products: [
MockProduct(name: "A1", targets: ["A1"]),
MockProduct(name: "A2", targets: ["A2"]),
],
versions: ["1.0.0"]
)
],
customBinaryArchiver: archiver
)
// Create dummy zip files
let aPath = workspace.packagesDir.appending(components: "A")
let aFrameworksPath = aPath.appending(component: "XCFrameworks")
try fs.createDirectory(aFrameworksPath, recursive: true)
try fs.writeFileContents(aFrameworksPath.appending(component: "A1.zip"), bytes: ByteString([0xA1]))
let aArtifactBundlesPath = aPath.appending(component: "ArtifactBundles")
try fs.createDirectory(aArtifactBundlesPath, recursive: true)
try fs.writeFileContents(aArtifactBundlesPath.appending(component: "A2.zip"), bytes: ByteString([0xA2]))
workspace.checkPackageGraphFailure(roots: ["Foo"]) { diagnostics in
testDiagnostics(diagnostics) { result in
result.checkUnordered(diagnostic: .contains("local archive of binary target 'A1' does not contain expected binary artifact 'A1'") , severity: .error)
result.checkUnordered(diagnostic: .contains("local archive of binary target 'A2' does not contain expected binary artifact 'A2'") , severity: .error)
}
}
}
func testLocalArchivedArtifactChecksumChange() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
// create dummy xcframework directories from the request archive
let archiver = MockArchiver(handler: { archiver, archivePath, destinationPath, completion in
do {
let name: String
switch archivePath.basename {
case "A1.zip":
name = "A1.xcframework"
case "A2.zip":
name = "A2.xcframework"
default:
throw StringError("unexpected archivePath \(archivePath)")
}
try fs.createDirectory(destinationPath.appending(component: name), recursive: false)
archiver.extractions.append(MockArchiver.Extraction(archivePath: archivePath, destinationPath: destinationPath))
completion(.success(()))
} catch {
completion(.failure(error))
}
})
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo", dependencies: [
.product(name: "A1", package: "A"),
.product(name: "A2", package: "A")
]),
],
products: [],
dependencies: [
.sourceControl(path: "./A", requirement: .exact("1.0.0"))
]
),
],
packages: [
MockPackage(
name: "A",
targets: [
MockTarget(
name: "A1",
type: .binary,
path: "XCFrameworks/A1.zip"
),
MockTarget(
name: "A2",
type: .binary,
path: "XCFrameworks/A2.zip"
)
],
products: [
MockProduct(name: "A1", targets: ["A1"]),
MockProduct(name: "A2", targets: ["A2"])
],
versions: ["1.0.0"]
)
],
customBinaryArchiver: archiver
)
// Pin A to 1.0.0, Checkout B to 1.0.0
let aPath = workspace.pathToPackage(withName: "A")
let aRef = PackageReference.localSourceControl(identity: PackageIdentity(path: aPath), path: aPath)
let aRepo = workspace.repositoryProvider.specifierMap[RepositorySpecifier(path: aPath)]!
let aRevision = try aRepo.resolveRevision(tag: "1.0.0")
let aState = CheckoutState.version("1.0.0", revision: aRevision)
// Set an initial workspace state
try workspace.set(
pins: [aRef: aState],
managedDependencies: [],
managedArtifacts: [
.init(
packageRef: aRef,
targetName: "A1",
source: .local(checksum: "old-checksum"),
path: workspace.artifactsDir.appending(components: "a", "A1.xcframework")
),
.init(
packageRef: aRef,
targetName: "A2",
source: .local(checksum: "a2"),
path: workspace.artifactsDir.appending(components: "a", "A2.xcframework")
)
]
)
// Create dummy zip files
let aFrameworksPath = workspace.packagesDir.appending(components: "A", "XCFrameworks")
try fs.createDirectory(aFrameworksPath, recursive: true)
let a1FrameworkArchivePath = aFrameworksPath.appending(component: "A1.zip")
try fs.writeFileContents(a1FrameworkArchivePath, bytes: ByteString([0xA1]))
let a2FrameworkArchivePath = aFrameworksPath.appending(component: "A2.zip")
try fs.writeFileContents(a2FrameworkArchivePath, bytes: ByteString([0xA2]))
try workspace.checkPackageGraph(roots: ["Foo"]) { graph, diagnostics in
// Ensure that only the artifact archive with the changed checksum has been extracted
XCTAssertEqual(workspace.archiver.extractions.map { $0.destinationPath.parentDirectory }.sorted(), [
AbsolutePath("/tmp/ws/.build/artifacts/extract/a/A1")
])
}
workspace.checkManagedArtifacts { result in
result.check(packageIdentity: .plain("a"),
targetName: "A1",
source: .local(checksum: "a1"),
path: workspace.artifactsDir.appending(components: "a", "A1.xcframework")
)
result.check(packageIdentity: .plain("a"),
targetName: "A2",
source: .local(checksum: "a2"),
path: workspace.artifactsDir.appending(components: "a", "A2.xcframework")
)
}
}
func testChecksumForBinaryArtifact() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo", dependencies: ["Foo"]),
],
products: []
),
],
packages: []
)
let ws = try workspace.getOrCreateWorkspace()
// Checks the valid case.
do {
let binaryPath = sandbox.appending(component: "binary.zip")
try fs.writeFileContents(binaryPath, bytes: ByteString([0xAA, 0xBB, 0xCC]))
let checksum = try ws.checksum(forBinaryArtifactAt: binaryPath)
XCTAssertEqual(workspace.checksumAlgorithm.hashes.map { $0.contents }, [[0xAA, 0xBB, 0xCC]])
XCTAssertEqual(checksum, "ccbbaa")
}
// Checks an unsupported extension.
do {
let unknownPath = sandbox.appending(component: "unknown")
XCTAssertThrowsError(try ws.checksum(forBinaryArtifactAt: unknownPath), "error expected") { error in
XCTAssertEqual(error as? StringError, StringError("unexpected file type; supported extensions are: zip"))
}
}
// Checks a supported extension that is not a file (does not exist).
do {
let unknownPath = sandbox.appending(component: "missingFile.zip")
XCTAssertThrowsError(try ws.checksum(forBinaryArtifactAt: unknownPath), "error expected") { error in
XCTAssertEqual(error as? StringError, StringError("file not found at path: /tmp/ws/missingFile.zip"))
}
}
// Checks a supported extension that is a directory instead of a file.
do {
let unknownPath = sandbox.appending(component: "aDirectory.zip")
try fs.createDirectory(unknownPath)
XCTAssertThrowsError(try ws.checksum(forBinaryArtifactAt: unknownPath), "error expected") { error in
XCTAssertEqual(error as? StringError, StringError("file not found at path: /tmp/ws/aDirectory.zip"))
}
}
}
func testArtifactDownloadHappyPath() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let downloads = ThreadSafeKeyValueStore<Foundation.URL, AbsolutePath>()
// returns a dummy zipfile for the requested artifact
let httpClient = HTTPClient(handler: { request, _, completion in
do {
guard case .download(let fileSystem, let destination) = request.kind else {
throw StringError("invalid request \(request.kind)")
}
let contents: [UInt8]
switch request.url.lastPathComponent {
case "a1.zip":
contents = [0xA1]
case "a2.zip":
contents = [0xA2]
case "b.zip":
contents = [0xB0]
default:
throw StringError("unexpected url \(request.url)")
}
try fileSystem.writeFileContents(
destination,
bytes: ByteString(contents),
atomically: true
)
downloads[request.url] = destination
completion(.success(.okay()))
} catch {
completion(.failure(error))
}
})
// create a dummy xcframework directory from the request archive
let archiver = MockArchiver(handler: { archiver, archivePath, destinationPath, completion in
do {
let name: String
switch archivePath.basename {
case "a1.zip":
name = "A1.xcframework"
case "a2.zip":
name = "A2.xcframework"
case "b.zip":
name = "B.xcframework"
default:
throw StringError("unexpected archivePath \(archivePath)")
}
try fs.createDirectory(destinationPath.appending(component: name), recursive: false)
archiver.extractions.append(MockArchiver.Extraction(archivePath: archivePath, destinationPath: destinationPath))
completion(.success(()))
} catch {
completion(.failure(error))
}
})
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo", dependencies: [
.product(name: "A1", package: "A"),
.product(name: "A2", package: "A"),
"B"
]),
],
products: [],
dependencies: [
.sourceControl(path: "./A", requirement: .exact("1.0.0")),
.sourceControl(path: "./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"
)
],
products: [
MockProduct(name: "A1", targets: ["A1"]),
MockProduct(name: "A2", targets: ["A2"])
],
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"]
),
],
customHttpClient: httpClient,
customBinaryArchiver: archiver
)
try workspace.checkPackageGraph(roots: ["Foo"]) { graph, diagnostics in
XCTAssertNoDiagnostics(diagnostics)
XCTAssert(fs.isDirectory(AbsolutePath("/tmp/ws/.build/artifacts/a")))
XCTAssert(fs.isDirectory(AbsolutePath("/tmp/ws/.build/artifacts/b")))
XCTAssertEqual(downloads.map { $0.key.absoluteString }.sorted(), [
"https://a.com/a1.zip",
"https://a.com/a2.zip",
"https://b.com/b.zip",
])
XCTAssertEqual(workspace.checksumAlgorithm.hashes.map{ $0.hexadecimalRepresentation }.sorted(), [
ByteString([0xA1]).hexadecimalRepresentation,
ByteString([0xA2]).hexadecimalRepresentation,
ByteString([0xB0]).hexadecimalRepresentation,
])
XCTAssertEqual(workspace.archiver.extractions.map { $0.destinationPath.parentDirectory }.sorted(), [
AbsolutePath("/tmp/ws/.build/artifacts/extract/a/A1"),
AbsolutePath("/tmp/ws/.build/artifacts/extract/a/A2"),
AbsolutePath("/tmp/ws/.build/artifacts/extract/b/B")
])
XCTAssertEqual(
downloads.map { $0.value }.sorted(),
workspace.archiver.extractions.map { $0.archivePath }.sorted()
)
}
workspace.checkManagedArtifacts { result in
result.check(packageIdentity: .plain("a"),
targetName: "A1",
source: .remote(
url: "https://a.com/a1.zip",
checksum: "a1"
),
path: workspace.artifactsDir.appending(components: "a", "A1.xcframework")
)
result.check(packageIdentity: .plain("a"),
targetName: "A2",
source: .remote(
url: "https://a.com/a2.zip",
checksum: "a2"
),
path: workspace.artifactsDir.appending(components: "a", "A2.xcframework")
)
result.check(packageIdentity: .plain("b"),
targetName: "B",
source: .remote(
url: "https://b.com/b.zip",
checksum: "b0"
),
path: workspace.artifactsDir.appending(components: "b", "B.xcframework")
)
}
}
func testArtifactDownloadWithPreviousState() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let downloads = ThreadSafeKeyValueStore<Foundation.URL, AbsolutePath>()
// returns a dummy zipfile for the requested artifact
let httpClient = HTTPClient(handler: { request, _, completion in
do {
guard case .download(let fileSystem, let destination) = request.kind else {
throw StringError("invalid request \(request.kind)")
}
let contents: [UInt8]
switch request.url.lastPathComponent {
case "a1.zip":
contents = [0xA1]
case "a2.zip":
contents = [0xA2]
case "a3.zip":
contents = [0xA3]
case "a7.zip":
contents = [0xA7]
case "b.zip":
contents = [0xB0]
default:
throw StringError("unexpected url \(request.url)")
}
try fileSystem.writeFileContents(
destination,
bytes: ByteString(contents),
atomically: true
)
downloads[request.url] = destination
completion(.success(.okay()))
} catch {
completion(.failure(error))
}
})
// create a dummy xcframework directory from the request archive
let archiver = MockArchiver(handler: { archiver, archivePath, destinationPath, completion in
do {
let name: String
switch archivePath.basename {
case "a1.zip":
name = "A1.xcframework"
case "a2.zip":
name = "A2.xcframework"
case "a3.zip":
name = "incorrect-name.xcframework"
case "a7.zip":
name = "A7.xcframework"
case "b.zip":
name = "B.xcframework"
default:
throw StringError("unexpected archivePath \(archivePath)")
}
try fs.createDirectory(destinationPath.appending(component: name), recursive: false)
archiver.extractions.append(MockArchiver.Extraction(archivePath: archivePath, destinationPath: destinationPath))
completion(.success(()))
} catch {
completion(.failure(error))
}
})
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
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"),
.product(name: "A7", package: "A")
]),
],
products: [],
dependencies: [
.sourceControl(path: "./A", requirement: .exact("1.0.0")),
.sourceControl(path: "./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: "XCFrameworks/A4.xcframework"
),
MockTarget(
name: "A7",
type: .binary,
url: "https://a.com/a7.zip",
checksum: "a7"
)
],
products: [
MockProduct(name: "A1", targets: ["A1"]),
MockProduct(name: "A2", targets: ["A2"]),
MockProduct(name: "A3", targets: ["A3"]),
MockProduct(name: "A4", targets: ["A4"]),
MockProduct(name: "A7", targets: ["A7"])
],
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"]
),
],
customHttpClient: httpClient,
customBinaryArchiver: archiver
)
let a4FrameworkPath = workspace.packagesDir.appending(components: "A", "XCFrameworks", "A4.xcframework")
try fs.createDirectory(a4FrameworkPath, recursive: true)
// Pin A to 1.0.0, Checkout B to 1.0.0
let aPath = workspace.pathToPackage(withName: "A")
let aRef = PackageReference.localSourceControl(identity: PackageIdentity(path: aPath), path: aPath)
let aRepo = workspace.repositoryProvider.specifierMap[RepositorySpecifier(path: aPath)]!
let aRevision = try aRepo.resolveRevision(tag: "1.0.0")
let aState = CheckoutState.version("1.0.0", revision: aRevision)
try workspace.set(
pins: [aRef: aState],
managedDependencies: [],
managedArtifacts: [
.init(
packageRef: aRef,
targetName: "A1",
source: .remote(
url: "https://a.com/a1.zip",
checksum: "a1"
),
path: workspace.artifactsDir.appending(components: "a", "A1.xcframework")
),
.init(
packageRef: aRef,
targetName: "A3",
source: .remote(
url: "https://a.com/old/a3.zip",
checksum: "a3-old-checksum"
),
path: workspace.artifactsDir.appending(components: "a", "A3.xcframework")
),
.init(
packageRef: aRef,
targetName: "A4",
source: .remote(
url: "https://a.com/a4.zip",
checksum: "a4"
),
path: workspace.artifactsDir.appending(components: "a", "A4.xcframework")
),
.init(
packageRef: aRef,
targetName: "A5",
source: .remote(
url: "https://a.com/a5.zip",
checksum: "a5"
),
path: workspace.artifactsDir.appending(components: "a", "A5.xcframework")
),
.init(
packageRef: aRef,
targetName: "A6",
source: .local(),
path: workspace.artifactsDir.appending(components: "a", "A6.xcframework")
),
.init(
packageRef: aRef,
targetName: "A7",
source: .local(),
path: workspace.packagesDir.appending(components: "a", "XCFrameworks", "A7.xcframework")
)
]
)
workspace.checkPackageGraphFailure(roots: ["Foo"]) { diagnostics in
testDiagnostics(diagnostics) { result in
result.check(diagnostic: "downloaded archive of binary target 'A3' does not contain expected binary artifact 'A3'", severity: .error)
}
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/pkgs/a/XCFrameworks/A7.xcframework")))
XCTAssert(!fs.exists(AbsolutePath("/tmp/ws/.build/artifacts/Foo")))
XCTAssertEqual(downloads.map { $0.key.absoluteString }.sorted(), [
"https://a.com/a2.zip",
"https://a.com/a3.zip",
"https://a.com/a7.zip",
"https://b.com/b.zip",
])
XCTAssertEqual(workspace.checksumAlgorithm.hashes.map{ $0.hexadecimalRepresentation }.sorted(), [
ByteString([0xA2]).hexadecimalRepresentation,
ByteString([0xA3]).hexadecimalRepresentation,
ByteString([0xA7]).hexadecimalRepresentation,
ByteString([0xB0]).hexadecimalRepresentation,
])
XCTAssertEqual(workspace.archiver.extractions.map { $0.destinationPath.parentDirectory }.sorted(), [
AbsolutePath("/tmp/ws/.build/artifacts/extract/a/A2"),
AbsolutePath("/tmp/ws/.build/artifacts/extract/a/A3"),
AbsolutePath("/tmp/ws/.build/artifacts/extract/a/A7"),
AbsolutePath("/tmp/ws/.build/artifacts/extract/b/B"),
])
XCTAssertEqual(
downloads.map { $0.value }.sorted(),
workspace.archiver.extractions.map { $0.archivePath }.sorted()
)
}
workspace.checkManagedArtifacts { result in
result.check(packageIdentity: .plain("a"),
targetName: "A1",
source: .remote(
url: "https://a.com/a1.zip",
checksum: "a1"
),
path: workspace.artifactsDir.appending(components: "a", "A1.xcframework")
)
result.check(packageIdentity: .plain("a"),
targetName: "A2",
source: .remote(
url: "https://a.com/a2.zip",
checksum: "a2"
),
path: workspace.artifactsDir.appending(components: "a", "A2.xcframework")
)
result.checkNotPresent(packageName: "A", targetName: "A3")
result.check(packageIdentity: .plain("a"),
targetName: "A4",
source: .local(),
path: a4FrameworkPath
)
result.check(packageIdentity: .plain("a"),
targetName: "A7",
source: .remote(
url: "https://a.com/a7.zip",
checksum: "a7"
),
path: workspace.artifactsDir.appending(components: "a", "A7.xcframework")
)
result.checkNotPresent(packageName: "A", targetName: "A5")
result.check(packageIdentity: .plain("b"),
targetName: "B",
source: .remote(
url: "https://b.com/b.zip",
checksum: "b0"
),
path: workspace.artifactsDir.appending(components: "b", "B.xcframework")
)
}
}
func testArtifactDownloadTwice() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let downloads = ThreadSafeArrayStore<(Foundation.URL, AbsolutePath)>()
// returns a dummy zipfile for the requested artifact
let httpClient = HTTPClient(handler: { request, _, completion in
do {
guard case .download(let fileSystem, let destination) = request.kind else {
throw StringError("invalid request \(request.kind)")
}
let contents: [UInt8]
switch request.url.lastPathComponent {
case "a1.zip":
contents = [0xA1]
default:
throw StringError("unexpected url \(request.url)")
}
try fileSystem.writeFileContents(
destination,
bytes: ByteString(contents),
atomically: true
)
downloads.append((request.url, destination))
completion(.success(.okay()))
} catch {
completion(.failure(error))
}
})
// create a dummy xcframework directory from the request archive
let archiver = MockArchiver(handler: { archiver, archivePath, destinationPath, completion in
do {
let name: String
switch archivePath.basename {
case "a1.zip":
name = "A1.xcframework"
default:
throw StringError("unexpected archivePath \(archivePath)")
}
let path = destinationPath.appending(component: name)
if fs.exists(path) {
throw StringError("\(path) already exists")
}
try fs.createDirectory(path, recursive: false)
archiver.extractions.append(MockArchiver.Extraction(archivePath: archivePath, destinationPath: destinationPath))
completion(.success(()))
} catch {
completion(.failure(error))
}
})
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo", dependencies: [
.product(name: "A1", package: "A"),
]),
],
products: [],
dependencies: [
.sourceControl(path: "./A", requirement: .exact("1.0.0")),
]
),
],
packages: [
MockPackage(
name: "A",
targets: [
MockTarget(
name: "A1",
type: .binary,
url: "https://a.com/a1.zip",
checksum: "a1"
),
],
products: [
MockProduct(name: "A1", targets: ["A1"]),
],
versions: ["1.0.0"]
)
],
customHttpClient: httpClient,
customBinaryArchiver: archiver
)
try workspace.checkPackageGraph(roots: ["Foo"]) { graph, diagnostics in
XCTAssertNoDiagnostics(diagnostics)
XCTAssert(fs.isDirectory(AbsolutePath("/tmp/ws/.build/artifacts/a")))
XCTAssertEqual(workspace.checksumAlgorithm.hashes.map{ $0.hexadecimalRepresentation }.sorted(), [
ByteString([0xA1]).hexadecimalRepresentation,
])
}
XCTAssertEqual(downloads.map { $0.0.absoluteString }.sorted(), [
"https://a.com/a1.zip",
])
XCTAssertEqual(archiver.extractions.map { $0.destinationPath.parentDirectory }.sorted(), [
AbsolutePath("/tmp/ws/.build/artifacts/extract/a/A1"),
])
XCTAssertEqual(
downloads.map { $0.1 }.sorted(),
archiver.extractions.map { $0.archivePath }.sorted()
)
// reset
try workspace.resetState()
// do it again
try workspace.checkPackageGraph(roots: ["Foo"]) { graph, diagnostics in
XCTAssertNoDiagnostics(diagnostics)
XCTAssert(fs.isDirectory(AbsolutePath("/tmp/ws/.build/artifacts/a")))
XCTAssertEqual(workspace.checksumAlgorithm.hashes.map{ $0.hexadecimalRepresentation }.sorted(), [
ByteString([0xA1]).hexadecimalRepresentation, ByteString([0xA1]).hexadecimalRepresentation,
])
}
XCTAssertEqual(downloads.map { $0.0.absoluteString }.sorted(), [
"https://a.com/a1.zip", "https://a.com/a1.zip",
])
XCTAssertEqual(archiver.extractions.map { $0.destinationPath.parentDirectory }.sorted(), [
AbsolutePath("/tmp/ws/.build/artifacts/extract/a/A1"),
AbsolutePath("/tmp/ws/.build/artifacts/extract/a/A1"),
])
XCTAssertEqual(
downloads.map { $0.1 }.sorted(),
archiver.extractions.map { $0.archivePath }.sorted()
)
}
func testArtifactDownloaderOrArchiverError() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
// returns a dummy zipfile for the requested artifact
let httpClient = HTTPClient(handler: { request, _, completion in
do {
guard case .download(let fileSystem, let destination) = request.kind else {
throw StringError("invalid request \(request.kind)")
}
switch request.url {
case URL(string: "https://a.com/a1.zip")!:
completion(.success(.serverError()))
case URL(string: "https://a.com/a2.zip")!:
try fileSystem.writeFileContents(destination, bytes: ByteString([0xA2]))
completion(.success(.okay()))
case URL(string: "https://a.com/a3.zip")!:
try fileSystem.writeFileContents(destination, bytes: "different contents = different checksum")
completion(.success(.okay()))
default:
XCTFail("unexpected url")
completion(.success(.okay()))
}
} catch {
completion(.failure(error))
}
})
let archiver = MockArchiver(handler: { _, _, destinationPath, completion in
XCTAssertEqual(destinationPath.parentDirectory, AbsolutePath("/tmp/ws/.build/artifacts/extract/a/A2"))
completion(.failure(DummyError()))
})
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo", dependencies: [
.product(name: "A1", package: "A"),
.product(name: "A2", package: "A"),
]),
],
products: [],
dependencies: [
.sourceControl(path: "./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"]
),
],
customHttpClient: httpClient,
customBinaryArchiver: archiver
)
workspace.checkPackageGraphFailure(roots: ["Foo"]) { diagnostics in
print(diagnostics)
testDiagnostics(diagnostics) { result in
result.checkUnordered(diagnostic: .contains("failed downloading 'https://a.com/a1.zip' which is required by binary target 'A1': badResponseStatusCode(500)"), severity: .error)
result.checkUnordered(diagnostic: .contains("failed extracting 'https://a.com/a2.zip' which is required by binary target 'A2': dummy error"), severity: .error)
result.checkUnordered(diagnostic: .contains("checksum of downloaded artifact of binary target 'A3' (6d75736b6365686320746e65726566666964203d2073746e65746e6f6320746e65726566666964) does not match checksum specified by the manifest (a3)"), severity: .error)
}
}
}
func testArtifactChecksumChange() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let httpClient = HTTPClient(handler: { request, _, completion in
XCTFail("should not be called")
})
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo", dependencies: ["A"]),
],
products: [],
dependencies: [
.sourceControl(path: "./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"]
),
],
customHttpClient: httpClient
)
// Pin A to 1.0.0, Checkout A to 1.0.0
let aPath = workspace.pathToPackage(withName: "A")
let aRef = PackageReference.localSourceControl(identity: PackageIdentity(path: aPath), path: aPath)
let aRepo = workspace.repositoryProvider.specifierMap[RepositorySpecifier(path: aPath)]!
let aRevision = try aRepo.resolveRevision(tag: "1.0.0")
let aState = CheckoutState.version("1.0.0", revision: aRevision)
let aDependency: Workspace.ManagedDependency = try .sourceControlCheckout(packageRef: aRef, state: aState, subpath: RelativePath("A"))
try workspace.set(
pins: [aRef: aState],
managedDependencies: [aDependency],
managedArtifacts: [
.init(
packageRef: aRef,
targetName: "A",
source: .remote(
url: "https://a.com/a.zip",
checksum: "old-checksum"
),
path: workspace.packagesDir.appending(components: "A", "A.xcframework")
),
]
)
workspace.checkPackageGraphFailure(roots: ["Foo"]) { diagnostics in
testDiagnostics(diagnostics) { result in
result.check(diagnostic: .contains("artifact of binary target 'A' has changed checksum"), severity: .error)
}
}
}
func testArtifactDownloadAddsAcceptHeader() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let downloads = ThreadSafeKeyValueStore<Foundation.URL, AbsolutePath>()
var acceptHeaders: [String] = []
// returns a dummy zipfile for the requested artifact
let httpClient = HTTPClient(handler: { request, _, completion in
do {
guard case .download(let fileSystem, let destination) = request.kind else {
throw StringError("invalid request \(request.kind)")
}
acceptHeaders.append(request.headers.get("accept").first!)
let contents: [UInt8]
switch request.url.lastPathComponent {
case "a1.zip":
contents = [0xA1]
default:
throw StringError("unexpected url \(request.url)")
}
try fileSystem.writeFileContents(
destination,
bytes: ByteString(contents),
atomically: true
)
downloads[request.url] = destination
completion(.success(.okay()))
} catch {
completion(.failure(error))
}
})
// create a dummy xcframework directory from the request archive
let archiver = MockArchiver(handler: { archiver, archivePath, destinationPath, completion in
do {
let name: String
switch archivePath.basename {
case "a1.zip":
name = "A1.xcframework"
default:
throw StringError("unexpected archivePath \(archivePath)")
}
try fs.createDirectory(destinationPath.appending(component: name), recursive: false)
archiver.extractions.append(MockArchiver.Extraction(archivePath: archivePath, destinationPath: destinationPath))
completion(.success(()))
} catch {
completion(.failure(error))
}
})
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo", dependencies: [
.product(name: "A1", package: "A"),
]),
],
products: [],
dependencies: [
.sourceControl(path: "./A", requirement: .exact("1.0.0")),
]
),
],
packages: [
MockPackage(
name: "A",
targets: [
MockTarget(
name: "A1",
type: .binary,
url: "https://a.com/a1.zip",
checksum: "a1"
)
],
products: [
MockProduct(name: "A1", targets: ["A1"]),
],
versions: ["1.0.0"]
)
],
customHttpClient: httpClient,
customBinaryArchiver: archiver
)
try workspace.checkPackageGraph(roots: ["Foo"]) { graph, diagnostics in
XCTAssertNoDiagnostics(diagnostics)
XCTAssertEqual(acceptHeaders, [
"application/octet-stream"
])
}
}
func testArtifactDownloadTransitive() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let downloads = ThreadSafeKeyValueStore<Foundation.URL, AbsolutePath>()
// returns a dummy zipfile for the requested artifact
let httpClient = HTTPClient(handler: { request, _, completion in
do {
guard case .download(let fileSystem, let destination) = request.kind else {
throw StringError("invalid request \(request.kind)")
}
let contents: [UInt8]
switch request.url.lastPathComponent {
case "a.zip":
contents = [0xA]
default:
throw StringError("unexpected url \(request.url)")
}
try fileSystem.writeFileContents(
destination,
bytes: ByteString(contents),
atomically: true
)
if downloads[request.url] != nil {
throw StringError("\(request.url) already requested")
}
downloads[request.url] = destination
completion(.success(.okay()))
} catch {
completion(.failure(error))
}
})
// create a dummy xcframework directory from the request archive
let archiver = MockArchiver(handler: { archiver, archivePath, destinationPath, completion in
do {
let name: String
switch archivePath.basename {
case "a.zip":
name = "A.xcframework"
default:
throw StringError("unexpected archivePath \(archivePath)")
}
try fs.createDirectory(destinationPath.appending(component: name), recursive: false)
if archiver.extractions.get().contains(where: { $0.archivePath == archivePath }) {
throw StringError("\(archivePath) already extracted")
}
archiver.extractions.append(MockArchiver.Extraction(archivePath: archivePath, destinationPath: destinationPath))
completion(.success(()))
} catch {
completion(.failure(error))
}
})
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo", dependencies: [
.product(name: "A", package: "A"),
.product(name: "B", package: "B"),
]),
],
products: [],
dependencies: [
.sourceControl(path: "./A", requirement: .exact("1.0.0")),
.sourceControl(path: "./B", requirement: .exact("1.0.0")),
]
),
],
packages: [
MockPackage(
name: "A",
targets: [
MockTarget(name: "A", type: .binary, url: "https://a.com/a.zip", checksum: "0a")
],
products: [
MockProduct(name: "A", targets: ["A"]),
],
versions: ["1.0.0"]
),
MockPackage(
name: "B",
targets: [
MockTarget(name: "B", dependencies: [
.product(name: "C", package: "C"),
.product(name: "D", package: "D"),
]),
],
products: [
MockProduct(name: "B", targets: ["B"]),
],
dependencies: [
.sourceControl(path: "./C", requirement: .exact("1.0.0")),
.sourceControl(path: "./D", requirement: .exact("1.0.0")),
],
versions: ["1.0.0"]
),
MockPackage(
name: "C",
targets: [
MockTarget(name: "C", dependencies: [
.product(name: "A", package: "A"),
]),
],
products: [
MockProduct(name: "C", targets: ["C"]),
],
dependencies: [
.sourceControl(path: "./A", requirement: .exact("1.0.0")),
],
versions: ["1.0.0"]
),
MockPackage(
name: "D",
targets: [
MockTarget(name: "D", dependencies: [
.product(name: "A", package: "A"),
]),
],
products: [
MockProduct(name: "D", targets: ["D"]),
],
dependencies: [
.sourceControl(path: "./A", requirement: .exact("1.0.0")),
],
versions: ["1.0.0"]
)
],
customHttpClient: httpClient,
customBinaryArchiver: archiver
)
try workspace.checkPackageGraph(roots: ["Foo"]) { graph, diagnostics in
XCTAssertNoDiagnostics(diagnostics)
XCTAssert(fs.isDirectory(AbsolutePath("/tmp/ws/.build/artifacts/a")))
XCTAssertEqual(downloads.map { $0.key.absoluteString }.sorted(), [
"https://a.com/a.zip"
])
XCTAssertEqual(workspace.checksumAlgorithm.hashes.map{ $0.hexadecimalRepresentation }.sorted(), [
ByteString([0xA]).hexadecimalRepresentation
])
XCTAssertEqual(workspace.archiver.extractions.map { $0.destinationPath.parentDirectory }.sorted(), [
AbsolutePath("/tmp/ws/.build/artifacts/extract/a/A")
])
XCTAssertEqual(
downloads.map { $0.value }.sorted(),
workspace.archiver.extractions.map { $0.archivePath }.sorted()
)
}
workspace.checkManagedArtifacts { result in
result.check(
packageIdentity: .plain("a"),
targetName: "A",
source: .remote(
url: "https://a.com/a.zip",
checksum: "0a"
),
path: workspace.artifactsDir.appending(components: "a", "A.xcframework")
)
}
}
func testArtifactDownloadArchiveExists() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
// this relies on internal knowledge of the destination path construction
let expectedDownloadDestination = sandbox.appending(components: ".build", "artifacts", "library", "binary.zip")
// returns a dummy zipfile for the requested artifact
let httpClient = HTTPClient(handler: { request, _, completion in
do {
guard case .download(let fileSystem, let destination) = request.kind else {
throw StringError("invalid request \(request.kind)")
}
// this is to test the test's integrity, as it relied on internal knowledge of the destination path construction
guard expectedDownloadDestination == destination else {
throw StringError("expected destination of \(expectedDownloadDestination)")
}
let contents: [UInt8]
switch request.url.lastPathComponent {
case "binary.zip":
contents = [0x01]
default:
throw StringError("unexpected url \(request.url)")
}
// in-memory fs does not check for this!
if fileSystem.exists(destination) {
throw StringError("\(destination) already exists")
}
try fileSystem.writeFileContents(
destination,
bytes: ByteString(contents),
atomically: true
)
completion(.success(.okay()))
} catch {
completion(.failure(error))
}
})
// create a dummy xcframework directory from the request archive
let archiver = MockArchiver(handler: { archiver, archivePath, destinationPath, completion in
do {
let name: String
switch archivePath.basename {
case "binary.zip":
name = "binary.xcframework"
default:
throw StringError("unexpected archivePath \(archivePath)")
}
try fs.createDirectory(destinationPath.appending(component: name), recursive: false)
archiver.extractions.append(MockArchiver.Extraction(archivePath: archivePath, destinationPath: destinationPath))
completion(.success(()))
} catch {
completion(.failure(error))
}
})
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "App",
targets: [
MockTarget(name: "App", dependencies: [
.product(name: "binary", package: "library"),
]),
],
products: [],
dependencies: [
.sourceControl(path: "./library", requirement: .exact("1.0.0")),
]
),
],
packages: [
MockPackage(
name: "library",
targets: [
MockTarget(
name: "binary",
type: .binary,
url: "https://a.com/binary.zip",
checksum: "01"
)
],
products: [
MockProduct(name: "binary", targets: ["binary"]),
],
versions: ["1.0.0"]
)
],
customHttpClient: httpClient,
customBinaryArchiver: archiver
)
// write the file to test it gets deleted
try fs.createDirectory(expectedDownloadDestination.parentDirectory, recursive: true)
try fs.writeFileContents(
expectedDownloadDestination,
bytes: [],
atomically: true
)
try workspace.checkPackageGraph(roots: ["App"]) { graph, diagnostics in
XCTAssertNoDiagnostics(diagnostics)
}
workspace.checkManagedArtifacts { result in
result.check(
packageIdentity: .plain("library"),
targetName: "binary",
source: .remote(
url: "https://a.com/binary.zip",
checksum: "01"
),
path: workspace.artifactsDir.appending(components: "library", "binary.xcframework")
)
}
}
func testDownloadArchiveIndexFilesHappyPath() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let downloads = ThreadSafeKeyValueStore<Foundation.URL, AbsolutePath>()
let hostToolchain = try UserToolchain(destination: .hostDestination())
let ariFiles = [
"""
{
"schemaVersion": "1.0",
"archives": [
{
"fileName": "a1.zip",
"checksum": "a1",
"supportedTriples": ["\(hostToolchain.triple.tripleString)"]
}
]
}
""",
"""
{
"schemaVersion": "1.0",
"archives": [
{
"fileName": "a2/a2.zip",
"checksum": "a2",
"supportedTriples": ["\(hostToolchain.triple.tripleString)"]
}
]
}
"""
]
let checksumAlgorithm = MockHashAlgorithm() // used in tests
let ariFilesChecksums = ariFiles.map { checksumAlgorithm.hash($0).hexadecimalRepresentation }
// returns a dummy file for the requested artifact
let httpClient = HTTPClient(handler: { request, _, completion in
switch request.kind {
case .generic:
do {
let contents: String
switch request.url.lastPathComponent {
case "a1.artifactbundleindex":
contents = ariFiles[0]
case "a2.artifactbundleindex":
contents = ariFiles[1]
default:
throw StringError("unexpected url \(request.url)")
}
completion(.success(.okay(body: contents)))
} catch {
completion(.failure(error))
}
case .download(let fileSystem, let destination):
do {
let contents: [UInt8]
switch request.url.lastPathComponent {
case "a1.zip":
contents = [0xA1]
case "a2.zip":
contents = [0xA2]
case "b.zip":
contents = [0xB0]
default:
throw StringError("unexpected url \(request.url)")
}
try fileSystem.writeFileContents(
destination,
bytes: ByteString(contents),
atomically: true
)
downloads[request.url] = destination
completion(.success(.okay()))
} catch {
completion(.failure(error))
}
}
})
// create a dummy xcframework directory from the request archive
let archiver = MockArchiver(handler: { archiver, archivePath, destinationPath, completion in
do {
let name: String
switch archivePath.basename {
case "a1.zip":
name = "A1.artifactbundle"
case "a2.zip":
name = "A2.artifactbundle"
case "b.zip":
name = "B.artifactbundle"
default:
throw StringError("unexpected archivePath \(archivePath)")
}
try fs.createDirectory(destinationPath.appending(component: name), recursive: false)
archiver.extractions.append(MockArchiver.Extraction(archivePath: archivePath, destinationPath: destinationPath))
completion(.success(()))
} catch {
completion(.failure(error))
}
})
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo", dependencies: [
.product(name: "A1", package: "A"),
.product(name: "A2", package: "A"),
"B"
]),
],
products: [],
dependencies: [
.sourceControl(path: "./A", requirement: .exact("1.0.0")),
.sourceControl(path: "./B", requirement: .exact("1.0.0")),
]
),
],
packages: [
MockPackage(
name: "A",
targets: [
MockTarget(
name: "A1",
type: .binary,
url: "https://a.com/a1.artifactbundleindex",
checksum: ariFilesChecksums[0]
),
MockTarget(
name: "A2",
type: .binary,
url: "https://a.com/a2.artifactbundleindex",
checksum: ariFilesChecksums[1]
)
],
products: [
MockProduct(name: "A1", targets: ["A1"]),
MockProduct(name: "A2", targets: ["A2"])
],
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"]
),
],
customHttpClient: httpClient,
customBinaryArchiver: archiver,
customChecksumAlgorithm: checksumAlgorithm
)
try workspace.checkPackageGraph(roots: ["Foo"]) { graph, diagnostics in
XCTAssertNoDiagnostics(diagnostics)
XCTAssert(fs.isDirectory(AbsolutePath("/tmp/ws/.build/artifacts/a")))
XCTAssert(fs.isDirectory(AbsolutePath("/tmp/ws/.build/artifacts/b")))
XCTAssertEqual(downloads.map { $0.key.absoluteString }.sorted(), [
"https://a.com/a1.zip",
"https://a.com/a2/a2.zip",
"https://b.com/b.zip",
])
XCTAssertEqual(workspace.checksumAlgorithm.hashes.map{ $0.hexadecimalRepresentation }.sorted(),
(
ariFiles.map(ByteString.init(encodingAsUTF8:)) +
ariFiles.map(ByteString.init(encodingAsUTF8:)) +
[
ByteString([0xA1]),
ByteString([0xA2]),
ByteString([0xB0]),
]
).map{ $0.hexadecimalRepresentation }.sorted()
)
XCTAssertEqual(workspace.archiver.extractions.map { $0.destinationPath.parentDirectory }.sorted(), [
AbsolutePath("/tmp/ws/.build/artifacts/extract/a/A1"),
AbsolutePath("/tmp/ws/.build/artifacts/extract/a/A2"),
AbsolutePath("/tmp/ws/.build/artifacts/extract/b/B"),
])
XCTAssertEqual(
downloads.map { $0.value }.sorted(),
workspace.archiver.extractions.map { $0.archivePath }.sorted()
)
}
workspace.checkManagedArtifacts { result in
result.check(packageIdentity: .plain("a"),
targetName: "A1",
source: .remote(
url: "https://a.com/a1.zip",
checksum: "a1"
),
path: workspace.artifactsDir.appending(components: "a", "A1.artifactbundle")
)
result.check(packageIdentity: .plain("a"),
targetName: "A2",
source: .remote(
url: "https://a.com/a2/a2.zip",
checksum: "a2"
),
path: workspace.artifactsDir.appending(components: "a", "A2.artifactbundle")
)
result.check(packageIdentity: .plain("b"),
targetName: "B",
source: .remote(
url: "https://b.com/b.zip",
checksum: "b0"
),
path: workspace.artifactsDir.appending(components: "b", "B.artifactbundle")
)
}
}
func testDownloadArchiveIndexServerError() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
// returns a dummy files for the requested artifact
let httpClient = HTTPClient(handler: { request, _, completion in
completion(.success(.serverError()))
})
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo", dependencies: ["A"]),
],
products: [],
dependencies: [
.sourceControl(path: "./A", requirement: .exact("1.0.0")),
]
),
],
packages: [
MockPackage(
name: "A",
targets: [
MockTarget(name: "A", type: .binary, url: "https://a.com/a.artifactbundleindex", checksum: "does-not-matter"),
],
products: [
MockProduct(name: "A", targets: ["A"]),
],
versions: ["0.9.0", "1.0.0"]
),
],
customHttpClient: httpClient
)
workspace.checkPackageGraphFailure(roots: ["Foo"]) { diagnostics in
testDiagnostics(diagnostics) { result in
result.check(diagnostic: .contains("failed retrieving 'https://a.com/a.artifactbundleindex': badResponseStatusCode(500)"), severity: .error)
}
}
}
func testDownloadArchiveIndexFileBadChecksum() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let hostToolchain = try UserToolchain(destination: .hostDestination())
let ari = """
{
"schemaVersion": "1.0",
"archives": [
{
"fileName": "a1.zip",
"checksum": "a1",
"supportedTriples": ["\(hostToolchain.triple.tripleString)"]
}
]
}
"""
let checksumAlgorithm = MockHashAlgorithm() // used in tests
let ariChecksums = checksumAlgorithm.hash(ari).hexadecimalRepresentation
// returns a dummy files for the requested artifact
let httpClient = HTTPClient(handler: { request, _, completion in
do {
let contents: String
switch request.url.lastPathComponent {
case "a.artifactbundleindex":
contents = ari
default:
throw StringError("unexpected url \(request.url)")
}
completion(.success(.okay(body: contents)))
} catch {
completion(.failure(error))
}
})
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo", dependencies: ["A"]),
],
products: [],
dependencies: [
.sourceControl(path: "./A", requirement: .exact("1.0.0")),
]
),
],
packages: [
MockPackage(
name: "A",
targets: [
MockTarget(name: "A", type: .binary, url: "https://a.com/a.artifactbundleindex", checksum: "incorrect"),
],
products: [
MockProduct(name: "A", targets: ["A"]),
],
versions: ["0.9.0", "1.0.0"]
),
],
customHttpClient: httpClient
)
workspace.checkPackageGraphFailure(roots: ["Foo"]) { diagnostics in
testDiagnostics(diagnostics) { result in
result.check(diagnostic: .contains("failed retrieving 'https://a.com/a.artifactbundleindex': checksum of downloaded artifact of binary target 'A' (\(ariChecksums)) does not match checksum specified by the manifest (incorrect)"), severity: .error)
}
}
}
func testDownloadArchiveIndexFileChecksumChanges() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo", dependencies: ["A"]),
],
products: [],
dependencies: [
.sourceControl(path: "./A", requirement: .exact("1.0.0")),
]
),
],
packages: [
MockPackage(
name: "A",
targets: [
MockTarget(name: "A", type: .binary, url: "https://a.com/a.artifactbundleindex", 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 aPath = workspace.pathToPackage(withName: "A")
let aRef = PackageReference.localSourceControl(identity: PackageIdentity(path: aPath), path: aPath)
let aRepo = workspace.repositoryProvider.specifierMap[RepositorySpecifier(path: aPath)]!
let aRevision = try aRepo.resolveRevision(tag: "1.0.0")
let aState = CheckoutState.version("1.0.0", revision: aRevision)
let aDependency: Workspace.ManagedDependency = try .sourceControlCheckout(packageRef: aRef, state: aState, subpath: RelativePath("A"))
try workspace.set(
pins: [aRef: aState],
managedDependencies: [aDependency],
managedArtifacts: [
.init(
packageRef: aRef,
targetName: "A",
source: .remote(
url: "https://a.com/a.artifactbundleindex",
checksum: "old-checksum"
),
path: workspace.packagesDir.appending(components: "A", "A.xcframework")
),
]
)
workspace.checkPackageGraphFailure(roots: ["Foo"]) { diagnostics in
testDiagnostics(diagnostics) { result in
result.check(diagnostic: .contains("artifact of binary target 'A' has changed checksum"), severity: .error)
}
}
}
func testDownloadArchiveIndexFileBadArchivesChecksum() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let hostToolchain = try UserToolchain(destination: .hostDestination())
let ari = """
{
"schemaVersion": "1.0",
"archives": [
{
"fileName": "a.zip",
"checksum": "a",
"supportedTriples": ["\(hostToolchain.triple.tripleString)"]
}
]
}
"""
let checksumAlgorithm = MockHashAlgorithm() // used in tests
let ariChecksums = checksumAlgorithm.hash(ari).hexadecimalRepresentation
// returns a dummy files for the requested artifact
let httpClient = HTTPClient(handler: { request, _, completion in
switch request.kind {
case .generic:
do {
let contents: String
switch request.url.lastPathComponent {
case "a.artifactbundleindex":
contents = ari
default:
throw StringError("unexpected url \(request.url)")
}
completion(.success(.okay(body: contents)))
} catch {
completion(.failure(error))
}
case .download(let fileSystem, let destination):
do {
let contents: [UInt8]
switch request.url.lastPathComponent {
case "a.zip":
contents = [0x42]
default:
throw StringError("unexpected url \(request.url)")
}
try fileSystem.writeFileContents(
destination,
bytes: ByteString(contents),
atomically: true
)
completion(.success(.okay()))
} catch {
completion(.failure(error))
}
}
})
// create a dummy xcframework directory from the request archive
let archiver = MockArchiver(handler: { archiver, archivePath, destinationPath, completion in
do {
let name: String
switch archivePath.basename {
case "a.zip":
name = "A.artifactbundle"
default:
throw StringError("unexpected archivePath \(archivePath)")
}
try fs.createDirectory(destinationPath.appending(component: name), recursive: false)
archiver.extractions.append(MockArchiver.Extraction(archivePath: archivePath, destinationPath: destinationPath))
completion(.success(()))
} catch {
completion(.failure(error))
}
})
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo", dependencies: ["A"]),
],
products: [],
dependencies: [
.sourceControl(path: "./A", requirement: .exact("1.0.0")),
]
),
],
packages: [
MockPackage(
name: "A",
targets: [
MockTarget(name: "A", type: .binary, url: "https://a.com/a.artifactbundleindex", checksum: ariChecksums),
],
products: [
MockProduct(name: "A", targets: ["A"]),
],
versions: ["0.9.0", "1.0.0"]
),
],
customHttpClient: httpClient,
customBinaryArchiver: archiver
)
workspace.checkPackageGraphFailure(roots: ["Foo"]) { diagnostics in
testDiagnostics(diagnostics) { result in
result.check(diagnostic: .contains("checksum of downloaded artifact of binary target 'A' (42) does not match checksum specified by the manifest (a)"), severity: .error)
}
}
}
func testDownloadArchiveIndexFileArchiveNotFound() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let hostToolchain = try UserToolchain(destination: .hostDestination())
let ari = """
{
"schemaVersion": "1.0",
"archives": [
{
"fileName": "not-found.zip",
"checksum": "a",
"supportedTriples": ["\(hostToolchain.triple.tripleString)"]
}
]
}
"""
let checksumAlgorithm = MockHashAlgorithm() // used in tests
let ariChecksums = checksumAlgorithm.hash(ari).hexadecimalRepresentation
// returns a dummy files for the requested artifact
let httpClient = HTTPClient(handler: { request, _, completion in
switch request.kind {
case .generic:
do {
let contents: String
switch request.url.lastPathComponent {
case "a.artifactbundleindex":
contents = ari
default:
throw StringError("unexpected url \(request.url)")
}
completion(.success(.okay(body: contents)))
} catch {
completion(.failure(error))
}
case .download:
completion(.success(.notFound()))
}
})
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo", dependencies: ["A"]),
],
products: [],
dependencies: [
.sourceControl(path: "./A", requirement: .exact("1.0.0")),
]
),
],
packages: [
MockPackage(
name: "A",
targets: [
MockTarget(name: "A", type: .binary, url: "https://a.com/a.artifactbundleindex", checksum: ariChecksums),
],
products: [
MockProduct(name: "A", targets: ["A"]),
],
versions: ["0.9.0", "1.0.0"]
),
],
customHttpClient: httpClient
)
workspace.checkPackageGraphFailure(roots: ["Foo"]) { diagnostics in
testDiagnostics(diagnostics) { result in
result.check(diagnostic: .contains("failed downloading 'https://a.com/not-found.zip' which is required by binary target 'A': badResponseStatusCode(404)"), severity: .error)
}
}
}
func testDownloadArchiveIndexTripleNotFound() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let hostToolchain = try UserToolchain(destination: .hostDestination())
let andriodTriple = try Triple("x86_64-unknown-linux-android")
let notHostTriple = hostToolchain.triple == andriodTriple ? .macOS : andriodTriple
let ari = """
{
"schemaVersion": "1.0",
"archives": [
{
"fileName": "a1.zip",
"checksum": "a1",
"supportedTriples": ["\(notHostTriple.tripleString)"]
}
]
}
"""
let checksumAlgorithm = MockHashAlgorithm() // used in tests
let ariChecksum = checksumAlgorithm.hash(ari).hexadecimalRepresentation
// returns a dummy files for the requested artifact
let httpClient = HTTPClient(handler: { request, _, completion in
do {
let contents: String
switch request.url.lastPathComponent {
case "a.artifactbundleindex":
contents = ari
default:
throw StringError("unexpected url \(request.url)")
}
completion(.success(.okay(body: contents)))
} catch {
completion(.failure(error))
}
})
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo", dependencies: ["A"]),
],
products: [],
dependencies: [
.sourceControl(path: "./A", requirement: .exact("1.0.0")),
]
),
],
packages: [
MockPackage(
name: "A",
targets: [
MockTarget(name: "A", type: .binary, url: "https://a.com/a.artifactbundleindex", checksum: ariChecksum),
],
products: [
MockProduct(name: "A", targets: ["A"]),
],
versions: ["0.9.0", "1.0.0"]
),
],
customHttpClient: httpClient
)
workspace.checkPackageGraphFailure(roots: ["Foo"]) { diagnostics in
testDiagnostics(diagnostics) { result in
result.check(diagnostic: .contains("failed retrieving 'https://a.com/a.artifactbundleindex': No supported archive was found for '\(hostToolchain.triple.tripleString)'"), severity: .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,
])
}
func testDuplicateDependencyIdentityWithNameAtRoot() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "Root",
targets: [
MockTarget(name: "RootTarget", dependencies: [
.product(name: "FooProduct", package: "FooUtilityPackage"),
.product(name: "BarProduct", package: "BarUtilityPackage")
]),
],
products: [],
dependencies: [
.sourceControlWithDeprecatedName(name: "FooUtilityPackage", path: "foo/utility", requirement: .upToNextMajor(from: "1.0.0")),
.sourceControlWithDeprecatedName(name: "BarUtilityPackage", path: "bar/utility", requirement: .upToNextMajor(from: "1.0.0")),
],
toolsVersion: .v5
),
],
packages: [
MockPackage(
name: "FooUtilityPackage",
path: "foo/utility",
targets: [
MockTarget(name: "FooTarget"),
],
products: [
MockProduct(name: "FooProduct", targets: ["FooTarget"]),
],
versions: ["1.0.0", "2.0.0"]
),
// this package never gets loaded since the dependency declaration identity is the same as "FooPackage"
MockPackage(
name: "BarUtilityPackage",
path: "bar/utility",
targets: [
MockTarget(name: "BarTarget"),
],
products: [
MockProduct(name: "BarProduct", targets: ["BarTarget"]),
],
versions: ["1.0.0", "2.0.0"]
),
]
)
try workspace.checkPackageGraph(roots: ["Root"]) { graph, diagnostics in
testDiagnostics(diagnostics) { result in
result.check(
diagnostic: "'root' dependency on '/tmp/ws/pkgs/bar/utility' conflicts with dependency on '/tmp/ws/pkgs/foo/utility' which has the same identity 'utility'",
severity: .error
)
}
}
}
func testDuplicateDependencyIdentityWithoutNameAtRoot() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "Root",
targets: [
MockTarget(name: "RootTarget", dependencies: [
.product(name: "FooProduct", package: "FooUtilityPackage"),
.product(name: "BarProduct", package: "BarUtilityPackage")
]),
],
products: [],
dependencies: [
.sourceControl(path: "foo/utility", requirement: .upToNextMajor(from: "1.0.0")),
.sourceControl(path: "bar/utility", requirement: .upToNextMajor(from: "1.0.0")),
],
toolsVersion: .v5
),
],
packages: [
MockPackage(
name: "FooUtilityPackage",
path: "foo/utility",
targets: [
MockTarget(name: "FooTarget"),
],
products: [
MockProduct(name: "FooProduct", targets: ["FooTarget"]),
],
versions: ["1.0.0", "2.0.0"]
),
// this package never gets loaded since the dependency declaration identity is the same as "FooPackage"
MockPackage(
name: "BarUtilityPackage",
path: "bar/utility",
targets: [
MockTarget(name: "BarTarget"),
],
products: [
MockProduct(name: "BarProduct", targets: ["BarTarget"]),
],
versions: ["1.0.0", "2.0.0"]
),
]
)
try workspace.checkPackageGraph(roots: ["Root"]) { graph, diagnostics in
testDiagnostics(diagnostics) { result in
result.check(
diagnostic: "'root' dependency on '/tmp/ws/pkgs/bar/utility' conflicts with dependency on '/tmp/ws/pkgs/foo/utility' which has the same identity 'utility'",
severity: .error
)
}
}
}
func testDuplicateExplicitDependencyName_AtRoot() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "Root",
targets: [
MockTarget(name: "RootTarget", dependencies: [
.product(name: "FooProduct", package: "FooPackage"),
.product(name: "BarProduct", package: "BarPackage")
]),
],
products: [],
dependencies: [
.sourceControlWithDeprecatedName(name: "FooPackage", path: "foo", requirement: .upToNextMajor(from: "1.0.0")),
.sourceControlWithDeprecatedName(name: "FooPackage", path: "bar", requirement: .upToNextMajor(from: "1.0.0")),
],
toolsVersion: .v5
),
],
packages: [
MockPackage(
name: "FooPackage",
path: "foo",
targets: [
MockTarget(name: "FooTarget"),
],
products: [
MockProduct(name: "FooProduct", targets: ["FooTarget"]),
],
versions: ["1.0.0", "2.0.0"]
),
// this package never gets loaded since the dependency declaration name is the same as "FooPackage"
MockPackage(
name: "BarPackage",
path: "bar",
targets: [
MockTarget(name: "BarTarget"),
],
products: [
MockProduct(name: "BarProduct", targets: ["BarTarget"]),
],
versions: ["1.0.0", "2.0.0"]
),
]
)
try workspace.checkPackageGraph(roots: ["Root"]) { graph, diagnostics in
testDiagnostics(diagnostics) { result in
result.check(
diagnostic: "'root' dependency on '/tmp/ws/pkgs/bar' conflicts with dependency on '/tmp/ws/pkgs/foo' which has the same explicit name 'FooPackage'",
severity: .error
)
}
}
}
func testDuplicateManifestNameAtRoot() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "Root",
targets: [
MockTarget(name: "RootTarget", dependencies: [
"FooProduct",
"BarProduct"
]),
],
products: [],
dependencies: [
.sourceControl(path: "foo", requirement: .upToNextMajor(from: "1.0.0")),
.sourceControl(path: "bar", requirement: .upToNextMajor(from: "1.0.0")),
],
toolsVersion: .v5
),
],
packages: [
MockPackage(
name: "MyPackage",
path: "foo",
targets: [
MockTarget(name: "FooTarget"),
],
products: [
MockProduct(name: "FooProduct", targets: ["FooTarget"]),
],
versions: ["1.0.0", "2.0.0"]
),
MockPackage(
name: "MyPackage",
path: "bar",
targets: [
MockTarget(name: "BarTarget"),
],
products: [
MockProduct(name: "BarProduct", targets: ["BarTarget"]),
],
versions: ["1.0.0", "2.0.0"]
),
]
)
try workspace.checkPackageGraph(roots: ["Root"]) { graph, diagnostics in
XCTAssertNoDiagnostics(diagnostics)
}
}
func testDuplicateManifestName_ExplicitProductPackage_AtRoot() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "Root",
targets: [
MockTarget(name: "RootTarget", dependencies: [
.product(name: "FooProduct", package: "foo"),
.product(name: "BarProduct", package: "bar"),
]),
],
products: [],
dependencies: [
.sourceControl(path: "foo", requirement: .upToNextMajor(from: "1.0.0")),
.sourceControl(path: "bar", requirement: .upToNextMajor(from: "1.0.0")),
],
toolsVersion: .v5
),
],
packages: [
MockPackage(
name: "MyPackage",
path: "foo",
targets: [
MockTarget(name: "FooTarget"),
],
products: [
MockProduct(name: "FooProduct", targets: ["FooTarget"]),
],
versions: ["1.0.0", "2.0.0"]
),
MockPackage(
name: "MyPackage",
path: "bar",
targets: [
MockTarget(name: "BarTarget"),
],
products: [
MockProduct(name: "BarProduct", targets: ["BarTarget"]),
],
versions: ["1.0.0", "2.0.0"]
),
]
)
try workspace.checkPackageGraph(roots: ["Root"]) { graph, diagnostics in
XCTAssertNoDiagnostics(diagnostics)
}
}
func testManifestNameAndIdentityConflict_AtRoot_Pre52() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "Root",
targets: [
MockTarget(name: "RootTarget", dependencies: [
"FooProduct",
"BarProduct"
]),
],
products: [],
dependencies: [
.sourceControl(path: "foo", requirement: .upToNextMajor(from: "1.0.0")),
.sourceControl(path: "bar", requirement: .upToNextMajor(from: "1.0.0")),
],
toolsVersion: .v5
),
],
packages: [
MockPackage(
name: "foo",
path: "foo",
targets: [
MockTarget(name: "FooTarget"),
],
products: [
MockProduct(name: "FooProduct", targets: ["FooTarget"]),
],
versions: ["1.0.0", "2.0.0"]
),
MockPackage(
name: "foo",
path: "bar",
targets: [
MockTarget(name: "BarTarget"),
],
products: [
MockProduct(name: "BarProduct", targets: ["BarTarget"]),
],
versions: ["1.0.0", "2.0.0"]
),
]
)
try workspace.checkPackageGraph(roots: ["Root"]) { graph, diagnostics in
XCTAssertNoDiagnostics(diagnostics)
}
}
func testManifestNameAndIdentityConflict_AtRoot_Post52_Incorrect() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "Root",
targets: [
MockTarget(name: "RootTarget", dependencies: [
"FooProduct",
"BarProduct"
]),
],
products: [],
dependencies: [
.sourceControl(path: "foo", requirement: .upToNextMajor(from: "1.0.0")),
.sourceControl(path: "bar", requirement: .upToNextMajor(from: "1.0.0")),
],
toolsVersion: .v5_3
),
],
packages: [
MockPackage(
name: "foo",
path: "foo",
targets: [
MockTarget(name: "FooTarget"),
],
products: [
MockProduct(name: "FooProduct", targets: ["FooTarget"]),
],
versions: ["1.0.0", "2.0.0"]
),
MockPackage(
name: "foo",
path: "bar",
targets: [
MockTarget(name: "BarTarget"),
],
products: [
MockProduct(name: "BarProduct", targets: ["BarTarget"]),
],
versions: ["1.0.0", "2.0.0"]
),
]
)
try workspace.checkPackageGraph(roots: ["Root"]) { graph, diagnostics in
testDiagnostics(diagnostics) { result in
result.check(
diagnostic: "dependency 'FooProduct' in target 'RootTarget' requires explicit declaration; reference the package in the target dependency with '.product(name: \"FooProduct\", package: \"foo\")'",
severity: .error
)
result.check(
diagnostic: "dependency 'BarProduct' in target 'RootTarget' requires explicit declaration; reference the package in the target dependency with '.product(name: \"BarProduct\", package: \"bar\")'",
severity: .error
)
}
}
}
func testManifestNameAndIdentityConflict_AtRoot_Post52_Correct() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "Root",
targets: [
MockTarget(name: "RootTarget", dependencies: [
.product(name: "FooProduct", package: "foo"),
.product(name: "BarProduct", package: "bar"),
]),
],
products: [],
dependencies: [
.sourceControl(path: "foo", requirement: .upToNextMajor(from: "1.0.0")),
.sourceControl(path: "bar", requirement: .upToNextMajor(from: "1.0.0")),
],
toolsVersion: .v5_3
),
],
packages: [
MockPackage(
name: "foo",
path: "foo",
targets: [
MockTarget(name: "FooTarget"),
],
products: [
MockProduct(name: "FooProduct", targets: ["FooTarget"]),
],
versions: ["1.0.0", "2.0.0"]
),
MockPackage(
name: "foo",
path: "bar",
targets: [
MockTarget(name: "BarTarget"),
],
products: [
MockProduct(name: "BarProduct", targets: ["BarTarget"]),
],
versions: ["1.0.0", "2.0.0"]
),
]
)
try workspace.checkPackageGraph(roots: ["Root"]) { graph, diagnostics in
XCTAssertNoDiagnostics(diagnostics)
}
}
func testManifestNameAndIdentityConflict_ExplicitDependencyNames_AtRoot() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "Root",
targets: [
MockTarget(name: "RootTarget", dependencies: [
"FooProduct",
"BarProduct"
]),
],
products: [],
dependencies: [
.sourceControl(path: "foo", requirement: .upToNextMajor(from: "1.0.0")),
.sourceControlWithDeprecatedName(name: "foo", path: "bar", requirement: .upToNextMajor(from: "1.0.0")),
],
toolsVersion: .v5
),
],
packages: [
MockPackage(
name: "foo",
path: "foo",
targets: [
MockTarget(name: "FooTarget"),
],
products: [
MockProduct(name: "FooProduct", targets: ["FooTarget"]),
],
versions: ["1.0.0", "2.0.0"]
),
MockPackage(
name: "foo",
path: "bar",
targets: [
MockTarget(name: "BarTarget"),
],
products: [
MockProduct(name: "BarProduct", targets: ["BarTarget"]),
],
versions: ["1.0.0", "2.0.0"]
),
]
)
try workspace.checkPackageGraph(roots: ["Root"]) { graph, diagnostics in
testDiagnostics(diagnostics) { result in
result.check(
diagnostic: "'root' dependency on '/tmp/ws/pkgs/bar' conflicts with dependency on '/tmp/ws/pkgs/foo' which has the same explicit name 'foo'",
severity: .error
)
}
}
}
func testManifestNameAndIdentityConflict_ExplicitDependencyNames_ExplicitProductPackage_AtRoot() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "Root",
targets: [
MockTarget(name: "RootTarget", dependencies: [
.product(name: "FooProduct", package: "foo"),
.product(name: "BarProduct", package: "bar"),
]),
],
products: [],
dependencies: [
.sourceControl(path: "foo", requirement: .upToNextMajor(from: "1.0.0")),
.sourceControlWithDeprecatedName(name: "foo", path: "bar", requirement: .upToNextMajor(from: "1.0.0")),
],
toolsVersion: .v5_3
),
],
packages: [
MockPackage(
name: "foo",
path: "foo",
targets: [
MockTarget(name: "FooTarget"),
],
products: [
MockProduct(name: "FooProduct", targets: ["FooTarget"]),
],
versions: ["1.0.0", "2.0.0"]
),
MockPackage(
name: "foo",
path: "bar",
targets: [
MockTarget(name: "BarTarget"),
],
products: [
MockProduct(name: "BarProduct", targets: ["BarTarget"]),
],
versions: ["1.0.0", "2.0.0"]
),
]
)
try workspace.checkPackageGraph(roots: ["Root"]) { graph, diagnostics in
testDiagnostics(diagnostics) { result in
result.check(
diagnostic: "'root' dependency on '/tmp/ws/pkgs/bar' conflicts with dependency on '/tmp/ws/pkgs/foo' which has the same explicit name 'foo'",
severity: .error
)
}
}
}
func testDuplicateTransitiveIdentityWithNames() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "Root",
targets: [
MockTarget(name: "RootTarget", dependencies: [
.product(name: "FooUtilityProduct", package: "FooUtilityPackage"),
.product(name: "BarProduct", package: "BarPackage")
]),
],
products: [],
dependencies: [
.sourceControlWithDeprecatedName(name: "FooUtilityPackage", path: "foo/utility", requirement: .upToNextMajor(from: "1.0.0")),
.sourceControlWithDeprecatedName(name: "BarPackage", path: "bar", requirement: .upToNextMajor(from: "1.0.0")),
],
toolsVersion: .v5
),
],
packages: [
MockPackage(
name: "FooUtilityPackage",
path: "foo/utility",
targets: [
MockTarget(name: "FooUtilityTarget"),
],
products: [
MockProduct(name: "FooUtilityProduct", targets: ["FooUtilityTarget"]),
],
versions: ["1.0.0"]
),
MockPackage(
name: "BarPackage",
path: "bar",
targets: [
MockTarget(name: "BarTarget", dependencies: [
.product(name: "OtherUtilityProduct", package: "OtherUtilityPackage"),
]),
],
products: [
MockProduct(name: "BarProduct", targets: ["BarTarget"]),
],
dependencies: [
.sourceControlWithDeprecatedName(name: "OtherUtilityPackage", path: "other/utility", requirement: .upToNextMajor(from: "1.0.0")),
],
versions: ["1.0.0"]
),
// this package never gets loaded since its identity is the same as "FooPackage"
MockPackage(
name: "OtherUtilityPackage",
path: "other/utility",
targets: [
MockTarget(name: "OtherUtilityTarget"),
],
products: [
MockProduct(name: "OtherUtilityProduct", targets: ["OtherUtilityTarget"]),
],
versions: ["1.0.0"]
),
]
)
try workspace.checkPackageGraph(roots: ["Root"]) { graph, diagnostics in
testDiagnostics(diagnostics) { result in
result.check(
diagnostic: "'bar' dependency on '/tmp/ws/pkgs/other/utility' conflicts with dependency on '/tmp/ws/pkgs/foo/utility' which has the same identity 'utility'",
severity: .error
)
}
}
}
func testDuplicateTransitiveIdentityWithoutNames() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "Root",
targets: [
MockTarget(name: "RootTarget", dependencies: [
.product(name: "FooUtilityProduct", package: "utility"),
.product(name: "BarProduct", package: "bar")
]),
],
products: [],
dependencies: [
.sourceControl(path: "foo/utility", requirement: .upToNextMajor(from: "1.0.0")),
.sourceControl(path: "bar", requirement: .upToNextMajor(from: "1.0.0")),
],
toolsVersion: .v5
),
],
packages: [
MockPackage(
name: "FooUtilityPackage",
path: "foo/utility",
targets: [
MockTarget(name: "FooUtilityTarget"),
],
products: [
MockProduct(name: "FooUtilityProduct", targets: ["FooUtilityTarget"]),
],
versions: ["1.0.0"]
),
MockPackage(
name: "BarPackage",
path: "bar",
targets: [
MockTarget(name: "BarTarget", dependencies: [
.product(name: "OtherUtilityProduct", package: "utility"),
]),
],
products: [
MockProduct(name: "BarProduct", targets: ["BarTarget"]),
],
dependencies: [
.sourceControl(path: "other-foo/utility", requirement: .upToNextMajor(from: "1.0.0")),
],
versions: ["1.0.0"]
),
// this package never gets loaded since its identity is the same as "FooPackage"
MockPackage(
name: "OtherUtilityPackage",
path: "other-foo/utility",
targets: [
MockTarget(name: "OtherUtilityTarget"),
],
products: [
MockProduct(name: "OtherUtilityProduct", targets: ["OtherUtilityTarget"]),
],
versions: ["1.0.0"]
),
]
)
// 9/2021 this is currently emitting a warning only to support backwards compatibility
// we will escalate this to an error in a few versions to tighten up the validation
try workspace.checkPackageGraph(roots: ["Root"]) { graph, diagnostics in
testDiagnostics(diagnostics) { result in
result.check(
diagnostic: "'bar' dependency on '/tmp/ws/pkgs/other-foo/utility' conflicts with dependency on '/tmp/ws/pkgs/foo/utility' which has the same identity 'utility'. this will be escalated to an error in future versions of SwiftPM.",
severity: .warning
)
// FIXME: rdar://72940946
// we need to improve this situation or diagnostics when working on identity
result.check(
diagnostic: "product 'OtherUtilityProduct' required by package 'bar' target 'BarTarget' not found in package 'utility'.",
severity: .error
)
}
}
}
func testDuplicateTransitiveIdentitySimilarURLs1() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "Root",
targets: [
MockTarget(name: "RootTarget", dependencies: [
.product(name: "FooProduct", package: "foo"),
.product(name: "BarProduct", package: "bar")
]),
],
products: [],
dependencies: [
.sourceControl(url: "https://github.com/foo/foo", requirement: .upToNextMajor(from: "1.0.0")),
.sourceControl(path: "bar", requirement: .upToNextMajor(from: "1.0.0")),
],
toolsVersion: .v5_6
),
],
packages: [
MockPackage(
name: "FooPackage",
url: "https://github.com/foo/foo",
targets: [
MockTarget(name: "FooTarget"),
],
products: [
MockProduct(name: "FooProduct", targets: ["FooTarget"]),
],
versions: ["1.0.0"]
),
MockPackage(
name: "BarPackage",
path: "bar",
targets: [
MockTarget(name: "BarTarget", dependencies: [
.product(name: "FooProduct", package: "foo"),
]),
],
products: [
MockProduct(name: "BarProduct", targets: ["BarTarget"]),
],
dependencies: [
.sourceControl(url: "https://github.com/foo/foo.git", requirement: .upToNextMajor(from: "1.0.0")),
],
versions: ["1.0.0"]
),
// this package never gets loaded since its identity is the same as "FooPackage"
MockPackage(
name: "FooPackage",
url: "https://github.com/foo/foo.git",
targets: [
MockTarget(name: "FooTarget"),
],
products: [
MockProduct(name: "FooProduct", targets: ["FooTarget"]),
],
versions: ["1.0.0"]
),
]
)
try workspace.checkPackageGraph(roots: ["Root"]) { graph, diagnostics in
XCTAssertNoDiagnostics(diagnostics)
}
}
func testDuplicateTransitiveIdentitySimilarURLs2() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "Root",
targets: [
MockTarget(name: "RootTarget", dependencies: [
.product(name: "FooProduct", package: "foo"),
.product(name: "BarProduct", package: "bar")
]),
],
products: [],
dependencies: [
.sourceControl(url: "https://github.com/foo/foo.git", requirement: .upToNextMajor(from: "1.0.0")),
.sourceControl(path: "bar", requirement: .upToNextMajor(from: "1.0.0")),
],
toolsVersion: .v5_6
),
],
packages: [
MockPackage(
name: "FooPackage",
url: "https://github.com/foo/foo.git",
targets: [
MockTarget(name: "FooTarget"),
],
products: [
MockProduct(name: "FooProduct", targets: ["FooTarget"]),
],
versions: ["1.0.0"]
),
MockPackage(
name: "BarPackage",
path: "bar",
targets: [
MockTarget(name: "BarTarget", dependencies: [
.product(name: "FooProduct", package: "foo"),
]),
],
products: [
MockProduct(name: "BarProduct", targets: ["BarTarget"]),
],
dependencies: [
.sourceControl(url: "http://github.com/foo/foo", requirement: .upToNextMajor(from: "1.0.0")),
],
versions: ["1.0.0"]
),
// this package never gets loaded since its identity is the same as "FooPackage"
MockPackage(
name: "FooPackage",
url: "http://github.com/foo/foo",
targets: [
MockTarget(name: "FooTarget"),
],
products: [
MockProduct(name: "FooProduct", targets: ["FooTarget"]),
],
versions: ["1.0.0"]
),
]
)
try workspace.checkPackageGraph(roots: ["Root"]) { graph, diagnostics in
XCTAssertNoDiagnostics(diagnostics)
}
}
func testDuplicateTransitiveIdentityGitHubURLs1() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "Root",
targets: [
MockTarget(name: "RootTarget", dependencies: [
.product(name: "FooProduct", package: "foo"),
.product(name: "BarProduct", package: "bar")
]),
],
products: [],
dependencies: [
.sourceControl(url: "https://github.com/foo/foo.git", requirement: .upToNextMajor(from: "1.0.0")),
.sourceControl(path: "bar", requirement: .upToNextMajor(from: "1.0.0")),
],
toolsVersion: .v5_6
),
],
packages: [
MockPackage(
name: "FooPackage",
url: "https://github.com/foo/foo.git",
targets: [
MockTarget(name: "FooTarget"),
],
products: [
MockProduct(name: "FooProduct", targets: ["FooTarget"]),
],
versions: ["1.0.0"]
),
MockPackage(
name: "BarPackage",
path: "bar",
targets: [
MockTarget(name: "BarTarget", dependencies: [
.product(name: "FooProduct", package: "foo"),
]),
],
products: [
MockProduct(name: "BarProduct", targets: ["BarTarget"]),
],
dependencies: [
.sourceControl(url: "[email protected]:foo/foo.git", requirement: .upToNextMajor(from: "1.0.0")),
],
versions: ["1.0.0"]
),
// this package never gets loaded since its identity is the same as "FooPackage"
MockPackage(
name: "FooPackage",
url: "[email protected]:foo/foo.git",
targets: [
MockTarget(name: "FooTarget"),
],
products: [
MockProduct(name: "FooProduct", targets: ["FooTarget"]),
],
versions: ["1.0.0"]
),
]
)
try workspace.checkPackageGraph(roots: ["Root"]) { graph, diagnostics in
XCTAssertNoDiagnostics(diagnostics)
}
}
func testDuplicateTransitiveIdentityGitHubURLs2() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "Root",
targets: [
MockTarget(name: "RootTarget", dependencies: [
.product(name: "FooProduct", package: "foo"),
.product(name: "BarProduct", package: "bar")
]),
],
products: [],
dependencies: [
.sourceControl(url: "https://github.enterprise.com/foo/foo", requirement: .upToNextMajor(from: "1.0.0")),
.sourceControl(path: "bar", requirement: .upToNextMajor(from: "1.0.0")),
],
toolsVersion: .v5_6
),
],
packages: [
MockPackage(
name: "FooPackage",
url: "https://github.enterprise.com/foo/foo",
targets: [
MockTarget(name: "FooTarget"),
],
products: [
MockProduct(name: "FooProduct", targets: ["FooTarget"]),
],
versions: ["1.0.0"]
),
MockPackage(
name: "BarPackage",
path: "bar",
targets: [
MockTarget(name: "BarTarget", dependencies: [
.product(name: "FooProduct", package: "foo"),
]),
],
products: [
MockProduct(name: "BarProduct", targets: ["BarTarget"]),
],
dependencies: [
.sourceControl(url: "[email protected]:foo/foo.git", requirement: .upToNextMajor(from: "1.0.0")),
],
versions: ["1.0.0"]
),
// this package never gets loaded since its identity is the same as "FooPackage"
MockPackage(
name: "FooPackage",
url: "[email protected]:foo/foo.git",
targets: [
MockTarget(name: "FooTarget"),
],
products: [
MockProduct(name: "FooProduct", targets: ["FooTarget"]),
],
versions: ["1.0.0"]
),
]
)
try workspace.checkPackageGraph(roots: ["Root"]) { graph, diagnostics in
XCTAssertNoDiagnostics(diagnostics)
}
}
func testDuplicateTransitiveIdentityUnfamiliarURLs() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "Root",
targets: [
MockTarget(name: "RootTarget", dependencies: [
.product(name: "FooProduct", package: "foo"),
.product(name: "BarProduct", package: "bar")
]),
],
products: [],
dependencies: [
.sourceControl(url: "https://github.com/foo/foo.git", requirement: .upToNextMajor(from: "1.0.0")),
.sourceControl(path: "bar", requirement: .upToNextMajor(from: "1.0.0")),
],
toolsVersion: .v5_6
),
],
packages: [
MockPackage(
name: "FooPackage",
url: "https://github.com/foo/foo.git",
targets: [
MockTarget(name: "FooTarget"),
],
products: [
MockProduct(name: "FooProduct", targets: ["FooTarget"]),
],
versions: ["1.0.0"]
),
MockPackage(
name: "BarPackage",
path: "bar",
targets: [
MockTarget(name: "BarTarget", dependencies: [
.product(name: "FooProduct", package: "foo"),
]),
],
products: [
MockProduct(name: "BarProduct", targets: ["BarTarget"]),
],
dependencies: [
.sourceControl(url: "https://github.com/foo-moved/foo.git", requirement: .upToNextMajor(from: "1.0.0")),
],
versions: ["1.0.0"]
),
// this package never gets loaded since its identity is the same as "FooPackage"
MockPackage(
name: "FooPackage",
url: "https://github.com/foo-moved/foo.git",
targets: [
MockTarget(name: "FooTarget"),
],
products: [
MockProduct(name: "FooProduct", targets: ["FooTarget"]),
],
versions: ["1.0.0"]
),
]
)
// 9/2021 this is currently emitting a warning only to support backwards compatibility
// we will escalate this to an error in a few versions to tighten up the validation
try workspace.checkPackageGraph(roots: ["Root"]) { graph, diagnostics in
testDiagnostics(diagnostics) { result in
result.check(
diagnostic: "'bar' dependency on 'https://github.com/foo-moved/foo.git' conflicts with dependency on 'https://github.com/foo/foo.git' which has the same identity 'foo'. this will be escalated to an error in future versions of SwiftPM.",
severity: .warning
)
}
}
}
func testDuplicateTransitiveIdentityWithSimilarURLs() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "Root",
targets: [
MockTarget(name: "RootTarget", dependencies: [
.product(name: "FooProduct", package: "foo"),
.product(name: "BarProduct", package: "bar"),
.product(name: "BazProduct", package: "baz")
]),
],
products: [],
dependencies: [
.sourceControl(url: "https://github.com/org/foo.git", requirement: .upToNextMajor(from: "1.0.0")),
.sourceControl(url: "https://github.com/org/bar.git", requirement: .upToNextMajor(from: "1.0.0")),
.sourceControl(url: "https://github.com/org/baz.git", requirement: .upToNextMajor(from: "1.0.0")),
],
toolsVersion: .v5_6
),
],
packages: [
MockPackage(
name: "FooPackage",
url: "https://github.com/org/foo.git",
targets: [
MockTarget(name: "FooTarget"),
],
products: [
MockProduct(name: "FooProduct", targets: ["FooTarget"]),
],
versions: ["1.0.0"]
),
MockPackage(
name: "BarPackage",
url: "https://github.com/org/bar.git",
targets: [
MockTarget(name: "BarTarget", dependencies: [
.product(name: "FooProduct", package: "Foo"),
.product(name: "BazProduct", package: "baz"),
]),
],
products: [
MockProduct(name: "BarProduct", targets: ["BarTarget"]),
],
dependencies: [
.sourceControl(url: "https://github.com/ORG/Foo.git", requirement: .upToNextMajor(from: "1.0.0")),
.sourceControl(url: "https://github.com/org/baz", requirement: .upToNextMajor(from: "1.0.0")),
],
versions: ["1.0.0"]
),
MockPackage(
name: "BazPackage",
url: "https://github.com/org/baz.git",
targets: [
MockTarget(name: "BazTarget"),
],
products: [
MockProduct(name: "BazProduct", targets: ["BazTarget"]),
],
versions: ["1.0.0"]
),
// URL with different casing
MockPackage(
name: "FooPackage",
url: "https://github.com/ORG/Foo.git",
targets: [
MockTarget(name: "FooTarget"),
],
products: [
MockProduct(name: "FooProduct", targets: ["FooTarget"]),
],
versions: ["1.0.0"]
),
// URL with no .git extension
MockPackage(
name: "BazPackage",
url: "https://github.com/org/baz",
targets: [
MockTarget(name: "BazTarget"),
],
products: [
MockProduct(name: "BazProduct", targets: ["BazTarget"]),
],
versions: ["1.0.0"]
),
]
)
// 9/2021 this is currently emitting a warning only to support backwards compatibility
// we will escalate this to an error in a few versions to tighten up the validation
try workspace.checkPackageGraph(roots: ["Root"]) { graph, diagnostics in
testDiagnostics(diagnostics, minSeverity: .info) { result in
result.checkUnordered(
diagnostic: "dependency on 'foo' is represented by similar locations ('https://github.com/org/foo.git' and 'https://github.com/ORG/Foo.git') which are treated as the same canonical location 'github.com/org/foo'.",
severity: .info
)
result.checkUnordered(
diagnostic: "dependency on 'baz' is represented by similar locations ('https://github.com/org/baz.git' and 'https://github.com/org/baz') which are treated as the same canonical location 'github.com/org/baz'.",
severity: .info
)
}
}
}
func testDuplicateNestedTransitiveIdentityWithNames() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "Root",
targets: [
MockTarget(name: "RootTarget", dependencies: [
.product(name: "FooUtilityProduct", package: "FooUtilityPackage")
]),
],
products: [],
dependencies: [
.sourceControlWithDeprecatedName(name: "FooUtilityPackage", path: "foo/utility", requirement: .upToNextMajor(from: "1.0.0")),
],
toolsVersion: .v5
),
],
packages: [
MockPackage(
name: "FooUtilityPackage",
path: "foo/utility",
targets: [
MockTarget(name: "FooUtilityTarget", dependencies: [
.product(name: "BarProduct", package: "BarPackage")
]),
],
products: [
MockProduct(name: "FooUtilityProduct", targets: ["FooUtilityTarget"]),
],
dependencies: [
.sourceControlWithDeprecatedName(name: "BarPackage", path: "bar", requirement: .upToNextMajor(from: "1.0.0")),
],
versions: ["1.0.0"]
),
MockPackage(
name: "BarPackage",
path: "bar",
targets: [
MockTarget(name: "BarTarget", dependencies: [
.product(name: "OtherUtilityProduct", package: "OtherUtilityPackage"),
]),
],
products: [
MockProduct(name: "BarProduct", targets: ["BarTarget"]),
],
dependencies: [
.sourceControlWithDeprecatedName(name: "OtherUtilityPackage", path: "other/utility", requirement: .upToNextMajor(from: "1.0.0")),
],
versions: ["1.0.0"]
),
// this package never gets loaded since its identity is the same as "FooPackage"
MockPackage(
name: "OtherUtilityPackage",
path: "other/utility",
targets: [
MockTarget(name: "OtherUtilityTarget"),
],
products: [
MockProduct(name: "OtherUtilityProduct", targets: ["OtherUtilityTarget"]),
],
versions: ["1.0.0"]
),
]
)
try workspace.checkPackageGraph(roots: ["Root"]) { graph, diagnostics in
testDiagnostics(diagnostics) { result in
// FIXME: rdar://72940946
// we need to improve this situation or diagnostics when working on identity
result.check(
diagnostic: "cyclic dependency declaration found: Root -> FooUtilityPackage -> BarPackage -> FooUtilityPackage",
severity: .error
)
}
}
}
func testDuplicateNestedTransitiveIdentityWithoutNames() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "Root",
targets: [
MockTarget(name: "RootTarget", dependencies: [
.product(name: "FooUtilityProduct", package: "FooUtilityPackage")
]),
],
products: [],
dependencies: [
.sourceControl(path: "foo/utility", requirement: .upToNextMajor(from: "1.0.0")),
],
toolsVersion: .v5
),
],
packages: [
MockPackage(
name: "FooUtilityPackage",
path: "foo/utility",
targets: [
MockTarget(name: "FooUtilityTarget", dependencies: [
.product(name: "BarProduct", package: "BarPackage")
]),
],
products: [
MockProduct(name: "FooUtilityProduct", targets: ["FooUtilityTarget"]),
],
dependencies: [
.sourceControl(path: "bar", requirement: .upToNextMajor(from: "1.0.0")),
],
versions: ["1.0.0"],
toolsVersion: .v5
),
MockPackage(
name: "BarPackage",
path: "bar",
targets: [
MockTarget(name: "BarTarget", dependencies: [
.product(name: "OtherUtilityProduct", package: "OtherUtilityPackage"),
]),
],
products: [
MockProduct(name: "BarProduct", targets: ["BarTarget"]),
],
dependencies: [
.sourceControl(path: "other/utility", requirement: .upToNextMajor(from: "1.0.0")),
],
versions: ["1.0.0"],
toolsVersion: .v5
),
// this package never gets loaded since its identity is the same as "FooPackage"
MockPackage(
name: "OtherUtilityPackage",
path: "other/utility",
targets: [
MockTarget(name: "OtherUtilityTarget"),
],
products: [
MockProduct(name: "OtherUtilityProduct", targets: ["OtherUtilityTarget"]),
],
versions: ["1.0.0"]
),
]
)
try workspace.checkPackageGraph(roots: ["Root"]) { graph, diagnostics in
testDiagnostics(diagnostics) { result in
// FIXME: rdar://72940946
// we need to improve this situation or diagnostics when working on identity
result.check(
diagnostic: "cyclic dependency declaration found: Root -> FooUtilityPackage -> BarPackage -> FooUtilityPackage",
severity: .error
)
}
}
}
func testRootPathConflictsWithTransitiveIdentity() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "Root",
path: "foo",
targets: [
MockTarget(name: "RootTarget", dependencies: [
.product(name: "BarProduct", package: "BarPackage")
]),
],
products: [],
dependencies: [
.sourceControlWithDeprecatedName(name: "BarPackage", path: "bar", requirement: .upToNextMajor(from: "1.0.0")),
],
toolsVersion: .v5
),
],
packages: [
MockPackage(
name: "BarPackage",
path: "bar",
targets: [
MockTarget(name: "BarTarget", dependencies: [
.product(name: "FooProduct", package: "FooPackage"),
]),
],
products: [
MockProduct(name: "BarProduct", targets: ["BarTarget"]),
],
dependencies: [
.sourceControlWithDeprecatedName(name: "FooPackage", path: "foo", requirement: .upToNextMajor(from: "1.0.0")),
],
versions: ["1.0.0"]
),
// this package never gets loaded since its identity is the same as "FooPackage"
MockPackage(
name: "FooPackage",
path: "foo",
targets: [
MockTarget(name: "FooTarget"),
],
products: [
MockProduct(name: "FooProduct", targets: ["FooTarget"]),
],
versions: ["1.0.0"]
),
]
)
try workspace.checkPackageGraph(roots: ["foo"]) { graph, diagnostics in
testDiagnostics(diagnostics) { result in
// FIXME: rdar://72940946
// we need to improve this situation or diagnostics when working on identity
result.check(
diagnostic: "cyclic dependency declaration found: Root -> BarPackage -> Root",
severity: .error
)
}
}
}
func testBinaryArtifactsInvalidPath() throws {
try testWithTemporaryDirectory { path in
let fs = localFileSystem
let observability = ObservabilitySystem.makeForTesting()
let foo = path.appending(component: "foo")
try fs.writeFileContents(foo.appending(component: "Package.swift")) {
$0 <<<
"""
// swift-tools-version:5.3
import PackageDescription
let package = Package(
name: "Best",
targets: [
.binaryTarget(name: "best", path: "/best.xcframework")
]
)
"""
}
let manifestLoader = ManifestLoader(toolchain: ToolchainConfiguration.default)
let sandbox = path.appending(component: "ws")
let workspace = try Workspace(
fileSystem: fs,
location: .init(forRootPackage: sandbox, fileSystem: fs),
customManifestLoader: manifestLoader,
delegate: MockWorkspaceDelegate()
)
do {
try workspace.resolve(root: .init(packages: [foo]), observabilityScope: observability.topScope)
} catch {
XCTAssertEqual(error.localizedDescription, "invalid relative path '/best.xcframework'; relative path should not begin with '/' or '~'")
return
}
XCTFail("unexpected success")
}
}
func testManifestLoaderDiagnostics() throws {
struct TestLoader: ManifestLoaderProtocol {
let error: Error?
init (error: Error?) {
self.error = error
}
func load(
at path: AbsolutePath,
packageIdentity: PackageIdentity,
packageKind: PackageReference.Kind,
packageLocation: String,
version: Version?,
revision: String?,
toolsVersion: ToolsVersion,
identityResolver: IdentityResolver,
fileSystem: FileSystem,
observabilityScope: ObservabilityScope,
on queue: DispatchQueue,
completion: @escaping (Result<Manifest, Error>) -> Void
) {
if let error = self.error {
completion(.failure(error))
} else {
completion(.success(
.init(
displayName: packageIdentity.description,
path: path,
packageKind: packageKind,
packageLocation: packageLocation,
platforms: [],
toolsVersion: toolsVersion)
)
)
}
}
func resetCache() throws {}
func purgeCache() throws {}
}
let fs = InMemoryFileSystem()
let observability = ObservabilitySystem.makeForTesting()
do {
// no error
let delegate = MockWorkspaceDelegate()
let workspace = try Workspace(
fileSystem: fs,
location: .init(forRootPackage: .root, fileSystem: fs),
customManifestLoader: TestLoader(error: .none),
delegate: delegate
)
try workspace.loadPackageGraph(rootPath: .root, observabilityScope: observability.topScope)
XCTAssertNotNil(delegate.manifest)
XCTAssertEqual(delegate.manifestLoadingDiagnostics?.count, 0)
}
do {
// Diagnostics.fatalError
let delegate = MockWorkspaceDelegate()
let workspace = try Workspace(
fileSystem: fs,
location: .init(forRootPackage: .root, fileSystem: fs),
customManifestLoader: TestLoader(error: Diagnostics.fatalError),
delegate: delegate
)
try workspace.loadPackageGraph(rootPath: .root, observabilityScope: observability.topScope)
XCTAssertNil(delegate.manifest)
XCTAssertEqual(delegate.manifestLoadingDiagnostics?.count, 0)
}
do {
// actual error
let delegate = MockWorkspaceDelegate()
let workspace = try Workspace(
fileSystem: fs,
location: .init(forRootPackage: .root, fileSystem: fs),
customManifestLoader: TestLoader(error: StringError("boom")),
delegate: delegate
)
try workspace.loadPackageGraph(rootPath: .root, observabilityScope: observability.topScope)
XCTAssertNil(delegate.manifest)
XCTAssertEqual(delegate.manifestLoadingDiagnostics?.count, 1)
XCTAssertEqual(delegate.manifestLoadingDiagnostics?.first?.message, "boom")
}
}
func testBasicResolutionFromSourceControl() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "MyPackage",
targets: [
MockTarget(
name: "MyTarget1",
dependencies: [
.product(name: "Foo", package: "foo")
]),
MockTarget(
name: "MyTarget2",
dependencies: [
.product(name: "Bar", package: "bar")
]),
],
products: [
MockProduct(name: "MyProduct", targets: ["MyTarget1", "MyTarget2"]),
],
dependencies: [
.sourceControl(url: "http://localhost/org/foo", requirement: .upToNextMajor(from: "1.0.0")),
.sourceControl(url: "http://localhost/org/bar", requirement: .upToNextMajor(from: "2.0.0")),
]
),
],
packages: [
MockPackage(
name: "Foo",
url: "http://localhost/org/foo",
targets: [
MockTarget(name: "Foo")
],
products: [
MockProduct(name: "Foo", targets: ["Foo"]),
],
versions: ["1.0.0", "1.1.0", "1.2.0", "1.3.0", "1.4.0", "1.5.0", "1.5.1"]
),
MockPackage(
name: "Bar",
url: "http://localhost/org/bar",
targets: [
MockTarget(name: "Bar")
],
products: [
MockProduct(name: "Bar", targets: ["Bar"]),
],
versions: ["2.0.0", "2.1.0", "2.2.0"]
),
]
)
try workspace.checkPackageGraph(roots: ["MyPackage"]) { graph, diagnostics in
XCTAssertNoDiagnostics(diagnostics)
PackageGraphTester(graph) { result in
result.check(roots: "MyPackage")
result.check(packages: "Bar", "Foo", "MyPackage")
result.check(targets: "Foo", "Bar", "MyTarget1", "MyTarget2")
result.checkTarget("MyTarget1") { result in result.check(dependencies: "Foo") }
result.checkTarget("MyTarget2") { result in result.check(dependencies: "Bar") }
}
}
workspace.checkManagedDependencies { result in
result.check(dependency: "foo", at: .checkout(.version("1.5.1")))
result.check(dependency: "bar", at: .checkout(.version("2.2.0")))
}
// Check the load-package callbacks.
XCTAssertMatch(workspace.delegate.events, ["will load manifest for root package: /tmp/ws/roots/MyPackage"])
XCTAssertMatch(workspace.delegate.events, ["did load manifest for root package: /tmp/ws/roots/MyPackage"])
XCTAssertMatch(workspace.delegate.events, ["will load manifest for remoteSourceControl package: http://localhost/org/foo"])
XCTAssertMatch(workspace.delegate.events, ["did load manifest for remoteSourceControl package: http://localhost/org/foo"])
XCTAssertMatch(workspace.delegate.events, ["will load manifest for remoteSourceControl package: http://localhost/org/bar"])
XCTAssertMatch(workspace.delegate.events, ["did load manifest for remoteSourceControl package: http://localhost/org/bar"])
}
func testBasicTransitiveResolutionFromSourceControl() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "MyPackage",
targets: [
MockTarget(
name: "MyTarget1",
dependencies: [
.product(name: "Foo", package: "foo")
]),
MockTarget(
name: "MyTarget2",
dependencies: [
.product(name: "Bar", package: "bar")
]),
],
products: [
MockProduct(name: "MyProduct", targets: ["MyTarget1", "MyTarget2"]),
],
dependencies: [
.sourceControl(url: "http://localhost/org/foo", requirement: .upToNextMajor(from: "1.0.0")),
.sourceControl(url: "http://localhost/org/bar", requirement: .upToNextMajor(from: "2.0.0")),
]
),
],
packages: [
MockPackage(
name: "Foo",
url: "http://localhost/org/foo",
targets: [
MockTarget(
name: "Foo",
dependencies: [
.product(name: "Baz", package: "baz")
]),
],
products: [
MockProduct(name: "Foo", targets: ["Foo"]),
],
dependencies: [
.sourceControl(url: "http://localhost/org/baz", requirement: .range("2.0.0" ..< "4.0.0")),
],
versions: ["1.0.0", "1.1.0"]
),
MockPackage(
name: "Bar",
url: "http://localhost/org/bar",
targets: [
MockTarget(
name: "Bar",
dependencies: [
.product(name: "Baz", package: "baz")
]),
],
products: [
MockProduct(name: "Bar", targets: ["Bar"]),
],
dependencies: [
.sourceControl(url: "http://localhost/org/baz", requirement: .upToNextMajor(from: "3.0.0")),
],
versions: ["2.0.0", "2.1.0"]
),
MockPackage(
name: "Baz",
url: "http://localhost/org/baz",
targets: [
MockTarget(name: "Baz"),
],
products: [
MockProduct(name: "Baz", targets: ["Baz"]),
],
versions: ["1.0.0", "1.1.0", "2.0.0", "2.1.0", "3.0.0", "3.1.0"]
),
]
)
try workspace.checkPackageGraph(roots: ["MyPackage"]) { graph, diagnostics in
XCTAssertNoDiagnostics(diagnostics)
PackageGraphTester(graph) { result in
result.check(roots: "MyPackage")
result.check(packages: "Bar", "Baz", "Foo", "MyPackage")
result.check(targets: "Foo", "Bar", "Baz", "MyTarget1", "MyTarget2")
result.checkTarget("MyTarget1") { result in result.check(dependencies: "Foo") }
result.checkTarget("MyTarget2") { result in result.check(dependencies: "Bar") }
result.checkTarget("Foo") { result in result.check(dependencies: "Baz") }
result.checkTarget("Bar") { result in result.check(dependencies: "Baz") }
}
}
workspace.checkManagedDependencies { result in
result.check(dependency: "foo", at: .checkout(.version("1.1.0")))
result.check(dependency: "bar", at: .checkout(.version("2.1.0")))
result.check(dependency: "baz", at: .checkout(.version("3.1.0")))
}
// Check the load-package callbacks.
XCTAssertMatch(workspace.delegate.events, ["will load manifest for root package: /tmp/ws/roots/MyPackage"])
XCTAssertMatch(workspace.delegate.events, ["did load manifest for root package: /tmp/ws/roots/MyPackage"])
XCTAssertMatch(workspace.delegate.events, ["will load manifest for remoteSourceControl package: http://localhost/org/foo"])
XCTAssertMatch(workspace.delegate.events, ["did load manifest for remoteSourceControl package: http://localhost/org/foo"])
XCTAssertMatch(workspace.delegate.events, ["will load manifest for remoteSourceControl package: http://localhost/org/bar"])
XCTAssertMatch(workspace.delegate.events, ["did load manifest for remoteSourceControl package: http://localhost/org/bar"])
XCTAssertMatch(workspace.delegate.events, ["will load manifest for remoteSourceControl package: http://localhost/org/baz"])
XCTAssertMatch(workspace.delegate.events, ["did load manifest for remoteSourceControl package: http://localhost/org/baz"])
}
func testBasicResolutionFromRegistry() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "MyPackage",
targets: [
MockTarget(
name: "MyTarget1",
dependencies: [
.product(name: "Foo", package: "org.foo")
]),
MockTarget(
name: "MyTarget2",
dependencies: [
.product(name: "Bar", package: "org.bar")
]),
],
products: [
MockProduct(name: "MyProduct", targets: ["MyTarget1", "MyTarget2"]),
],
dependencies: [
.registry(identity: "org.foo", requirement: .upToNextMajor(from: "1.0.0")),
.registry(identity: "org.bar", requirement: .upToNextMajor(from: "2.0.0")),
]
),
],
packages: [
MockPackage(
name: "Foo",
identity: "org.foo",
targets: [
MockTarget(name: "Foo"),
],
products: [
MockProduct(name: "Foo", targets: ["Foo"]),
],
versions: ["1.0.0", "1.1.0", "1.2.0", "1.3.0", "1.4.0", "1.5.0", "1.5.1"]
),
MockPackage(
name: "Bar",
identity: "org.bar",
targets: [
MockTarget(name: "Bar"),
],
products: [
MockProduct(name: "Bar", targets: ["Bar"]),
],
versions: ["2.0.0", "2.1.0", "2.2.0"]
),
]
)
try workspace.checkPackageGraph(roots: ["MyPackage"]) { graph, diagnostics in
XCTAssertNoDiagnostics(diagnostics)
PackageGraphTester(graph) { result in
result.check(roots: "MyPackage")
result.check(packages: "Bar", "Foo", "MyPackage")
result.check(targets: "Foo", "Bar", "MyTarget1", "MyTarget2")
result.checkTarget("MyTarget1") { result in result.check(dependencies: "Foo") }
result.checkTarget("MyTarget2") { result in result.check(dependencies: "Bar") }
}
}
workspace.checkManagedDependencies { result in
result.check(dependency: "org.foo", at: .registryDownload("1.5.1"))
result.check(dependency: "org.bar", at: .registryDownload("2.2.0"))
}
// Check the load-package callbacks.
XCTAssertMatch(workspace.delegate.events, ["will load manifest for root package: /tmp/ws/roots/MyPackage"])
XCTAssertMatch(workspace.delegate.events, ["did load manifest for root package: /tmp/ws/roots/MyPackage"])
XCTAssertMatch(workspace.delegate.events, ["will load manifest for registry package: org.foo"])
XCTAssertMatch(workspace.delegate.events, ["did load manifest for registry package: org.foo"])
XCTAssertMatch(workspace.delegate.events, ["will load manifest for registry package: org.bar"])
XCTAssertMatch(workspace.delegate.events, ["did load manifest for registry package: org.bar"])
}
func testBasicTransitiveResolutionFromRegistry() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "MyPackage",
targets: [
MockTarget(
name: "MyTarget1",
dependencies: [
.product(name: "Foo", package: "org.foo")
]),
MockTarget(
name: "MyTarget2",
dependencies: [
.product(name: "Bar", package: "org.bar")
]),
],
products: [
MockProduct(name: "MyProduct", targets: ["MyTarget1", "MyTarget2"]),
],
dependencies: [
.registry(identity: "org.foo", requirement: .upToNextMajor(from: "1.0.0")),
.registry(identity: "org.bar", requirement: .upToNextMajor(from: "2.0.0")),
]
),
],
packages: [
MockPackage(
name: "Foo",
identity: "org.foo",
targets: [
MockTarget(
name: "Foo",
dependencies: [
.product(name: "Baz", package: "org.baz")
]),
],
products: [
MockProduct(name: "Foo", targets: ["Foo"]),
],
dependencies: [
.registry(identity: "org.baz", requirement: .range("2.0.0" ..< "4.0.0")),
],
versions: ["1.0.0", "1.1.0"]
),
MockPackage(
name: "Bar",
identity: "org.bar",
targets: [
MockTarget(
name: "Bar",
dependencies: [
.product(name: "Baz", package: "org.baz")
]),
],
products: [
MockProduct(name: "Bar", targets: ["Bar"]),
],
dependencies: [
.registry(identity: "org.baz", requirement: .upToNextMajor(from: "3.0.0")),
],
versions: ["1.0.0", "1.1.0", "2.0.0", "2.1.0"]
),
MockPackage(
name: "Baz",
identity: "org.baz",
targets: [
MockTarget(name: "Baz"),
],
products: [
MockProduct(name: "Baz", targets: ["Baz"]),
],
versions: ["1.0.0", "1.1.0", "2.0.0", "2.1.0", "3.0.0", "3.1.0"]
),
]
)
try workspace.checkPackageGraph(roots: ["MyPackage"]) { graph, diagnostics in
XCTAssertNoDiagnostics(diagnostics)
PackageGraphTester(graph) { result in
result.check(roots: "MyPackage")
result.check(packages: "Bar", "Baz", "Foo", "MyPackage")
result.check(targets: "Foo", "Bar", "Baz", "MyTarget1", "MyTarget2")
result.checkTarget("MyTarget1") { result in result.check(dependencies: "Foo") }
result.checkTarget("MyTarget2") { result in result.check(dependencies: "Bar") }
result.checkTarget("Foo") { result in result.check(dependencies: "Baz") }
result.checkTarget("Bar") { result in result.check(dependencies: "Baz") }
}
}
workspace.checkManagedDependencies { result in
result.check(dependency: "org.foo", at: .registryDownload("1.1.0"))
result.check(dependency: "org.bar", at: .registryDownload("2.1.0"))
result.check(dependency: "org.baz", at: .registryDownload("3.1.0"))
}
// Check the load-package callbacks.
XCTAssertMatch(workspace.delegate.events, ["will load manifest for root package: /tmp/ws/roots/MyPackage"])
XCTAssertMatch(workspace.delegate.events, ["did load manifest for root package: /tmp/ws/roots/MyPackage"])
XCTAssertMatch(workspace.delegate.events, ["will load manifest for registry package: org.foo"])
XCTAssertMatch(workspace.delegate.events, ["did load manifest for registry package: org.foo"])
XCTAssertMatch(workspace.delegate.events, ["will load manifest for registry package: org.bar"])
XCTAssertMatch(workspace.delegate.events, ["did load manifest for registry package: org.bar"])
XCTAssertMatch(workspace.delegate.events, ["will load manifest for registry package: org.baz"])
XCTAssertMatch(workspace.delegate.events, ["did load manifest for registry package: org.baz"])
}
func testBasicMixedTransitiveResolution() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "MyPackage",
targets: [
MockTarget(
name: "MyTarget1",
dependencies: [
.product(name: "Foo", package: "org.foo")
]),
MockTarget(
name: "MyTarget2",
dependencies: [
.product(name: "Bar", package: "org.bar")
]),
],
products: [
MockProduct(name: "MyProduct", targets: ["MyTarget1", "MyTarget2"]),
],
dependencies: [
.registry(identity: "org.foo", requirement: .upToNextMajor(from: "1.0.0")),
.sourceControl(url: "http://localhost/org/bar", requirement: .upToNextMajor(from: "2.0.0")),
]
),
],
packages: [
MockPackage(
name: "Foo",
identity: "org.foo",
targets: [
MockTarget(
name: "Foo",
dependencies: [
.product(name: "Baz", package: "org.baz")
]),
],
products: [
MockProduct(name: "Foo", targets: ["Foo"]),
],
dependencies: [
.registry(identity: "org.baz", requirement: .range("2.0.0" ..< "4.0.0")),
],
versions: ["1.0.0", "1.1.0"]
),
MockPackage(
name: "Bar",
url: "http://localhost/org/bar",
targets: [
MockTarget(
name: "Bar",
dependencies: [
.product(name: "Baz", package: "org.baz")
]),
],
products: [
MockProduct(name: "Bar", targets: ["Bar"]),
],
dependencies: [
.registry(identity: "org.baz", requirement: .upToNextMajor(from: "3.0.0")),
],
versions: ["1.0.0", "1.1.0", "2.0.0", "2.1.0"]
),
MockPackage(
name: "Baz",
identity: "org.baz",
targets: [
MockTarget(name: "Baz"),
],
products: [
MockProduct(name: "Baz", targets: ["Baz"]),
],
versions: ["1.0.0", "1.1.0", "2.0.0", "2.1.0", "3.0.0", "3.1.0"]
),
]
)
try workspace.checkPackageGraph(roots: ["MyPackage"]) { graph, diagnostics in
XCTAssertNoDiagnostics(diagnostics)
PackageGraphTester(graph) { result in
result.check(roots: "MyPackage")
result.check(packages: "Bar", "Baz", "Foo", "MyPackage")
result.check(targets: "Foo", "Bar", "Baz", "MyTarget1", "MyTarget2")
result.checkTarget("MyTarget1") { result in result.check(dependencies: "Foo") }
result.checkTarget("MyTarget2") { result in result.check(dependencies: "Bar") }
result.checkTarget("Foo") { result in result.check(dependencies: "Baz") }
result.checkTarget("Bar") { result in result.check(dependencies: "Baz") }
}
}
workspace.checkManagedDependencies { result in
result.check(dependency: "org.foo", at: .registryDownload("1.1.0"))
result.check(dependency: "bar", at: .checkout(.version("2.1.0")))
result.check(dependency: "org.baz", at: .registryDownload("3.1.0"))
}
// Check the load-package callbacks.
XCTAssertMatch(workspace.delegate.events, ["will load manifest for root package: /tmp/ws/roots/MyPackage"])
XCTAssertMatch(workspace.delegate.events, ["did load manifest for root package: /tmp/ws/roots/MyPackage"])
XCTAssertMatch(workspace.delegate.events, ["will load manifest for registry package: org.foo"])
XCTAssertMatch(workspace.delegate.events, ["did load manifest for registry package: org.foo"])
XCTAssertMatch(workspace.delegate.events, ["will load manifest for remoteSourceControl package: http://localhost/org/bar"])
XCTAssertMatch(workspace.delegate.events, ["did load manifest for remoteSourceControl package: http://localhost/org/bar"])
XCTAssertMatch(workspace.delegate.events, ["will load manifest for registry package: org.baz"])
XCTAssertMatch(workspace.delegate.events, ["did load manifest for registry package: org.baz"])
}
func testCustomPackageContainerProvider() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let customFS = InMemoryFileSystem()
let sourcesDir = AbsolutePath("/Sources")
let targetDir = sourcesDir.appending(component: "Baz")
try customFS.createDirectory(targetDir, recursive: true)
try customFS.writeFileContents(targetDir.appending(component: "file.swift"), bytes: "")
let bazURL = try XCTUnwrap(URL(string: "https://example.com/baz"))
let bazPackageReference = PackageReference(identity: PackageIdentity(url: bazURL), kind: .remoteSourceControl(bazURL))
let bazContainer = MockPackageContainer(package: bazPackageReference, dependencies: ["1.0.0": []], fileSystem: customFS, customRetrievalPath: .root)
let fooPath = AbsolutePath("/tmp/ws/Foo")
let fooPackageReference = PackageReference(identity: PackageIdentity(path: fooPath), kind: .root(fooPath))
let fooContainer = MockPackageContainer(package: fooPackageReference)
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "Foo",
targets: [
MockTarget(name: "Foo", dependencies: ["Bar"]),
MockTarget(name: "Bar", dependencies: [.product(name: "Baz", package: "baz")]),
MockTarget(name: "BarTests", dependencies: ["Bar"], type: .test),
],
products: [
MockProduct(name: "Foo", targets: ["Foo", "Bar"]),
],
dependencies: [
.sourceControl(url: bazURL, requirement: .upToNextMajor(from: "1.0.0")),
]
),
],
packages: [
MockPackage(
name: "Baz",
url: bazURL.absoluteString,
targets: [
MockTarget(name: "Baz"),
],
products: [
MockProduct(name: "Baz", targets: ["Baz"]),
],
versions: ["1.0.0"]
),
],
customPackageContainerProvider: MockPackageContainerProvider(containers: [fooContainer, bazContainer])
)
let deps: [MockDependency] = [
.sourceControl(url: bazURL, requirement: .exact("1.0.0")),
]
try workspace.checkPackageGraph(roots: ["Foo"], deps: deps) { graph, diagnostics in
PackageGraphTester(graph) { result in
result.check(roots: "Foo")
result.check(packages: "Baz", "Foo")
result.check(targets: "Bar", "Baz", "Foo")
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: .custom(Version(1, 0, 0), .root))
}
}
func testRegistryMissingConfigurationErrors() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let registryClient = try makeRegistryClient(
packageIdentity: .plain("org.foo"),
packageVersion: "1.0.0",
workspaceDirectory: sandbox,
fileSystem: fs,
configuration: .init()
)
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "MyPackage",
targets: [
MockTarget(
name: "MyTarget",
dependencies: [
.product(name: "Foo", package: "org.foo")
]),
],
dependencies: [
.registry(identity: "org.foo", requirement: .upToNextMajor(from: "1.0.0")),
]
),
],
packages: [
MockPackage(
name: "Foo",
identity: "org.foo",
targets: [
MockTarget(name: "Foo"),
],
products: [
MockProduct(name: "Foo", targets: ["Foo"]),
],
versions: ["1.0.0"]
)
],
customRegistryClient: registryClient
)
workspace.checkPackageGraphFailure(roots: ["MyPackage"]) { diagnostics in
testDiagnostics(diagnostics) { result in
result.check(diagnostic: .equal("No registry configured for 'org' scope"), severity: .error)
}
}
}
func testRegistryReleasesServerErrors() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "MyPackage",
targets: [
MockTarget(
name: "MyTarget",
dependencies: [
.product(name: "Foo", package: "org.foo")
]),
],
dependencies: [
.registry(identity: "org.foo", requirement: .upToNextMajor(from: "1.0.0")),
]
),
],
packages: [
MockPackage(
name: "Foo",
identity: "org.foo",
targets: [
MockTarget(name: "Foo"),
],
products: [
MockProduct(name: "Foo", targets: ["Foo"]),
],
versions: ["1.0.0"]
)
]
)
do {
let registryClient = try makeRegistryClient(
packageIdentity: .plain("org.foo"),
packageVersion: "1.0.0",
workspaceDirectory: sandbox,
fileSystem: fs,
releasesRequestHandler: { _, _ , completion in
completion(.failure(StringError("boom")))
}
)
workspace.checkReset{ XCTAssertNoDiagnostics($0) }
workspace.closeWorkspace()
workspace.registryClient = registryClient
workspace.checkPackageGraphFailure(roots: ["MyPackage"]) { diagnostics in
testDiagnostics(diagnostics) { result in
result.check(diagnostic: .equal("Failed fetching releases from registry: boom"), severity: .error)
}
}
}
do {
let registryClient = try makeRegistryClient(
packageIdentity: .plain("org.foo"),
packageVersion: "1.0.0",
workspaceDirectory: sandbox,
fileSystem: fs,
releasesRequestHandler: { _, _ , completion in
completion(.success(.serverError()))
}
)
workspace.checkReset{ XCTAssertNoDiagnostics($0) }
workspace.closeWorkspace()
workspace.registryClient = registryClient
workspace.checkPackageGraphFailure(roots: ["MyPackage"]) { diagnostics in
testDiagnostics(diagnostics) { result in
result.check(diagnostic: .equal("Failed fetching releases from registry: Invalid registry response status '500', expected '200'"), severity: .error)
}
}
}
}
func testRegistryReleaseChecksumServerErrors() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "MyPackage",
targets: [
MockTarget(
name: "MyTarget",
dependencies: [
.product(name: "Foo", package: "org.foo")
]),
],
dependencies: [
.registry(identity: "org.foo", requirement: .upToNextMajor(from: "1.0.0")),
]
),
],
packages: [
MockPackage(
name: "Foo",
identity: "org.foo",
targets: [
MockTarget(name: "Foo"),
],
products: [
MockProduct(name: "Foo", targets: ["Foo"]),
],
versions: ["1.0.0"]
)
]
)
do {
let registryClient = try makeRegistryClient(
packageIdentity: .plain("org.foo"),
packageVersion: "1.0.0",
workspaceDirectory: sandbox,
fileSystem: fs,
versionMetadataRequestHandler: { _, _ , completion in
completion(.failure(StringError("boom")))
}
)
workspace.checkReset{ XCTAssertNoDiagnostics($0) }
workspace.closeWorkspace()
workspace.registryClient = registryClient
workspace.checkPackageGraphFailure(roots: ["MyPackage"]) { diagnostics in
testDiagnostics(diagnostics) { result in
result.check(diagnostic: .equal("Failed fetching release checksum from registry: boom"), severity: .error)
}
}
}
do {
let registryClient = try makeRegistryClient(
packageIdentity: .plain("org.foo"),
packageVersion: "1.0.0",
workspaceDirectory: sandbox,
fileSystem: fs,
versionMetadataRequestHandler: { _, _ , completion in
completion(.success(.serverError()))
}
)
workspace.checkReset{ XCTAssertNoDiagnostics($0) }
workspace.closeWorkspace()
workspace.registryClient = registryClient
workspace.checkPackageGraphFailure(roots: ["MyPackage"]) { diagnostics in
testDiagnostics(diagnostics) { result in
result.check(diagnostic: .equal("Failed fetching release checksum from registry: Invalid registry response status '500', expected '200'"), severity: .error)
}
}
}
}
func testRegistryManifestServerErrors() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "MyPackage",
targets: [
MockTarget(
name: "MyTarget",
dependencies: [
.product(name: "Foo", package: "org.foo")
]),
],
dependencies: [
.registry(identity: "org.foo", requirement: .upToNextMajor(from: "1.0.0")),
]
),
],
packages: [
MockPackage(
name: "Foo",
identity: "org.foo",
targets: [
MockTarget(name: "Foo"),
],
products: [
MockProduct(name: "Foo", targets: ["Foo"]),
],
versions: ["1.0.0"]
)
]
)
do {
let registryClient = try makeRegistryClient(
packageIdentity: .plain("org.foo"),
packageVersion: "1.0.0",
workspaceDirectory: sandbox,
fileSystem: fs,
manifestRequestHandler: { _, _ , completion in
completion(.failure(StringError("boom")))
}
)
workspace.checkReset{ XCTAssertNoDiagnostics($0) }
workspace.closeWorkspace()
workspace.registryClient = registryClient
workspace.checkPackageGraphFailure(roots: ["MyPackage"]) { diagnostics in
testDiagnostics(diagnostics) { result in
result.check(diagnostic: .equal("Failed retrieving manifest from registry: boom"), severity: .error)
}
}
}
do {
let registryClient = try makeRegistryClient(
packageIdentity: .plain("org.foo"),
packageVersion: "1.0.0",
workspaceDirectory: sandbox,
fileSystem: fs,
manifestRequestHandler: { _, _ , completion in
completion(.success(.serverError()))
}
)
workspace.checkReset{ XCTAssertNoDiagnostics($0) }
workspace.closeWorkspace()
workspace.registryClient = registryClient
workspace.checkPackageGraphFailure(roots: ["MyPackage"]) { diagnostics in
testDiagnostics(diagnostics) { result in
result.check(diagnostic: .equal("Failed retrieving manifest from registry: Invalid registry response status '500', expected '200'"), severity: .error)
}
}
}
}
func testRegistryDownloadServerErrors() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "MyPackage",
targets: [
MockTarget(
name: "MyTarget",
dependencies: [
.product(name: "Foo", package: "org.foo")
]),
],
dependencies: [
.registry(identity: "org.foo", requirement: .upToNextMajor(from: "1.0.0")),
]
),
],
packages: [
MockPackage(
name: "Foo",
identity: "org.foo",
targets: [
MockTarget(name: "Foo"),
],
products: [
MockProduct(name: "Foo", targets: ["Foo"]),
],
versions: ["1.0.0"]
)
]
)
do {
let registryClient = try makeRegistryClient(
packageIdentity: .plain("org.foo"),
packageVersion: "1.0.0",
workspaceDirectory: sandbox,
fileSystem: fs,
downloadArchiveRequestHandler: { _, _ , completion in
completion(.failure(StringError("boom")))
}
)
workspace.checkReset{ XCTAssertNoDiagnostics($0) }
workspace.closeWorkspace()
workspace.registryClient = registryClient
workspace.checkPackageGraphFailure(roots: ["MyPackage"]) { diagnostics in
testDiagnostics(diagnostics) { result in
result.check(diagnostic: .equal("Failed downloading source archive from registry: boom"), severity: .error)
}
}
}
do {
let registryClient = try makeRegistryClient(
packageIdentity: .plain("org.foo"),
packageVersion: "1.0.0",
workspaceDirectory: sandbox,
fileSystem: fs,
downloadArchiveRequestHandler: { _, _ , completion in
completion(.success(.serverError()))
}
)
workspace.checkReset{ XCTAssertNoDiagnostics($0) }
workspace.closeWorkspace()
workspace.registryClient = registryClient
workspace.checkPackageGraphFailure(roots: ["MyPackage"]) { diagnostics in
testDiagnostics(diagnostics) { result in
result.check(diagnostic: .equal("Failed downloading source archive from registry: Invalid registry response status '500', expected '200'"), severity: .error)
}
}
}
}
func testRegistryArchiveErrors() throws {
let sandbox = AbsolutePath("/tmp/ws/")
let fs = InMemoryFileSystem()
let workspace = try MockWorkspace(
sandbox: sandbox,
fileSystem: fs,
roots: [
MockPackage(
name: "MyPackage",
targets: [
MockTarget(
name: "MyTarget",
dependencies: [
.product(name: "Foo", package: "org.foo")
]),
],
dependencies: [
.registry(identity: "org.foo", requirement: .upToNextMajor(from: "1.0.0")),
]
),
],
packages: [
MockPackage(
name: "Foo",
identity: "org.foo",
targets: [
MockTarget(name: "Foo"),
],
products: [
MockProduct(name: "Foo", targets: ["Foo"]),
],
versions: ["1.0.0"]
)
]
)
do {
let registryClient = try makeRegistryClient(
packageIdentity: .plain("org.foo"),
packageVersion: "1.0.0",
workspaceDirectory: sandbox,
fileSystem: fs,
archiver: MockArchiver(handler: { archiver, from, to, completion in
completion(.failure(StringError("boom")))
})
)
workspace.checkReset{ XCTAssertNoDiagnostics($0) }
workspace.closeWorkspace()
workspace.registryClient = registryClient
workspace.checkPackageGraphFailure(roots: ["MyPackage"]) { diagnostics in
testDiagnostics(diagnostics) { result in
result.check(diagnostic: .equal("failed extracting '\(sandbox.pathString)/.build/registry/downloads/org/foo/1.0.0.zip' to '\(sandbox.pathString)/.build/registry/downloads/org/foo/1.0.0': boom"), severity: .error)
}
}
}
}
func makeRegistryClient(
packageIdentity: PackageIdentity,
packageVersion: Version,
workspaceDirectory: AbsolutePath,
fileSystem: FileSystem,
configuration: PackageRegistry.RegistryConfiguration? = .none,
identityResolver: IdentityResolver? = .none,
fingerprintStorage: PackageFingerprintStorage? = .none,
fingerprintCheckingMode: FingerprintCheckingMode = .strict,
authorizationProvider: AuthorizationProvider? = .none,
releasesRequestHandler: HTTPClient.Handler? = .none,
versionMetadataRequestHandler: HTTPClient.Handler? = .none,
manifestRequestHandler: HTTPClient.Handler? = .none,
downloadArchiveRequestHandler: HTTPClient.Handler? = .none,
archiver: Archiver? = .none
) throws -> RegistryClient {
let jsonEncoder = JSONEncoder.makeWithDefaults()
let identityResolver = identityResolver ?? DefaultIdentityResolver()
guard let (packageScope, packageName) = packageIdentity.scopeAndName else {
throw StringError("Invalid package identity")
}
var configuration = configuration
if configuration == nil {
configuration = PackageRegistry.RegistryConfiguration()
configuration!.defaultRegistry = .init(url: URL(string: "http://localhost")!)
}
let releasesRequestHandler = releasesRequestHandler ?? { request, _ , completion in
let metadata = RegistryClient.Serialization.PackageMetadata(
releases: [packageVersion.description: .init(url: .none, problem: .none)]
)
completion(.success(
HTTPClientResponse(
statusCode: 200,
headers: [
"Content-Version": "1",
"Content-Type": "application/json"
],
body: try! jsonEncoder.encode(metadata)
)
))
}
let versionMetadataRequestHandler = versionMetadataRequestHandler ?? { request, _ , completion in
let metadata = RegistryClient.Serialization.VersionMetadata(
id: packageIdentity.description,
version: packageVersion.description,
resources: [
.init(
name: "source-archive",
type: "application/zip",
checksum: ""
)
],
metadata: .init(description: "")
)
completion(.success(
HTTPClientResponse(
statusCode: 200,
headers: [
"Content-Version": "1",
"Content-Type": "application/json"
],
body: try! jsonEncoder.encode(metadata)
)
))
}
let manifestRequestHandler = manifestRequestHandler ?? { request, _ , completion in
completion(.success(
HTTPClientResponse(
statusCode: 200,
headers: [
"Content-Version": "1",
"Content-Type": "text/x-swift"
],
body: "// swift-tools-version:\(ToolsVersion.currentToolsVersion)".data(using: .utf8)
)
))
}
let downloadArchiveRequestHandler = downloadArchiveRequestHandler ?? { request, _ , completion in
// meh
let path = workspaceDirectory
.appending(components: ".build", "registry", "downloads", packageScope.description, packageName.description)
.appending(component: "\(packageVersion).zip")
try! fileSystem.createDirectory(path.parentDirectory, recursive: true)
try! fileSystem.writeFileContents(path, string: "")
completion(.success(
HTTPClientResponse(
statusCode: 200,
headers: [
"Content-Version": "1",
"Content-Type": "application/zip"
],
body: "".data(using: .utf8)
)
))
}
let archiver = archiver ?? MockArchiver(handler: { archiver, from, to, completion in
do {
try fileSystem.createDirectory(to.appending(component: "top"), recursive: true)
completion(.success(()))
} catch {
completion(.failure(error))
}
})
let fingerprintStorage = fingerprintStorage ?? MockPackageFingerprintStorage()
return RegistryClient(
configuration: configuration!,
identityResolver: identityResolver,
fingerprintStorage: fingerprintStorage,
fingerprintCheckingMode: fingerprintCheckingMode,
authorizationProvider: authorizationProvider?.httpAuthorizationHeader(for:),
customHTTPClient: HTTPClient(configuration: .init(), handler: { request, progress , completion in
switch request.url {
// request to get package releases
case URL(string: "http://localhost/\(packageScope)/\(packageName)")!:
releasesRequestHandler(request, progress, completion)
// request to get package version metadata
case URL(string: "http://localhost/\(packageScope)/\(packageName)/\(packageVersion)")!:
versionMetadataRequestHandler(request, progress, completion)
// request to get package manifest
case URL(string: "http://localhost/\(packageScope)/\(packageName)/\(packageVersion)/Package.swift")!:
manifestRequestHandler(request, progress, completion)
// request to get download the version source archive
case URL(string: "http://localhost/\(packageScope)/\(packageName)/\(packageVersion).zip")!:
downloadArchiveRequestHandler(request, progress, completion)
default:
completion(.failure(StringError("unexpected url \(request.url)")))
}
}),
customArchiverProvider: { _ in archiver }
)
}
}
struct DummyError: LocalizedError, Equatable {
public var errorDescription: String? { "dummy error" }
}
| 40.74635 | 332 | 0.464598 |
7acfd0c2703986e93a7707e2a3ca8c9d7a729526 | 1,391 | //
// FloatExtensions.swift
// SwifterSwift
//
// Created by Omar Albeik on 8/8/16.
// Copyright © 2016 SwifterSwift
//
#if canImport(CoreGraphics)
import CoreGraphics
#endif
// MARK: - Properties
public extension Float {
/// SwifterSwift: Int.
var int: Int {
return Int(self)
}
/// SwifterSwift: Double.
var double: Double {
return Double(self)
}
#if canImport(CoreGraphics)
/// SwifterSwift: CGFloat.
var cgFloat: CGFloat {
return CGFloat(self)
}
#endif
}
// MARK: - Operators
#if canImport(Foundation) && !os(Linux)
precedencegroup PowerPrecedence { higherThan: MultiplicationPrecedence }
infix operator ** : PowerPrecedence
/// SwifterSwift: Value of exponentiation.
///
/// - Parameters:
/// - lhs: base float.
/// - rhs: exponent float.
/// - Returns: exponentiation result (4.4 ** 0.5 = 2.0976176963).
func ** (lhs: Float, rhs: Float) -> Float {
// http://nshipster.com/swift-operators/
return pow(lhs, rhs)
}
#endif
#if canImport(Foundation) && !os(Linux)
prefix operator √
/// SwifterSwift: Square root of float.
///
/// - Parameter float: float value to find square root for
/// - Returns: square root of given float.
// swiftlint:disable:next identifier_name
public prefix func √ (float: Float) -> Float {
// http://nshipster.com/swift-operators/
return sqrt(float)
}
#endif
| 20.455882 | 72 | 0.653487 |
ed16e1fbf63ed8e325583c6b683f518f5f71f65e | 3,647 | /* Copyright 2018 Tua Rua Ltd.
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 FreSwift
import Foundation
import SwiftyStoreKit
extension SwiftController: FreSwiftMainController {
// Must have this function. It exposes the methods to our entry ObjC.
@objc public func getFunctions(prefix: String) -> [String] {
functionsToSet["\(prefix)init"] = initController
functionsToSet["\(prefix)createGUID"] = createGUID
functionsToSet["\(prefix)retrieveProductsInfo"] = retrieveProductsInfo
functionsToSet["\(prefix)getProductsInfo"] = getProductsInfo
functionsToSet["\(prefix)canMakePayments"] = canMakePayments
functionsToSet["\(prefix)purchaseProduct"] = purchaseProduct
functionsToSet["\(prefix)getPurchaseProduct"] = getPurchaseProduct
functionsToSet["\(prefix)finishTransaction"] = finishTransaction
functionsToSet["\(prefix)verifyPurchase"] = verifyPurchase
functionsToSet["\(prefix)verifyReceipt"] = verifyReceipt
functionsToSet["\(prefix)verifySubscription"] = verifySubscription
functionsToSet["\(prefix)fetchReceipt"] = fetchReceipt
functionsToSet["\(prefix)restorePurchases"] = restorePurchases
functionsToSet["\(prefix)getRestore"] = getRestore
functionsToSet["\(prefix)start"] = start
functionsToSet["\(prefix)pause"] = pause
functionsToSet["\(prefix)resume"] = resume
functionsToSet["\(prefix)cancel"] = cancel
var arr: [String] = []
for key in functionsToSet.keys {
arr.append(key)
}
return arr
}
func createGUID(ctx: FREContext, argc: FREArgc, argv: FREArgv) -> FREObject? {
return UUID().uuidString.toFREObject()
}
@objc func applicationDidFinishLaunching(_ notification: Notification) {
SwiftyStoreKit.completeTransactions(atomically: false) { purchases in
self.launchPurchases = purchases
}
SwiftyStoreKit.updatedDownloadsHandler = { downloads in
}
}
@objc public func dispose() {
}
// Must have these 3 functions.
//Exposes the methods to our entry ObjC.
@objc public func callSwiftFunction(name: String, ctx: FREContext, argc: FREArgc, argv: FREArgv) -> FREObject? {
if let fm = functionsToSet[name] {
return fm(ctx, argc, argv)
}
return nil
}
//Here we set our FREContext
@objc public func setFREContext(ctx: FREContext) {
self.context = FreContextSwift.init(freContext: ctx)
FreSwiftLogger.shared.context = context
}
@objc public func onLoad() {
#if os(iOS) || os(tvOS)
NotificationCenter.default.addObserver(self, selector: #selector(applicationDidFinishLaunching),
name: UIApplication.didFinishLaunchingNotification, object: nil)
#else
NotificationCenter.default.addObserver(self, selector: #selector(applicationDidFinishLaunching),
name: NSApplication.didFinishLaunchingNotification, object: nil)
#endif
}
}
| 40.076923 | 116 | 0.674801 |
567e934639c3ef15e28680e88becd750cbc0d8e6 | 1,054 | //
// PoliticalOffices.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
open class PoliticalOffices: JSONEncodable {
public var id: Int64?
public var description: String?
public var name: String?
public var resourceUri: String?
public var term: Int32?
public var slug: String?
public var wikipedia: String?
public init() {}
// MARK: JSONEncodable
open func encodeToJSON() -> Any {
var nillableDictionary = [String:Any?]()
nillableDictionary["id"] = self.id?.encodeToJSON()
nillableDictionary["description"] = self.description
nillableDictionary["name"] = self.name
nillableDictionary["resource_uri"] = self.resourceUri
nillableDictionary["term"] = self.term?.encodeToJSON()
nillableDictionary["slug"] = self.slug
nillableDictionary["wikipedia"] = self.wikipedia
let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:]
return dictionary
}
}
| 29.277778 | 85 | 0.672676 |
8a4720168e78eff1accfddf88eafe217211d6323 | 1,652 | //
// MockActionSheetPresenter.swift
// SheeeeeeeeetTests
//
// Created by Daniel Saidi on 2018-04-27.
// Copyright © 2018 Daniel Saidi. All rights reserved.
//
import Sheeeeeeeeet
import MockingKit
import UIKit
class MockActionSheetPresenter: Mock, ActionSheetPresenter {
lazy var dismissRef = MockReference(dismiss)
lazy var presentFromViewRef = MockReference(present as (ActionSheet, UIViewController, UIView?, @escaping () -> Void) -> Void)
lazy var presentFromBarItemRef = MockReference(present as (ActionSheet, UIViewController, UIBarButtonItem, @escaping () -> Void) -> Void)
lazy var refreshActionSheetRef = MockReference(refreshActionSheet)
var events = ActionSheetPresenterEvents()
var isDismissable = false
var shouldDismissOnDidEnterBackground = false
typealias PresentFromViewSignature = (ActionSheet, UIViewController, UIView?, @escaping () -> Void) -> Void
typealias PresentFromItemSignature = (ActionSheet, UIViewController, UIBarButtonItem, @escaping () -> Void) -> Void
func dismiss(completion: @escaping () -> ()) {
call(dismissRef, args: (completion))
}
func present(sheet: ActionSheet, in vc: UIViewController, from view: UIView?, completion: @escaping () -> Void) {
call(presentFromViewRef, args: (sheet, vc, view, completion))
}
func present(sheet: ActionSheet, in vc: UIViewController, from item: UIBarButtonItem, completion: @escaping () -> Void) {
call(presentFromBarItemRef, args: (sheet, vc, item, completion))
}
func refreshActionSheet() {
call(refreshActionSheetRef, args: ())
}
}
| 38.418605 | 141 | 0.705206 |
f8debe85c6e65353051a2d1fb30975b0f4209f96 | 515 | // swift-tools-version:4.0
import PackageDescription
let package = Package(
name: "Rocket",
products: [
.library(name: "Rocket", targets: ["Rocket"])
],
dependencies: [
.package(url: "https://github.com/Alamofire/Alamofire.git", .exact("4.7.2")),
.package(url: "https://github.com/antitypical/Result.git", .exact("4.0.0")),
],
targets: [
.target(name: "Rocket", dependencies: [
"Alamofire",
"Result",
], path: "Sources")
]
)
| 24.52381 | 85 | 0.55534 |
1897eb010370fe885ad5192fd4066f19dc0b9b1c | 1,303 | //
// DetailViewController.swift
// Project1
//
// Created by Woodshox on 08.12.21.
//
import UIKit
class DetailViewController: UIViewController {
@IBOutlet var imageView: UIImageView!
var selectedImage: String?
var selectedPictureNumber = 0
var totalPictures = 0
override func viewDidLoad() {
super.viewDidLoad()
title = "This image is \(selectedPictureNumber) of \(totalPictures)"
navigationItem.largeTitleDisplayMode = .never
if let imageToLoad = selectedImage {
imageView.image = UIImage(named: imageToLoad)
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.hidesBarsOnTap = true
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
navigationController?.hidesBarsOnTap = false
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
| 25.54902 | 106 | 0.655411 |
6ac6cbf136147cd6678f4e1112a994e832658ff0 | 1,130 | //
// Created by Andrew Podkovyrin
// Copyright © 2020 Andrew Podkovyrin. All rights reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://opensource.org/licenses/MIT
//
// 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
protocol SwitcherFormCellModelChangesObserver: AnyObject {
func switcherFormCellModelDidChangeIsOn(_ model: SwitcherFormCellModel)
}
final class SwitcherFormCellModel: TitledFormCellModel {
var isOn: Bool = false {
didSet {
changesObserver?.switcherFormCellModelDidChangeIsOn(self)
}
}
var action: ((SwitcherFormCellModel, UITableViewCell) -> Void)?
internal weak var changesObserver: SwitcherFormCellModelChangesObserver?
}
| 33.235294 | 76 | 0.743363 |
4b6c8789309be7409bf95d56364036dac8b44e29 | 3,447 | //
// ImageScrollView.swift
// MyWallpaper
//
// Created by Linsw on 16/4/30.
// Copyright © 2016年 Linsw. All rights reserved.
//
import UIKit
import AVFoundation
import Haneke
class ImageScrollView: UIScrollView {
var pictures = [Picture](){
didSet{
guard pictures.count != 0 else {return}
for view in self.subviews where view is UIImageView {
view.removeFromSuperview()
}
contentSize = CGSize(width: frame.width * CGFloat(pictures.count), height: frame.height)
for index in 0...pictures.count-1 {
let scrollImageView = createScrollImageView(index)
let cache = Cache<UIImage>(name: "indexImageCache")
let URL = NSURL(string: pictures[index].url)!
cache.fetch(URL:URL).onSuccess{ [unowned self] image in
scrollImageView.image = image
scrollImageView.setupForImageViewer(URL, backgroundColor: self.backgroundColor!)
self.addSubview(scrollImageView)
}
}
initTimer()
}
}
var currentIndex = 0
var timer:NSTimer?
required init?(coder aDecoder: NSCoder) {
super.init(coder:aDecoder)
pagingEnabled = true
showsHorizontalScrollIndicator = false
showsVerticalScrollIndicator = false
backgroundColor = themeBlack.detailViewBackgroundColor
}
func initTimer(){
guard timer == nil || timer?.valid == false else{ return}
timer = NSTimer.scheduledTimerWithTimeInterval(2, target: self, selector: #selector(ImageScrollView.moveToNextPage), userInfo: nil, repeats: true)
}
func moveToNextPage (){
userInteractionEnabled = false
for view in subviews {
view.userInteractionEnabled = false
}
let pageWidth:CGFloat = frame.width
let maxWidth:CGFloat = pageWidth * CGFloat(pictures.count)
let contentOffset:CGFloat = self.contentOffset.x
var slideToX = contentOffset + pageWidth
if contentOffset + pageWidth == maxWidth{
slideToX = 0
}
scrollRectToVisible(CGRect(x: slideToX, y: 0, width: pageWidth, height: frame.height), animated: true)
}
func prepareForDragging() {
userInteractionEnabled = false
for view in subviews {
view.userInteractionEnabled = false
}
if let timer = timer {
timer.invalidate()
}
}
func updateCurrentPage()->Int{
userInteractionEnabled = true
for view in subviews {
view.userInteractionEnabled = true
}
let pageWidth:CGFloat = frame.width
let currentPage:Int = Int(floor((self.contentOffset.x-pageWidth/2)/pageWidth)+1)
currentIndex = currentPage
assert(0..<pictures.count ~= currentPage)
return currentPage
}
private func createScrollImageView(index:Int)->UIImageView {
var frame = centerFrameFromImageSize(pictures[index].size)
frame.origin.x += self.frame.width * CGFloat(index)
return UIImageView(frame: frame)
}
private func centerFrameFromImageSize(imageSize:CGSize) -> CGRect {
return AVMakeRectWithAspectRatioInsideRect(imageSize, CGRect(x: 0, y: 0, width: bounds.width, height: bounds.height))
}
}
| 34.128713 | 154 | 0.615898 |
3320b63c032e61b362cecdab341c7b64e5afc5ff | 2,361 | //
// SceneDelegate.swift
// InteractiveUITest
//
// Created by fahid.attique on 24/12/2019.
// Copyright © 2019 fahid.attique. All rights reserved.
//
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 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.
}
}
| 43.722222 | 147 | 0.714951 |
d79d69eb848c502b2f6e614c70b3b99f8f0d01b2 | 518 | //
// ViewController.swift
// MeshbluBeaconKit
//
// Created by sqrtofsaturn on 08/31/2016.
// Copyright (c) 2016 sqrtofsaturn. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 20.72 | 80 | 0.679537 |
39ee3557dbc0ad8cb1f4735278aa0fbecfb15147 | 2,231 | //
// UIFontExtensionTest.swift
// RSFontSizes_Tests
//
// Created by German on 3/29/19.
// Copyright © 2019 CocoaPods. All rights reserved.
//
import Foundation
import Quick
import Nimble
import RSFontSizes
class FontWeightsSpecs: QuickSpec {
let testFont = "Raleway".font()!
override func spec() {
describe("UIFont.Weight extension") {
context("faceName enum method") {
it("returns the correct name for every style") {
expect(UIFont.Weight.ultraLight.faceName) == "UltraLight"
expect(UIFont.Weight.extraLight.faceName) == "ExtraLight"
expect(UIFont.Weight.thin.faceName) == "Thin"
expect(UIFont.Weight.book.faceName) == "Book"
expect(UIFont.Weight.demi.faceName) == "Demi"
expect(UIFont.Weight.normal.faceName) == "Normal"
expect(UIFont.Weight.light.faceName) == "Light"
expect(UIFont.Weight.medium.faceName) == "Medium"
expect(UIFont.Weight.demibold.faceName) == "DemiBold"
expect(UIFont.Weight.semibold.faceName) == "SemiBold"
expect(UIFont.Weight.bold.faceName) == "Bold"
expect(UIFont.Weight.extraBold.faceName) == "ExtraBold"
expect(UIFont.Weight.heavy.faceName) == "Heavy"
expect(UIFont.Weight.black.faceName) == "Black"
expect(UIFont.Weight.extraBlack.faceName) == "ExtraBlack"
expect(UIFont.Weight.ultraBlack.faceName) == "UltraBlack"
expect(UIFont.Weight.fat.faceName) == "Fat"
expect(UIFont.Weight.poster.faceName) == "Poster"
expect(UIFont.Weight.ultraLight.faceName) == "UltraLight"
expect(UIFont.Weight.regular.faceName) == "Regular"
}
}
context("Font weight modifiers") {
it("Does not change the font size") {
let initialSize = self.testFont.pointSize
let font = self.testFont.bold
expect(font.pointSize) == initialSize
}
}
context("Font Size modifiers") {
it("Does not change the font weight") {
let initialName = self.testFont.fontName
let resizedFont = self.testFont.huge
expect(resizedFont.fontName) == initialName
}
}
}
}
}
| 34.323077 | 67 | 0.625728 |
204f53c44883db375780965100842ec029c54fa5 | 1,289 | // ----------------------------------------------------------------------------
//
// Check.GreaterThan.swift
//
// @author Alexander Bragin <[email protected]>
// @copyright Copyright (c) 2017, Roxie Mobile Ltd. All rights reserved.
// @link http://www.roxiemobile.com/
//
// ----------------------------------------------------------------------------
extension Check
{
// MARK: - Methods
/// Checks that the parameter value is greater than the minimum value.
///
/// - Parameters:
/// - value: The parameter value.
/// - min: The minimum.
/// - message: The identifying message for the `CheckError` (`nil` okay). The default is an empty string.
/// - file: The file name. The default is the file where function is called.
/// - line: The line number. The default is the line number where function is called.
///
/// - Throws:
/// CheckError
///
public static func greaterThan<T:Comparable>(_ value: T, _ min: T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) throws {
guard value > min else {
throw newCheckError(message, file, line)
}
}
}
// ----------------------------------------------------------------------------
| 36.828571 | 170 | 0.497285 |
288dc81fe012ca7275688ac0c4bfdb4cbeffea77 | 249 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
struct S {
let a {
enum S {
protocol C {
class B {
var d = ( {
{
}
class
case ,
| 16.6 | 87 | 0.702811 |
18f499f8253839d35199e0ed7a7cb1ac3781fef0 | 785 | //import XCTest
//import IOTPayiOSTest4
//class Tests: XCTestCase {
//
// override func setUp() {
// super.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.
// super.tearDown()
// }
//
// func testExample() {
// // This is an example of a functional test case.
// XCTAssert(true, "Pass")
// }
//
// func testPerformanceExample() {
// // This is an example of a performance test case.
// self.measure() {
// // Put the code you want to measure the time of here.
// }
// }
//
//}
| 27.068966 | 113 | 0.57707 |
ac059c22e16c3a8ed06217730e45d81a00baa218 | 7,003 | //
// RingControl.swift
// MyProduct
//
// Created by 王雪慧 on 2020/2/10.
// Copyright © 2020 王雪慧. All rights reserved.
//
import UIKit
class RingControl: UIView {
var selectedView: RingView!
var previousView: RingView! // Last tool used.
var tapRecognizer: UITapGestureRecognizer!
var ringViews = [RingView]()
var ringRadius: CGFloat {
return bounds.width / 2.0
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func setupRings(itemCount: Int) {
// Define some nice colors.
let borderColorSelected = #colorLiteral(red: 0, green: 0.7445889711, blue: 1, alpha: 1).cgColor
let borderColorNormal = UIColor.darkGray.cgColor
let fillColorSelected = #colorLiteral(red: 0.6543883085, green: 0.8743371367, blue: 1, alpha: 1)
let fillColorNormal = UIColor.white
// We define generators to return closures which we use to define
// the different states of our item ring views. Since we add those
// to the view, they need to capture the view unowned to avoid a
// retain cycle.
let selectedGenerator = { (view: RingView) -> () -> Void in
return { [unowned view] in
view.layer.borderColor = borderColorSelected
view.backgroundColor = fillColorSelected
}
}
let normalGenerator = { (view: RingView) -> () -> Void in
return { [unowned view] in
view.layer.borderColor = borderColorNormal
view.backgroundColor = fillColorNormal
}
}
let startPosition = bounds.center
let locationNormalGenerator = { (view: RingView) -> () -> Void in
return { [unowned view] in
view.center = startPosition
if !view.selected {
view.alpha = 0.0
}
}
}
let locationFanGenerator = { (view: RingView, offset: CGVector) -> () -> Void in
return { [unowned view] in
view.center = startPosition + offset
view.alpha = 1.0
}
}
// tau is a full circle in radians
let tau = CGFloat.pi * 2
let absoluteRingSegment = tau / 4.0
let requiredLengthPerRing = ringRadius * 2 + 5.0
let totalRequiredCirlceSegment = requiredLengthPerRing * CGFloat(itemCount - 1)
let fannedControlRadius = max(requiredLengthPerRing, totalRequiredCirlceSegment / absoluteRingSegment)
let normalDistance = CGVector(dx: 0, dy: -1 * fannedControlRadius)
let scale = UIScreen.main.scale
// Setup our item views.
for index in 0..<itemCount {
let view = RingView(frame: self.bounds)
view.stateClosures[.selected] = selectedGenerator(view)
view.stateClosures[.normal] = normalGenerator(view)
let transformToApply = CGAffineTransform(rotationAngle: CGFloat(index) / CGFloat(itemCount - 1) * (absoluteRingSegment))
view.stateClosures[.locationFan] = locationFanGenerator(view, normalDistance.applying(transformToApply).rounding(toScale: scale))
view.stateClosures[.locationOrigin] = locationNormalGenerator(view)
self.addSubview(view)
ringViews.append(view)
let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(tap(_:)))
view.addGestureRecognizer(tapRecognizer)
}
}
func setupInitialSelectionState() {
guard let selectedView = ringViews.first else { return }
addSubview(selectedView)
selectedView.selected = true
self.selectedView = selectedView
self.previousView = selectedView
updateViews(animated: false)
}
// MARK: View interaction and animation
@objc
func tap(_ recognizer: UITapGestureRecognizer) {
guard let view = recognizer.view as? RingView else { return }
let fanState = view.fannedOut
if fanState {
select(view: view)
} else {
for view in ringViews {
view.fannedOut = true
}
}
self.updateViews(animated: true)
}
func cancelInteraction() {
guard selectedView.fannedOut else { return }
for view in ringViews {
view.fannedOut = false
}
self.updateViews(animated: true)
}
func select(view: RingView) {
for view in ringViews {
if view.selected {
view.selected = false
view.selectionState?()
}
view.fannedOut = false
}
view.selected = true
// Is the selected view changing?
if selectedView !== view {
// Yes, so remember it as the previous view.
previousView = selectedView
}
selectedView = view
view.actionClosure?()
}
func updateViews(animated: Bool) {
// Order the selected view in front.
self.addSubview(selectedView)
var stateTransitions = [() -> Void]()
for view in ringViews {
if let state = view.selectionState {
stateTransitions.append(state)
}
if let state = view.locationState {
stateTransitions.append(state)
}
}
let transition = {
for transition in stateTransitions {
transition()
}
}
if animated {
UIView.animate(withDuration: 0.25, animations: transition)
} else {
transition()
}
}
// MARK: Hit testing
// Hit test on our ring views regardless of our own bounds.
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
for view in self.subviews.reversed() {
let localPoint = view.convert(point, from: self)
if view.point(inside: localPoint, with: event) {
return view
}
}
// Don't hit-test ourself.
return nil
}
override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
for view in self.subviews.reversed() {
if view.point(inside: view.convert(point, from: self), with: event) {
return true
}
}
return super.point(inside: point, with: event)
}
}
// MARK: - Pencil interaction
extension RingControl {
func switchToPreviousTool() {
// If the tools aren't fanned out, fan out the
// previous one to animate it from its fan location.
if selectedView.fannedOut == false {
previousView.fannedOut = true
updateViews(animated: false)
}
select(view: previousView)
updateViews(animated: true)
}
}
| 32.123853 | 141 | 0.57304 |
eb7184ba65ef86ca7e7a76daaa6a3016f31bcf83 | 6,811 | //
// RNTrimmerView.swift
// RNVideoProcessing
//
import UIKit
import AVKit
@objc(RNTrimmerView)
class RNTrimmerView: RCTView, ICGVideoTrimmerDelegate {
var trimmerView: ICGVideoTrimmerView?
var asset: AVAsset!
var rect: CGRect = CGRect.zero
var mThemeColor = UIColor.clear
var bridge: RCTBridge!
var onChange: RCTBubblingEventBlock?
var onTrackerMove: RCTBubblingEventBlock?
var _minLength: CGFloat? = nil
var _maxLength: CGFloat? = nil
var _thumbWidth: CGFloat? = nil
var _trackerColor: UIColor = UIColor.clear
var _trackerHandleColor: UIColor = UIColor.clear
var _showTrackerHandle = false
var source: NSString? {
set {
setSource(source: newValue)
}
get {
return nil
}
}
var showTrackerHandle: NSNumber? {
set {
if newValue == nil {
return
}
let _nVal = newValue! == 1 ? true : false
if _showTrackerHandle != _nVal {
_showTrackerHandle = _nVal
self.updateView()
}
}
get {
return nil
}
}
var trackerHandleColor: NSString? {
set {
if newValue != nil {
let color = NumberFormatter().number(from: newValue! as String)
let formattedColor = RCTConvert.uiColor(color)
if formattedColor != nil {
self._trackerHandleColor = formattedColor!
self.updateView();
}
}
}
get {
return nil
}
}
var height: NSNumber? {
set {
self.rect.size.height = RCTConvert.cgFloat(newValue) + 40
self.updateView()
}
get {
return nil
}
}
var width: NSNumber? {
set {
self.rect.size.width = RCTConvert.cgFloat(newValue)
self.updateView()
}
get {
return nil
}
}
var themeColor: NSString? {
set {
if newValue != nil {
let color = NumberFormatter().number(from: newValue! as String)
self.mThemeColor = RCTConvert.uiColor(color)
self.updateView()
}
}
get {
return nil
}
}
var maxLength: NSNumber? {
set {
if newValue != nil {
self._maxLength = RCTConvert.cgFloat(newValue!)
self.updateView()
}
}
get {
return nil
}
}
var minLength: NSNumber? {
set {
if newValue != nil {
self._minLength = RCTConvert.cgFloat(newValue!)
self.updateView()
}
}
get {
return nil
}
}
var thumbWidth: NSNumber? {
set {
if newValue != nil {
self._thumbWidth = RCTConvert.cgFloat(newValue!)
self.updateView()
}
}
get {
return nil
}
}
var currentTime: NSNumber? {
set {
print("CHANGED: [TrimmerView]: currentTime: \(newValue)")
if newValue != nil && self.trimmerView != nil {
let convertedValue = newValue as! CGFloat
self.trimmerView?.seek(toTime: convertedValue)
// self.trimmerView
}
}
get {
return nil
}
}
var trackerColor: NSString? {
set {
if newValue == nil {
return
}
print("CHANGED: trackerColor \(newValue!)")
let color = NumberFormatter().number(from: newValue! as String)
let formattedColor = RCTConvert.uiColor(color)
if formattedColor != nil {
self._trackerColor = formattedColor!
self.updateView()
}
}
get {
return nil
}
}
func updateView() {
self.frame = rect
if trimmerView != nil {
trimmerView!.frame = rect
trimmerView!.themeColor = self.mThemeColor
trimmerView!.trackerColor = self._trackerColor
trimmerView!.trackerHandleColor = self._trackerHandleColor
trimmerView!.showTrackerHandle = self._showTrackerHandle
trimmerView!.maxLength = _maxLength == nil ? CGFloat(self.asset.duration.seconds) : _maxLength!
self.frame = CGRect(x: rect.origin.x, y: rect.origin.y, width: rect.size.width, height: rect.size.height + 20)
if _minLength != nil {
trimmerView!.minLength = _minLength!
}
if _thumbWidth != nil {
trimmerView!.thumbWidth = _thumbWidth!
}
self.trimmerView!.resetSubviews()
// Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(self.updateTrimmer), userInfo: nil, repeats: false)
}
}
func updateTrimmer() {
self.trimmerView!.resetSubviews()
}
func setSource(source: NSString?) {
if source != nil {
let pathToSource = NSURL(string: source! as String)
self.asset = AVURLAsset(url: pathToSource! as URL, options: nil)
trimmerView = ICGVideoTrimmerView(frame: rect, asset: self.asset)
trimmerView!.showsRulerView = false
trimmerView!.hideTracker(false)
trimmerView!.delegate = self
trimmerView!.trackerColor = self._trackerColor
self.addSubview(trimmerView!)
self.updateView()
}
}
init(frame: CGRect, bridge: RCTBridge) {
super.init(frame: frame)
self.bridge = bridge
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func onTrimmerPositionChange(startTime: CGFloat, endTime: CGFloat) {
if self.onChange != nil {
let event = ["startTime": startTime, "endTime": endTime]
self.onChange!(event)
}
}
func trimmerView(_ trimmerView: ICGVideoTrimmerView, didChangeLeftPosition startTime: CGFloat, rightPosition endTime: CGFloat) {
onTrimmerPositionChange(startTime: startTime, endTime: endTime)
}
public func trimmerView(_ trimmerView: ICGVideoTrimmerView, currentPosition currentTime: CGFloat) {
print("current", currentTime)
if onTrackerMove == nil {
return
}
let event = ["currentTime": currentTime]
self.onTrackerMove!(event)
}
}
| 28.617647 | 145 | 0.526208 |
9c06cb5df00065fd1ae1af0719f68bc470387108 | 1,913 | //
// DefaultTableViewController.swift
// Lego_DS_Example
//
// Created by Vitor Spessoto on 29/06/21.
// Copyright © 2021 CocoaPods. All rights reserved.
//
import UIKit
import Lego_DS
class DefaultTableViewController: UITableViewController {
@IBOutlet weak var cell: DefaultTableViewCell!
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(DefaultTableViewCell.nib, forCellReuseIdentifier: DefaultTableViewCell.identifier)
// Uncomment the following line to preserve selection between presentations
self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 2
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: DefaultTableViewCell.identifier, for: indexPath) as! DefaultTableViewCell
let viewModel = DefaultCellViewModel(title: "Default Cell \(indexPath.row + 1)")
cell.viewModel = viewModel
cell.setup()
return cell
}
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return false
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 56
}
}
| 33.561404 | 138 | 0.705698 |
ccb102260b3cc3ebe95474ff1e006991d7d38d40 | 956 | //
// Texture.swift
// Engine
//
// Created by Nick Lockwood on 13/02/2020.
// Copyright © 2019 Nick Lockwood. All rights reserved.
//
public enum Texture: String, CaseIterable {
case wall, wall2
case crackWall, crackWall2
case slimeWall, slimeWall2
case door, door2
case doorjamb, doorjamb2
case floor
case crackFloor
case ceiling
case monster
case monsterWalk1, monsterWalk2
case monsterScratch1, monsterScratch2, monsterScratch3, monsterScratch4
case monsterScratch5, monsterScratch6, monsterScratch7, monsterScratch8
case monsterHurt, monsterDeath1, monsterDeath2, monsterDead
case pistol
case pistolFire1, pistolFire2, pistolFire3, pistolFire4
case shotgun
case shotgunFire1, shotgunFire2, shotgunFire3, shotgunFire4
case shotgunPickup
case switch1, switch2, switch3, switch4
case elevatorFloor, elevatorCeiling, elevatorSideWall, elevatorBackWall
case medkit
}
| 29.875 | 75 | 0.748954 |
e6159d01ad145ae5407aab5e4553d73f36043ff9 | 7,453 | //
// KeychainItem.swift
//
// Copyright © 2017-2021 Purgatory Design. Licensed under the MIT License.
//
// Based on KeychainPasswordItem from GenericKeychain sample code.
// Copyright (C) 2016 Apple Inc. All Rights Reserved.
//
#if canImport(ObjectiveC)
import Foundation
public struct KeychainItem {
// MARK: Types
public enum KeychainError: Error {
case itemNotFound
case unexpectedItemData
case unexpectedStringData
case unexpectedError(OSStatus)
}
// MARK: Properties
public let service: String
public let accessGroup: String?
public private(set) var account: String
// MARK: Intialization
public init(service: String, account: String, accessGroup: String? = nil) {
self.service = service
self.account = account
self.accessGroup = accessGroup
}
// MARK: Keychain access
public func restore() throws -> Data {
// Build a query to find the item that matches the service, account and access group.
var query = KeychainItem.keychainQuery(withService: service, account: account, accessGroup: accessGroup)
query[kSecMatchLimit as String] = kSecMatchLimitOne
query[kSecReturnAttributes as String] = kCFBooleanTrue
query[kSecReturnData as String] = kCFBooleanTrue
// Try to fetch the existing keychain item that matches the query.
var queryResult: AnyObject?
let status = withUnsafeMutablePointer(to: &queryResult) {
SecItemCopyMatching(query as CFDictionary, UnsafeMutablePointer($0))
}
// Check the return status and throw an error if appropriate.
guard status != errSecItemNotFound else { throw KeychainError.itemNotFound }
guard status == noErr else { throw KeychainError.unexpectedError(status) }
// Parse the data from the query result.
guard let existingItem = queryResult as? [String : AnyObject],
let result = existingItem[kSecValueData as String] as? Data
else { throw KeychainError.unexpectedItemData }
return result
}
public func restoreString() throws -> String {
// Parse the string from the query result.
let keychainData = try restore()
guard let result = String(data: keychainData, encoding: String.Encoding.utf8)
else { throw KeychainError.unexpectedStringData }
return result
}
public func archive(data: Data) throws {
do {
// Check for an existing item in the keychain.
try _ = restore()
// Update the existing item with the new data.
var attributesToUpdate = [String : AnyObject]()
attributesToUpdate[kSecValueData as String] = data as AnyObject?
let query = KeychainItem.keychainQuery(withService: service, account: account, accessGroup: accessGroup)
let status = SecItemUpdate(query as CFDictionary, attributesToUpdate as CFDictionary)
// Throw an error if an unexpected status was returned.
guard status == noErr else { throw KeychainError.unexpectedError(status) }
}
catch KeychainError.itemNotFound {
// No item was found in the keychain. Create a dictionary to save as a new keychain item.
var newItem = KeychainItem.keychainQuery(withService: service, account: account, accessGroup: accessGroup)
newItem[kSecValueData as String] = data as AnyObject?
// Add a the new item to the keychain.
let status = SecItemAdd(newItem as CFDictionary, nil)
// Throw an error if an unexpected status was returned.
guard status == noErr else { throw KeychainError.unexpectedError(status) }
}
}
public func archive(string: String) throws {
// Encode the string into a Data object and archive it.
let encodedString = string.data(using: String.Encoding.utf8)!
try archive(data: encodedString)
}
public mutating func renameAccount(_ newAccountName: String) throws {
// Try to update an existing item with the new account name.
var attributesToUpdate = [String : AnyObject]()
attributesToUpdate[kSecAttrAccount as String] = newAccountName as AnyObject?
let query = KeychainItem.keychainQuery(withService: service, account: self.account, accessGroup: accessGroup)
let status = SecItemUpdate(query as CFDictionary, attributesToUpdate as CFDictionary)
// Throw an error if an unexpected status was returned.
guard status == noErr || status == errSecItemNotFound else { throw KeychainError.unexpectedError(status) }
self.account = newAccountName
}
public func delete() throws {
// Delete the existing item from the keychain.
let query = KeychainItem.keychainQuery(withService: service, account: account, accessGroup: accessGroup)
let status = SecItemDelete(query as CFDictionary)
// Throw an error if an unexpected status was returned.
guard status == noErr || status == errSecItemNotFound else { throw KeychainError.unexpectedError(status) }
}
public static func keychainItems(forService service: String, accessGroup: String? = nil) throws -> [KeychainItem] {
// Build a query for all items that match the service and access group.
var query = KeychainItem.keychainQuery(withService: service, accessGroup: accessGroup)
query[kSecMatchLimit as String] = kSecMatchLimitAll
query[kSecReturnAttributes as String] = kCFBooleanTrue
query[kSecReturnData as String] = kCFBooleanFalse
// Fetch matching items from the keychain.
var queryResult: AnyObject?
let status = withUnsafeMutablePointer(to: &queryResult) {
SecItemCopyMatching(query as CFDictionary, UnsafeMutablePointer($0))
}
// If no items were found, return an empty array.
guard status != errSecItemNotFound else { return [] }
// Throw an error if an unexpected status was returned.
guard status == noErr else { throw KeychainError.unexpectedError(status) }
// Cast the query result to an array of dictionaries.
guard let resultData = queryResult as? [[String : AnyObject]] else { throw KeychainError.unexpectedItemData }
// Create a `KeychainItem` for each dictionary in the query result.
var keychainItems = [KeychainItem]()
for result in resultData {
guard let account = result[kSecAttrAccount as String] as? String else { throw KeychainError.unexpectedItemData }
let keychainItem = KeychainItem(service: service, account: account, accessGroup: accessGroup)
keychainItems.append(keychainItem)
}
return keychainItems
}
// MARK: Convenience
private static func keychainQuery(withService service: String, account: String? = nil, accessGroup: String? = nil) -> [String: AnyObject] {
var query = [String : AnyObject]()
query[kSecClass as String] = kSecClassGenericPassword
query[kSecAttrService as String] = service as AnyObject?
if let account = account {
query[kSecAttrAccount as String] = account as AnyObject?
}
if let accessGroup = accessGroup {
query[kSecAttrAccessGroup as String] = accessGroup as AnyObject?
}
return query
}
}
#endif
| 41.176796 | 143 | 0.676104 |
7968ed58062bbc6c861ec034d691d74e809162fa | 299 | import Swift
extension String {
func snakeToCamelCased() -> String {
return split(separator: "_")
.enumerated()
.map { index, element in
return index > 0 ? String(element).capitalized : String(element)
}
.joined()
}
}
| 23 | 80 | 0.521739 |
48fa74638d6f81000dbb2fc3fc21c0e52c0157b5 | 1,385 | //
// ViewController.swift
// JavaWebApp
//
// Created by tm on 16/9/21.
// Copyright © 2016年 tm. All rights reserved.
//
import UIKit
import Alamofire
import SVProgressHUD
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// let sss = MyDes.decode("D9788155D80EDBC3", key: "asdfaasfsdfqwfeasdfsd")
let sss = MyDes.decrypt(withDESString: "A67671A5E810611E", key: "asdfaasfsdfqwfeasdfsd", andiV: "12345678")
print(sss)
// Do any additional setup after loading the view, typically from a nib.
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
// Alamofire.request("http://192.168.11.184:8080/admin/users",method:.post,parameters:["nickname":"哥哥","firstName":"哇哈哈","lastName":"地雷","password":"圣诞节复活节阿斯"]).responseJSON
Alamofire.request("http://192.168.11.184:8080/admin/users",method:.post,parameters:["nickname":"哥哥","firstName":"哇哈哈","lastName":"地雷","password":"圣诞节复活节阿斯"]).responseString { (responseString) in
let string = MyDes.decode("", key: "asdfaasfsdfqwfeasdfsd")
print("JSON: \(string)")
}
// Alamofire.reque
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 32.209302 | 202 | 0.65343 |
8a9f2c8f2887589c7660ae23fdb1e9ba9ad2141e | 17,759 | // Copyright 2019 Kakao Corp.
//
// 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 Foundation
import Alamofire
import KakaoSDKCommon
import KakaoSDKTemplate
import UIKit
/// 카카오링크 호출을 담당하는 클래스입니다.
public class LinkApi {
// MARK: Fields
/// 간편하게 API를 호출할 수 있도록 제공되는 공용 싱글톤 객체입니다.
public static let shared = LinkApi()
/// 카카오링크 API로부터 리다이렉트 된 URL 인지 체크합니다.
public static func isKakaoLinkUrl(_ url:URL) -> Bool {
if url.absoluteString.hasPrefix("\(try! KakaoSDKCommon.shared.scheme())://kakaolink") {
return true
}
return false
}
public static func isKakaoLinkAvailable() -> Bool {
return UIApplication.shared.canOpenURL(URL(string:Urls.compose(.TalkLink, path:Paths.talkLink))!)
}
}
extension LinkApi {
// MARK: Fields
public static func isExceededLimit(linkParameters: [String: Any]?, validationResult: ValidationResult, extras: [String: Any]?) -> Bool {
var attachment = [String: Any]()
if let linkParameters = linkParameters {
attachment["ak"] = linkParameters["appkey"] as? String
attachment["av"] = linkParameters["appver"] as? String
attachment["lv"] = linkParameters["linkver"] as? String
}
attachment["ti"] = validationResult.templateId.description
attachment["p"] = validationResult.templateMsg["P"]
attachment["c"] = validationResult.templateMsg["C"]
if let templateArgs = validationResult.templateArgs, templateArgs.toJsonString() != nil, templateArgs.count > 0 {
attachment["ta"] = templateArgs
}
if let extras = extras, extras.toJsonString() != nil, extras.count > 0 {
attachment["extras"] = extras
}
guard let count = attachment.toJsonString()?.data(using: .utf8)?.count else {
// 측정 불가 bypass
return false
}
return count >= 1024 * 24
}
// MARK: Using Web Sharer
/// 기본 템플릿을 공유하는 웹 공유 URL을 얻습니다.
///
/// 획득한 URL을 브라우저에 요청하면 카카오톡이 없는 환경에서도 메시지를 공유할 수 있습니다. 공유 웹페이지 진입시 로그인된 계정 쿠키가 없다면 카카오톡에 연결된 카카오계정으로 로그인이 필요합니다.
///
/// - seealso: [Template](../../KakaoSDKTemplate/Protocols/Templatable.html)
public func makeSharerUrlforDefaultLink(templatable:Templatable, serverCallbackArgs:[String:String]? = nil) -> URL? {
return self.makeSharerUrl(url: Urls.compose(.SharerLink, path:Paths.sharerLink),
action:"default",
parameters:["link_ver":"4.0",
"template_object":templatable.toJsonObject()].filterNil(),
serverCallbackArgs:serverCallbackArgs)
}
/// 기본 템플릿을 공유하는 웹 공유 URL을 얻습니다.
/// 획득한 URL을 브라우저에 요청하면 카카오톡이 없는 환경에서도 메시지를 공유할 수 있습니다. 공유 웹페이지 진입시 로그인된 계정 쿠키가 없다면 카카오톡에 연결된 카카오계정으로 로그인이 필요합니다.
public func makeSharerUrlforDefaultLink(templateObject:[String:Any], serverCallbackArgs:[String:String]? = nil) -> URL? {
return self.makeSharerUrl(url: Urls.compose(.SharerLink, path:Paths.sharerLink),
action:"default",
parameters:["link_ver":"4.0",
"template_object":templateObject].filterNil(),
serverCallbackArgs:serverCallbackArgs)
}
/// 지정된 URL을 스크랩하여 만들어진 템플릿을 공유하는 웹 공유 URL을 얻습니다.
///
/// 획득한 URL을 브라우저에 요청하면 카카오톡이 없는 환경에서도 메시지를 공유할 수 있습니다. 공유 웹페이지 진입시 로그인된 계정 쿠키가 없다면 카카오톡에 연결된 카카오계정으로 로그인이 필요합니다.
public func makeSharerUrlforScrapLink(requestUrl:String, templateId:Int64? = nil, templateArgs:[String:String]? = nil, serverCallbackArgs:[String:String]? = nil) -> URL? {
return self.makeSharerUrl(url: Urls.compose(.SharerLink, path:Paths.sharerLink),
action:"scrap",
parameters:["link_ver":"4.0",
"request_url":requestUrl,
"template_id":templateId,
"template_args":templateArgs].filterNil(),
serverCallbackArgs:serverCallbackArgs)
}
/// 카카오 디벨로퍼스에서 생성한 메시지 템플릿을 공유하는 웹 공유 URL을 얻습니다.
///
/// 획득한 URL을 브라우저에 요청하면 카카오톡이 없는 환경에서도 메시지를 공유할 수 있습니다. 공유 웹페이지 진입시 로그인된 계정 쿠키가 없다면 카카오톡에 연결된 카카오계정으로 로그인이 필요합니다.
public func makeSharerUrlforCustomLink(templateId:Int64, templateArgs:[String:String]? = nil, serverCallbackArgs:[String:String]? = nil) -> URL? {
return self.makeSharerUrl(url: Urls.compose(.SharerLink, path:Paths.sharerLink),
action:"custom",
parameters:["link_ver":"4.0",
"template_id":templateId,
"template_args":templateArgs].filterNil(),
serverCallbackArgs:serverCallbackArgs)
}
//공통
private func makeSharerUrl(url:String, action:String, parameters:[String:Any]? = nil, serverCallbackArgs:[String:String]? = nil) -> URL? {
return SdkUtils.makeUrlWithParameters(url, parameters: ["app_key":try! KakaoSDKCommon.shared.appKey(),
"validation_action":action,
"validation_params":parameters?.toJsonString(),
"ka":Constants.kaHeader,
"lcba":serverCallbackArgs?.toJsonString()].filterNil())
}
}
extension LinkApi {
// MARK: Fields
public func transformResponseToLinkResult(response: HTTPURLResponse?, data:Data?, targetAppKey: String? = nil, serverCallbackArgs:[String:String]? = nil,
completion:@escaping (LinkResult?, Error?) -> Void) {
if let data = data, let validationResult = try? SdkJSONDecoder.default.decode(ValidationResult.self, from: data) {
let extraParameters = ["KA":Constants.kaHeader,
"iosBundleId":Bundle.main.bundleIdentifier,
"lcba":serverCallbackArgs?.toJsonString()
].filterNil()
let linkParameters = ["appkey" : try! KakaoSDKCommon.shared.appKey(),
"target_app_key" : targetAppKey,
"appver" : Constants.appVersion(),
"linkver" : "4.0",
"template_json" : validationResult.templateMsg.toJsonString(),
"template_id" : validationResult.templateId,
"template_args" : validationResult.templateArgs?.toJsonString(),
"extras" : extraParameters?.toJsonString()
].filterNil()
if let url = SdkUtils.makeUrlWithParameters(Urls.compose(.TalkLink, path:Paths.talkLink), parameters: linkParameters) {
SdkLog.d("--------------------------------url \(url)")
if LinkApi.isExceededLimit(linkParameters: linkParameters, validationResult: validationResult, extras: extraParameters) {
completion(nil, SdkError(reason: .ExceedKakaoLinkSizeLimit))
} else {
completion(LinkResult(url:url, warningMsg: validationResult.warningMsg, argumentMsg: validationResult.argumentMsg), nil)
}
}
else {
completion(nil, SdkError(reason:.BadParameter, message: "Invalid Url."))
}
}
}
// MARK: Using KakaoTalk
func defaultLink(templateObjectJsonString:String?,
serverCallbackArgs:[String:String]? = nil,
completion:@escaping (LinkResult?, Error?) -> Void ) {
return API.responseData(.post,
Urls.compose(path:Paths.defalutLink),
parameters: ["link_ver":"4.0",
"template_object":templateObjectJsonString].filterNil(),
headers: ["Authorization":"KakaoAK \(try! KakaoSDKCommon.shared.appKey())"],
sessionType: .Api,
apiType: .KApi) { [weak self] (response, data, error) in
let strongSelf = self
strongSelf?.transformResponseToLinkResult(response: response, data: data, serverCallbackArgs: serverCallbackArgs) { (linkResult, error) in
if let error = error {
completion(nil, error)
}
else {
if let linkResult = linkResult {
completion(linkResult, nil)
}
else {
completion(nil, SdkError(reason:.Unknown, message: "linkResult is nil"))
}
}
}
}
}
/// 기본 템플릿을 카카오톡으로 공유합니다.
/// - seealso: [Template](../../KakaoSDKTemplate/Protocols/Templatable.html) <br> `LinkResult`
public func defaultLink(templatable: Templatable, serverCallbackArgs:[String:String]? = nil,
completion:@escaping (LinkResult?, Error?) -> Void) {
self.defaultLink(templateObjectJsonString: templatable.toJsonObject()?.toJsonString(), serverCallbackArgs:serverCallbackArgs, completion: completion)
}
/// 기본 템플릿을 카카오톡으로 공유합니다.
/// - seealso: `LinkResult`
public func defaultLink(templateObject:[String:Any], serverCallbackArgs:[String:String]? = nil,
completion:@escaping (LinkResult?, Error?) -> Void ) {
self.defaultLink(templateObjectJsonString: templateObject.toJsonString(), serverCallbackArgs:serverCallbackArgs, completion: completion)
}
/// 지정된 URL을 스크랩하여 만들어진 템플릿을 카카오톡으로 공유합니다.
/// - seealso: `LinkResult`
public func scrapLink(requestUrl:String, templateId:Int64? = nil, templateArgs:[String:String]? = nil, serverCallbackArgs:[String:String]? = nil,
completion:@escaping (LinkResult?, Error?) -> Void ) {
return API.responseData(.post,
Urls.compose(path:Paths.scrapLink),
parameters: ["link_ver":"4.0",
"request_url":requestUrl,
"template_id":templateId,
"template_args":templateArgs?.toJsonString()]
.filterNil(),
headers: ["Authorization":"KakaoAK \(try! KakaoSDKCommon.shared.appKey())"],
sessionType: .Api,
apiType: .KApi) { [weak self] (response, data, error) in
let strongSelf = self
strongSelf?.transformResponseToLinkResult(response: response, data: data, serverCallbackArgs: serverCallbackArgs) { (linkResult, error) in
if let error = error {
completion(nil, error)
}
else {
if let linkResult = linkResult {
completion(linkResult, nil)
}
else {
completion(nil, SdkError(reason:.Unknown, message: "linkResult is nil"))
}
}
}
}
}
/// 카카오 디벨로퍼스에서 생성한 메시지 템플릿을 카카오톡으로 공유합니다. 템플릿을 생성하는 방법은 https://developers.kakao.com/docs/latest/ko/message/ios#create-message 을 참고하시기 바랍니다.
/// - seealso: `LinkResult`
public func customLink(templateId:Int64, templateArgs:[String:String]? = nil, serverCallbackArgs:[String:String]? = nil,
completion:@escaping (LinkResult?, Error?) -> Void ) {
return API.responseData(.post,
Urls.compose(path:Paths.validateLink),
parameters: ["link_ver":"4.0",
"template_id":templateId,
"template_args":templateArgs?.toJsonString()]
.filterNil(),
headers: ["Authorization":"KakaoAK \(try! KakaoSDKCommon.shared.appKey())"],
sessionType: .Api,
apiType: .KApi ) { [weak self] (response, data, error) in
let strongSelf = self
strongSelf?.transformResponseToLinkResult(response: response, data: data, serverCallbackArgs: serverCallbackArgs) { (linkResult, error) in
if let error = error {
completion(nil, error)
}
else {
if let linkResult = linkResult {
completion(linkResult, nil)
}
else {
completion(nil, SdkError(reason:.Unknown, message: "linkResult is nil"))
}
}
}
}
}
// MARK: Image Upload
/// 카카오링크 컨텐츠 이미지로 활용하기 위해 로컬 이미지를 카카오 이미지 서버로 업로드 합니다.
public func imageUpload(image: UIImage, secureResource: Bool = true,
completion:@escaping (ImageUploadResult?, Error?) -> Void ) {
return API.upload(.post, Urls.compose(path:Paths.imageUploadLink),
images: [image],
parameters: ["secure_resource": secureResource],
headers: ["Authorization":"KakaoAK \(try! KakaoSDKCommon.shared.appKey())"],
sessionType: .Api,
apiType: .KApi) { (response, data, error) in
if let error = error {
completion(nil, error)
}
else {
if let data = data {
completion(try? SdkJSONDecoder.custom.decode(ImageUploadResult.self, from: data), nil)
}
else {
completion(nil, SdkError())
}
}
}
}
/// 카카오링크 컨텐츠 이미지로 활용하기 위해 원격 이미지를 카카오 이미지 서버로 스크랩 합니다.
public func imageScrap(imageUrl: URL, secureResource: Bool = true,
completion:@escaping (ImageUploadResult?, Error?) -> Void) {
API.responseData(.post, Urls.compose(path:Paths.imageScrapLink),
parameters: ["image_url": imageUrl.absoluteString, "secure_resource": secureResource],
headers: ["Authorization":"KakaoAK \(try! KakaoSDKCommon.shared.appKey())"],
sessionType: .Api,
apiType: .KApi) { (response, data, error) in
if let error = error {
completion(nil, error)
}
else {
if let data = data {
completion(try? SdkJSONDecoder.custom.decode(ImageUploadResult.self, from: data), nil)
}
else {
completion(nil, SdkError())
}
}
}
}
}
| 53.978723 | 175 | 0.481333 |
bbbf1e4daa6ba53b2d9076b9e0aedc30ec3e1b21 | 323 | //
// PokeCollectionViewCell.swift
// pokedex
//
// Created by Jean Macena on 13/07/20.
// Copyright © 2020 Jean Macena. All rights reserved.
//
import UIKit
class PokeCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var pokeImage: UIImageView!
@IBOutlet weak var pokeName: UILabel!
}
| 17.944444 | 54 | 0.693498 |
0ea332511c6db9415130194ceee90aef548bb377 | 44,136 | //
// DarwinTests.swift
// Bluetooth
//
// Created by Alsey Coleman Miller on 6/1/18.
// Copyright © 2018 PureSwift. All rights reserved.
//
import XCTest
import Foundation
@testable import Bluetooth
#if os(macOS)
import CoreBluetooth
import IOKit
import Darwin
final class DarwinTests: XCTestCase {
// MARK: - Assigned Numbers
func testGAPAppearance() {
XCTAssertEqual(GAPAppearance.Unknown.unknown.rawValue, IOKitBluetoothGAPAppearance.Unknown.rawValue)
XCTAssertEqual(GAPAppearance.Phone.generic.rawValue, IOKitBluetoothGAPAppearance.GenericPhone.rawValue)
XCTAssertEqual(GAPAppearance.Computer.generic.rawValue, IOKitBluetoothGAPAppearance.GenericComputer.rawValue)
}
func testCompanyIdentifiers() {
XCTAssertEqual(CompanyIdentifier.ericssonTechnologyLicensing.rawValue, IOKitBluetoothCompanyIdentifers.EricssonTechnologyLicensing.rawValue)
XCTAssertEqual(CompanyIdentifier.nokiaMobilePhones.rawValue, IOKitBluetoothCompanyIdentifers.NokiaMobilePhones.rawValue)
XCTAssertEqual(CompanyIdentifier.ibm.rawValue, IOKitBluetoothCompanyIdentifers.IBM.rawValue)
XCTAssertEqual(CompanyIdentifier.intel.rawValue, IOKitBluetoothCompanyIdentifers.Intel.rawValue)
XCTAssertEqual(CompanyIdentifier.apple.rawValue, IOKitBluetoothCompanyIdentifers.Apple.rawValue)
XCTAssertEqual(CompanyIdentifier.google.rawValue, IOKitBluetoothCompanyIdentifers.Google.rawValue)
XCTAssertEqual(CompanyIdentifier.microsoft.rawValue, IOKitBluetoothCompanyIdentifers.Microsoft.rawValue)
}
// MARK: - BluetoothUUID
func testCoreBluetoothUUID() {
do {
let uuid = BluetoothUUID.bit16(0xFEA9)
let coreBluetoothUUID = CBUUID(uuid)
XCTAssert(coreBluetoothUUID.uuidString == uuid.rawValue)
XCTAssert(uuid.bigEndian.data == coreBluetoothUUID.data, "\(uuid.data) == \(coreBluetoothUUID.data)")
}
do {
let uuid = BluetoothUUID() // 128 bit
let coreBluetoothUUID = CBUUID(uuid)
XCTAssert(coreBluetoothUUID.uuidString == uuid.rawValue)
XCTAssert(uuid.bigEndian.data == coreBluetoothUUID.data, "\(uuid.data) == \(coreBluetoothUUID.data)")
}
do {
let coreBluetoothUUID = CBUUID(string: "FEA9")
let uuid = BluetoothUUID(coreBluetoothUUID)
XCTAssert(coreBluetoothUUID.uuidString == uuid.rawValue)
XCTAssert(uuid.bigEndian.data == coreBluetoothUUID.data, "\(uuid.data) == \(coreBluetoothUUID.data)")
}
do {
let coreBluetoothUUID = CBUUID(string: "68753A44-4D6F-1226-9C60-0050E4C00067")
let uuid = BluetoothUUID(coreBluetoothUUID)
XCTAssert(coreBluetoothUUID.uuidString == uuid.rawValue)
XCTAssert(uuid.bigEndian.data == coreBluetoothUUID.data, "\(uuid.data) == \(coreBluetoothUUID.data)")
}
}
func testCoreBluetoothPerfomanceStringParseUUID() {
let uuids = randomUUIDs.map { $0.uuidString }
measure { uuids.forEach { _ = CBUUID(string: $0) } }
}
func testCoreBluetoothPerfomanceStringUUID() {
let uuids = randomUUIDs.map { CBUUID(nsuuid: $0) }
measure { uuids.forEach { let _ = $0.uuidString } }
}
func testCoreBluetoothPerformanceDataParseUUID() {
let uuids = randomUUIDs.map { $0.data }
measure { uuids.forEach { _ = CBUUID(data: $0) } }
}
func testCoreBluetoothPerformanceDataUUID() {
let uuids = randomUUIDs.map { CBUUID(nsuuid: $0) }
measure { uuids.forEach { let _ = $0.data } }
}
// MARK: - Code Generators
func testGenerateDefinedUUID() {
let uuids = definedUUIDs.sorted(by: { $0.key < $1.key })
var generatedCode = ""
var memberNameCache = [UInt16: String]()
func 🖨(_ text: String) {
generatedCode += text + "\n"
}
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .short
dateFormatter.timeStyle = .none
let fileDate = dateFormatter.string(from: Date())
🖨("//")
🖨("// DefinedUUIDExtension.swift")
🖨("// Bluetooth")
🖨("//")
🖨("// Generated by Alsey Coleman Miller on \(fileDate).")
🖨("//")
🖨("")
🖨("public extension BluetoothUUID {")
🖨("")
for (uuidValue, name) in uuids {
let uuid = BluetoothUUID.bit16(uuidValue)
let sanitizedName = sanitize(name: name)
let llamaCaseName = llamaCase(sanitizedName)
var memberName = llamaCaseName
// prevent duplicate entries
var duplicateNumber = 1
while memberNameCache.values.contains(memberName) {
duplicateNumber += 1
memberName = llamaCaseName + "\(duplicateNumber)"
}
let comment = name + " " + "(`0x\(uuid.rawValue)`)"
🖨(" /// " + comment)
🖨(" static var " + memberName + ": BluetoothUUID {")
🖨(" return .bit16(0x" + uuid.rawValue + ")")
🖨(" }")
🖨("")
memberNameCache[uuidValue] = memberName
}
🖨("}")
var filename = NSTemporaryDirectory() + "DefinedUUIDExtension.swift"
XCTAssertNoThrow(try generatedCode.write(toFile: filename, atomically: true, encoding: .utf8))
print("Generated Swift code \(filename)")
// generate unit test for extensions
generatedCode = ""
🖨("//")
🖨("// DefinedUUIDTests.swift")
🖨("// Bluetooth")
🖨("//")
🖨("// Generated by Alsey Coleman Miller on \(fileDate).")
🖨("//")
🖨("")
🖨("import XCTest")
🖨("import Foundation")
🖨("@testable import Bluetooth")
🖨("")
🖨("// swiftlint:disable type_body_length")
🖨("final class DefinedUUIDTests: XCTestCase {")
🖨("")
🖨(" static let allTests = [")
🖨(" (\"testDefinedUUID\", testDefinedUUID)")
🖨(" ]")
🖨("")
🖨(" func testDefinedUUID() {")
🖨("")
// generate test methods
for (uuidValue, name) in uuids {
let uuid = BluetoothUUID.bit16(uuidValue)
guard let memberName = memberNameCache[uuidValue]
else { XCTFail("No extension generated for \(uuid)"); return }
🖨(" /// \(name)")
🖨(" XCTAssertEqual(BluetoothUUID.\(memberName).rawValue, \"\(uuid.rawValue)\")")
🖨(" XCTAssertEqual(BluetoothUUID.\(memberName), .bit16(0x\(uuid.rawValue)))")
🖨(" XCTAssertEqual(BluetoothUUID.\(memberName), .bit16(\(uuidValue)))")
🖨(" XCTAssertEqual(BluetoothUUID.\(memberName).name, \"\(name)\")")
🖨(" XCTAssertNotEqual(BluetoothUUID.\(memberName), .bit32(\(uuidValue)))")
🖨(" XCTAssertNotEqual(BluetoothUUID.\(memberName), .bit32(0x\(uuid.rawValue)))")
🖨("")
}
🖨(" }")
🖨("")
🖨("}")
🖨("// swiftlint:enable type_body_length")
filename = NSTemporaryDirectory() + "DefinedUUIDTests.swift"
XCTAssertNoThrow(try generatedCode.write(toFile: filename, atomically: true, encoding: .utf8))
print("Generated Swift code \(filename)")
}
func testGenerateDefinedCompanyIdentifier() {
let blacklist: [UInt16] = [
.max // remove internal use identifier
]
let companies = companyIdentifiers
.sorted(by: { $0.key < $1.key })
.filter { blacklist.contains($0.key) == false }
var generatedCode = ""
var memberNameCache = [UInt16: String]()
func 🖨(_ text: String) {
generatedCode += text + "\n"
}
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .short
dateFormatter.timeStyle = .none
let fileDate = dateFormatter.string(from: Date())
🖨("//")
🖨("// CompanyIdentifierExtension.swift")
🖨("// Bluetooth")
🖨("//")
🖨("// Generated by Alsey Coleman Miller on \(fileDate).")
🖨("//")
🖨("")
🖨("public extension CompanyIdentifier {")
🖨("")
for (identifier, name) in companies {
let sanitizedName = sanitize(name: name)
let llamaCaseName = llamaCase(sanitizedName)
var memberName = llamaCaseName
// prevent duplicate entries
var duplicateNumber = 1
while memberNameCache.values.contains(memberName) {
duplicateNumber += 1
memberName = llamaCaseName + "\(duplicateNumber)"
}
let comment = name + " " + "(`\(identifier)`)"
🖨(" /// " + comment)
🖨(" static var " + memberName + ": CompanyIdentifier {")
🖨(" return CompanyIdentifier(rawValue: \(identifier))")
🖨(" }")
🖨("")
memberNameCache[identifier] = memberName
}
🖨("}")
var filename = NSTemporaryDirectory() + "CompanyIdentifierExtension.swift"
XCTAssertNoThrow(try generatedCode.write(toFile: filename, atomically: true, encoding: .utf8))
print("Generated Swift code \(filename)")
// generate unit test for extensions
generatedCode = """
//
// CompanyIdentifierTests.swift
// Bluetooth
//
// Generated by Alsey Coleman Miller on \(fileDate).
//
import XCTest
import Foundation
@testable import Bluetooth
// swiftlint:disable type_body_length
final class CompanyIdentifierTests: XCTestCase {
static let allTests = [
("testInvalid", testInvalid),
("testCompanies", testCompanies)
]
func testInvalid() {
XCTAssertEqual(CompanyIdentifier(rawValue: .max - 1).description, "\(UInt16.max - 1)")
}
func testCompanies() {
"""
// generate test methods
for (identifier, name) in companies {
guard let memberName = memberNameCache[identifier]
else { XCTFail("No extension generated for \(identifier)"); return }
let stringLiteral = name.replacingOccurrences(of: "\"", with: "\\\"")
🖨("""
// \(name)
XCTAssertEqual(CompanyIdentifier.\(memberName).rawValue, \(identifier))
XCTAssertEqual(CompanyIdentifier.\(memberName).name, \"\(stringLiteral)\")
XCTAssertEqual(CompanyIdentifier.\(memberName).description, \"\(stringLiteral)\")
""")
}
🖨("""
}
}
// swiftlint:enable type_body_length
""")
filename = NSTemporaryDirectory() + "CompanyIdentifierTests.swift"
XCTAssertNoThrow(try generatedCode.write(toFile: filename, atomically: true, encoding: .utf8))
print("Generated Swift code \(filename)")
}
func testGenerateUnitIdentifier() {
let unitsMethodNames: [UInt16: String] = [
0x2700: "unitless",
0x2701: "metre",
0x2702: "kilogram",
0x2703: "second",
0x2704: "ampere",
0x2705: "kelvin",
0x2706: "mole",
0x2707: "candela",
0x2710: "area",
0x2711: "volume",
0x2712: "velocity",
0x2713: "acceleration",
0x2714: "wavenumber",
0x2715: "density",
0x2716: "surfaceDensity",
0x2717: "specificVolume",
0x2718: "currentDensity",
0x2719: "magneticFieldStrengh",
0x271A: "amountConcentration",
0x271B: "massConcentration",
0x271C: "luminance",
0x271D: "refractiveIndex",
0x271E: "relativePermeability",
0x2720: "planeAngle",
0x2721: "solidAngle",
0x2722: "frequency",
0x2723: "force",
0x2724: "pascalPressure",
0x2725: "energy",
0x2726: "power",
0x2727: "coulomb",
0x2728: "electricPotential",
0x2729: "capitance",
0x272A: "electricResistance",
0x272B: "electricConductance",
0x272C: "magneticFlux",
0x272D: "magneticFluxDensity",
0x272E: "inductance",
0x272F: "celsius",
0x2730: "luminousFlux",
0x2731: "illuminance",
0x2732: "becquerel",
0x2733: "absorbedDose",
0x2734: "sievert",
0x2735: "katal",
0x2740: "pascalSecond",
0x2741: "newtonMetre",
0x2742: "surfaceTension",
0x2743: "angularVelocity",
0x2744: "angularAcceleration",
0x2745: "heatFluxDensity",
0x2746: "heatCapacity",
0x2747: "specificHeatCapacity",
0x2748: "specificEnergy",
0x2749: "thermalConductivity",
0x274A: "energyDensity",
0x274B: "electricFieldStrength",
0x274C: "electricChargeDensity",
0x274D: "surfaceChargeDensity",
0x274E: "electricFluxDensity",
0x274F: "permittivity",
0x2750: "permeability",
0x2751: "molarEnergy",
0x2752: "molarEntropy",
0x2753: "exposure",
0x2754: "absorbedDoseRate",
0x2755: "radradiantIntensityiance",
0x2756: "radiance",
0x2757: "catalyticActivity",
0x2760: "minute",
0x2761: "hour",
0x2762: "day",
0x2763: "degree",
0x2764: "planeAngleMinute",
0x2765: "planeAngleSecond",
0x2766: "hectare",
0x2767: "litre",
0x2768: "tonne",
0x2780: "bar",
0x2781: "millimetreOfMercury",
0x2782: "ngstrm",
0x2783: "nauticalMile",
0x2784: "barn",
0x2785: "velocityKnot",
0x2786: "neper",
0x2787: "bel",
0x27A0: "yard",
0x27A1: "parsec",
0x27A2: "inch",
0x27A3: "foot",
0x27A4: "mile",
0x27A5: "pressurePoundForce",
0x27A6: "kilometrePerHour",
0x27A7: "milePerHour",
0x27A8: "revolutionPerMinute",
0x27A9: "gramCalorie",
0x27AA: "kilogramCalorie",
0x27AB: "kilowattHour",
0x27AC: "degreeFahrenheit",
0x27AD: "percentage",
0x27AE: "perMille",
0x27AF: "beatsPerMinute",
0x27B0: "ampereHours",
0x27B1: "milligramPerDecilitre",
0x27B2: "millimolePerLitre",
0x27B3: "year",
0x27B4: "month",
0x27B5: "concentration",
0x27B6: "irrandiance",
0x27B7: "millilitre",
0x27B8: "pound",
0x27B9: "metabolicEquivalent",
0x27BA: "step",
0x27BC: "stroke",
0x27BD: "pace",
0x27BE: "luminousEfficacy",
0x27BF: "luminousEnergy",
0x27C0: "luminousExposure",
0x27C1: "massFlow",
0x27C2: "volumeFlow"
]
var generatedCode = ""
var memberNameCache = [UInt16: String]()
func 🖨(_ text: String) {
generatedCode += text + "\n"
}
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .short
dateFormatter.timeStyle = .none
let fileDate = dateFormatter.string(from: Date())
🖨("//")
🖨("// UnitIdentifierExtension.swift")
🖨("// Bluetooth")
🖨("//")
🖨("// Generated by Carlos Duclos on \(fileDate).")
🖨("//")
🖨("")
🖨("public extension UnitIdentifier {")
🖨("")
for (identifier, unit) in units {
var memberName = unitsMethodNames[identifier]!
// prevent duplicate entries
var duplicateNumber = 1
while memberNameCache.values.contains(memberName) {
duplicateNumber += 1
memberName = memberName + "\(duplicateNumber)"
}
let hexValue = "0x\(identifier.toHexadecimal())"
let comment = unit.name + " " + "(`\(hexValue)`)"
🖨(" /// " + comment)
🖨(" static var " + memberName + ": UnitIdentifier {")
🖨(" return UnitIdentifier(rawValue: \(hexValue))")
🖨(" }")
🖨("")
memberNameCache[identifier] = memberName
}
🖨("}")
var filename = NSTemporaryDirectory() + "UnitIdentifierExtension.swift"
XCTAssertNoThrow(try generatedCode.write(toFile: filename, atomically: true, encoding: .utf8))
print("Generated Swift code \(filename)")
// generate unit test for extensions
generatedCode = ""
🖨("//")
🖨("// UnitIdentifierTests.swift")
🖨("// Bluetooth")
🖨("//")
🖨("// Generated by Carlos Duclos on \(fileDate).")
🖨("//")
🖨("")
🖨("import XCTest")
🖨("import Foundation")
🖨("@testable import Bluetooth")
🖨("")
🖨("// swiftlint:disable type_body_length")
🖨("final class UnitIdentifierTests: XCTestCase {")
🖨("")
🖨(" static let allTests = [")
🖨(" (\"testUnits\", testUnits)")
🖨(" ]")
🖨("")
🖨(" func testUnits() {")
🖨("")
// generate test methods
for (identifier, unit) in units {
guard let memberName = memberNameCache[identifier]
else { XCTFail("No extension generated for \(identifier)"); return }
let stringLiteral = unit.name.replacingOccurrences(of: "\"", with: "\\\"")
let hexValue = "0x\(identifier.toHexadecimal())"
🖨(" /// \(unit.name)")
🖨(" XCTAssertEqual(UnitIdentifier.\(memberName).rawValue, \(hexValue))")
🖨(" XCTAssertEqual(UnitIdentifier.\(memberName).type, \"\(unit.type)\")")
🖨(" XCTAssertEqual(UnitIdentifier.\(memberName).name, \"\(stringLiteral)\")")
🖨(" XCTAssertEqual(UnitIdentifier.\(memberName).description, \"\(identifier.toHexadecimal()) (\(stringLiteral))\")")
🖨("")
}
🖨(" }")
🖨("")
🖨("}")
🖨("// swiftlint:enable type_body_length")
filename = NSTemporaryDirectory() + "UnitIdentifierTests.swift"
XCTAssertNoThrow(try generatedCode.write(toFile: filename, atomically: true, encoding: .utf8))
print("Generated Swift code \(filename)")
}
}
// MARK: - Utilities
// https://gist.github.com/AmitaiB/bbfcba3a21411ee6d3f972320bcd1ecd
func camelCase(_ string: String) -> String {
return string.components(separatedBy: CharacterSet.alphanumerics.inverted)
.filter { !$0.isEmpty }
.map { $0.capitalized }
.joined()
}
func llamaCase(_ string: String) -> String {
var result = camelCase(string)
if let firstLetterCharacter = result.first {
result = String(result.dropFirst())
let firstLetter = String(firstLetterCharacter)
result = firstLetter.lowercased() + result
}
return result
}
func uppercaseFirstLetter(_ string: String) -> String {
var result = string
if let firstLetterCharacter = result.first {
result = String(result.dropFirst())
let firstLetter = String(firstLetterCharacter)
result = firstLetter.uppercased() + result
}
return result
}
func sanitize(name: String) -> String {
let blackList = ["ASSA ABLOY"]
guard blackList.contains(name) == false
else { return name }
var name = name
.replacingOccurrences(of: "LLC \"", with: "")
.replacingOccurrences(of: "\"", with: "")
.replacingOccurrences(of: "3D ", with: "uuid3D")
.replacingOccurrences(of: "IF, LLC", with: "ifLLC")
.replacingOccurrences(of: "WHERE, Inc.", with: "whereInc")
.replacingOccurrences(of: "Amazon.com Services, Inc.", with: "Amazon")
.replacingOccurrences(of: ", Ltd. (QTIL)", with: "")
.replacingOccurrences(of: "The ", with: "")
.replacingOccurrences(of: "A/V", with: "av")
.replacingOccurrences(of: " Incorporated", with: "")
.replacingOccurrences(of: " Corporation", with: "")
.replacingOccurrences(of: " Limited", with: "")
.replacingOccurrences(of: " Pvt.", with: "")
.replacingOccurrences(of: "GmbH & Co. KG", with: "")
.replacingOccurrences(of: "GmbH & Co KG", with: "")
.replacingOccurrences(of: "AG & Co. KGaA", with: "")
.replacingOccurrences(of: "AG & Co. KG", with: "")
.replacingOccurrences(of: "AG & Co.", with: "")
.replacingOccurrences(of: " Corp.", with: "")
.replacingOccurrences(of: " Corp", with: "")
.replacingOccurrences(of: "Co.,Ltd", with: "")
.replacingOccurrences(of: ",Co.Ltd", with: "")
.replacingOccurrences(of: "CO.,LTD.", with: "")
.replacingOccurrences(of: "Co.,", with: "")
.replacingOccurrences(of: " Sp. z o.o.", with: "")
.replacingOccurrences(of: " ASA", with: "")
.replacingOccurrences(of: " AS", with: "")
.replacingOccurrences(of: " SA", with: "")
.replacingOccurrences(of: " AB", with: "")
.replacingOccurrences(of: " BV", with: "")
.replacingOccurrences(of: " AG", with: "")
.replacingOccurrences(of: " d.o.o.", with: "")
.replacingOccurrences(of: " D.O.O.", with: "")
.replacingOccurrences(of: " Oy", with: "")
.replacingOccurrences(of: " gmbh", with: "")
.replacingOccurrences(of: " GmbH", with: "")
.replacingOccurrences(of: " B.V.", with: "")
.replacingOccurrences(of: " b.v.", with: "")
.replacingOccurrences(of: ",Inc.", with: "")
.replacingOccurrences(of: ", inc.", with: "")
.replacingOccurrences(of: " Inc", with: "")
.replacingOccurrences(of: " INC", with: "")
.replacingOccurrences(of: " LLC", with: "")
.replacingOccurrences(of: " LTD", with: "")
.replacingOccurrences(of: " Ltd", with: "")
.replacingOccurrences(of: " ltd", with: "")
.replacingOccurrences(of: " A/S", with: "")
.replacingOccurrences(of: " S.A.", with: "")
.replacingOccurrences(of: " S.L.", with: "")
.replacingOccurrences(of: " ApS", with: "")
.replacingOccurrences(of: " s.r.o.", with: "")
.replacingOccurrences(of: " Srl", with: "")
// if first letter is a number, add prefix
if let firstCharacter = name.first,
let _ = Int(String(firstCharacter)) {
name = "uuid" + name
}
return name
}
#endif
/*
BluetoothCompanyIdentifers
The "living document" can be found on the Bluetooth SIG website:
https://www.bluetooth.com/specifications/assigned-numbers/company-identifiers
*/
enum IOKitBluetoothCompanyIdentifers: UInt16
{
case EricssonTechnologyLicensing = 0
case NokiaMobilePhones = 1
case Intel = 2
case IBM = 3
case Toshiba = 4
case _3Com = 5
case Microsoft = 6
case Lucent = 7
case Motorola = 8
case InfineonTechnologiesAG = 9
case CambridgeSiliconRadio = 10
case SiliconWave = 11
case DigianswerAS = 12
case TexasInstruments = 13
case ParthusTechnologies = 14
case Broadcom = 15
case MitelSemiconductor = 16
case Widcomm = 17
case Zeevo = 18
case Atmel = 19
case MistubishiElectric = 20
case RTXTelecom = 21
case KCTechnology = 22
case Newlogic = 23
case Transilica = 24
case RohdeandSchwarz = 25
case TTPCom = 26
case SigniaTechnologies = 27
case ConexantSystems = 28
case Qualcomm = 29
case Inventel = 30
case AVMBerlin = 31
case Bandspeed = 32
case Mansella = 33
case NEC = 34
case WavePlusTechnology = 35
case Alcatel = 36
case PhilipsSemiconductor = 37
case CTechnologies = 38
case OpenInterface = 39
case RFCMicroDevices = 40
case Hitachi = 41
case SymbolTechnologies = 42
case Tenovis = 43
case MacronixInternational = 44
case GCTSemiconductor = 45
case NorwoodSystems = 46
case MewTelTechnology = 47
case STMicroelectronics = 48
case Synopsys = 49
case RedMCommunications = 50
case Commil = 51
case CATC = 52
case Eclipse = 53
case RenesasTechnology = 54
case Mobilian = 55
case Terax = 56
case IntegratedSystemSolution = 57
case MatsushitaElectricIndustrial = 58
case Gennum = 59
case ResearchInMotion = 60
case IPextreme = 61
case SystemsAndChips = 62
case BluetoothSIG = 63
case SeikoEpson = 64
case IntegratedSiliconSolution = 65
case CONWISETechnology = 66
case ParrotSA = 67
case SocketCommunications = 68
case AtherosCommunications = 69
case MediaTek = 70
case Bluegiga = 71
case MarvellTechnologyGroup = 72
case _3DSP = 73
case AccelSemiconductor = 74
case ContinentialAutomotiveSystems = 75
case Apple = 76
case StaccatoCommunications = 77
case AvagoTechnologies = 78
case APT = 79
case SiRFTechnology = 80
case TZeroTechnologies = 81
case JandM = 82
case Free2Move = 83
case _3DiJoy = 84
case Plantronics = 85
case SonyEricssonMobileCommunications = 86
case HarmonInternational = 87
case Visio = 88
case NordicSemiconductor = 89
case EMMicroElectronicMarin = 90
case RalinkTechnology = 91
case BelkinInternational = 92
case RealtekSemiconductor = 93
case StonestreetOne = 94
case Wicentric = 95
case RivieraWaves = 96
case RDAMicroelectronics = 97
case GibsonGuitars = 98
case MiCommand = 99
case BandXIInternational = 100
case HewlettPackard = 101
case _9SolutionsOy = 102
case GNNetcom = 103
case GeneralMotors = 104
case AAndDEngineering = 105
case MindTree = 106
case PolarElectroOY = 107
case BeautifulEnterprise = 108
case BriarTek = 109
case SummitDataCommunications = 110
case SoundID = 111
case Monster = 112
case ConnectBlueAB = 113
case ShangHaiSuperSmartElectronics = 114
case GroupSense = 115
case Zomm = 116
case SamsungElectronics = 117
case CreativeTechnology = 118
case LairdTechnologies = 119
case Nike = 120
case LessWire = 121
case MStarTechnologies = 122
case HanlynnTechnologies = 123
case AAndRCambridge = 124
case SeersTechnology = 125
case SportsTrackingTechnologies = 126
case AutonetMobile = 127
case DeLormePublishingCompany = 128
case WuXiVimicro = 129
case SennheiserCommunications = 130
case TimeKeepingSystems = 131
case LudusHelsinki = 132
case BlueRadios = 133
case Equinux = 134
case GarminInternational = 135
case Ecotest = 136
case GNResound = 137
case Jawbone = 138
case TopconPositioningSystems = 139
case Gimbal = 140
case ZscanSoftware = 141
case Quintic = 142
case TelitWirelessSolutions = 143
case FunaiElectric = 144
case AdvancedPANMOBILSystems = 145
case ThinkOptics = 146
case UniversalElectriconics = 147
case AirohaTechnology = 148
case NECLightning = 149
case ODMTechnology = 150
case ConnecteDevice = 151
case Zero1TV = 152
case ITechDynamicGlobalDistribution = 153
case Alpwise = 154
case JiangsuToppowerAutomotiveElectronics = 155
case Colorfy = 156
case Geoforce = 157
case Bose = 158
case SuuntoOy = 159
case KensingtonComputerProductsGroup = 160
case SRMedizinelektronik = 161
case Vertu = 162
case MetaWatch = 163
case Linak = 164
case OTLDynamics = 165
case PandaOcean = 166
case Visteon = 167
case ARPDevicesUnlimited = 168
case MagnetiMarelli = 169
case CaenRFID = 170
case IngenieurSystemgruppeZahn = 171
case GreenThrottleGames = 172
case PeterSystemtechnik = 173
case Omegawave = 174
case Cinetix = 175
case PassifSemiconductor = 176
case SarisCyclingGroup = 177
case Bekey = 178
case ClarinoxTechnologies = 179
case BDETechnology = 180
case SwirlNetworks = 181
case MesoInternational = 182
case TreLab = 183
case QualcommInnovationCenter = 184
case JohnsonControls = 185
case StarkeyLaboratories = 186
case SPowerElectronics = 187
case AceSensor = 188
case Aplix = 189
case AAMPofAmerica = 190
case StalmartTechnology = 191
case AMICCOMElectronics = 192
case ShenzhenExcelsecuDataTechnology = 193
case Geneq = 194
case Adidas = 195
case LGElectronics = 196
case OnsetComputer = 197
case SelflyBV = 198
case Quupa = 199
case GeLo = 200
case Evluma = 201
case MC10 = 202
case BinauricSE = 203
case BeatsElectronics = 204
case MicrochipTechnology = 205
case ElgatoSystems = 206
case ARCHOS = 207
case Dexcom = 208
case PolarElectroEurope = 209
case DialogSemiconductor = 210
case TaixingbangTechnology = 211
case Kawantech = 212
case AustcoCommunicationsSystems = 213
case TimexGroup = 214
case QualcommTechnologies = 215
case QualcommConnectedExperiences = 216
case VoyetraTurtleBeach = 217
case txtrGMBH = 218
case Biosentronics = 219
case ProctorAndGamble = 220
case Hosiden = 221
case Musik = 222
case MisfitWearables = 223
case Google = 224
case Danlers = 225
case Semilink = 226
case InMusicBrands = 227
case LSResearch = 228
case EdenSoftwareConsultants = 229
case Freshtemp = 230
case KSTechnologies = 231
case ACTSTechnologies = 232
case VtrackSystems = 233
case NielsenKellerman = 234
case ServerTechnology = 235
case BioResearchAssociates = 236
case JollyLogic = 237
case AboveAverageOutcomes = 238
case Bitsplitters = 239
case PayPal = 240
case WitronTechnology = 241
case MorseProject = 242
case KentDisplays = 243
case Nautilus = 244
case Smartifier = 245
case Elcometer = 246
case VSNTechnologies = 247
case AceUni = 248
case StickNFind = 249
case CrystalCode = 250
case KOUKAMM = 251
case Delphi = 252
case ValenceTech = 253
case StanleyBlackAndDecker = 254
case TypeProducts = 255
case TomTomInternational = 256
case FuGoo = 257
case Keiser = 258
case BangAndOlufson = 259
case PLUSLocationSystems = 260
case UbiquitousComputingTechnology = 261
case InnovativeYachtterSolutions = 262
case WilliamDemantHolding = 263
case InteropIdentifier = 65535
};
enum IOKitBluetoothGAPAppearance: UInt16 {
case Unknown = 0
case GenericPhone = 64
case GenericComputer = 128
case GenericWatch = 192
case GenericClock = 256
case GenericDisplay = 320
case GenericRemoteControl = 384
case GenericEyeGlasses = 448
case GenericTag = 512
case GenericKeyring = 576
case GenericMediaPlayer = 640
case GenericBarcodeScanner = 704
case GenericThermometer = 768
case GenericHeartrateSensor = 832
case GenericBloodPressure = 896
case GenericHumanInterfaceDevice = 960
case HumanInterfaceDeviceKeyboard = 961
case HumanInterfaceDeviceMouse = 962
case HumanInterfaceDeviceJoystick = 963
case HumanInterfaceDeviceGamepad = 964
case HumanInterfaceDeviceDigitizerTablet = 965
case HumanInterfaceDeviceCardReader = 966
case HumanInterfaceDeviceDigitalPen = 967
case HumanInterfaceDeviceBarcodeScanner = 968
case GenericGlucoseMeter = 1024
case GenericRunningWalkingSensor = 1088
case GenericCycling = 1152
}
| 43.39823 | 148 | 0.432481 |
acf8dad67db4f4f590876c6d27e7305cc0394c4e | 4,703 | //
// AGMasterViewController.swift
// AppGroupsMaster
//
// Created by wwwins on 2014/10/30.
// Copyright (c) 2014年 isobar. All rights reserved.
//
import UIKit
class AGMasterViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
@IBOutlet weak var textFieldForInput: UITextField!
@IBOutlet weak var buttonForShow: UIButton!
@IBOutlet weak var buttonForSave: UIButton!
@IBOutlet weak var textViewForLog: UITextView!
@IBOutlet weak var imageView: UIImageView!
struct Constants {
static let AppGroupName = "group.com.isobar.AppGroupsDemo"
static let FileName = "image01.png"
static let FileNameForPicker = "image02.png"
}
var imagePickerController:UIImagePickerController!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK:- Image picker controller
func isCameraAvailable() -> Bool {
if (UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)) {
return true
}
return false
}
func initImagePickerController() {
if isCameraAvailable() {
if ((imagePickerController) == nil) {
imagePickerController = UIImagePickerController()
imagePickerController.delegate = self
imagePickerController.allowsEditing = false
imagePickerController.sourceType = UIImagePickerControllerSourceType.Camera
// imagePickerController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
imagePickerController.mediaTypes = UIImagePickerController.availableMediaTypesForSourceType(UIImagePickerControllerSourceType.Camera)!
}
}
}
// MARK:- Delegate
func imagePickerController(picker: UIImagePickerController!, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) {
imageView.image = image
image.imageOrientation
saveShareFile(Constants.FileNameForPicker, image: fixOrientation(image))
self.dismissViewControllerAnimated(true, completion: nil)
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
print("Cancel!!")
}
// MARK:- Fix image Orientation
func fixOrientation(image:UIImage) -> UIImage {
if (image.imageOrientation == UIImageOrientation.Up) {
return image;
}
UIGraphicsBeginImageContextWithOptions(image.size, false, image.scale)
image.drawInRect(CGRectMake(0, 0, image.size.width, image.size.height))
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
// MARK:- Save a shared file
func saveShareFile(fileName:NSString, image:UIImage) -> Bool {
var storeURL = NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier(Constants.AppGroupName)
storeURL = storeURL?.URLByAppendingPathComponent(fileName as String)
print("storeURL:\(storeURL)")
let imageData = UIImagePNGRepresentation(image)
let result = imageData.writeToURL(storeURL!, atomically: true)
return result
}
// MARK:- Snapshot
func snapshot(view: UIView) -> UIImage {
UIGraphicsBeginImageContextWithOptions(view.bounds.size, true, 0)
view.drawViewHierarchyInRect(view.bounds, afterScreenUpdates: true)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
// MARK:- Actions
@IBAction func saveClicked(sender: AnyObject) {
print("save clicked: \(textFieldForInput.text)")
var myShareDefaults = NSUserDefaults(suiteName: Constants.AppGroupName)
if let passData = textFieldForInput.text {
myShareDefaults?.setValue(passData, forKey: "PassData")
textViewForLog.text = textViewForLog.text + "Add:" + textFieldForInput.text + "\n"
myShareDefaults?.synchronize()
}
if (saveShareFile(Constants.FileName, image: snapshot(self.view))) {
print("Success")
}
else {
print("Failure")
}
}
@IBAction func showClicked(sender: AnyObject) {
let myShareDefaults = NSUserDefaults(suiteName: Constants.AppGroupName)
if let stringInput = myShareDefaults?.stringForKey("PassData") {
textViewForLog.text = textViewForLog.text + "Result:" + stringInput + "\n"
}
}
@IBAction func captureClicked(sender: AnyObject) {
print("Capture")
initImagePickerController()
self.presentViewController(imagePickerController, animated: true, completion: {
print("Completion")
})
}
}
| 31.777027 | 142 | 0.725494 |
fb0199cba8d2ed342f03f5c2fd5cec529dc5ea53 | 5,440 | //
// Copyright (C) 2005-2020 Alfresco Software Limited.
//
// This file is part of the Alfresco Content Mobile iOS App.
//
// 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 Foundation
import UIKit
import AlfrescoAuth
import AlfrescoContent
class MyLibrariesViewModel: PageFetchingViewModel, ListViewModelProtocol {
var listRequest: SearchRequest?
var coordinatorServices: CoordinatorServices?
var supportedNodeTypes: [NodeType] = []
// MARK: - Init
required init(with coordinatorServices: CoordinatorServices?, listRequest: SearchRequest?) {
self.coordinatorServices = coordinatorServices
self.listRequest = listRequest
}
// MARK: - ListViewModelProtocol
func isEmpty() -> Bool {
return results.isEmpty
}
func emptyList() -> EmptyListProtocol {
return EmptyFolder()
}
func numberOfSections() -> Int {
return (results.isEmpty) ? 0 : 1
}
func numberOfItems(in section: Int) -> Int {
return results.count
}
func refreshList() {
refreshedList = true
currentPage = 1
request(with: nil)
}
func listNode(for indexPath: IndexPath) -> ListNode {
return results[indexPath.row]
}
func shouldDisplayListLoadingIndicator() -> Bool {
return self.shouldDisplayNextPageLoadingIndicator
}
func shouldDisplayNodePath() -> Bool {
return false
}
func performListAction() {
// Do nothing
}
// MARK: - PageFetchingViewModel
override func fetchItems(with requestPagination: RequestPagination, userInfo: Any?, completionHandler: @escaping PagedResponseCompletionHandler) {
request(with: requestPagination)
}
override func handlePage(results: [ListNode], pagination: Pagination?, error: Error?) {
updateResults(results: results, pagination: pagination, error: error)
}
override func updatedResults(results: [ListNode], pagination: Pagination) {
pageUpdatingDelegate?.didUpdateList(error: nil,
pagination: pagination)
}
// MARK: - Public methods
func request(with paginationRequest: RequestPagination?) {
pageFetchingGroup.enter()
let accountService = coordinatorServices?.accountService
accountService?.getSessionForCurrentAccount(completionHandler: { [weak self] authenticationProvider in
guard let sSelf = self else { return }
AlfrescoContentAPI.customHeaders = authenticationProvider.authorizationHeader()
let skipCount = paginationRequest?.skipCount
let maxItems = paginationRequest?.maxItems ?? APIConstants.pageSize
SitesAPI.listSiteMembershipsForPerson(personId: APIConstants.me,
skipCount: skipCount,
maxItems: maxItems,
orderBy: nil,
relations: nil,
fields: nil,
_where: nil) { (result, error) in
var listNodes: [ListNode] = []
if let entries = result?.list.entries {
listNodes = SitesNodeMapper.map(entries)
} else {
if let error = error {
AlfrescoLog.error(error)
}
}
let paginatedResponse = PaginatedResponse(results: listNodes,
error: error,
requestPagination: paginationRequest,
responsePagination: result?.list.pagination)
sSelf.handlePaginatedResponse(response: paginatedResponse)
}
})
}
}
// MARK: - Event observable
extension MyLibrariesViewModel: EventObservable {
func handle(event: BaseNodeEvent, on queue: EventQueueType) {
if let publishedEvent = event as? FavouriteEvent {
handleFavorite(event: publishedEvent)
} else if let publishedEvent = event as? MoveEvent {
handleMove(event: publishedEvent)
}
}
private func handleFavorite(event: FavouriteEvent) {
let node = event.node
for listNode in results where listNode == node {
listNode.favorite = node.favorite
}
}
private func handleMove(event: MoveEvent) {
let node = event.node
switch event.eventType {
case .moveToTrash:
if let indexOfMovedNode = results.firstIndex(of: node) {
results.remove(at: indexOfMovedNode)
}
case .restore:
refreshList()
default: break
}
}
}
| 34.43038 | 150 | 0.596691 |
89a482d0f97cc1b266d4f0590470a93f5e453c14 | 2,945 | //
// UndoReducer.swift
// ReSwiftUndo
//
// Created by Guillermo Peralta Scura on 8/4/17.
// Copyright © 2017 voluntadpear. All rights reserved.
//
import Foundation
import ReSwift
public struct UndoableState<T>: StateType {
public var past: [T]
public var present: T
public var future: [T]
public init(past: [T], present: T, future: [T]) {
self.past = past
self.present = present
self.future = future
}
}
public typealias UndoableFilter<T> = (Action, T, UndoableState<T>) -> Bool
public func undoable<T: Equatable>(reducer: @escaping Reducer<T>,
filter: UndoableFilter<T>? = nil) -> Reducer<UndoableState<T>> {
let initialState = UndoableState<T>(past: [], present: reducer(DummyAction(), nil), future: [])
return { (action: Action, state: UndoableState<T>?) in
var state = state ?? initialState
switch action {
case _ as Undo:
if let previous = state.past.first {
let previousArrays = Array(state.past.dropFirst())
state.past = previousArrays
let present = state.present
state.present = previous
state.future = [present] + state.future
}
case _ as Redo:
if let next = state.future.first {
let newFutureArray = Array(state.future.dropFirst())
state.past = [state.present] + state.past
state.present = next
state.future = newFutureArray
}
case _ as UndoAll:
if let oldest = state.past.last {
let past = state.past
let previousArrays = Array(state.past.dropLast())
state.past = []
let present = state.present
state.present = oldest
state.future = previousArrays + [present] + state.future
}
case _ as ClearPast:
state.past = []
case _ as ClearFuture:
state.future = []
default:
let previousArray = [state.present] + state.past
let newPresent = reducer(action, state.present)
if newPresent == state.present {
//Don't handle this action
return state
}
if(filter == nil || (filter != nil && filter!(action, newPresent, state))) {
// If the action wasn't filtered, insert normally
state.past = previousArray
state.future = []
} // else do nothing
state.present = newPresent
}
return state
}
}
struct DummyAction: Action {}
public struct Undo: Action { public init() {} }
public struct Redo: Action { public init() {} }
public struct UndoAll: Action { public init() {} }
public struct ClearPast: Action { public init() {} }
public struct ClearFuture: Action { public init() {} }
| 34.244186 | 99 | 0.558574 |
201e3e3c2baf71a08a96463a118a6269bd5d36a6 | 1,196 | //
// CityHourlyView.swift
// Weather
//
// Created by Lunabee on 13/06/2019.
// Copyright © 2019 Snopia. All rights reserved.
//
import SwiftUI
struct CityHourlyView : View {
@ObservedObject var city: City
private let rowHeight: CGFloat = 110
var body: some View {
ScrollView(.horizontal, showsIndicators: false) {
HStack(spacing: 16) {
ForEach(city.weather?.hours.list ?? []) { hour in
VStack(spacing: 16) {
Text(hour.time.formattedHour)
.font(.footnote)
hour.icon.image
.font(.body)
Text(hour.temperature.formattedTemperature)
.font(.headline)
}.frame(width: 88)
}
}
.padding([.trailing, .leading])
}
.listRowInsets(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0))
.padding([.top, .bottom])
}
}
//#if DEBUG
//struct CityHourlyView_Previews : PreviewProvider {
// static var previews: some View {
// CityHourlyView()
// }
//}
//#endif
| 26 | 78 | 0.503344 |
fe9c3a934b10ff373be169dc63ccf5f3871acb4e | 21,512 | import UIKit
protocol PagingControllerSizeDelegate: class {
func width(for: PagingItem, isSelected: Bool) -> CGFloat
}
final class PagingController: NSObject {
weak var dataSource: PagingMenuDataSource?
weak var sizeDelegate: PagingControllerSizeDelegate?
weak var delegate: PagingMenuDelegate?
weak var collectionView: CollectionView! {
didSet {
configureCollectionView()
}
}
weak var collectionViewLayout: CollectionViewLayout! {
didSet {
configureCollectionViewLayout()
}
}
var options: PagingOptions {
didSet {
optionsChanged(oldValue: oldValue)
}
}
private(set) var state: PagingState {
didSet {
collectionViewLayout.state = state
}
}
private(set) var visibleItems: PagingItems {
didSet {
collectionViewLayout.visibleItems = visibleItems
}
}
private(set) var sizeCache: PagingSizeCache {
didSet {
collectionViewLayout.sizeCache = sizeCache
}
}
private var swipeGestureRecognizerLeft: UISwipeGestureRecognizer?
private var swipeGestureRecognizerRight: UISwipeGestureRecognizer?
init(options: PagingOptions) {
self.options = options
self.sizeCache = PagingSizeCache(options: options)
self.visibleItems = PagingItems(items: [])
self.state = .empty
}
// MARK: Public
func select(indexPath: IndexPath, animated: Bool) {
let pagingItem = visibleItems.pagingItem(for: indexPath)
select(pagingItem: pagingItem, animated: animated)
}
func select(pagingItem: PagingItem, animated: Bool) {
if collectionView.superview == nil || collectionView.window == nil {
state = .selected(pagingItem: pagingItem)
return
}
switch state {
case .empty:
state = .selected(pagingItem: pagingItem)
reloadItems(around: pagingItem)
delegate?.selectContent(
pagingItem: pagingItem,
direction: .none,
animated: false
)
collectionView.selectItem(
at: visibleItems.indexPath(for: pagingItem),
animated: false,
scrollPosition: options.scrollPosition
)
case .selected:
if let currentPagingItem = state.currentPagingItem {
if pagingItem.isEqual(to: currentPagingItem) == false {
if animated {
appendItemsIfNeeded(upcomingPagingItem: pagingItem)
let transition = calculateTransition(
from: currentPagingItem,
to: pagingItem
)
state = .scrolling(
pagingItem: currentPagingItem,
upcomingPagingItem: pagingItem,
progress: 0,
initialContentOffset: transition.contentOffset,
distance: transition.distance
)
let direction = visibleItems.direction(
from: currentPagingItem,
to: pagingItem
)
delegate?.selectContent(
pagingItem: pagingItem,
direction: direction,
animated: animated
)
} else {
state = .selected(pagingItem: pagingItem)
reloadItems(around: pagingItem)
delegate?.selectContent(
pagingItem: pagingItem,
direction: .none,
animated: false
)
collectionView.selectItem(
at: visibleItems.indexPath(for: pagingItem),
animated: false,
scrollPosition: options.scrollPosition
)
}
}
}
default:
break
}
}
func contentScrolled(progress: CGFloat) {
switch state {
case let .selected(pagingItem):
var upcomingItem: PagingItem?
if progress > 0 {
upcomingItem = dataSource?.pagingItemAfter(pagingItem: pagingItem)
} else if progress < 0 {
upcomingItem = dataSource?.pagingItemBefore(pagingItem: pagingItem)
} else {
return
}
appendItemsIfNeeded(upcomingPagingItem: upcomingItem)
let transition = calculateTransition(from: pagingItem, to: upcomingItem)
updateScrollingState(
pagingItem: pagingItem,
upcomingPagingItem: upcomingItem,
initialContentOffset: transition.contentOffset,
distance: transition.distance,
progress: progress
)
case let .scrolling(pagingItem, upcomingPagingItem, oldProgress, initialContentOffset, distance):
if oldProgress < 0 && progress > 0 {
state = .selected(pagingItem: pagingItem)
} else if oldProgress > 0 && progress < 0 {
state = .selected(pagingItem: pagingItem)
} else if progress == 0 {
state = .selected(pagingItem: pagingItem)
} else {
updateScrollingState(
pagingItem: pagingItem,
upcomingPagingItem: upcomingPagingItem,
initialContentOffset: initialContentOffset,
distance: distance,
progress: progress
)
}
default:
break
}
}
func contentFinishedScrolling() {
guard case let .scrolling(pagingItem, upcomingPagingItem, _, _, _) = state else { return }
// If a transition finishes scrolling, but the upcoming paging
// item is nil it means that the user scrolled away from one of
// the items at the very edge. In this case, we don't want to
// fire a .finishScrolling event as this will select the current
// paging item, causing it to jump to that item even if it's
// scrolled out of view. We still need to fire an event that
// will reset the state to .selected.
if let upcomingPagingItem = upcomingPagingItem {
state = .selected(pagingItem: upcomingPagingItem)
// We only want to select the current paging item
// if the user is not scrolling the collection view.
if collectionView.isDragging == false {
reloadItems(around: upcomingPagingItem)
collectionView.selectItem(
at: visibleItems.indexPath(for: upcomingPagingItem),
animated: options.menuTransition == .animateAfter,
scrollPosition: options.scrollPosition
)
}
} else {
state = .selected(pagingItem: pagingItem)
}
}
func transitionSize() {
switch state {
case let .scrolling(pagingItem, _, _, _, _):
sizeCache.clear()
state = .selected(pagingItem: pagingItem)
reloadItems(around: pagingItem)
collectionView.selectItem(
at: visibleItems.indexPath(for: pagingItem),
animated: options.menuTransition == .animateAfter,
scrollPosition: options.scrollPosition
)
default:
if let pagingItem = state.currentPagingItem {
sizeCache.clear()
reloadItems(around: pagingItem)
collectionView.selectItem(
at: visibleItems.indexPath(for: pagingItem),
animated: options.menuTransition == .animateAfter,
scrollPosition: options.scrollPosition
)
}
}
}
func removeAll() {
state = .empty
sizeCache.clear()
visibleItems = PagingItems(items: [])
collectionView.reloadData()
delegate?.removeContent()
}
func viewAppeared() {
switch state {
case let .selected(pagingItem), let .scrolling(_, pagingItem?, _, _, _):
state = .selected(pagingItem: pagingItem)
reloadItems(around: pagingItem)
delegate?.selectContent(
pagingItem: pagingItem,
direction: .none,
animated: false
)
collectionView.selectItem(
at: visibleItems.indexPath(for: pagingItem),
animated: false,
scrollPosition: options.scrollPosition
)
default:
break
}
}
func reloadData(around pagingItem: PagingItem) {
reloadMenu(around: pagingItem)
delegate?.removeContent()
delegate?.selectContent(
pagingItem: pagingItem,
direction: .none,
animated: false
)
// Reloading the data triggers the didFinishScrollingFrom delegate
// to be called which in turn means the wrong item will be selected.
// For now, we just fix this by selecting the correct item manually.
state = .selected(pagingItem: pagingItem)
collectionViewLayout.invalidateLayout()
}
func reloadMenu(around pagingItem: PagingItem) {
sizeCache.clear()
let toItems = generateItems(around: pagingItem)
visibleItems = PagingItems(
items: toItems,
hasItemsBefore: hasItemBefore(pagingItem: toItems.first),
hasItemsAfter: hasItemAfter(pagingItem: toItems.last)
)
state = .selected(pagingItem: pagingItem)
collectionViewLayout.invalidateLayout()
collectionView.reloadData()
configureSizeCache(for: pagingItem)
}
func menuScrolled() {
// If we don't have any visible items there is no point in
// checking if we're near an edge. This seems to be empty quite
// often when scrolling very fast.
if collectionView.indexPathsForVisibleItems.isEmpty == true {
return
}
let contentInsets = collectionViewLayout.contentInsets
if collectionView.near(edge: .left, clearance: contentInsets.left) {
if let firstPagingItem = visibleItems.items.first {
if visibleItems.hasItemsBefore {
reloadItems(around: firstPagingItem)
}
}
} else if collectionView.near(edge: .right, clearance: contentInsets.right) {
if let lastPagingItem = visibleItems.items.last {
if visibleItems.hasItemsAfter {
reloadItems(around: lastPagingItem)
}
}
}
}
// MARK: Private
private func optionsChanged(oldValue: PagingOptions) {
if options.menuInteraction != oldValue.menuInteraction {
configureMenuInteraction()
}
sizeCache.options = options
collectionViewLayout.invalidateLayout()
}
private func configureCollectionViewLayout() {
collectionViewLayout.state = state
collectionViewLayout.visibleItems = visibleItems
collectionViewLayout.sizeCache = sizeCache
}
private func configureCollectionView() {
collectionView.isScrollEnabled = false
collectionView.alwaysBounceHorizontal = false
collectionView.showsHorizontalScrollIndicator = false
collectionView.dataSource = self
if #available(iOS 11.0, *) {
collectionView.contentInsetAdjustmentBehavior = .never
}
configureMenuInteraction()
}
private func configureMenuInteraction() {
if let swipeGestureRecognizerLeft = swipeGestureRecognizerLeft {
collectionView.removeGestureRecognizer(swipeGestureRecognizerLeft)
}
if let swipeGestureRecognizerRight = swipeGestureRecognizerRight {
collectionView.removeGestureRecognizer(swipeGestureRecognizerRight)
}
switch (options.menuInteraction) {
case .scrolling:
collectionView.isScrollEnabled = true
collectionView.alwaysBounceHorizontal = true
case .swipe:
setupGestureRecognizers()
case .none:
break
}
}
private func setupGestureRecognizers() {
let swipeGestureRecognizerLeft = UISwipeGestureRecognizer(
target: self,
action: #selector(handleSwipeGestureRecognizer)
)
let swipeGestureRecognizerRight = UISwipeGestureRecognizer(
target: self,
action: #selector(handleSwipeGestureRecognizer)
)
swipeGestureRecognizerLeft.direction = .left
swipeGestureRecognizerRight.direction = .right
collectionView.addGestureRecognizer(swipeGestureRecognizerLeft)
collectionView.addGestureRecognizer(swipeGestureRecognizerRight)
self.swipeGestureRecognizerLeft = swipeGestureRecognizerLeft
self.swipeGestureRecognizerRight = swipeGestureRecognizerRight
}
@objc private dynamic func handleSwipeGestureRecognizer(_ recognizer: UISwipeGestureRecognizer) {
guard let currentPagingItem = state.currentPagingItem else { return }
var upcomingPagingItem: PagingItem? = nil
if recognizer.direction.contains(.left) {
upcomingPagingItem = dataSource?.pagingItemAfter(pagingItem: currentPagingItem)
} else if recognizer.direction.contains(.right) {
upcomingPagingItem = dataSource?.pagingItemBefore(pagingItem: currentPagingItem)
}
if let pagingItem = upcomingPagingItem {
select(pagingItem: pagingItem, animated: false)
}
}
private func updateScrollingState(
pagingItem: PagingItem,
upcomingPagingItem: PagingItem?,
initialContentOffset: CGPoint,
distance: CGFloat,
progress: CGFloat
) {
state = .scrolling(
pagingItem: pagingItem,
upcomingPagingItem: upcomingPagingItem,
progress: progress,
initialContentOffset: initialContentOffset,
distance: distance
)
if options.menuTransition == .scrollAlongside {
let invalidationContext = PagingInvalidationContext()
// We don't want to update the content offset if there is no
// upcoming item to scroll to. We still need to invalidate the
// layout in order to update the layout attributes for the
// decoration views. We need to use setContentOffset with no
// animation in order to stop any ongoing scroll.
if upcomingPagingItem != nil {
if collectionView.contentSize.width >= collectionView.bounds.width && state.progress != 0 {
let contentOffset = CGPoint(
x: initialContentOffset.x + (distance * abs(progress)),
y: initialContentOffset.y
)
collectionView.setContentOffset(contentOffset, animated: false)
}
if sizeCache.implementsSizeDelegate {
invalidationContext.invalidateSizes = true
}
}
collectionViewLayout.invalidateLayout(with: invalidationContext)
}
}
private func calculateTransition(
from pagingItem: PagingItem,
to upcomingPagingItem: PagingItem?
) -> PagingTransition {
guard let upcomingPagingItem = upcomingPagingItem else {
return PagingTransition(contentOffset: .zero, distance: 0)
}
let distance = PagingDistance(
view: collectionView,
currentPagingItem: pagingItem,
upcomingPagingItem: upcomingPagingItem,
visibleItems: visibleItems,
sizeCache: sizeCache,
selectedScrollPosition: options.selectedScrollPosition,
layoutAttributes: collectionViewLayout.layoutAttributes,
navigationOrientation: options.contentNavigationOrientation
)
return PagingTransition(
contentOffset: collectionView.contentOffset,
distance: distance?.calculate() ?? 0
)
}
/// If the upcoming item is outside the currently visible
/// items we need to append the items that are around the
/// upcoming item so we can animate the transition.
private func appendItemsIfNeeded(upcomingPagingItem: PagingItem?) {
if let upcomingPagingItem = upcomingPagingItem {
if visibleItems.contains(upcomingPagingItem) == false {
reloadItems(around: upcomingPagingItem, keepExisting: true)
}
}
}
private func reloadItems(around pagingItem: PagingItem, keepExisting: Bool = false) {
var toItems = generateItems(around: pagingItem)
if keepExisting {
toItems = visibleItems.union(toItems)
}
let oldLayoutAttributes = collectionViewLayout.layoutAttributes
let oldContentOffset = collectionView.contentOffset
let oldVisibleItems = visibleItems
configureSizeCache(for: pagingItem)
visibleItems = PagingItems(
items: toItems,
hasItemsBefore: hasItemBefore(pagingItem: toItems.first),
hasItemsAfter: hasItemAfter(pagingItem: toItems.last)
)
collectionView.reloadData()
collectionViewLayout.prepare()
// After reloading the data the content offset is going to be
// reset. We need to diff which items where added/removed and
// update the content offset so it looks it is the same as before
// reloading. This gives the perception of a smooth scroll.
let newLayoutAttributes = collectionViewLayout.layoutAttributes
var offset: CGFloat = 0
let diff = PagingDiff(from: oldVisibleItems, to: visibleItems)
for indexPath in diff.removed() {
offset += oldLayoutAttributes[indexPath]?.bounds.width ?? 0
offset += options.menuItemSpacing
}
for indexPath in diff.added() {
offset -= newLayoutAttributes[indexPath]?.bounds.width ?? 0
offset -= options.menuItemSpacing
}
collectionView.contentOffset = CGPoint(
x: oldContentOffset.x - offset,
y: oldContentOffset.y
)
// We need to perform layout here, if not the collection view
// seems to get in a weird state.
collectionView.layoutIfNeeded()
// The content offset and distance between items can change while a
// transition is in progress meaning the current transition will be
// wrong. For instance, when hitting the edge of the collection view
// while transitioning we need to reload all the paging items and
// update the transition data.
if case let .scrolling(pagingItem, upcomingPagingItem, progress, _, distance) = state {
let transition = calculateTransition(
from: pagingItem,
to: upcomingPagingItem
)
let contentOffset = collectionView.contentOffset
let newContentOffset = CGPoint(
x: contentOffset.x - (distance - transition.distance),
y: contentOffset.y
)
state = .scrolling(
pagingItem: pagingItem,
upcomingPagingItem: upcomingPagingItem,
progress: progress,
initialContentOffset: newContentOffset,
distance: distance
)
}
}
private func generateItems(around pagingItem: PagingItem) -> [PagingItem] {
var items: [PagingItem] = [pagingItem]
var previousItem: PagingItem = pagingItem
var nextItem: PagingItem = pagingItem
let menuWidth = collectionView.bounds.width
// Add as many items as we can before the current paging item to
// fill up the same width as the bounds.
var widthBefore: CGFloat = menuWidth
while widthBefore > 0 {
if let item = dataSource?.pagingItemBefore(pagingItem: previousItem) {
widthBefore -= itemWidth(for: item)
widthBefore -= options.menuItemSpacing
previousItem = item
items.insert(item, at: 0)
} else {
break
}
}
// When filling up the items after the current item we need to
// include any remaining space left before the current item.
var widthAfter: CGFloat = menuWidth + widthBefore
while widthAfter > 0 {
if let item = dataSource?.pagingItemAfter(pagingItem: nextItem) {
widthAfter -= itemWidth(for: item)
widthAfter -= options.menuItemSpacing
nextItem = item
items.append(item)
} else {
break
}
}
// Make sure we add even more items if there is any remaining
// space available after filling items items after the current.
var remainingWidth = widthAfter
while remainingWidth > 0 {
if let item = dataSource?.pagingItemBefore(pagingItem: previousItem) {
remainingWidth -= itemWidth(for: item)
remainingWidth -= options.menuItemSpacing
previousItem = item
items.insert(item, at: 0)
} else {
break
}
}
return items
}
private func itemWidth(for pagingItem: PagingItem) -> CGFloat {
guard let currentPagingItem = state.currentPagingItem else { return options.estimatedItemWidth }
if currentPagingItem.isEqual(to: pagingItem) {
return sizeCache.itemWidthSelected(for: pagingItem)
} else {
return sizeCache.itemSize(for: pagingItem)
}
}
private func configureSizeCache(for pagingItem: PagingItem) {
if sizeDelegate != nil {
sizeCache.implementsSizeDelegate = true
sizeCache.sizeForPagingItem = { [weak self] item, selected in
return self?.sizeDelegate?.width(for: item, isSelected: selected)
}
}
}
private func hasItemBefore(pagingItem: PagingItem?) -> Bool {
guard let item = pagingItem else { return false }
return dataSource?.pagingItemBefore(pagingItem: item) != nil
}
private func hasItemAfter(pagingItem: PagingItem?) -> Bool {
guard let item = pagingItem else { return false }
return dataSource?.pagingItemAfter(pagingItem: item) != nil
}
}
extension PagingController: UICollectionViewDataSource {
// MARK: UICollectionViewDataSource
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let pagingItem = visibleItems.items[indexPath.item]
let cell = collectionView.dequeueReusableCell(
withReuseIdentifier: String(describing: type(of: pagingItem)),
for: indexPath) as! PagingCell
var selected: Bool = false
if let currentPagingItem = state.currentPagingItem {
selected = currentPagingItem.isEqual(to: pagingItem)
}
cell.setPagingItem(pagingItem, selected: selected, options: options)
return cell
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return visibleItems.items.count
}
}
| 31.681885 | 119 | 0.667767 |
7a18f77600fe36d7d8fc75411c98198422f953d4 | 1,237 | //
// UIImageView+Hook.swift
// SwiftExpand
//
// Created by Bin Shang on 2019/1/2.
// Copyright © 2021 Bin Shang. All rights reserved.
//
import UIKit
@objc extension UIImageView{
override public class func initializeMethod() {
super.initializeMethod()
if self != UIImageView.self {
return
}
let onceToken = "Hook_\(NSStringFromClass(classForCoder()))"
DispatchQueue.once(token: onceToken) {
let oriSel = #selector(setter: self.tintColor)
let repSel = #selector(self.hook_tintColor(_:))
hookInstanceMethod(of: oriSel, with: repSel)
}
}
private func hook_tintColor(_ color: UIColor!) {
//需要注入的代码写在此处
hook_tintColor(color)
// let obj1:AnyClass = NSClassFromString(kUITabBarButton)!
// if self.superview?.isKind(of: obj1) == true {
// DDLog(self.superview as Any,obj1)
// return
// }
// if self.image != nil {
// if self.image?.renderingMode != UIImage.RenderingMode.alwaysTemplate {
// self.image = self.image!.withRenderingMode(.alwaysTemplate)
// }
// }
}
}
| 27.488889 | 84 | 0.567502 |
8f4bf38ba1071d8b39e9769535a91e0017913bd2 | 4,546 | //: [Previous](@previous)
import Foundation
import UIKit
struct Run {
let id: String
let startTime: Date
let endTime: Date
let distance: Float
let onRunningTrack: Bool
}
struct Cycle{
enum CycleType{
case regular
case mountainBike
case racetrack
}
let id: String
let startTime: Date
let endTime: Date
let distance: Float
let inclince: Int
let type: CycleType
}
struct Pushups {
let id: String
let repetitions:[Int]
let date:Date
}
enum Workout{
case run(Run)
case cycle(Cycle)
case pushups(Pushups)
}
let pushup1 = Pushups(id: "121", repetitions: [22,20,21], date: Date())
let workout = Workout.pushups(pushup1)
switch workout{
case .run(let run):
print("Run \(run)")
case .cycle(let cycle):
print("Cycle \(cycle)")
case .pushups(let pushups):
print("Pushups \(pushups)")
}
print(Date())
let arr: [Any] = [Date(), "string_#1", "string_#2", 2021]
for element in arr{
switch element{
case let stringValue as String: print("received a string \(stringValue)")
case let intValue as Int: print("received an Int: \(intValue)")
case let dateValue as Date: print("recived date: \(dateValue)")
default: print("Unknown type")
}
}
print(arr)
//Compile-time polymorphism
let now = Date()
let hourFromNow = Date(timeIntervalSinceNow: 3600)
enum DateType{
case singleDate(Date)
case dateRange(Range<Date>)
case year(Int)
}
let dates:[DateType] = [
DateType.singleDate(now),
DateType.dateRange(now..<hourFromNow)
]
for dateType in dates{
switch dateType{
case .singleDate(let date): print("Date is \(date)")
case .dateRange(let range): print("Range is \(range)")
case .year(let year): print("Year is \(year)")
}
}
//Enum
//algebraic data types - sum types - or types
//enum can only be one thing at once
//mutually exclusive properties
struct MessageStruct {
let userId: String
let contents: String?
let date: Date
let hasJoined: Bool
let hasLeft: Bool
let isBeingDrafted: Bool
let isSendingBalloons: Bool
}
let joinMessage = MessageStruct(userId: "1",
contents: nil,
date: Date(),
hasJoined: true, // We set the joined boolean
hasLeft: false,
isBeingDrafted: false,
isSendingBalloons: false)
let textMessage = MessageStruct(userId: "2",
contents: "Hey everyone!", // We pass a message
date: Date(),
hasJoined: false,
hasLeft: false,
isBeingDrafted: false,
isSendingBalloons: false)
//associated values
enum Message {
case text(userId:String, contents:String, date:Date)
case draft(userId:String, date:Date)
case join(userId:String, date:Date)
case leave(userId:String, date:Date)
case balloon(userId:String, date:Date)
}
let textMessageEnum = Message.text(userId: "2", contents: "Bonjour!", date: Date())
let joinMessageEnum = Message.join(userId: "2", date: Date())
func logMessage(message: Message){
switch message{
case let .text(userId: id, contents: contents, date: date):
print("[\(date)] User \(id) sends message: \(contents)")
case let .draft(userId: id, date: date):
print("[\(date)] User \(id) is drafting a message")
case let .join(userId: id, date: date):
print("[\(date)] User \(id) has joined the chatroom")
case let .leave(userId: id, date: date):
print("[\(date)] User \(id) has left the chatroom")
case let .balloon(userId: id, date: date):
print("[\(date)] User \(id) is sending balloons")
}
}
logMessage(message: textMessageEnum)
logMessage(message: joinMessageEnum)
if case let Message.text(userId: _, contents: contents, date: _) = textMessageEnum{
print("Received: \(contents)")
}
enum ImageType:String{
case jpg
case bmp
case gif
init?(rawValue: String) {
switch rawValue.lowercased(){
case "jpg", "jpeg": self = .jpg
case "bmp", "bitmap": self = .bmp
case "gif", "gifv": self = .gif
default: return nil
}
}
}
//: [Next](@next)
| 12.420765 | 83 | 0.58073 |
d93d34004d6b608ccd4974a487154b24fac5c72b | 292 | //
// SampleLoggerImplementation.swift
// MyFirstFramework
//
// Created by Ganesh Manickam on 15/10/20.
// Copyright © 2020 Ganesh Manickam. All rights reserved.
//
import Foundation
class SampleLoggerImplementation: NSObject {
override init() {
super.init()
}
}
| 16.222222 | 58 | 0.678082 |
4bf6003e8f7a5059c6283f378cc837b8387338c2 | 4,634 | import Foundation
import ArgumentParser
import Cocodol
import CodeGen
import LLVM
/// The compiler driver.
struct Cocodoc: ParsableCommand {
/// The default library search paths.
static var librarySearchPaths = ["/usr/lib", "/usr/local/lib", "/opt/local/lib"]
@Argument(help: "The source program.", transform: URL.init(fileURLWithPath:))
var inputFile: URL
@Flag(name: [.customShort("O"), .long], help: "Compile with optimizations.")
var optimize = false
@Option(name: [.short, .customLong("output")],
help: "Write the output to <output>.")
var outputFile: String?
@Option(name: [.customShort("L"), .customLong("lib")],
help: ArgumentHelp("Add a custom library search path.", valueName: "path"))
var customLibrarySearchPath: String?
@Option(name: [.customLong("clang")], help: "The path to clang.")
var clangPath: String = {
(try? exec("/usr/bin/which", args: ["clang"])) ?? "/usr/bin/clang"
}()
@Flag(help: "Print the program as it has been parsed without compiling it.")
var unparse = false
@Flag(help: "Evaluate the program without compiling it.")
var eval = false
@Flag(help: "Emits the LLVM IR of the program.")
var emitIR = false
@Flag(help: "Emits an assembly file.")
var emitAssembly = false
@Flag(help: "Emits an object file.")
var emitObject = false
/// The output path the driver's product.
var productFile: URL {
if let path = outputFile {
return URL(fileURLWithPath: path)
} else {
let cwd = FileManager.default.currentDirectoryPath
return URL(fileURLWithPath: cwd)
.appendingPathComponent(inputFile.deletingPathExtension().lastPathComponent)
}
}
mutating func run() throws {
// Open and read the input file.
let source = try String(contentsOf: inputFile)
// Parse the program.
let context = Context(source: source)
let parser = Parser(in: context)
let decls = parser.parse()
// Unparse the program, if requested to.
if unparse {
for decl in decls {
print(decl.unparse())
}
return
}
// Evaluate the program, if requested to.
if eval {
let vm = Interpreter(in: context)
vm.eval(program: decls)
return
}
// Emit the LLVM IR fo the program.
let module = try Emitter.emit(program: decls)
// Apply optimizations, if requested to.
if optimize {
let pipeliner = PassPipeliner(module: module)
pipeliner.addStandardModulePipeline("opt", optimization: .default, size: .default)
pipeliner.execute()
}
// Emit human readable assembly, if requested to.
var file = productFile
if emitIR {
if file.pathExtension.isEmpty {
file.appendPathExtension("ll")
}
try String(describing: module).write(to: file, atomically: true, encoding: .utf8)
return
}
// Compile the program.
let target = try TargetMachine(optLevel: optimize ? .default : .none)
module.targetTriple = target.triple
// Emit the requested output.
if emitAssembly {
if file.pathExtension.isEmpty {
file.appendPathExtension("s")
}
try target.emitToFile(module: module, type: .assembly, path: file.path)
return
}
if emitObject {
if file.pathExtension.isEmpty {
file.appendPathExtension("o")
}
try target.emitToFile(module: module, type: .object, path: file.path)
return
}
try makeExec(target: target, module: module)
}
/// Generates an executable.
func makeExec(target: TargetMachine, module: Module) throws {
let manager = FileManager.default
// Create a temporary directory.
let tmp = try manager.url(
for: .itemReplacementDirectory,
in: .userDomainMask,
appropriateFor: productFile,
create: true)
// Search for the runtime library.
var searchPaths = Cocodoc.librarySearchPaths
if let customPath = customLibrarySearchPath {
searchPaths.insert(customPath, at: 0)
}
var runtimePath = "libcocodol_rt.a"
for directory in searchPaths {
let path = URL(fileURLWithPath: directory).appendingPathComponent("libcocodol_rt.a").path
if manager.fileExists(atPath: path) {
runtimePath = path
break
}
}
// Compile the LLVM module.
let moduleObject = tmp.appendingPathComponent(module.name).appendingPathExtension("o")
try target.emitToFile(module: module, type: .object, path: moduleObject.path)
// Produce the executable.
try exec(clangPath, args: [moduleObject.path, runtimePath, "-lm", "-o", productFile.path])
}
}
Cocodoc.main()
| 28.084848 | 95 | 0.660121 |
395028492758edb538a30e1be9ca6aa856876247 | 899 | //
// Copyright (c) 2018 Google Inc.
//
// 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 FirebaseAnalytics
import FirebaseDynamicLinks
class ViewController: UIViewController {
@IBOutlet var textField: UITextField!
@IBAction func triggerEvent(_ sender: Any) {
if let text = textField.text {
Analytics.logEvent(text, parameters: nil)
}
}
}
| 27.242424 | 76 | 0.728587 |
9b77f19381558c5a0a4329b8f59d79c1497597d6 | 848 | import Foundation
import GRDB
public class ChartPoint {
public let timestamp: TimeInterval
public let value: Decimal
public var extra: [String: Decimal]
public init(timestamp: TimeInterval, value: Decimal, extra: [String: Decimal] = [:]) {
self.timestamp = timestamp
self.value = value
self.extra = extra
}
@discardableResult public func added(field: String, value: Decimal?) -> Self {
if let value = value {
extra[field] = value
} else {
extra.removeValue(forKey: field)
}
return self
}
}
extension ChartPoint {
public static let volume = "volume"
}
extension ChartPoint: Equatable {
public static func ==(lhs: ChartPoint, rhs: ChartPoint) -> Bool {
lhs.timestamp == rhs.timestamp && lhs.value == rhs.value
}
}
| 22.918919 | 90 | 0.620283 |
5d66583b799a7d0e93b4edadb7017a1b09b10aec | 403 | //
// Mappable+CustomStringConvertible.swift
// NPOKit
//
// Created by Jeroen Wesbeek on 14/07/16.
// Copyright © 2016 Jeroen Wesbeek. All rights reserved.
//
import Foundation
import ObjectMapper
extension Mappable where Self: CustomStringConvertible {
// MARK: CustomDebugStringConvertible
public var description: String {
return String(describing: type(of: self))
}
}
| 21.210526 | 57 | 0.71464 |
626be407fd2ae7f9de0cf381ab4280ef867ad353 | 1,257 | //
// MainTabViewController.swift
// nytimes
//
// Created by shunnamiki on 2021/06/10.
//
import UIKit
class MainTabViewController: UITabBarController {
let homeVC: UINavigationController = {
let vc: HomeCollectionViewController = {
let layout = UICollectionViewLayout()
let vc = HomeCollectionViewController(collectionViewLayout: layout)
let image = TextImage.imageWith(name: "𝔑")
vc.tabBarItem = UITabBarItem(title: "Home", image: image, tag: 1)
return vc
}()
let nav = UINavigationController(rootViewController: vc)
return nav
}()
let searchVC: UINavigationController = {
let vc: SearchTableViewController = {
let layout = UICollectionViewLayout()
let vc = SearchTableViewController()
let image = UIImage(systemName: "magnifyingglass")
vc.tabBarItem = UITabBarItem(title: "Search", image: image, tag: 2)
return vc
}()
let nav = UINavigationController(rootViewController: vc)
return nav
}()
override func viewDidLoad() {
super.viewDidLoad()
viewControllers = [
homeVC,
searchVC,
]
}
}
| 28.568182 | 79 | 0.604614 |
e62d76dd685b1f89cce4366012e14a28e09b1c2c | 1,449 | //
// BRCoderTests.swift
// ravenwallet
//
// Created by Samuel Sutch on 12/7/16.
// Copyright © 2018 Ravenwallet Team. All rights reserved.
//
import XCTest
@testable import breadwallet
class TestObject: BRCoding {
var string: String
var int: Int
var date: Date
init(string: String, int: Int, date: Date) {
self.string = string
self.int = int
self.date = date
}
required init?(coder decoder: BRCoder) {
string = decoder.decode("string")
int = decoder.decode("int")
date = decoder.decode("date")
}
func encode(_ coder: BRCoder) {
coder.encode(string, key: "string")
coder.encode(int, key: "int")
coder.encode(date, key: "date")
}
}
class BRCodingTests: XCTestCase {
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func testBasicEncodeAndDecode() {
let orig = TestObject(string: "hello", int: 823483, date: Date(timeIntervalSince1970: 872347))
let dat = BRKeyedArchiver.archivedDataWithRootObject(orig)
guard let new: TestObject = BRKeyedUnarchiver.unarchiveObjectWithData(dat) else {
XCTFail("unarchived a nil object")
return
}
XCTAssertEqual(orig.string, new.string)
XCTAssertEqual(orig.int, new.int)
XCTAssertEqual(orig.date, new.date)
}
}
| 24.982759 | 102 | 0.606625 |
79cb00e15a0a7bbb170227d7124faa21058ff18a | 28,248 | //
// Quickly
//
open class QPageContainerViewController : QViewController, IQPageContainerViewController, IQStackContentViewController, IQGroupContentViewController, IQModalContentViewController, IQHamburgerContentViewController, IQJalousieContentViewController {
open var barView: QPagebar? {
set(value) { self.set(barView: value) }
get { return self._barView }
}
open var barHeight: CGFloat {
set(value) { self.set(barHeight: value) }
get { return self._barHeight }
}
open var barHidden: Bool {
set(value) { self.set(barHidden: value) }
get { return self._barHidden }
}
open var viewControllers: [IQPageViewController] {
set(value) { self.set(viewControllers: value) }
get { return self._viewControllers }
}
open private(set) var currentViewController: IQPageViewController?
open private(set) var forwardViewController: IQPageViewController?
open private(set) var backwardViewController: IQPageViewController?
open var forwardAnimation: IQPageViewControllerAnimation
open var backwardAnimation: IQPageViewControllerAnimation
open var interactiveAnimation: IQPageViewControllerInteractiveAnimation?
open private(set) var isAnimating: Bool {
didSet {
if let pagebar = self._barView {
pagebar.isUserInteractionEnabled = self.isAnimating == false
}
}
}
public private(set) lazy var interactiveGesture: UIPanGestureRecognizer = {
let gesture = UIPanGestureRecognizer(target: self, action: #selector(self._handleInteractiveGesture(_:)))
gesture.delaysTouchesBegan = true
gesture.delegate = self
return gesture
}()
private var _barView: QPagebar?
private var _barHeight: CGFloat
private var _barHidden: Bool
private var _viewControllers: [IQPageViewController]
private var _activeInteractiveCurrentViewController: IQPageViewController?
private var _activeInteractiveForwardViewController: IQPageViewController?
private var _activeInteractiveBackwardViewController: IQPageViewController?
private var _activeInteractiveAnimation: IQPageViewControllerInteractiveAnimation?
public init(
forwardAnimation: IQPageViewControllerAnimation = QPageViewControllerForwardAnimation(),
backwardAnimation: IQPageViewControllerAnimation = QPageViewControllerBackwardAnimation(),
interactiveAnimation: IQPageViewControllerInteractiveAnimation? = QPageViewControllerInteractiveAnimation()
) {
self._barHeight = 44
self._barHidden = false
self._viewControllers = []
self.forwardAnimation = forwardAnimation
self.backwardAnimation = backwardAnimation
self.interactiveAnimation = interactiveAnimation
self.isAnimating = false
super.init()
}
open override func didLoad() {
self._updateAdditionalEdgeInsets()
self.view.addGestureRecognizer(self.interactiveGesture)
let displayed = self._displayed(viewController: self.currentViewController)
if let vc = displayed.0 {
self._appear(viewController: vc, frame: self._backwardViewControllerFrame())
self.backwardViewController = vc
}
if let vc = displayed.1 {
self._appear(viewController: vc, frame: self._currentViewControllerFrame())
self.currentViewController = vc
}
if let vc = displayed.2 {
self._appear(viewController: vc, frame: self._forwardViewControllerFrame())
self.forwardViewController = vc
}
if let pagebar = self._barView {
pagebar.items = self._viewControllers.compactMap({ return $0.item })
pagebar.setSelectedItem(self.currentViewController?.item, animated: false)
self.view.addSubview(pagebar)
self.view.bringSubviewToFront(pagebar)
}
}
open override func layout(bounds: CGRect) {
guard self.isAnimating == false else {
return
}
if let vc = self.backwardViewController {
vc.view.frame = self._backwardViewControllerFrame()
}
if let vc = self.currentViewController {
vc.view.frame = self._currentViewControllerFrame()
}
if let vc = self.forwardViewController {
vc.view.frame = self._forwardViewControllerFrame()
}
if let pagebar = self._barView {
pagebar.edgeInsets = self._barEdgeInsets()
pagebar.frame = self._barFrame(bounds: bounds)
}
}
open override func prepareInteractivePresent() {
super.prepareInteractivePresent()
if let vc = self.currentViewController {
vc.prepareInteractivePresent()
}
}
open override func cancelInteractivePresent() {
super.cancelInteractivePresent()
if let vc = self.currentViewController {
vc.cancelInteractivePresent()
}
}
open override func finishInteractivePresent() {
super.finishInteractivePresent()
if let vc = self.currentViewController {
vc.finishInteractivePresent()
}
}
open override func willPresent(animated: Bool) {
super.willPresent(animated: animated)
if let vc = self.currentViewController {
vc.willPresent(animated: animated)
}
}
open override func didPresent(animated: Bool) {
super.didPresent(animated: animated)
if let vc = self.currentViewController {
vc.didPresent(animated: animated)
}
}
open override func prepareInteractiveDismiss() {
super.prepareInteractiveDismiss()
if let vc = self.currentViewController {
vc.prepareInteractiveDismiss()
}
}
open override func cancelInteractiveDismiss() {
super.cancelInteractiveDismiss()
if let vc = self.currentViewController {
vc.cancelInteractiveDismiss()
}
}
open override func finishInteractiveDismiss() {
super.finishInteractiveDismiss()
if let vc = self.currentViewController {
vc.finishInteractiveDismiss()
}
}
open override func willDismiss(animated: Bool) {
super.willDismiss(animated: animated)
if let vc = self.currentViewController {
vc.willDismiss(animated: animated)
}
}
open override func didDismiss(animated: Bool) {
super.didDismiss(animated: animated)
if let vc = self.currentViewController {
vc.didDismiss(animated: animated)
}
}
open override func willTransition(size: CGSize) {
super.willTransition(size: size)
if let vc = self.currentViewController {
vc.willTransition(size: size)
}
}
open override func didTransition(size: CGSize) {
super.didTransition(size: size)
if let vc = self.currentViewController {
vc.didTransition(size: size)
}
}
open override func supportedOrientations() -> UIInterfaceOrientationMask {
guard let vc = self.currentViewController else { return super.supportedOrientations() }
return vc.supportedOrientations()
}
open override func preferedStatusBarHidden() -> Bool {
guard let vc = self.currentViewController else { return super.preferedStatusBarHidden() }
return vc.preferedStatusBarHidden()
}
open override func preferedStatusBarStyle() -> UIStatusBarStyle {
guard let vc = self.currentViewController else { return super.preferedStatusBarStyle() }
return vc.preferedStatusBarStyle()
}
open override func preferedStatusBarAnimation() -> UIStatusBarAnimation {
guard let vc = self.currentViewController else { return super.preferedStatusBarAnimation() }
return vc.preferedStatusBarAnimation()
}
open func set(barView: QPagebar?, animated: Bool = false) {
if self.isLoaded == true {
if let pagebar = self._barView {
pagebar.removeFromSuperview()
pagebar.delegate = nil
}
self._barView = barView
if let pagebar = self._barView {
pagebar.frame = self._barFrame(bounds: self.view.bounds)
pagebar.edgeInsets = self._barEdgeInsets()
pagebar.delegate = self
self.view.addSubview(pagebar)
self.view.bringSubviewToFront(pagebar)
}
self.setNeedLayout()
} else {
if let pagebar = self._barView {
pagebar.delegate = nil
}
self._barView = barView
if let pagebar = self._barView {
pagebar.delegate = self
}
}
self._updateAdditionalEdgeInsets()
}
open func set(barHeight: CGFloat, animated: Bool = false) {
if self._barHeight != barHeight {
self._barHeight = barHeight
if let pagebar = self._barView {
pagebar.frame = self._barFrame(bounds: self.view.bounds)
}
self.setNeedLayout()
self._updateAdditionalEdgeInsets()
if self.isLoaded == true {
if animated == true {
UIView.animate(withDuration: 0.1, delay: 0, options: [ .beginFromCurrentState ], animations: {
self.layoutIfNeeded()
})
}
}
}
}
open func set(barHidden: Bool, animated: Bool = false) {
if self._barHidden != barHidden {
self._barHidden = barHidden
if let pagebar = self._barView {
pagebar.frame = self._barFrame(bounds: self.view.bounds)
}
self.setNeedLayout()
self._updateAdditionalEdgeInsets()
if self.isLoaded == true {
if animated == true {
UIView.animate(withDuration: 0.1, delay: 0, options: [ .beginFromCurrentState ], animations: {
self.layoutIfNeeded()
})
}
}
}
}
open func set(viewControllers: [IQPageViewController], mode: QPageViewControllerAnimationMode = .none, completion: (() -> Swift.Void)? = nil) {
self._viewControllers.forEach({
self._disappear(viewController: $0)
self._remove(childViewController: $0)
})
self._viewControllers = viewControllers
self._viewControllers.forEach({ self._add(childViewController: $0) })
if self.isLoaded == true {
self._update(viewController: self.currentViewController, mode: mode, updation: {
if let pagebar = self._barView {
let pagebarItems = self._viewControllers.compactMap({ return $0.item })
let selectedPagebarItem = self.currentViewController?.item
switch mode {
case .none:
pagebar.items = pagebarItems
pagebar.setSelectedItem(selectedPagebarItem, animated: true)
case .backward,
.forward:
pagebar.performBatchUpdates({
pagebar.deleteItem(pagebar.items)
pagebar.appendItem(pagebarItems)
}, completion: { _ in
pagebar.setSelectedItem(selectedPagebarItem, animated: true)
})
}
}
}, completion: completion)
}
}
open func set(currentViewController: IQPageViewController, mode: QPageViewControllerAnimationMode = .none, completion: (() -> Swift.Void)? = nil) {
guard self._viewControllers.contains(where: { currentViewController === $0 }) == true else { return }
if self.isLoaded == true {
self._update(viewController: currentViewController, mode: mode, updation: {
if let pagebar = self._barView {
pagebar.setSelectedItem(currentViewController.item, animated: mode.isAnimating)
}
}, completion: completion)
} else {
self.currentViewController = currentViewController
}
}
open func didUpdate(viewController: IQPageViewController, animated: Bool) {
guard let pagebar = self._barView else { return }
guard let index = self._viewControllers.firstIndex(where: { $0 === viewController }) else { return }
guard let pagebarItem = viewController.item else { return }
pagebar.replaceItem(pagebarItem, index: index)
}
// MARK: IQContentViewController
public var contentOffset: CGPoint {
get { return CGPoint.zero }
}
public var contentSize: CGSize {
get { return CGSize.zero }
}
open func notifyBeginUpdateContent() {
if let viewController = self.contentOwnerViewController {
viewController.beginUpdateContent()
}
}
open func notifyUpdateContent() {
if let viewController = self.contentOwnerViewController {
viewController.updateContent()
}
}
open func notifyFinishUpdateContent(velocity: CGPoint) -> CGPoint? {
if let viewController = self.contentOwnerViewController {
return viewController.finishUpdateContent(velocity: velocity)
}
return nil
}
open func notifyEndUpdateContent() {
if let viewController = self.contentOwnerViewController {
viewController.endUpdateContent()
}
}
// MARK: IQModalContentViewController
open func modalShouldInteractive() -> Bool {
guard let currentViewController = self.currentViewController as? IQModalContentViewController else { return false }
return currentViewController.modalShouldInteractive()
}
// MARK: IQHamburgerContentViewController
open func hamburgerShouldInteractive() -> Bool {
guard let currentViewController = self.currentViewController as? IQHamburgerContentViewController else { return false }
return currentViewController.hamburgerShouldInteractive()
}
// MARK: IQJalousieContentViewController
open func jalousieShouldInteractive() -> Bool {
guard let currentViewController = self.currentViewController as? IQJalousieContentViewController else { return false }
return currentViewController.jalousieShouldInteractive()
}
}
// MARK: Private
private extension QPageContainerViewController {
func _displayed(viewController: IQPageViewController?) -> (IQPageViewController?, IQPageViewController?, IQPageViewController?) {
var displayedBackward: IQPageViewController?
var displayedCurrent: IQPageViewController?
var displayedForward: IQPageViewController?
if self._viewControllers.contains(where: { viewController === $0 }) == true {
displayedCurrent = viewController
} else {
displayedCurrent = self._viewControllers.first
}
if let current = displayedCurrent {
if let index = self._viewControllers.firstIndex(where: { $0 === current }) {
displayedBackward = (index != self._viewControllers.startIndex) ? self._viewControllers[index - 1] : nil
displayedForward = (index != self._viewControllers.endIndex - 1) ? self._viewControllers[index + 1] : nil
} else {
displayedForward = (self._viewControllers.count > 1) ? self._viewControllers[self._viewControllers.startIndex + 1] : nil
}
}
return (displayedBackward, displayedCurrent, displayedForward)
}
func _update(viewController: IQPageViewController?, mode: QPageViewControllerAnimationMode, updation: (() -> Swift.Void)? = nil, completion: (() -> Swift.Void)? = nil) {
let currently = (self.backwardViewController, self.currentViewController, self.forwardViewController)
let displayed = self._displayed(viewController: viewController)
if currently.0 !== displayed.0 {
self.backwardViewController = displayed.0
if let vc = self.backwardViewController {
let frame = self._backwardViewControllerFrame()
self._appear(viewController: vc, frame: frame)
}
}
if currently.2 !== displayed.2 {
self.forwardViewController = displayed.2
if let vc = self.forwardViewController {
let frame = self._forwardViewControllerFrame()
self._appear(viewController: vc, frame: frame)
}
}
if currently.1 !== displayed.1 {
self.currentViewController = displayed.1
if let vc = self.currentViewController {
let frame = self._currentViewControllerFrame()
self._appear(viewController: vc, frame: frame)
}
updation?()
if mode.isAnimating == true, let currentViewController = currently.1, let targetViewController = displayed.1 {
var animation: IQPageViewControllerAnimation
switch mode {
case .none: fatalError("Invalid mode")
case .backward: animation = self._backwardAnimation(viewController: currentViewController)
case .forward: animation = self._forwardAnimation(viewController: currentViewController)
}
self.isAnimating = true
animation.animate(
contentView: self.view,
currentViewController: currentViewController,
targetViewController: targetViewController,
animated: true,
complete: { [weak self] in
if let self = self {
self._disappear(old: currently, new: displayed)
self.isAnimating = false
}
completion?()
}
)
} else {
if let vc = currently.1 {
vc.willDismiss(animated: false)
vc.didDismiss(animated: false)
}
if let vc = displayed.1 {
vc.willPresent(animated: false)
vc.didPresent(animated: false)
}
self._disappear(old: currently, new: displayed)
completion?()
}
} else {
updation?()
self._disappear(old: currently, new: displayed)
completion?()
}
}
func _add(childViewController: IQPageViewController) {
childViewController.parentViewController = self
}
func _remove(childViewController: IQPageViewController) {
childViewController.parentViewController = nil
}
func _appear(viewController: IQPageViewController, frame: CGRect) {
viewController.view.frame = frame
if viewController.view.superview !== self.view {
if let pagebar = self._barView {
self.view.insertSubview(viewController.view, belowSubview: pagebar)
} else {
self.view.addSubview(viewController.view)
}
}
}
func _disappear(old: (IQPageViewController?, IQPageViewController?, IQPageViewController?), new: (IQPageViewController?, IQPageViewController?, IQPageViewController?)) {
if let vc = old.0, (new.0 !== vc) && (new.1 !== vc) && (new.2 !== vc) {
self._disappear(viewController: vc)
}
if let vc = old.1, (new.0 !== vc) && (new.1 !== vc) && (new.2 !== vc) {
self._disappear(viewController: vc)
}
if let vc = old.2, (new.0 !== vc) && (new.1 !== vc) && (new.2 !== vc) {
self._disappear(viewController: vc)
}
}
func _disappear(viewController: IQPageViewController) {
viewController.view.removeFromSuperview()
}
func _forwardAnimation(viewController: IQPageViewController) -> IQPageViewControllerAnimation {
if let animation = viewController.forwardAnimation { return animation }
return self.forwardAnimation
}
func _backwardAnimation(viewController: IQPageViewController) -> IQPageViewControllerAnimation {
if let animation = viewController.backwardAnimation { return animation }
return self.backwardAnimation
}
func _interactiveAnimation(viewController: IQPageViewController) -> IQPageViewControllerInteractiveAnimation? {
if let animation = viewController.interactiveAnimation { return animation }
return self.interactiveAnimation
}
func _updateAdditionalEdgeInsets() {
self.additionalEdgeInsets = UIEdgeInsets(
top: (self._barView != nil && self._barHidden == false) ? self._barHeight : 0,
left: 0,
bottom: 0,
right: 0
)
}
func _currentViewControllerFrame() -> CGRect {
return self.view.bounds
}
func _forwardViewControllerFrame() -> CGRect {
let current = self._currentViewControllerFrame()
return CGRect(
x: current.origin.x + current.size.width,
y: current.origin.y,
width: current.size.width,
height: current.size.height
)
}
func _backwardViewControllerFrame() -> CGRect {
let current = self._currentViewControllerFrame()
return CGRect(
x: current.origin.x - current.size.width,
y: current.origin.y,
width: current.size.width,
height: current.size.height
)
}
func _barFrame(bounds: CGRect) -> CGRect {
let edgeInsets = self.inheritedEdgeInsets
let fullHeight = self._barHeight + edgeInsets.top
if self._barHidden == true {
return CGRect(
x: bounds.origin.x,
y: bounds.origin.y - fullHeight,
width: bounds.size.width,
height: fullHeight
)
}
return CGRect(
x: bounds.origin.x,
y: bounds.origin.y,
width: bounds.size.width,
height: fullHeight
)
}
func _barEdgeInsets() -> UIEdgeInsets {
let edgeInsets = self.inheritedEdgeInsets
return UIEdgeInsets(
top: edgeInsets.top,
left: edgeInsets.left,
bottom: 0,
right: edgeInsets.right
)
}
@objc
func _handleInteractiveGesture(_ sender: Any) {
let position = self.interactiveGesture.location(in: nil)
let velocity = self.interactiveGesture.velocity(in: nil)
switch self.interactiveGesture.state {
case .began:
guard
let currentViewController = self.currentViewController,
let animation = self._interactiveAnimation(viewController: currentViewController)
else { return }
self._activeInteractiveBackwardViewController = self.backwardViewController
self._activeInteractiveForwardViewController = self.forwardViewController
self._activeInteractiveCurrentViewController = currentViewController
self._activeInteractiveAnimation = animation
self.isAnimating = true
animation.prepare(
contentView: self.view,
backwardViewController: self.backwardViewController,
currentViewController: currentViewController,
forwardViewController: self.forwardViewController,
position: position,
velocity: velocity
)
break
case .changed:
guard let animation = self._activeInteractiveAnimation else { return }
animation.update(position: position, velocity: velocity)
break
case .ended, .failed, .cancelled:
guard let animation = self._activeInteractiveAnimation else { return }
if animation.canFinish == true {
animation.finish({ [weak self] (completed: Bool) in
guard let self = self else { return }
switch animation.finishMode {
case .none: self._endInteractive()
case .backward: self._endInteractive(viewController: self._activeInteractiveBackwardViewController)
case .forward: self._endInteractive(viewController: self._activeInteractiveForwardViewController)
}
})
} else {
animation.cancel({ [weak self] (completed: Bool) in
guard let self = self else { return }
self._endInteractive()
})
}
break
default:
break
}
}
func _endInteractive(viewController: IQPageViewController?) {
let currently = (
self._activeInteractiveBackwardViewController,
self._activeInteractiveCurrentViewController,
self._activeInteractiveForwardViewController
)
let displayed = self._displayed(viewController: viewController)
if currently.0 !== displayed.0 {
self.backwardViewController = displayed.0
if let vc = self.backwardViewController {
let frame = self._backwardViewControllerFrame()
self._appear(viewController: vc, frame: frame)
}
}
if currently.1 !== displayed.1 {
self.currentViewController = displayed.1
if let vc = self.currentViewController {
let frame = self._currentViewControllerFrame()
self._appear(viewController: vc, frame: frame)
}
}
if currently.2 !== displayed.2 {
self.forwardViewController = displayed.2
if let vc = self.forwardViewController {
let frame = self._forwardViewControllerFrame()
self._appear(viewController: vc, frame: frame)
}
}
self._disappear(old: currently, new: displayed)
if let pagebar = self._barView {
pagebar.setSelectedItem(self.currentViewController?.item, animated: true)
}
self._endInteractive()
}
func _endInteractive() {
self._activeInteractiveBackwardViewController = nil
self._activeInteractiveCurrentViewController = nil
self._activeInteractiveForwardViewController = nil
self._activeInteractiveAnimation = nil
self.isAnimating = false
}
}
// MARK: QPagebarDelegate
extension QPageContainerViewController : QPagebarDelegate {
public func pagebar(_ pagebar: QPagebar, didSelectItem: QPagebarItem) {
guard let index = self._viewControllers.firstIndex(where: { return $0.item === didSelectItem }) else { return }
let viewController = self._viewControllers[index]
var mode: QPageViewControllerAnimationMode = .forward
if let currentViewController = self.currentViewController {
if let currentIndex = self._viewControllers.firstIndex(where: { return $0 === currentViewController }) {
mode = (currentIndex > index) ? .backward : .forward
}
}
self._update(viewController: viewController, mode: mode)
}
}
// MARK: UIGestureRecognizerDelegate
extension QPageContainerViewController : UIGestureRecognizerDelegate {
open func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
guard gestureRecognizer == self.interactiveGesture else { return false }
if let pagebar = self._barView {
let location = touch.location(in: self.view)
if pagebar.point(inside: location, with: nil) == true {
return false
}
}
return true
}
}
| 39.39749 | 247 | 0.61569 |
d967efa9f595e1ba67072ddf38c37fffa508ee3d | 2,843 | import ComponentBase
import DealerComponent
import DealersComponent
import DealersJourney
import EurofurenceModel
import EventDetailComponent
import EventFeedbackComponent
import EventsJourney
import KnowledgeDetailComponent
import KnowledgeGroupsComponent
import KnowledgeJourney
import RouterCore
import ScheduleComponent
import UIKit
struct PrincipalWindowRoutes: RouteProvider {
var contentWireframe: ContentWireframe
var modalWireframe: ModalWireframe
var componentRegistry: ComponentRegistry
var authenticationService: AuthenticationService
var linksService: ContentLinksService
var urlOpener: URLOpener
var window: UIWindow
var routes: Routes {
Routes { (router) in
let routeAuthenticationHandler = AuthenticateOnDemandRouteAuthenticationHandler(
service: authenticationService,
router: router
)
NewsRoute(newsPresentation: ResetNewsAfterLogout(window: window))
NewsRoutes(
components: componentRegistry,
routeAuthenticationHandler: routeAuthenticationHandler,
contentWireframe: contentWireframe,
modalWireframe: modalWireframe,
window: window
)
DealersRouters(
dealerDetailModuleProviding: componentRegistry.dealerDetailModuleProviding,
contentWireframe: contentWireframe,
window: window
)
EventsRoutes(
globalRouter: router,
eventDetailComponentFactory: componentRegistry.eventDetailComponentFactory,
contentWireframe: contentWireframe,
window: window
)
EventFeedbackRoute(
eventFeedbackFactory: FormSheetEventFeedbackComponentFactory(
eventFeedbackComponentFactory: componentRegistry.eventFeedbackComponentFactory
),
modalWireframe: modalWireframe
)
KnowledgeRoutes(
components: componentRegistry,
contentWireframe: contentWireframe,
linksService: linksService,
window: window
)
MapRoute(
mapModuleProviding: componentRegistry.mapDetailComponentFactory,
contentWireframe: contentWireframe,
delegate: ShowDealerFromMap(router: router)
)
WebPageRoute(
webComponentFactory: componentRegistry.webComponentFactory,
modalWireframe: modalWireframe
)
ExternalApplicationRoute(urlOpener: urlOpener)
}
}
}
| 33.05814 | 98 | 0.621878 |
69bb2353ed1b254c8a1b54d3b6802a6f8e97c8cb | 840 | import Foundation
@objcMembers public class SmartyBatch: NSObject {
let maxBatchSize = 100
public var namedLookups:[String:Any]
public var allLookups:NSMutableArray
override public init() {
self.namedLookups = [String:Any]()
self.allLookups = NSMutableArray()
}
@objc func add(newAddress:Any, error: UnsafeMutablePointer<NSError?>) -> Bool {
return true
}
public func getLookupById(inputId:String) -> Any {
return self.namedLookups[inputId]!
}
public func getLookupAtIndex(index:Int) -> Any {
return self.allLookups[index]
}
public func count() -> Int {
return self.allLookups.count
}
func removeAllObjects() {
self.allLookups.removeAllObjects()
self.namedLookups.removeAll()
}
}
| 24 | 83 | 0.627381 |
50ac4de9050375672419610053bfe69bab48b22c | 248 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
for c
extension{var d{class
case,
| 27.555556 | 87 | 0.758065 |
d700a074d412472a1dc7892e72d873ac3a815791 | 465 | /// This file is generated by Weaver 0.12.4
/// DO NOT EDIT!
// MARK: - FooTest6
protocol FooTest6DependencyResolver {
var fuu: FuuProtocolTest6? { get }
}
final class FooTest6DependencyContainer: FooTest6DependencyResolver {
private var _fuu: FuuProtocolTest6??
var fuu: FuuProtocolTest6? {
if let value = _fuu { return value }
let value = FuuTest6()
_fuu = value
return value
}
init() {
_ = fuu
}
}
| 24.473684 | 69 | 0.634409 |
bbc892e46ddf23f62871df31fedbce60e60ba53a | 502 | import Fox
func id<A>(a: A) -> A {
return a
}
func compose<A, B, C>(fa: A -> B, fb: B -> C) -> A -> C {
return { x in fb(fa(x)) }
}
func curry<A, B, C>(f: (A, B) -> C) -> A -> B -> C {
return { a in { b in f(a, b) }}
}
func append(x: String) -> String {
return x + "bar"
}
func prepend(x: String) -> String {
return "baz" + x
}
func generateString(block:String -> Bool) -> FOXGenerator {
return forAll(string()) { string in
return block(string as! String)
}
}
| 17.928571 | 59 | 0.51992 |
9cce16d5570c2ac5aaeaa60ecaa78a59d0c11cae | 12,192 | //
// MoreInfo.swift
// tabijiman
//
// Copyright (c) 2016 FUKUI Association of information & system industry
//
// 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
import Foundation
import CoreLocation
import Alamofire
import SwiftyJSON
class MoreInfo: UIViewController, UITextViewDelegate {
static let placeImage = UIImage(named: "icon_location_name.png")
static let frameImage = UIImage(named: "icon_frame_name.png")
static let collectionImage = UIImage(named: "icon_pin_l.png")
static let noImage = UIImage(named: "img_frame.png")
static let go_button_jaImage = UIImage(named: "btn_go_s.png")
static let search_button_jaImage = UIImage(named: "btn_more.png")
static let take_picture_jaImage = UIImage(named: "btn_take_photo_s.png")
static let frame_get_button_jaImage = UIImage(named: "btn_frame_get_on.png")
static let GetFrameImage_jaImage = UIImage(named: "get_frame.png")
var dic: Dictionary<String, AnyObject>? = [:]
var take_pic_flag: Bool! // 写真をとるボタンの表示
var frame_get_flag: Bool! // フレームGETボタンの表示
var color: String! // カラーリングの属性決定
var distance_flag: Bool! = false // ViewControllerからの遷移時。取得可能フレームの場合 true
var getFrameFlag: Bool! = false // ViewControllerからの遷移時。取得済みフレームの場合 true
var fromCollectionFlag: Bool! = false // FrameCollectionからの遷移時に true
var initFrameFlag: Bool = false // FrameCollectionからの遷移時。initフレームの場合 true
@IBOutlet var gotoCenter: NSLayoutConstraint!
@IBOutlet var view_color: UIView!
@IBOutlet var effectView: UIVisualEffectView!
@IBOutlet var title_view: UILabel!
@IBOutlet weak var icon_image: UIImageView!
@IBOutlet var address: UILabel!
@IBOutlet var img_view: UIImageView!
@IBOutlet var test_viewer: UITextView!
@IBOutlet var head_view: UIView!
@IBOutlet var frame_get_action_view: UIView!
@IBOutlet var get_image: UIImageView!
@IBOutlet weak var GetFrameImage: UIImageView!
@IBOutlet var go_button: UIButton!
@IBOutlet var search_button: UIButton!
@IBOutlet var take_picture: UIButton!
@IBOutlet var frame_get_button: UIButton!
@IBAction func frame_get( sender: UIButton ) {
// AppSetting.startUp_flag = false
if self.distance_flag! {
// 取得フレームの表示
self.get_image.image = img_view.image!
self.frame_get_action_view.fadeIn(.Normal, completed: nil)
let delay = 5.0 * Double(NSEC_PER_SEC)
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
dispatch_after(time, dispatch_get_main_queue(), {
self.frame_get_action_view.fadeOut(.Normal, completed: nil)
})
// 画像を表示して、フォルダへ保存
let image = UIImagePNGRepresentation(img_view.image!)
let filename = title_view.text! + ".png"
let imageFilePath = AppSetting.imagesPath + filename
image!.writeToFile(imageFilePath, atomically: true)
// 保存したファイル名で元の画像ファイルへのURLを上書き
self.dic!["img"] = filename as String
print("start to insert: \(dic)")
// Dbへ保存
_ = SQLite.sharedInstance.insertData("getFrame", datas: self.dic!)
// 取得済みフラグをたてる
SQLite.sharedInstance.enableGetFlag(self.dic!["name"]! as! String)
} else {
// Can not get
let alertController = UIAlertController(title: NSLocalizedString("oops!", comment: "") , message: NSLocalizedString("You are so far from the place. Design can not be gotton. \n Please come to the place & try it again.", comment: ""), preferredStyle: .Alert)
let defaultAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
alertController.addAction(defaultAction)
presentViewController(alertController, animated: true, completion: nil)
}
}
@IBAction func take_picture( sender: UIButton ) {
performSegueWithIdentifier("TakePicture", sender: nil)
}
@IBAction func go_there(sender: UIButton) {
let locate: CLLocation = CLLocation(latitude: self.dic!["lat"]! as! CLLocationDegrees, longitude: self.dic!["lng"]! as! CLLocationDegrees)
self.showLocation(locate)
}
@IBAction func searching(sender: UIButton) {
let url : NSString = "http://google.com/#q=" + self.dic!["name"]!.stringByAddingPercentEncodingWithAllowedCharacters( NSCharacterSet.URLFragmentAllowedCharacterSet() )!
let searchURL : NSURL = NSURL(string: url as String)!
// ブラウザ起動
if UIApplication.sharedApplication().canOpenURL(searchURL){
UIApplication.sharedApplication().openURL(searchURL)
}
}
override func viewDidLoad() {
super.viewDidLoad()
let logoImage = UIImageView(image: UIImage(named: "HeadLogo"))
logoImage.contentMode = .ScaleAspectFit
self.navigationItem.titleView = logoImage
self.judgeLocalizationUiImage()
// color set of 'place'
self.view_color.backgroundColor = UIColor.rgbColor(0xedf5d3)
self.address.textColor = UIColor.rgbColor(0x85a80f)
self.icon_image.image = MoreInfo.placeImage
if let _ = self.dic!["address"] as? String {
self.address.text = self.dic!["address"] as? String
}else {
self.address.text = "テストテストテストテスト"
self.address.hidden = true
}
self.title_view.text = self.dic?["name"] as? String
self.title_view.sizeToFit()
self.test_viewer.text = self.dic!["desc"] as? String
self.test_viewer.delegate = self // TODO : delegateで何を行っているのか確認
self.test_viewer.font = UIFont.systemFontOfSize(CGFloat(17))
self.take_picture.hidden = !take_pic_flag
self.search_button.hidden = frame_get_flag
self.frame_get_button.hidden = !frame_get_flag
if self.color == "frame" {
// color set of 'frame'
self.view_color.backgroundColor = UIColor.rgbColor(0xffecca)
self.address.textColor = UIColor.rgbColor(0xff6000)
self.icon_image.image = MoreInfo.frameImage
}
if self.color == "collection" {
// color set of 'collection'
self.view_color.backgroundColor = UIColor.rgbColor(0xffecca)
self.address.textColor = UIColor.rgbColor(0xff6000)
self.icon_image.image = MoreInfo.collectionImage
}
if !take_pic_flag {
gotoCenter.constant = 0
}
if !self.initFrameFlag && !self.fromCollectionFlag {
// should be Place
let url = String(self.dic!["img"]!)
if ((url.rangeOfString("://") != nil) || (url.rangeOfString("https://")) != nil) {
let request = NSMutableURLRequest(URL: NSURL(string: url)! , cachePolicy:.ReloadIgnoringLocalCacheData, timeoutInterval:2.0)
Alamofire.request(.GET, request)
.validate(statusCode: 200..<300)
.response { ( request, response, data, error ) in
if (error == nil) {
if let check = UIImage(data: data!) {
self.img_view.image = check
if !self.getFrameFlag! {
// 未取得の場合、EffectView を表示する
//self.effectView.alpha = 1
self.effectView.hidden = false
}
}
} else {
// HTTP request failed
print(error)
self.img_view.image = MoreInfo.noImage
}
}
} else {
// set No Image
self.img_view.image = MoreInfo.noImage
}
} else if !self.initFrameFlag {
// should be getFrame
if (self.dic!["img"] != nil) {
let filename = self.dic!["img"] as! String
self.img_view.image = UIImage(contentsOfFile: getPathInImagesDir(filename))
} else {
// fail to get getFrame
self.img_view.image = MoreInfo.noImage
}
} else {
// should be initFile
let filename = self.dic!["img"] as! String
let imageData = getDataFromResource(filename)
self.img_view.image = UIImage(data: imageData!)!
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
// UITextView を 上寄せ表示するための設定 (上寄せの概念がレイアウト上はない)
self.test_viewer.setContentOffset(CGPointZero, animated: false)
}
// 目的地周辺の地図を表示する(アプリへ)
func showLocation(location: CLLocation) {
let daddr = NSString(format: "%f,%f", location.coordinate.latitude, location.coordinate.longitude)
var urlString: String
if self.dic?["address"] != nil {
urlString = "http://maps.apple.com/?ll=\(daddr)&q=\(self.dic!["name"]!)&z=15"
}else {
urlString = "http://maps.apple.com/?ll=\(daddr)&q=\(self.dic!["name"]!)&z=15"
}
let encodedUrl = urlString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
let url = NSURL(string: encodedUrl)!
UIApplication.sharedApplication().openURL(url)
}
// 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
if segue.identifier! == "TakePicture" {
// let constant: TakePicture = segue.destinationViewController as! TakePicture
}
}
/// UI言語判断と設定
func judgeLocalizationUiImage() {
if AppSetting.langUi == "ja" {
self.go_button.setImage(MoreInfo.go_button_jaImage, forState: .Normal)
self.search_button.setImage(MoreInfo.search_button_jaImage, forState: .Normal)
self.take_picture.setImage(MoreInfo.take_picture_jaImage, forState: .Normal)
self.frame_get_button.setImage(MoreInfo.frame_get_button_jaImage, forState: .Normal)
self.GetFrameImage.image = MoreInfo.GetFrameImage_jaImage
}
}
}
| 40.504983 | 269 | 0.609826 |
0117449e6735da1a05c6b1995dba5e7fa4cf9bde | 2,577 | import Foundation
import struct TSCUtility.Version
import TuistSupport
import XCTest
@testable import TuistEnvKit
@testable import TuistSupportTesting
final class UpdaterTests: TuistUnitTestCase {
var versionsController: MockVersionsController!
var installer: MockInstaller!
var envUpdater: MockEnvUpdater!
var versionProvider: MockVersionProvider!
var subject: Updater!
override func setUp() {
super.setUp()
versionsController = try! MockVersionsController()
installer = MockInstaller()
envUpdater = MockEnvUpdater()
versionProvider = MockVersionProvider()
subject = Updater(
versionsController: versionsController,
installer: installer,
envUpdater: envUpdater,
versionProvider: versionProvider
)
}
override func tearDown() {
versionsController = nil
installer = nil
envUpdater = nil
subject = nil
versionProvider = nil
super.tearDown()
}
func test_update_when_there_are_no_updates() throws {
versionsController.semverVersionsStub = ["3.2.1"]
versionProvider.stubbedLatestVersionResult = .success(Version("3.2.1"))
try subject.update()
XCTAssertPrinterOutputContains("There are no updates available")
XCTAssertEqual(envUpdater.updateCallCount, 1)
}
func test_update_when_there_are_updates() throws {
versionsController.semverVersionsStub = ["3.1.1"]
versionProvider.stubbedLatestVersionResult = .success(Version("3.2.1"))
var installArgs: [String] = []
installer.installStub = { version in installArgs.append(version) }
try subject.update()
XCTAssertPrinterOutputContains("Installing new version available 3.2.1")
XCTAssertEqual(installArgs.count, 1)
XCTAssertEqual(installArgs.first, "3.2.1")
XCTAssertEqual(envUpdater.updateCallCount, 1)
}
func test_update_when_no_local_versions_available() throws {
versionsController.semverVersionsStub = []
versionProvider.stubbedLatestVersionResult = .success(Version("3.2.1"))
var installArgs: [String] = []
installer.installStub = { version in installArgs.append(version) }
try subject.update()
XCTAssertPrinterOutputContains("No local versions available. Installing the latest version 3.2.1")
XCTAssertEqual(installArgs.count, 1)
XCTAssertEqual(installArgs.first, "3.2.1")
XCTAssertEqual(envUpdater.updateCallCount, 1)
}
}
| 33.038462 | 106 | 0.687621 |
ff05045ad01eef83e6ac9c112f8cfe6a833e97db | 1,819 | //
// ImageCell.swift
// ALImagePickerViewController
//
// Created by Alex Littlejohn on 2015/06/09.
// Copyright (c) 2015 zero. All rights reserved.
//
import UIKit
import Photos
class ImageCell: UICollectionViewCell {
let imageView : UIImageView = {
let imageView = UIImageView()
imageView.contentMode = .scaleAspectFill
imageView.layer.masksToBounds = true
imageView.image = UIImage(named: "placeholder",
in: CameraGlobals.shared.bundle,
compatibleWith: nil)
return imageView
}()
override init(frame: CGRect) {
super.init(frame: frame)
contentView.addSubview(imageView)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func layoutSubviews() {
super.layoutSubviews()
imageView.frame = bounds
}
override func prepareForReuse() {
super.prepareForReuse()
imageView.image = UIImage(named: "placeholder",
in: CameraGlobals.shared.bundle,
compatibleWith: nil)
}
override var isSelected: Bool {
didSet {
contentView.layer.borderWidth = 2.0
contentView.layer.borderColor = isSelected ? UIColor.blue.cgColor : UIColor.clear.cgColor
}
}
func configureWithModel(_ model: PHAsset) {
if tag != 0 {
PHImageManager.default().cancelImageRequest(PHImageRequestID(tag))
}
tag = Int(PHImageManager.default().requestImage(for: model, targetSize: contentView.bounds.size, contentMode: .aspectFill, options: nil) { image, info in
self.imageView.image = image
})
}
}
| 28.873016 | 161 | 0.587686 |
28e3bfb4b7d5d4f416f2089eda5f9aa1c6774336 | 477 | // swift-tools-version:5.1
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "RZTouchID",
platforms: [
.iOS(.v9),
.macOS(.v10_10),
],
products: [
.library(
name: "RZTouchID",
targets: ["RZTouchID"]),
],
targets: [
.target(
name: "RZTouchID",
path: "RZTouchID"),
]
)
| 21.681818 | 96 | 0.542977 |
e4d7398c68c216319d27efaef2231a4232b86c35 | 1,968 | //
// Created by Daniela Postigo on 6/30/17.
//
import Foundation
import AppKit
extension NSMenu {
public var fileMenu: NSMenu? {
return self.fileItem?.submenu
}
public var fileItem: NSMenuItem? {
return self.item(withTitle: "File")
}
public convenience init(forTableView tableView: NSTableView, state: Int = 0) {
self.init(title: tableView.autosaveName.map { $0.rawValue } ?? "Untitled", tableColumns: tableView.tableColumns, state: state)
}
public func addItem(title: String, action: Selector? = nil, keyEquivalent: String = "") {
self.addItem(withTitle: title, action: action, keyEquivalent: keyEquivalent)
}
public convenience init(title: String, tableColumns columns: [NSTableColumn], state: Int = 0) {
self.init(title: title)
let items: [NSMenuItem] = columns.map({ column in
let item = NSMenuItem(title: column.title, action: #selector(NSMenuItem.toggleState(_:)), keyEquivalent: "")
item.target = item
item.state = column.isHidden ? NSControl.StateValue.off : NSControl.StateValue.on
item.onStateImage = NSImage(named: NSImage.Name.menuOnStateTemplate)
column.bind(NSBindingName.hidden, to: item, withKeyPath: "state", options: [
NSBindingOption.valueTransformer: ValueTransformer(forName: .negateBooleanTransformerName)!,
NSBindingOption.continuouslyUpdatesValue: true
])
return item
})
items.forEach({ self.addItem($0) })
}
}
extension NSMenuItem {
public convenience init(title: String, action: Selector? = nil, keyEquivalent: String = "") {
self.init(title: title, action: action, keyEquivalent: keyEquivalent)
}
@objc public func toggleState(_ sender: AnyObject) {
self.state = self.state == NSControl.StateValue.on ? NSControl.StateValue.off : NSControl.StateValue.on
}
}
| 37.846154 | 134 | 0.655996 |
fcc777a5d9d15680dcf3a1f2005ccf17a3e78cb6 | 835 | //
// DrawInPlay.swift
// WildWestEngine
//
// Created by Hugues Stéphano TELOLAHY on 22/05/2021.
// Copyright © 2021 creativeGames. All rights reserved.
//
/**
Draw a card from other player's inPlay
*/
public class DrawInPlay: Effect {
@Argument(name: "player", defaultValue: .actor)
var player: PlayerArgument
@Argument(name: "other")
var other: PlayerArgument
@Argument(name: "card")
var card: CardArgument
override func apply(_ ctx: PlayContext) -> [GEvent]? {
guard let player = ctx.players(matching: player).first,
let other = ctx.players(matching: other).first else {
return nil
}
let cards = ctx.cards(matching: card, player: other)
return cards.map { .drawInPlay(player: player, other: other, card: $0) }
}
}
| 26.09375 | 80 | 0.626347 |
debf47e23a7a655e3b7dd386fecac8306758f046 | 12,977 | //
// Maybe.swift
// RxSwift
//
// Created by sergdort on 19/08/2017.
// Copyright © 2017 Krunoslav Zaher. All rights reserved.
//
#if DEBUG
import Foundation
#endif
/// Sequence containing 0 or 1 elements
public enum MaybeTrait { }
/// Represents a push style sequence containing 0 or 1 element.
public typealias Maybe<Element> = PrimitiveSequence<MaybeTrait, Element>
public enum MaybeEvent<Element> {
/// One and only sequence element is produced. (underlying observable sequence emits: `.next(Element)`, `.completed`)
case success(Element)
/// Sequence terminated with an error. (underlying observable sequence emits: `.error(Error)`)
case error(Swift.Error)
/// Sequence completed successfully.
case completed
}
extension PrimitiveSequenceType where TraitType == MaybeTrait {
public typealias MaybeObserver = (MaybeEvent<ElementType>) -> Void
/**
Creates an observable sequence from a specified subscribe method implementation.
- seealso: [create operator on reactivex.io](http://reactivex.io/documentation/operators/create.html)
- parameter subscribe: Implementation of the resulting observable sequence's `subscribe` method.
- returns: The observable sequence with the specified implementation for the `subscribe` method.
*/
public static func create(subscribe: @escaping (@escaping MaybeObserver) -> Disposable) -> PrimitiveSequence<TraitType, ElementType> {
let source = Observable<ElementType>.create { observer in
return subscribe { event in
switch event {
case .success(let element):
observer.on(.next(element))
observer.on(.completed)
case .error(let error):
observer.on(.error(error))
case .completed:
observer.on(.completed)
}
}
}
return PrimitiveSequence(raw: source)
}
/**
Subscribes `observer` to receive events for this sequence.
- returns: Subscription for `observer` that can be used to cancel production of sequence elements and free resources.
*/
public func subscribe(_ observer: @escaping (MaybeEvent<ElementType>) -> Void) -> Disposable {
var stopped = false
return self.primitiveSequence.asObservable().subscribe { event in
if stopped { return }
stopped = true
switch event {
case .next(let element):
observer(.success(element))
case .error(let error):
observer(.error(error))
case .completed:
observer(.completed)
}
}
}
/**
Subscribes a success handler, an error handler, and a completion handler for this sequence.
- parameter onSuccess: Action to invoke for each element in the observable sequence.
- parameter onError: Action to invoke upon errored termination of the observable sequence.
- parameter onCompleted: Action to invoke upon graceful termination of the observable sequence.
- returns: Subscription object used to unsubscribe from the observable sequence.
*/
public func subscribe(onSuccess: ((ElementType) -> Void)? = nil,
onError: ((Swift.Error) -> Void)? = nil,
onCompleted: (() -> Void)? = nil) -> Disposable {
#if DEBUG
let callStack = Hooks.recordCallStackOnError ? Thread.callStackSymbols : []
#else
let callStack = [String]()
#endif
return self.primitiveSequence.subscribe { event in
switch event {
case .success(let element):
onSuccess?(element)
case .error(let error):
if let onError = onError {
onError(error)
} else {
Hooks.defaultErrorHandler(callStack, error)
}
case .completed:
onCompleted?()
}
}
}
}
extension PrimitiveSequenceType where TraitType == MaybeTrait {
/**
Returns an observable sequence that contains a single element.
- seealso: [just operator on reactivex.io](http://reactivex.io/documentation/operators/just.html)
- parameter element: Single element in the resulting observable sequence.
- returns: An observable sequence containing the single specified element.
*/
public static func just(_ element: ElementType) -> Maybe<ElementType> {
return Maybe(raw: Observable.just(element))
}
/**
Returns an observable sequence that contains a single element.
- seealso: [just operator on reactivex.io](http://reactivex.io/documentation/operators/just.html)
- parameter element: Single element in the resulting observable sequence.
- parameter scheduler: Scheduler to send the single element on.
- returns: An observable sequence containing the single specified element.
*/
public static func just(_ element: ElementType, scheduler: ImmediateSchedulerType) -> Maybe<ElementType> {
return Maybe(raw: Observable.just(element, scheduler: scheduler))
}
/**
Returns an observable sequence that terminates with an `error`.
- seealso: [throw operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html)
- returns: The observable sequence that terminates with specified error.
*/
public static func error(_ error: Swift.Error) -> Maybe<ElementType> {
return PrimitiveSequence(raw: Observable.error(error))
}
/**
Returns a non-terminating observable sequence, which can be used to denote an infinite duration.
- seealso: [never operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html)
- returns: An observable sequence whose observers will never get called.
*/
public static func never() -> Maybe<ElementType> {
return PrimitiveSequence(raw: Observable.never())
}
/**
Returns an empty observable sequence, using the specified scheduler to send out the single `Completed` message.
- seealso: [empty operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html)
- returns: An observable sequence with no elements.
*/
public static func empty() -> Maybe<ElementType> {
return Maybe(raw: Observable.empty())
}
}
extension PrimitiveSequenceType where TraitType == MaybeTrait {
/**
Invokes an action for each event in the observable sequence, and propagates all observer messages through the result sequence.
- seealso: [do operator on reactivex.io](http://reactivex.io/documentation/operators/do.html)
- parameter onNext: Action to invoke for each element in the observable sequence.
- parameter onError: Action to invoke upon errored termination of the observable sequence.
- parameter onCompleted: Action to invoke upon graceful termination of the observable sequence.
- parameter onSubscribe: Action to invoke before subscribing to source observable sequence.
- parameter onSubscribed: Action to invoke after subscribing to source observable sequence.
- parameter onDispose: Action to invoke after subscription to source observable has been disposed for any reason. It can be either because sequence terminates for some reason or observer subscription being disposed.
- returns: The source sequence with the side-effecting behavior applied.
*/
public func `do`(onNext: ((ElementType) throws -> Void)? = nil,
onError: ((Swift.Error) throws -> Void)? = nil,
onCompleted: (() throws -> Void)? = nil,
onSubscribe: (() -> Void)? = nil,
onSubscribed: (() -> Void)? = nil,
onDispose: (() -> Void)? = nil)
-> Maybe<ElementType> {
return Maybe(raw: self.primitiveSequence.source.do(
onNext: onNext,
onError: onError,
onCompleted: onCompleted,
onSubscribe: onSubscribe,
onSubscribed: onSubscribed,
onDispose: onDispose)
)
}
/**
Filters the elements of an observable sequence based on a predicate.
- seealso: [filter operator on reactivex.io](http://reactivex.io/documentation/operators/filter.html)
- parameter predicate: A function to test each source element for a condition.
- returns: An observable sequence that contains elements from the input sequence that satisfy the condition.
*/
public func filter(_ predicate: @escaping (ElementType) throws -> Bool)
-> Maybe<ElementType> {
return Maybe(raw: self.primitiveSequence.source.filter(predicate))
}
/**
Projects each element of an observable sequence into a new form.
- seealso: [map operator on reactivex.io](http://reactivex.io/documentation/operators/map.html)
- parameter transform: A transform function to apply to each source element.
- returns: An observable sequence whose elements are the result of invoking the transform function on each element of source.
*/
public func map<R>(_ transform: @escaping (ElementType) throws -> R)
-> Maybe<R> {
return Maybe(raw: self.primitiveSequence.source.map(transform))
}
/**
Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
- seealso: [flatMap operator on reactivex.io](http://reactivex.io/documentation/operators/flatmap.html)
- parameter selector: A transform function to apply to each element.
- returns: An observable sequence whose elements are the result of invoking the one-to-many transform function on each element of the input sequence.
*/
public func flatMap<R>(_ selector: @escaping (ElementType) throws -> Maybe<R>)
-> Maybe<R> {
return Maybe<R>(raw: self.primitiveSequence.source.flatMap(selector))
}
/**
Emits elements from the source observable sequence, or a default element if the source observable sequence is empty.
- seealso: [DefaultIfEmpty operator on reactivex.io](http://reactivex.io/documentation/operators/defaultifempty.html)
- parameter default: Default element to be sent if the source does not emit any elements
- returns: An observable sequence which emits default element end completes in case the original sequence is empty
*/
public func ifEmpty(default: ElementType) -> Single<ElementType> {
return Single(raw: self.primitiveSequence.source.ifEmpty(default: `default`))
}
/**
Returns the elements of the specified sequence or `switchTo` sequence if the sequence is empty.
- seealso: [DefaultIfEmpty operator on reactivex.io](http://reactivex.io/documentation/operators/defaultifempty.html)
- parameter switchTo: Observable sequence being returned when source sequence is empty.
- returns: Observable sequence that contains elements from switchTo sequence if source is empty, otherwise returns source sequence elements.
*/
public func ifEmpty(switchTo other: Maybe<ElementType>) -> Maybe<ElementType> {
return Maybe(raw: self.primitiveSequence.source.ifEmpty(switchTo: other.primitiveSequence.source))
}
/**
Returns the elements of the specified sequence or `switchTo` sequence if the sequence is empty.
- seealso: [DefaultIfEmpty operator on reactivex.io](http://reactivex.io/documentation/operators/defaultifempty.html)
- parameter switchTo: Observable sequence being returned when source sequence is empty.
- returns: Observable sequence that contains elements from switchTo sequence if source is empty, otherwise returns source sequence elements.
*/
public func ifEmpty(switchTo other: Single<ElementType>) -> Single<ElementType> {
return Single(raw: self.primitiveSequence.source.ifEmpty(switchTo: other.primitiveSequence.source))
}
/**
Continues an observable sequence that is terminated by an error with a single element.
- seealso: [catch operator on reactivex.io](http://reactivex.io/documentation/operators/catch.html)
- parameter element: Last element in an observable sequence in case error occurs.
- returns: An observable sequence containing the source sequence's elements, followed by the `element` in case an error occurred.
*/
public func catchErrorJustReturn(_ element: ElementType)
-> PrimitiveSequence<TraitType, ElementType> {
return PrimitiveSequence(raw: self.primitiveSequence.source.catchErrorJustReturn(element))
}
}
| 44.139456 | 220 | 0.67165 |
cc9c1dc60249a1672b67204d8b01ea3f97bdb642 | 231 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
struct B {
deinit {
if true {
{
}
{
protocol P {
class
case ,
| 16.5 | 87 | 0.727273 |
017aac3d31de6965a2d32382253c914b885c459b | 3,499 | //
// QatarPaySceneWorkers.swift
// QatarPay
//
// Created by HE on 17/07/2021.
// Copyright (c) 2021 ___ORGANIZATIONNAME___. All rights reserved.
//
class QatarPaySceneWorkers {
func getToken(userName: String,
password: String,
success: @escaping (TokenModel) -> Void,
failure: @escaping (Error) -> Void) {
let router = ApiRequest.getToken(username: userName, password: password)
NetworkManager.sendRequest(router) { (statusCode, result: Result<TokenModel>) in
switch result {
case .success(let response):
success(response)
case .failure(let error):
failure(error)
}
}
}
func getQRPayment(token: String,
projectId: String,
amount: Double,
merchantId: String,
merchantDefineData: String,
merchantRefrence: String,
merchantEmail: String,
description: String,
privateKey: String,
privateKeyId: String,
secureHash: String,
success: @escaping (QRPaymentModel) -> Void,
failure: @escaping (Error) -> Void) {
let router = ApiRequest.getQrCodePaymentRequest(token: token,
projectId: projectId,
amount: amount,
merchantId: merchantId,
merchantDefineData: merchantDefineData,
merchantRefrence: merchantRefrence,
merchantEmail: merchantEmail,
description: description,
privateKey: privateKey,
privateKeyId: privateKeyId,
secureHash: secureHash)
NetworkManager.sendRequest(router) { (statusCode, result: Result<QRPaymentModel>) in
switch result {
case .success(let response):
success(response)
case .failure(let error):
failure(error)
}
}
}
func initatePayment(token: String,
pinCode: String,
email: String,
sessionId: String,
uuid: String,
success: @escaping (IniatePaymentModel) -> Void,
failure: @escaping (Error) -> Void) {
let router = ApiRequest.initiatePayment(token: token,
pinCode: pinCode,
email: email,
sessionId: sessionId,
uuid: uuid)
NetworkManager.sendRequest(router) { (statusCode, result: Result<IniatePaymentModel>) in
switch result {
case .success(let response):
success(response)
case .failure(let error):
failure(error)
}
}
}
}
| 41.164706 | 96 | 0.430123 |
50c56467c7704a07a76c472f788707c65629e97e | 18,492 | //
// ZIPFoundationWritingTests.swift
// ZIPFoundation
//
// Copyright © 2017-2021 Thomas Zoechling, https://www.peakstep.com and the ZIP Foundation project authors.
// Released under the MIT License.
//
// See https://github.com/weichsel/ZIPFoundation/blob/master/LICENSE for license information.
//
import XCTest
@testable import ZIPFoundation
extension ZIPFoundationTests {
func testCreateArchiveAddUncompressedEntry() {
let archive = self.archive(for: #function, mode: .create)
let assetURL = self.resourceURL(for: #function, pathExtension: "png")
do {
let relativePath = assetURL.lastPathComponent
let baseURL = assetURL.deletingLastPathComponent()
try archive.addEntry(with: relativePath, relativeTo: baseURL)
} catch {
XCTFail("Failed to add uncompressed entry archive with error : \(error)")
}
XCTAssert(archive.checkIntegrity())
}
func testCreateArchiveAddCompressedEntry() {
let archive = self.archive(for: #function, mode: .create)
let assetURL = self.resourceURL(for: #function, pathExtension: "png")
do {
let relativePath = assetURL.lastPathComponent
let baseURL = assetURL.deletingLastPathComponent()
try archive.addEntry(with: relativePath, relativeTo: baseURL, compressionMethod: .deflate)
} catch {
XCTFail("Failed to add compressed entry folder archive : \(error)")
}
let entry = archive[assetURL.lastPathComponent]
XCTAssertNotNil(entry)
XCTAssert(archive.checkIntegrity())
}
func testCreateArchiveAddDirectory() {
let archive = self.archive(for: #function, mode: .create)
do {
try archive.addEntry(with: "Test", type: .directory,
uncompressedSize: 0, provider: { _, _ in return Data()})
} catch {
XCTFail("Failed to add directory entry without file system representation to archive.")
}
let testEntry = archive["Test"]
XCTAssertNotNil(testEntry)
let uniqueString = ProcessInfo.processInfo.globallyUniqueString
let tempDirectoryURL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(uniqueString)
do {
let fileManager = FileManager()
try fileManager.createDirectory(at: tempDirectoryURL, withIntermediateDirectories: true, attributes: nil)
let relativePath = tempDirectoryURL.lastPathComponent
let baseURL = tempDirectoryURL.deletingLastPathComponent()
try archive.addEntry(with: relativePath + "/", relativeTo: baseURL)
} catch {
XCTFail("Failed to add directory entry to archive.")
}
let entry = archive[tempDirectoryURL.lastPathComponent + "/"]
XCTAssertNotNil(entry)
XCTAssert(archive.checkIntegrity())
}
func testCreateArchiveAddSymbolicLink() {
let archive = self.archive(for: #function, mode: .create)
let rootDirectoryURL = ZIPFoundationTests.tempZipDirectoryURL.appendingPathComponent("SymbolicLinkDirectory")
let symbolicLinkURL = rootDirectoryURL.appendingPathComponent("test.link")
let assetURL = self.resourceURL(for: #function, pathExtension: "png")
let fileManager = FileManager()
do {
try fileManager.createDirectory(at: rootDirectoryURL, withIntermediateDirectories: true, attributes: nil)
try fileManager.createSymbolicLink(atPath: symbolicLinkURL.path, withDestinationPath: assetURL.path)
let relativePath = symbolicLinkURL.lastPathComponent
let baseURL = symbolicLinkURL.deletingLastPathComponent()
try archive.addEntry(with: relativePath, relativeTo: baseURL)
} catch {
XCTFail("Failed to add symbolic link to archive")
}
let entry = archive[symbolicLinkURL.lastPathComponent]
XCTAssertNotNil(entry)
XCTAssert(archive.checkIntegrity())
do {
try archive.addEntry(with: "link", type: .symlink, uncompressedSize: 10, provider: { (_, count) -> Data in
return Data(count: count)
})
} catch {
XCTFail("Failed to add symbolic link to archive")
}
let entry2 = archive["link"]
XCTAssertNotNil(entry2)
XCTAssert(archive.checkIntegrity())
}
func testCreateArchiveAddEntryErrorConditions() {
var didCatchExpectedError = false
let archive = self.archive(for: #function, mode: .create)
let tempPath = NSTemporaryDirectory()
var nonExistantURL = URL(fileURLWithPath: tempPath)
nonExistantURL.appendPathComponent("invalid.path")
let nonExistantRelativePath = nonExistantURL.lastPathComponent
let nonExistantBaseURL = nonExistantURL.deletingLastPathComponent()
do {
try archive.addEntry(with: nonExistantRelativePath, relativeTo: nonExistantBaseURL)
} catch let error as CocoaError {
XCTAssert(error.code == .fileReadNoSuchFile)
didCatchExpectedError = true
} catch {
XCTFail("Unexpected error while trying to add non-existant file to an archive.")
}
XCTAssertTrue(didCatchExpectedError)
// Cover the error code path when `fopen` fails during entry addition.
let assetURL = self.resourceURL(for: #function, pathExtension: "txt")
self.runWithFileDescriptorLimit(0) {
do {
let relativePath = assetURL.lastPathComponent
let baseURL = assetURL.deletingLastPathComponent()
try archive.addEntry(with: relativePath, relativeTo: baseURL)
} catch {
didCatchExpectedError = true
}
}
XCTAssertTrue(didCatchExpectedError)
}
func testArchiveAddEntryErrorConditions() {
var didCatchExpectedError = false
let readonlyArchive = self.archive(for: #function, mode: .read)
do {
try readonlyArchive.addEntry(with: "Test", type: .directory,
uncompressedSize: 0, provider: { _, _ in return Data()})
} catch let error as Archive.ArchiveError {
XCTAssert(error == .unwritableArchive)
didCatchExpectedError = true
} catch {
XCTFail("Unexpected error while trying to add an entry to a readonly archive.")
}
XCTAssertTrue(didCatchExpectedError)
}
func testCreateArchiveAddZeroSizeUncompressedEntry() {
let archive = self.archive(for: #function, mode: .create)
let assetURL = self.resourceURL(for: #function, pathExtension: "txt")
do {
let relativePath = assetURL.lastPathComponent
let baseURL = assetURL.deletingLastPathComponent()
try archive.addEntry(with: relativePath, relativeTo: baseURL)
} catch {
XCTFail("Failed to add zero-size uncompressed entry to archive with error : \(error)")
}
let entry = archive[assetURL.lastPathComponent]
XCTAssertNotNil(entry)
XCTAssert(archive.checkIntegrity())
}
func testCreateArchiveAddZeroSizeCompressedEntry() {
let archive = self.archive(for: #function, mode: .create)
let assetURL = self.resourceURL(for: #function, pathExtension: "txt")
do {
let relativePath = assetURL.lastPathComponent
let baseURL = assetURL.deletingLastPathComponent()
try archive.addEntry(with: relativePath, relativeTo: baseURL, compressionMethod: .deflate)
} catch {
XCTFail("Failed to add zero-size compressed entry to archive with error : \(error)")
}
let entry = archive[assetURL.lastPathComponent]
XCTAssertNotNil(entry)
XCTAssert(archive.checkIntegrity())
}
func testCreateArchiveAddLargeUncompressedEntry() {
let archive = self.archive(for: #function, mode: .create)
let size = 1024*1024*20
let data = Data.makeRandomData(size: size)
let entryName = ProcessInfo.processInfo.globallyUniqueString
do {
try archive.addEntry(with: entryName, type: .file,
uncompressedSize: UInt32(size), provider: { (position, bufferSize) -> Data in
let upperBound = Swift.min(size, position + bufferSize)
let range = Range(uncheckedBounds: (lower: position, upper: upperBound))
return data.subdata(in: range)
})
} catch {
XCTFail("Failed to add large entry to uncompressed archive with error : \(error)")
}
guard let entry = archive[entryName] else {
XCTFail("Failed to add large entry to uncompressed archive")
return
}
XCTAssert(entry.checksum == data.crc32(checksum: 0))
XCTAssert(archive.checkIntegrity())
}
func testCreateArchiveAddLargeCompressedEntry() {
let archive = self.archive(for: #function, mode: .create)
let size = 1024*1024*20
let data = Data.makeRandomData(size: size)
let entryName = ProcessInfo.processInfo.globallyUniqueString
do {
try archive.addEntry(with: entryName, type: .file, uncompressedSize: UInt32(size),
compressionMethod: .deflate,
provider: { (position, bufferSize) -> Data in
let upperBound = Swift.min(size, position + bufferSize)
let range = Range(uncheckedBounds: (lower: position, upper: upperBound))
return data.subdata(in: range)
})
} catch {
XCTFail("Failed to add large entry to compressed archive with error : \(error)")
}
guard let entry = archive[entryName] else {
XCTFail("Failed to add large entry to compressed archive")
return
}
let dataCRC32 = data.crc32(checksum: 0)
XCTAssert(entry.checksum == dataCRC32)
XCTAssert(archive.checkIntegrity())
}
func testCreateArchiveAddTooLargeUncompressedEntry() {
let archive = self.archive(for: #function, mode: .create)
let fileName = ProcessInfo.processInfo.globallyUniqueString
var didCatchExpectedError = false
do {
try archive.addEntry(with: fileName, type: .file, uncompressedSize: UINT32_MAX,
provider: { (_, chunkSize) -> Data in
return Data(count: chunkSize)
})
} catch let error as Archive.ArchiveError {
XCTAssertNotNil(error == .invalidStartOfCentralDirectoryOffset)
didCatchExpectedError = true
} catch {
XCTFail("Unexpected error while trying to add an entry exceeding maximum size.")
}
XCTAssert(didCatchExpectedError)
}
func testRemoveUncompressedEntry() {
let archive = self.archive(for: #function, mode: .update)
guard let entryToRemove = archive["test/data.random"] else {
XCTFail("Failed to find entry to remove in uncompressed folder"); return
}
do {
try archive.remove(entryToRemove)
} catch {
XCTFail("Failed to remove entry from uncompressed folder archive with error : \(error)")
}
XCTAssert(archive.checkIntegrity())
}
func testRemoveCompressedEntry() {
let archive = self.archive(for: #function, mode: .update)
guard let entryToRemove = archive["test/data.random"] else {
XCTFail("Failed to find entry to remove in compressed folder archive"); return
}
do {
try archive.remove(entryToRemove)
} catch {
XCTFail("Failed to remove entry from compressed folder archive with error : \(error)")
}
XCTAssert(archive.checkIntegrity())
}
func testRemoveDataDescriptorCompressedEntry() {
let archive = self.archive(for: #function, mode: .update)
guard let entryToRemove = archive["second.txt"] else {
XCTFail("Failed to find entry to remove in compressed folder archive")
return
}
do {
try archive.remove(entryToRemove)
} catch {
XCTFail("Failed to remove entry to compressed folder archive with error : \(error)")
}
XCTAssert(archive.checkIntegrity())
}
func testRemoveEntryErrorConditions() {
var didCatchExpectedError = false
let archive = self.archive(for: #function, mode: .update)
guard let entryToRemove = archive["test/data.random"] else {
XCTFail("Failed to find entry to remove in uncompressed folder")
return
}
// We don't have access to the temp archive file that Archive.remove
// uses. To exercise the error code path, we temporarily limit the number of open files for
// the test process to exercise the error code path here.
self.runWithFileDescriptorLimit(0) {
do {
try archive.remove(entryToRemove)
} catch let error as Archive.ArchiveError {
XCTAssertNotNil(error == .unwritableArchive)
didCatchExpectedError = true
} catch {
XCTFail("Unexpected error while trying to remove entry from unwritable archive.")
}
}
XCTAssertTrue(didCatchExpectedError)
didCatchExpectedError = false
let readonlyArchive = self.archive(for: #function, mode: .read)
do {
try readonlyArchive.remove(entryToRemove)
} catch let error as Archive.ArchiveError {
XCTAssertNotNil(error == .unwritableArchive)
didCatchExpectedError = true
} catch {
XCTFail("Unexpected error while trying to remove entry from readonly archive.")
}
XCTAssertTrue(didCatchExpectedError)
}
func testArchiveCreateErrorConditions() {
let existantURL = ZIPFoundationTests.tempZipDirectoryURL
let nonCreatableArchive = Archive(url: existantURL, accessMode: .create)
XCTAssertNil(nonCreatableArchive)
let processInfo = ProcessInfo.processInfo
var noEndOfCentralDirectoryArchiveURL = ZIPFoundationTests.tempZipDirectoryURL
noEndOfCentralDirectoryArchiveURL.appendPathComponent(processInfo.globallyUniqueString)
let fullPermissionAttributes = [FileAttributeKey.posixPermissions: NSNumber(value: defaultFilePermissions)]
let fileManager = FileManager()
let result = fileManager.createFile(atPath: noEndOfCentralDirectoryArchiveURL.path, contents: nil,
attributes: fullPermissionAttributes)
XCTAssert(result == true)
let noEndOfCentralDirectoryArchive = Archive(url: noEndOfCentralDirectoryArchiveURL,
accessMode: .update)
XCTAssertNil(noEndOfCentralDirectoryArchive)
}
func testArchiveUpdateErrorConditions() {
var nonUpdatableArchiveURL = ZIPFoundationTests.tempZipDirectoryURL
let processInfo = ProcessInfo.processInfo
nonUpdatableArchiveURL.appendPathComponent(processInfo.globallyUniqueString)
let noPermissionAttributes = [FileAttributeKey.posixPermissions: NSNumber(value: Int16(0o000))]
let fileManager = FileManager()
let result = fileManager.createFile(atPath: nonUpdatableArchiveURL.path, contents: nil,
attributes: noPermissionAttributes)
XCTAssert(result == true)
let nonUpdatableArchive = Archive(url: nonUpdatableArchiveURL, accessMode: .update)
XCTAssertNil(nonUpdatableArchive)
}
func testReplaceCurrentArchiveWithArchiveCrossLink() {
#if os(macOS)
let createVolumeExpectation = expectation(description: "Creation of temporary additional volume")
let unmountVolumeExpectation = expectation(description: "Unmount temporary additional volume")
let tempDir = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(UUID().uuidString)
do {
try FileManager.default.createDirectory(at: tempDir, withIntermediateDirectories: true, attributes: nil)
let volName = "Test_\(UUID().uuidString)"
let task = try NSUserScriptTask.makeVolumeCreationTask(at: tempDir, volumeName: volName)
task.execute { (error) in
guard error == nil else {
XCTFail("\(String(describing: error))")
return
}
let vol2URL = URL(fileURLWithPath: "/Volumes/\(volName)")
defer {
FileManager.default.unmountVolume(at: vol2URL, options:
[.allPartitionsAndEjectDisk, .withoutUI], completionHandler: { (error) in
guard error == nil else {
XCTFail("\(String(describing: error))")
return
}
unmountVolumeExpectation.fulfill()
})
}
let vol1ArchiveURL = tempDir.appendingPathComponent("vol1Archive")
let vol2ArchiveURL = vol2URL.appendingPathComponent("vol2Archive")
guard let vol1Archive = Archive(url: vol1ArchiveURL, accessMode: .create),
let vol2Archive = Archive(url: vol2ArchiveURL, accessMode: .create) else {
XCTFail("Failed to create test archive '\(vol2ArchiveURL)'")
type(of: self).tearDown()
return
}
do {
try vol1Archive.replaceCurrentArchiveWithArchive(at: vol2Archive.url)
} catch {
XCTFail("\(String(describing: error))")
return
}
createVolumeExpectation.fulfill()
}
} catch {
XCTFail("\(error)")
return
}
defer { try? FileManager.default.removeItem(at: tempDir) }
waitForExpectations(timeout: 30.0)
#endif
}
}
| 46.579345 | 118 | 0.624108 |
f70a414b799f9808d1f514e02a6c1896ccff2870 | 2,065 | //
// StarRewardsRow.swift
// TortaCafe
//
// Created by Denis Sheikherev on 05.05.2021.
//
import UIKit
class StarRewardsRow: UIView {
let starAndPoints = StarAndPointsView()
let descriptionLabel = UILabel()
init(numberOfPoints: String, description: String) {
starAndPoints.pointsLabel.text = numberOfPoints
descriptionLabel.text = description
super.init(frame: .zero)
style()
layout()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func style() {
descriptionLabel.font = UIFont.preferredFont(forTextStyle: .footnote)
descriptionLabel.numberOfLines = 0
descriptionLabel.lineBreakMode = .byWordWrapping
descriptionLabel.sizeToFit()
}
func layout() {
addSubviewsUsingAutoLayout(starAndPoints, descriptionLabel)
NSLayoutConstraint.activate([
starAndPoints.topAnchor.constraint(equalTo: topAnchor),
starAndPoints.bottomAnchor.constraint(equalTo: bottomAnchor),
starAndPoints.leadingAnchor.constraint(equalTo: leadingAnchor),
descriptionLabel.topAnchor.constraint(equalTo: topAnchor),
descriptionLabel.leadingAnchor.constraint(equalTo: starAndPoints.trailingAnchor, constant: 4),
descriptionLabel.trailingAnchor.constraint(equalTo: trailingAnchor),
descriptionLabel.bottomAnchor.constraint(equalTo: bottomAnchor),
])
starAndPoints.setContentHuggingPriority(.defaultHigh, for: .horizontal)
descriptionLabel.heightAnchor.constraint(equalToConstant: descriptionLabel.frame.size.height).setActiveBreakable()
}
override var intrinsicContentSize: CGSize {
return CGSize(width: 10, height: 16)
}
}
public extension NSLayoutConstraint {
@objc func setActiveBreakable(priority: UILayoutPriority = UILayoutPriority(900)) {
self.priority = priority
isActive = true
}
}
| 31.769231 | 122 | 0.674092 |
ac4d08d3b5243309109760fafbe0b22d963b4282 | 4,912 | // PickerInputRow.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2016 Xmartlabs SRL ( http://xmartlabs.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 Foundation
//MARK: PickerInputCell
open class PickerInputCell<T: Equatable> : Cell<T>, CellType, UIPickerViewDataSource, UIPickerViewDelegate where T: Equatable, T: InputTypeInitiable {
public var picker: UIPickerView
private var pickerInputRow : _PickerInputRow<T>? { return row as? _PickerInputRow<T> }
public required init(style: UITableViewCellStyle, reuseIdentifier: String?){
self.picker = UIPickerView()
self.picker.translatesAutoresizingMaskIntoConstraints = false
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open override func setup() {
super.setup()
accessoryType = .none
editingAccessoryType = .none
picker.delegate = self
picker.dataSource = self
}
deinit {
picker.delegate = nil
picker.dataSource = nil
}
open override func update(){
super.update()
selectionStyle = row.isDisabled ? .none : .default
if row.title?.isEmpty == false {
detailTextLabel?.text = row.displayValueFor?(row.value) ?? (row as? NoValueDisplayTextConformance)?.noValueDisplayText
}
else {
textLabel?.text = row.displayValueFor?(row.value) ?? (row as? NoValueDisplayTextConformance)?.noValueDisplayText
detailTextLabel?.text = nil
}
textLabel?.textColor = row.isDisabled ? .gray : .black
if row.isHighlighted {
textLabel?.textColor = tintColor
}
picker.reloadAllComponents()
if let selectedValue = pickerInputRow?.value, let index = pickerInputRow?.options.index(of: selectedValue){
picker.selectRow(index, inComponent: 0, animated: true)
}
}
open override func didSelect() {
super.didSelect()
row.deselect()
}
open override var inputView: UIView? {
return picker
}
open override func cellCanBecomeFirstResponder() -> Bool {
return canBecomeFirstResponder
}
override open var canBecomeFirstResponder: Bool {
return !row.isDisabled
}
open func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
open func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return pickerInputRow?.options.count ?? 0
}
open func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return pickerInputRow?.displayValueFor?(pickerInputRow?.options[row])
}
open func pickerView(_ pickerView: UIPickerView, didSelectRow rowNumber: Int, inComponent component: Int) {
if let picker = pickerInputRow, picker.options.count > rowNumber {
picker.value = picker.options[rowNumber]
update()
}
}
}
//MARK: PickerInputRow
open class _PickerInputRow<T> : Row<PickerInputCell<T>>, NoValueDisplayTextConformance where T: Equatable, T: InputTypeInitiable {
open var noValueDisplayText: String? = nil
open var options = [T]()
required public init(tag: String?) {
super.init(tag: tag)
}
}
/// A generic row where the user can pick an option from a picker view displayed in the keyboard area
public final class PickerInputRow<T>: _PickerInputRow<T>, RowType where T: Equatable, T: InputTypeInitiable {
required public init(tag: String?) {
super.init(tag: tag)
}
}
| 34.836879 | 150 | 0.670603 |
e57b881ad36858fc7560d8f2b0075d9d6c39dde0 | 1,921 | //
// Copyright (c) 2019-Present Umobi - https://github.com/umobi
//
// 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
@frozen
public struct ColorGrayModifier<Color: ColorType>: ColorModifierType {
private let frozedComponent: ColorComponents
public init(_ color: Color) {
self.frozedComponent = color.components
}
public init?(hex: String) {
guard let components = ColorComponents(hex: hex) else {
return nil
}
self.frozedComponent = components
}
public var components: ColorComponents {
let components = self.frozedComponent
guard !components.isGrayScale else {
return components
}
let grayAvg = (components.red + components.blue + components.green) / 3.0
return .init(red: grayAvg, green: grayAvg, blue: grayAvg, alpha: components.alpha)
}
}
| 36.245283 | 90 | 0.716814 |
cc0da256647eddfac4c3bbb0bf75aab94f7fc19a | 101 | //
// RoomKitDelegate.swift
// Nimble
//
// Created by John Kotz on 2/5/18.
//
import Foundation
| 11.222222 | 35 | 0.643564 |
215c88fc5cd30080c7e7500ebcdc90baac89f78c | 23,870 | //
// SGTagsView.swift
// Flower
//
// Created by kingsic on 2020/11/5.
// Copyright © 2020 kingsic. All rights reserved.
//
import UIKit
/// Tag layout style: uniform vertical style, adaptive vertical style and horizontal style
public enum SGTagsStyle {
case equableVertical, vertical, horizontal
}
/// Position of tag content level
public enum SGTagContentHorizontalAlignment {
case center, left, right
}
/// The position of the image in the tag relative to the text
public enum SGImagePositionStyle {
case left, right, top, bottom
}
public class SGTagsViewConfigure: NSObject {
/// default false. if true, bounces past edge of content and back again
public var isBounces = false
/// default true. show indicator while we are tracking. fades out after tracking
public var isShowsVerticalScrollIndicator: Bool = true
/// default true. show indicator while we are tracking. fades out after tracking
public var isShowsHorizontalScrollIndicator: Bool = true
/// The tag layout style is equal vertical by default
public var style: SGTagsStyle = .equableVertical
/// Whether the tag can be selected, the default is true
public var isSelected = true
/// Whether the tag supports multiple selection. The default value is false
public var isMultipleSelect = false
/// The font size of tag text is 15 point font by default
public var font: UIFont = .systemFont(ofSize: 15)
/// In normal state, the color of tag text is black by default
public var color: UIColor = .black
/// In the selected state, the color of tag text is red by default
public var selectedColor: UIColor = .black
/// By default, the color is light gray
public var backgroundColor: UIColor = UIColor(white: 0.92, alpha: 1.0)
/// In the selected state, the tag background color is white by default
public var selectedBackgroundColor: UIColor = .white
/// Tag border width, the default is 0.0f
public var borderWidth: CGFloat = 0.0
/// In normal state, the color of tag border is white by default
public var borderColor: UIColor = .white
/// When selected, the color of tag border is red by default
public var selectedBorderColor: UIColor = .red
/// Tag fillet size, the default is 0.0f
public var cornerRadius: CGFloat = 0.0
/// The horizontal spacing between tags is 20.0f by default
public var horizontalSpacing: CGFloat = 20.0
/// The space between vertical tags is 20.0f by default
public var verticalSpacing: CGFloat = 20.0
/// The additional width of the tag. This width refers to the width beyond the tag text. The default value is 40.0f
public var additionalWidth: CGFloat = 40.0
/// In vertical style, the height of the tag is 30.0f by default
public var height: CGFloat = 30.0
/// In the equal style, the number of columns in each row of the tag is 3 by default
public var column: Int = 3
/// The distance between the tag and the inner edge of the parent view is 10 by default
public var contentInset: UIEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
/// The horizontal position of the tag content. The default is center
public var contentHorizontalAlignment: SGTagContentHorizontalAlignment = .center
/// When contenthorizontalalignment = left or right, the inner margin of the content is 5.0f by default
public var padding: CGFloat = 5.0
}
private class SGTagButton: UIButton {
override var isHighlighted: Bool {
set {}
get {return false}
}
}
public class SGTagsView: UIView {
public init(frame: CGRect, configure: SGTagsViewConfigure) {
super.init(frame: frame)
self.configure = configure
addSubview(contentView)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/// Tag titles
public var tags: Array<String>? {
didSet {
setupTags()
}
}
/// When initializing a tag, the tag subscript is selected by default (when multipleselect = no, only the tag corresponding to the last value is supported)
public var tagIndexs: Array<Int>? {
didSet {
guard let tempTagIndexs = tagIndexs else {
return
}
if tempTagIndexs.count == 0 {
return
}
for i in tempTagIndexs {
guard let btns = tempBtns else {
return
}
if btns.count == 0 {
return
}
tag_action(btn: btns[i])
}
}
}
/// In the equable vertical and vertical styles, whether to fix the height of the initial frame is set to false by default; if it is true, the content will scroll if it exceeds the height of the initial frame
public var isFixedHeight: Bool = false
public typealias SGTagsViewHeightBlock = (_ tagsView: SGTagsView, _ height: CGFloat) -> ()
private var heightBlock: SGTagsViewHeightBlock?
/// When isFixedheight = false, the callback function of SGTagsView height is returned after the tag layout is completed in equable Vertical and vertical styles
public func heightBlock(heightBlock: @escaping SGTagsViewHeightBlock) {
self.heightBlock = heightBlock;
}
public typealias SGTagsViewSingleSelectBlock = (_ tagsView: SGTagsView, _ tag: String, _ index: Int) -> ()
private var singleSelectBlock: SGTagsViewSingleSelectBlock?
/// Tag single selection callback function
public func singleSelectBlock(singleSelectBlock: @escaping SGTagsViewSingleSelectBlock) {
self.singleSelectBlock = singleSelectBlock
}
public typealias SGTagsViewMultipleSelectBlock = (_ tagsView: SGTagsView, _ tags: Array<Any>, _ index: Array<Int>) -> ()
private var multipleSelectBlock: SGTagsViewMultipleSelectBlock?
/// Tag multiple selection callback function
public func multipleSelectBlock(multipleSelectBlock: @escaping SGTagsViewMultipleSelectBlock) {
self.multipleSelectBlock = multipleSelectBlock
}
// MARK: 内部辅助属性
private var configure: SGTagsViewConfigure!
private lazy var contentView: UIScrollView = {
let tempContentView = UIScrollView()
tempContentView.bounces = configure.isBounces;
return tempContentView
}()
private var tempBtns: Array<SGTagButton>? = []
private var tempRow = 1
private var bodyBtns: Array<SGTagButton>? = []
private var tempBtn: UIButton?
private var previousBtn: UIButton?
private var titles: Array<String> = []
private var indexs: Array<Int> = []
public override func layoutSubviews() {
let x: CGFloat = 0
let y: CGFloat = 0
let width = frame.size.width
let height = frame.size.height
contentView.frame = CGRect.init(x: x, y: y, width: width, height: height)
if configure.style == .vertical {
layoutTagsVerticalStyle()
} else if configure.style == .horizontal {
layoutTagsHorizontalStyle()
} else {
layoutTagsEquableVerticalStyle()
}
}
}
// MARK: 给外界提供的方法
public extension SGTagsView {
/// Set tags image
///
/// Support local and network images
///
/// - parameter names: Tag images name
/// - parameter imagePositionStyle: Position of image relative to text
/// - parameter spacing: Space between image and text
func setImage(names: Array<String>, imagePositionStyle: SGImagePositionStyle, spacing: CGFloat) {
guard let btns = tempBtns else {
return
}
if btns.count == 0 {
return
}
if names.count < btns.count {
for (index, btn) in btns.enumerated() {
if index >= names.count {
return
}
setTagImage(btn: btn, imageName: names[index], imagePositionStyle: imagePositionStyle, spacing: spacing)
}
} else {
for (index, btn) in btns.enumerated() {
setTagImage(btn: btn, imageName: names[index], imagePositionStyle: imagePositionStyle, spacing: spacing)
}
}
}
/// Set the tag image according to the subscript
///
/// Support local and network images
///
/// - parameter names: Tag image name
/// - parameter imagePositionStyle: Position of image relative to text
/// - parameter spacing: Space between image and text
/// - parameter index: Tag subscript
func setImage(name: String, imagePositionStyle: SGImagePositionStyle, spacing: CGFloat, index: Int) {
guard let btns = tempBtns else {
return
}
if btns.count == 0 {
return
}
let btn = btns[index]
setTagImage(btn: btn, imageName: name, imagePositionStyle: imagePositionStyle, spacing: spacing)
}
/// Set inactive tags according to the subscript
///
/// - parameter alpha: Tag alpha
/// - parameter color: Tag title color
/// - parameter index: Tag subscript
func setUnEnabled(alpha: CGFloat = 0.8, color: UIColor = .gray, index: Int) {
guard let btns = tempBtns else {
return
}
if btns.count == 0 {
return
}
let btn = btns[index]
btn.isEnabled = false
btn.alpha = alpha
btn.layer.borderWidth = 0.01
btn.layer.borderColor = UIColor.clear.cgColor
btn.setTitleColor(color, for: .normal)
}
}
// MARK: - 辅助标签设置 image 的方法
private extension SGTagsView {
func setupTags() {
guard let tempTags = tags else { return }
if tempTags.count == 0 { return }
for (index, obj) in tempTags.enumerated() {
let btn = SGTagButton()
btn.tag = index
btn.titleLabel?.font = configure.font
btn.setTitle(obj, for: .normal)
btn.setTitleColor(configure.color, for: .normal)
btn.setTitleColor(configure.selectedColor, for: .selected)
btn.backgroundColor = configure.backgroundColor
if configure.isSelected {
btn.addTarget(self, action: #selector(tag_action(btn:)), for: .touchUpInside)
}
if configure.borderWidth > 2.0 {
btn.layer.borderWidth = 2
} else {
btn.layer.borderWidth = configure.borderWidth
}
if configure.cornerRadius > 0.5 * configure.height {
btn.layer.cornerRadius = 0.5 * configure.height
} else {
btn.layer.cornerRadius = configure.cornerRadius
}
btn.layer.borderColor = configure.borderColor.cgColor
if configure.contentHorizontalAlignment == .left {
btn.contentHorizontalAlignment = .left
btn.contentEdgeInsets = UIEdgeInsets(top: 0, left: configure.contentInset.left, bottom: 0, right: 0)
} else if configure.contentHorizontalAlignment == .right {
btn.contentHorizontalAlignment = .right
btn.contentEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: configure.contentInset.right)
}
contentView.addSubview(btn)
tempBtns!.append(btn)
bodyBtns!.append(btn)
}
}
func setTagImage(btn: UIButton, imageName: String, imagePositionStyle: SGImagePositionStyle, spacing: CGFloat) {
if imageName.hasPrefix("http") {
loadImage(urlString: imageName) { (image) in
btn.setImage(image, for: .normal)
self.setImage(btn: btn, imagePositionStyle: imagePositionStyle, spacing: spacing)
}
} else {
btn.setImage(UIImage.init(named: imageName), for: .normal)
setImage(btn: btn, imagePositionStyle: imagePositionStyle, spacing: spacing)
}
}
}
// MARK: - 标签点击事件相关逻辑方法处理
private extension SGTagsView {
@objc func tag_action(btn: SGTagButton) {
if configure.isMultipleSelect {
btn.isSelected = !btn.isSelected
if btn.isSelected {
btn.backgroundColor = configure.selectedBackgroundColor
btn.layer.borderColor = configure.selectedBorderColor.cgColor
btn.setTitleColor(configure.selectedColor, for: .normal)
titles.append(btn.titleLabel!.text!)
indexs.append(btn.tag)
} else {
btn.backgroundColor = configure.backgroundColor
btn.layer.borderColor = configure.borderColor.cgColor
btn.setTitleColor(configure.color, for: .normal)
titles.removeAll{$0 == btn.titleLabel!.text!}
indexs.removeAll{$0 == btn.tag}
}
if let tempMultipleSelectBlock = multipleSelectBlock {
tempMultipleSelectBlock(self, titles, indexs)
}
if contentView.contentSize.width > contentView.frame.size.width {
selectedBtnCenter(btn: btn)
}
} else {
changeSelectedBtn(btn: btn)
if let tempSingleSelectBlock = singleSelectBlock {
tempSingleSelectBlock(self, btn.titleLabel!.text!, btn.tag)
}
if contentView.contentSize.width > contentView.frame.size.width {
selectedBtnCenter(btn: btn)
}
}
}
func changeSelectedBtn(btn: UIButton) {
if tempBtn == nil {
btn.isSelected = true
tempBtn = btn
} else if tempBtn != nil && tempBtn == btn {
btn.isSelected = true
} else if tempBtn != nil && tempBtn != btn {
tempBtn!.isSelected = false
btn.isSelected = true
tempBtn = btn
}
if previousBtn != nil {
previousBtn?.backgroundColor = configure.backgroundColor
previousBtn?.layer.borderColor = configure.borderColor.cgColor
previousBtn?.setTitleColor(configure.color, for: .normal)
}
btn.backgroundColor = configure.selectedBackgroundColor
btn.layer.borderColor = configure.selectedBorderColor.cgColor
btn.setTitleColor(configure.selectedColor, for: .normal)
previousBtn = btn
}
func selectedBtnCenter(btn: UIButton) {
var offsetX = btn.center.x - contentView.frame.size.width * 0.5
if offsetX < 0 {
offsetX = 0
}
let maxOffsetX = contentView.contentSize.width - contentView.frame.size.width
if offsetX > maxOffsetX {
offsetX = maxOffsetX
}
contentView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: true)
}
}
// MARK: - 标签布局相关方法处理
private extension SGTagsView {
func layoutTagsVerticalStyle() {
auxLayoutTagsVerticalStyle()
guard let btns = tempBtns else { return }
if btns.count == 0 { return }
let lastBtn: SGTagButton = btns.last!
let contentViewHeight = lastBtn.frame.maxY + configure.contentInset.bottom
if isFixedHeight {
if contentViewHeight < contentView.frame.size.height {
contentView.contentSize = CGSize(width: contentView.frame.size.width, height: contentView.frame.size.height)
} else {
contentView.contentSize = CGSize(width: contentView.frame.size.width, height: contentViewHeight)
contentView.showsVerticalScrollIndicator = configure.isShowsVerticalScrollIndicator
}
} else {
contentView.frame.size.height = contentViewHeight
frame.size.height = contentViewHeight
if let tempHeightBlcok = heightBlock {
tempHeightBlcok(self, contentViewHeight)
}
}
}
func auxLayoutTagsVerticalStyle() {
guard let btns = bodyBtns else {
return
}
if btns.count == 0 {
return
}
var btnX = configure.contentInset.left
let btnY = CGFloat((tempRow - 1)) * (configure.verticalSpacing + configure.height)
+ configure.contentInset.top
let btnH = configure.height
let contentViewWidth = contentView.frame.size.width
for (index, btn) in btns.enumerated() {
let str_width = calculateWidth(str: btn.currentTitle!, font: configure.font)
let btnW = str_width + configure.additionalWidth
btn.frame = CGRect.init(x: btnX, y: btnY, width: btnW, height: btnH)
btnX = btn.frame.maxX + configure.horizontalSpacing
if btnX > contentViewWidth {
tempRow += 1
for _ in 0..<index {
bodyBtns?.removeFirst()
}
auxLayoutTagsVerticalStyle()
return
}
}
}
func layoutTagsHorizontalStyle() {
guard let btns = tempBtns else { return }
if btns.count == 0 { return }
var btnX = configure.contentInset.left
let btnY = configure.contentInset.top
let btnH = contentView.frame.size.height - btnY - configure.contentInset.bottom
for (_, btn) in btns.enumerated() {
let str_width = calculateWidth(str: btn.currentTitle!, font: configure.font)
let btnW = str_width + configure.additionalWidth
btn.frame = CGRect.init(x: btnX, y: btnY, width: btnW, height: btnH)
btnX = btn.frame.maxX + configure.horizontalSpacing
}
let lastBtn: SGTagButton = btns.last!
let lastBtnMaxX = lastBtn.frame.maxX
let allContentWidth = lastBtnMaxX + configure.contentInset.right
if allContentWidth < contentView.frame.size.width {
contentView.contentSize = CGSize(width: contentView.frame.size.width, height: btnH)
} else {
contentView.contentSize = CGSize(width: allContentWidth, height: btnH)
contentView.showsHorizontalScrollIndicator = configure.isShowsHorizontalScrollIndicator
}
}
func layoutTagsEquableVerticalStyle() {
guard let btns = tempBtns else { return }
if btns.count == 0 { return }
var btnX: CGFloat = 0.0
var btnY: CGFloat = 0.0
let btnW = (contentView.frame.size.width - configure.contentInset.left - configure.contentInset.right - CGFloat((configure.column - 1)) * configure.horizontalSpacing) / CGFloat(configure.column)
let btnH = configure.height
for (index, btn) in btns.enumerated() {
btnX = CGFloat((index % configure.column)) * (btnW + configure.horizontalSpacing) + configure.contentInset.left
btnY = CGFloat((index / configure.column)) * (btnH + configure.verticalSpacing) + configure.contentInset.top
btn.frame = CGRect.init(x: btnX, y: btnY, width: btnW, height: btnH)
}
let lastBtn: SGTagButton = btns.last!
let contentViewHeight = lastBtn.frame.maxY + configure.contentInset.bottom
if isFixedHeight {
if contentViewHeight < contentView.frame.size.height {
contentView.contentSize = CGSize(width: contentView.frame.size.width, height: contentView.frame.size.height)
} else {
contentView.contentSize = CGSize(width: contentView.frame.size.width, height: contentViewHeight)
contentView.showsVerticalScrollIndicator = configure.isShowsVerticalScrollIndicator
}
} else {
contentView.frame.size.height = contentViewHeight
frame.size.height = contentViewHeight
if let tempHeightBlcok = heightBlock {
tempHeightBlcok(self, contentViewHeight)
}
}
}
}
// MARK: - 内部相关方法抽取
private extension SGTagsView {
/// 计算字符串的宽度
func calculateWidth(str: String, font: UIFont) -> CGFloat {
let attrs = [NSAttributedString.Key.font: font]
let rect = (str as NSString).boundingRect(with: CGSize(width: 0, height: 0), options: .usesLineFragmentOrigin, attributes: attrs, context: nil)
return rect.size.width
}
/// 设置 UIButton 内部的 UIImageView 相对 UITitleLabel 的位置
func setImage(btn: UIButton, imagePositionStyle: SGImagePositionStyle, spacing: CGFloat) {
let imgView_width = btn.imageView?.frame.size.width
let imgView_height = btn.imageView?.frame.size.height
let titleLab_iCSWidth = btn.titleLabel?.intrinsicContentSize.width
let titleLab_iCSHeight = btn.titleLabel?.intrinsicContentSize.height
switch imagePositionStyle {
case .left:
if btn.contentHorizontalAlignment == .left {
btn.titleEdgeInsets = UIEdgeInsets.init(top: 0, left: spacing, bottom: 0, right: 0)
} else if btn.contentHorizontalAlignment == .right {
btn.imageEdgeInsets = UIEdgeInsets.init(top: 0, left: 0, bottom: 0, right: spacing)
} else {
let spacing_half = 0.5 * spacing;
btn.imageEdgeInsets = UIEdgeInsets.init(top: 0, left: -spacing_half, bottom: 0, right: spacing_half)
btn.titleEdgeInsets = UIEdgeInsets.init(top: 0, left: spacing_half, bottom: 0, right: -spacing_half)
}
case .right:
let titleLabWidth = btn.titleLabel?.frame.size.width
if btn.contentHorizontalAlignment == .left {
btn.imageEdgeInsets = UIEdgeInsets.init(top: 0, left: titleLabWidth! + spacing, bottom: 0, right: 0)
btn.titleEdgeInsets = UIEdgeInsets.init(top: 0, left: -imgView_width!, bottom: 0, right: 0)
} else if btn.contentHorizontalAlignment == .right {
btn.imageEdgeInsets = UIEdgeInsets.init(top: 0, left: 0, bottom: 0, right: -titleLabWidth!)
btn.titleEdgeInsets = UIEdgeInsets.init(top: 0, left: 0, bottom: 0, right: imgView_width! + spacing)
} else {
let imageOffset = titleLabWidth! + 0.5 * spacing
let titleOffset = titleLabWidth! + 0.5 * spacing
btn.imageEdgeInsets = UIEdgeInsets.init(top: 0, left: imageOffset, bottom: 0, right: -imageOffset)
btn.titleEdgeInsets = UIEdgeInsets.init(top: 0, left: -titleOffset, bottom: 0, right: titleOffset)
}
case .top:
btn.imageEdgeInsets = UIEdgeInsets.init(top: -(titleLab_iCSHeight! + spacing), left: 0, bottom: 0, right: -titleLab_iCSWidth!)
btn.titleEdgeInsets = UIEdgeInsets.init(top: 0, left: -imgView_width!, bottom: -(imgView_height! + spacing), right: 0)
case .bottom:
btn.imageEdgeInsets = UIEdgeInsets.init(top: titleLab_iCSHeight! + spacing, left: 0, bottom: 0, right: -titleLab_iCSWidth!)
btn.titleEdgeInsets = UIEdgeInsets.init(top: 0, left: -imgView_width!, bottom: imgView_height! + spacing, right: 0)
}
}
typealias LoadImageCompleteBlock = ((_ image: UIImage) -> ())?
func loadImage(urlString: String, complete: LoadImageCompleteBlock) {
let blockOperation = BlockOperation.init {
let url = URL.init(string: urlString)
guard let imageData = NSData(contentsOf: url!) else { return }
let image = UIImage(data: imageData as Data)
OperationQueue.main.addOperation {
if complete != nil {
complete!(image!)
}
}
}
OperationQueue().addOperation(blockOperation)
}
}
| 41.297578 | 212 | 0.621575 |
fed6a5afc5913aa30e163d96df3486c4b7e67e67 | 1,244 | //
// EventDetailViewController.swift
// BlockClubCalender
//
// Created by brian vilchez on 11/19/19.
// Copyright © 2019 brian vilchez. All rights reserved.
//
import UIKit
class EventDetailViewController: UIViewController {
//MARK: - properties
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var descriptionTextView: UITextView!
var event: Event? {
didSet {
updateViews()
}
}
override func viewDidLoad() {
super.viewDidLoad()
updateViews()
}
private func updateViews() {
guard isViewLoaded else { return }
guard let event = event else { return configureViews()}
titleLabel.text = event.title
descriptionTextView.text = event.eventDescription
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "mm-dd-yyyy HH:mm"
guard let date = event.eventDate else { return }
let formatedDate = dateFormatter.string(from: date)
dateLabel.text = "\(formatedDate)"
}
private func configureViews() {
dateLabel.text = ""
titleLabel.text = ""
descriptionTextView.text = ""
}
}
| 25.387755 | 63 | 0.624598 |
1ef4525466b5685e79de4ef2eb6149aa003d1780 | 1,902 | //
// NSManagedObject+DynamicModel.swift
// CoreStore
//
// Copyright © 2018 John Rommel Estropia
//
// 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 CoreData
// MARK: - NSManagedObject
extension NSManagedObject {
@nonobjc
internal weak var coreStoreObject: CoreStoreObject? {
get {
return Internals.getAssociatedObjectForKey(
&PropertyKeys.coreStoreObject,
inObject: self
)
}
set {
Internals.setAssociatedWeakObject(
newValue,
forKey: &PropertyKeys.coreStoreObject,
inObject: self
)
}
}
// MARK: Private
private struct PropertyKeys {
static var coreStoreObject: Void?
}
}
| 30.677419 | 82 | 0.660883 |
14e315d59c51be936aed82fe7c7757907ab32f3e | 177 | //
// ResultWithError.swift
// iOS_Bootstrap
//
// Created by Ahmad Mahmoud on 10/27/18.
//
public enum ResultWithError<T> {
case success(T?)
case failure(Error?)
}
| 14.75 | 41 | 0.655367 |
16ec48a99863c1bff3a3d4f1021a2ac0b8a29543 | 3,101 | //
// OldPullRequest.swift
// PRChecker
//
// Created by Bruce Evans on 2021/11/09.
//
import Foundation
import Apollo
import SwiftUI
class OldPullRequest: AbstractPullRequest {
let pullRequest: OldPrInfo
let username: String
init(pullRequest: OldPrInfo, username: String) {
self.pullRequest = pullRequest
self.username = username
}
override var id: GraphQLID {
pullRequest.id
}
override var isRead: Bool {
false // TODO: Can we get this data somewhere else?
}
override var url: String {
pullRequest.url
}
override var repositoryName: String {
pullRequest.repository.nameWithOwner
}
override var targetBranch: String {
pullRequest.baseRefName
}
override var headBranch: String {
pullRequest.headRefName
}
override var author: String {
pullRequest.author?.login ?? "Unknown"
}
override var title: String {
pullRequest.title
}
override var body: String {
pullRequest.body
}
override var changedFileCount: Int {
pullRequest.changedFiles
}
override var lineAdditions: Int {
pullRequest.additions
}
override var lineDeletions: Int {
pullRequest.deletions
}
override var commits: [GraphQLID] {
pullRequest.commits.nodes?.compactMap { $0 }.map(\.id) ?? []
}
override var labels: [LabelModel] {
pullRequest.labels?.nodes?.compactMap { $0 }.map(LabelModel.init) ?? []
}
override var state: PRState {
switch pullRequest.state {
case .open:
return .open
case .merged:
return .merged
case .closed:
return .closed
default:
fatalError("Unknown state: \(String(describing: pullRequest.state))")
}
}
override var viewerStatus: ViewerStatus {
guard let nodes = pullRequest.reviews?.nodes else {
return .waiting // No reviews at all
}
guard let viewersReview = nodes.last(where: { $0?.author?.login == username }) else {
return .waiting // Viewer has not reviewed
}
switch viewersReview?.state {
case .none, .pending, .dismissed:
return .waiting
case .approved:
return .approved
case .changesRequested:
return .blocked
case .commented:
return .commented
default:
assertionFailure("Unknown status: \(String(describing: viewersReview?.state))")
return .waiting
}
}
override var mergedAt: String? {
guard let mergedAt = pullRequest.mergedAt else {
return nil
}
return Self.relativeDateString(from: mergedAt)
}
override var rawUpdatedAt: String {
pullRequest.updatedAt
}
override var updatedAt: String {
Self.relativeDateString(from: pullRequest.updatedAt)
}
}
| 23.853846 | 93 | 0.579168 |
d616649551862a13fae2c170d6b79fbfbf642e07 | 887 | //
// NotificationObservable.swift
// Notifications
//
// Created by Leandro Perez on 11/24/18.
// Copyright © 2018 Leandro perez. All rights reserved.
//
import Foundation
import RxSwift
public protocol NotificationObservable {
var identifier: String {get}
var notificationName : Notification.Name {get}
func notificationObservable() -> Observable<Notification>
}
public extension NotificationObservable {
public var notificationName : Notification.Name {
return Notification.Name(self.identifier)
}
public func notificationObservable() -> Observable<Notification> {
return NotificationCenter.default.rx.notification(self.notificationName)
}
}
public extension NotificationObservable where Self : RawRepresentable, Self.RawValue == String {
var identifier: String {
return "\(type(of: self))" + self.rawValue
}
}
| 26.878788 | 96 | 0.726043 |
f9cfa765450a139b4d26631e9f3fcf5093ce86a5 | 786 | // swift-tools-version:5.1
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "ReactiveStore",
platforms: [
.iOS(.v12),
.macOS(.v10_14),
.watchOS(.v5),
.tvOS(.v12)
],
products: [
.library(name: "Dispatcher",
targets: ["Dispatcher"]),
.library(name: "ReactiveObject",
targets: ["ReactiveObject"]),
],
targets: [
.target(name: "Dispatcher",
dependencies: [],
path: "Dispatcher"),
.target(name: "ReactiveObject",
dependencies: [],
path: "ReactiveObject"),
],
swiftLanguageVersions: [ .v5 ]
)
| 26.2 | 96 | 0.533079 |
481b93c65efea69496678fa233e932b98117973c | 3,535 | /*
Video Core
Copyright (c) 2014 James G. Hurley
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.
*/
//
// ViewController.swift
// SampleBroadcaster-Swift
//
// Created by Josh Lieberman on 4/11/15.
// Copyright (c) 2015 videocore. All rights reserved.
//
import UIKit
class ViewController: UIViewController, VCSessionDelegate
{
@IBOutlet weak var previewView: UIView!
@IBOutlet weak var btnConnect: UIButton!
var session:VCSimpleSession = VCSimpleSession(videoSize: CGSize(width: 1280, height: 720), frameRate: 30, bitrate: 1000000, useInterfaceOrientation: false)
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
previewView.addSubview(session.previewView)
session.previewView.frame = previewView.bounds
session.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
deinit {
btnConnect = nil
previewView = nil
session.delegate = nil;
}
@IBAction func btnConnectTouch(sender: AnyObject) {
switch session.rtmpSessionState {
case .None, .PreviewStarted, .Ended, .Error:
session.startRtmpSessionWithURL("rtmp://192.168.1.151/live", andStreamKey: "myStream")
default:
session.endRtmpSession()
break
}
}
func connectionStatusChanged(sessionState: VCSessionState) {
switch session.rtmpSessionState {
case .Starting:
btnConnect.setTitle("Connecting", forState: .Normal)
case .Started:
btnConnect.setTitle("Disconnect", forState: .Normal)
default:
btnConnect.setTitle("Connect", forState: .Normal)
}
}
@IBAction func btnFilterTouch(sender: AnyObject) {
switch self.session.filter {
case .Normal:
self.session.filter = .Gray
case .Gray:
self.session.filter = .InvertColors
case .InvertColors:
self.session.filter = .Sepia
case .Sepia:
self.session.filter = .Fisheye
case .Fisheye:
self.session.filter = .Glow
case .Glow:
self.session.filter = .Normal
default: // Future proofing
break
}
}
}
| 30.474138 | 159 | 0.651202 |
e4cb6b530e233994633e52cdd1a422e49c47f7f1 | 756 | //
// DPAGSettingsDisclosureSubtitleTableViewCell.swift
// ginlo
//
// Created by RBU on 26/10/15.
// Copyright © 2020 ginlo.net GmbH. All rights reserved.
//
import SIMSmeCore
import UIKit
public protocol DPAGDisclosureSubtitleTableViewCellProtocol: DPAGBaseTableViewCellProtocol {}
class DPAGDisclosureSubtitleTableViewCell: DPAGBaseTableViewCell, DPAGDisclosureSubtitleTableViewCellProtocol {
override func configContentViews() {
super.configContentViews()
self.textLabel?.numberOfLines = 0
self.detailTextLabel?.numberOfLines = 0
}
override func updateFonts() {
super.updateFonts()
self.textLabel?.font = UIFont.kFontBody
self.detailTextLabel?.font = UIFont.kFontSubheadline
}
}
| 26.068966 | 111 | 0.742063 |
fb43d2e5277de9539cc006573da9479b488cb078 | 2,176 | //
// AppDelegate.swift
// LAN_Scanner
//
// Created by Marcin Kielesinski on 08.07.2018.
// Copyright © 2018 c&c. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> 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 invalidate graphics rendering callbacks. 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 active 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:.
}
}
| 46.297872 | 285 | 0.755515 |
ef7a74b707606b972b1a9855590ea99e78fcc0c2 | 348 | //
// ContentView.swift
// Enroute
//
// Created by Henrique Matheus Alves Pereira on 18/07/21.
//
import SwiftUI
struct ContentView: View {
var body: some View {
Text("Hello, world!")
.padding()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| 15.818182 | 58 | 0.614943 |
cceec81da9195e463d09cf2773da9d77fd870646 | 41,668 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2014-2021 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 the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Basics
import TSCBasic
import PackageGraph
import PackageModel
import PackageLoading
/// Errors encounter during Xcode project generation
public enum ProjectGenerationError: Swift.Error {
/// The given xcconfig override file does not exist
case xcconfigOverrideNotFound(path: AbsolutePath)
}
/// Generates the contents of the `project.pbxproj` for the package graph. The
/// project file is generated with the assumption that it will be written to an
/// .xcodeproj wrapper at `xcodeprojPath` (this affects relative references to
/// ancillary files inside the wrapper). Note that the root directory of the
/// sources is not necessarily related to this path; the source root directory
/// is the path of the root package in the package graph, independent of the
/// directory to which the .xcodeproj is being generated.
public func pbxproj(
xcodeprojPath: AbsolutePath,
graph: PackageGraph,
extraDirs: [AbsolutePath],
extraFiles: [AbsolutePath],
options: XcodeprojOptions,
fileSystem: FileSystem,
observabilityScope: ObservabilityScope
) throws -> Xcode.Project {
return try xcodeProject(
xcodeprojPath: xcodeprojPath,
graph: graph,
extraDirs: extraDirs,
extraFiles: extraFiles,
options: options,
fileSystem: fileSystem,
observabilityScope: observabilityScope.makeChildScope(description: "Xcode Project")
)
}
// FIXME: Handle case insensitive filesystems.
//
/// A set of c99 target names that are invalid for Xcode Framework targets.
/// They will conflict with the required Framework directory structure,
/// and cause a linker error (SR-3398).
fileprivate let invalidXcodeModuleNames = Set(["Modules", "Headers", "Versions"])
public func xcodeProject(
xcodeprojPath: AbsolutePath,
graph: PackageGraph,
extraDirs: [AbsolutePath],
extraFiles: [AbsolutePath],
options: XcodeprojOptions,
fileSystem: FileSystem,
observabilityScope: ObservabilityScope
) throws -> Xcode.Project {
// Create the project.
let project = Xcode.Project()
// Generates a dummy target to provide autocompletion for the manifest file.
func createPackageDescriptionTarget(for package: ResolvedPackage, manifestFileRef: Xcode.FileReference) {
guard let manifestLoader = options.manifestLoader else { return }
let pdTarget = project.addTarget(
objectID: "\(package.identity)::SwiftPMPackageDescription",
productType: .framework,
name: "\(package.manifest.displayName)PackageDescription" // TODO: use identity instead?
)
let compilePhase = pdTarget.addSourcesBuildPhase()
compilePhase.addBuildFile(fileRef: manifestFileRef)
var interpreterFlags = manifestLoader.interpreterFlags(for: package.manifest.toolsVersion)
if !interpreterFlags.isEmpty {
// Patch the interpreter flags to use Xcode supported toolchain macro instead of the resolved path.
interpreterFlags[3] = "$(TOOLCHAIN_DIR)/usr/lib/swift/pm/ManifestAPI"
}
pdTarget.buildSettings.common.OTHER_SWIFT_FLAGS += interpreterFlags
pdTarget.buildSettings.common.SWIFT_VERSION = package.manifest.toolsVersion.swiftLanguageVersion.xcodeBuildSettingValue
pdTarget.buildSettings.common.LD = "/usr/bin/true"
}
// Determine the source root directory (which is NOT necessarily related in
// any way to `xcodeprojPath`, i.e. we cannot assume that the Xcode project
// will be generated into to the source root directory).
let sourceRootDir = graph.rootPackages[0].path
// Set the project's notion of the source root directory to be a relative
// path from the directory that contains the .xcodeproj to the source root
// directory (note that those two directories might or might be the same).
// The effect is to make any `projectDir`-relative path be relative to the
// source root directory, i.e. the path of the root package.
project.projectDir = sourceRootDir.relative(to: xcodeprojPath.parentDirectory).pathString
// Configure the project settings.
let projectSettings = project.buildSettings
// First of all, set a standard definition of `PROJECT_NAME`.
projectSettings.common.PRODUCT_NAME = "$(TARGET_NAME)"
// Set the SUPPORTED_PLATFORMS to all platforms.
// FIXME: This doesn't seem correct, but was what the old project generation
// code did, so for now we do so too.
projectSettings.common.SUPPORTED_PLATFORMS = ["$(AVAILABLE_PLATFORMS)"]
projectSettings.common.SUPPORTS_MACCATALYST = "YES"
// Set the default `SDKROOT` to the latest macOS SDK.
projectSettings.common.SDKROOT = "macosx"
// Default to @rpath-based install names. Any target that links against
// these products will need to establish the appropriate runpath search
// paths so that all the products can be found.
projectSettings.common.DYLIB_INSTALL_NAME_BASE = "@rpath"
// Set the `Xcode` build preset in Swift to let code conditionalize on
// being built in Xcode.
projectSettings.common.OTHER_SWIFT_FLAGS = ["$(inherited)", "-DXcode"]
// Add any additional compiler and linker flags the user has specified.
if !options.flags.cCompilerFlags.isEmpty {
projectSettings.common.OTHER_CFLAGS = options.flags.cCompilerFlags
}
if !options.flags.linkerFlags.isEmpty {
projectSettings.common.OTHER_LDFLAGS = options.flags.linkerFlags
}
if !options.flags.swiftCompilerFlags.isEmpty {
projectSettings.common.OTHER_SWIFT_FLAGS += options.flags.swiftCompilerFlags
}
projectSettings.common.MACOSX_DEPLOYMENT_TARGET = "10.10"
// Prevent Xcode project upgrade warnings.
projectSettings.common.COMBINE_HIDPI_IMAGES = "YES"
// Defined for regular `swift build` instantiations, so also should be defined here.
projectSettings.common.SWIFT_ACTIVE_COMPILATION_CONDITIONS += ["$(inherited)", "SWIFT_PACKAGE"]
projectSettings.common.GCC_PREPROCESSOR_DEFINITIONS += ["$(inherited)", "SWIFT_PACKAGE=1"]
// Opt out of headermaps. The semantics of the build should be explicitly
// defined by the project structure, so that we don't get any additional
// magic behavior that isn't present in `swift build`.
projectSettings.common.USE_HEADERMAP = "NO"
// Enable `Automatic Reference Counting` for Objective-C sources
projectSettings.common.CLANG_ENABLE_OBJC_ARC = "YES"
// Add some debug-specific settings.
projectSettings.debug.COPY_PHASE_STRIP = "NO"
projectSettings.debug.DEBUG_INFORMATION_FORMAT = "dwarf"
projectSettings.debug.ENABLE_NS_ASSERTIONS = "YES"
projectSettings.debug.GCC_OPTIMIZATION_LEVEL = "0"
projectSettings.debug.GCC_PREPROCESSOR_DEFINITIONS = ["$(inherited)", "DEBUG=1"]
projectSettings.debug.ONLY_ACTIVE_ARCH = "YES"
projectSettings.debug.SWIFT_OPTIMIZATION_LEVEL = "-Onone"
projectSettings.debug.SWIFT_ACTIVE_COMPILATION_CONDITIONS += ["$(inherited)", "DEBUG"]
// Add some release-specific settings.
projectSettings.release.COPY_PHASE_STRIP = "YES"
projectSettings.release.DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"
projectSettings.release.GCC_OPTIMIZATION_LEVEL = "s"
projectSettings.release.SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"
// Add a file reference for the package manifest itself.
// FIXME: We should parameterize this so that a package can return the path
// of its manifest file.
let manifestFileRef = project.mainGroup.addFileReference(path: "Package.swift", fileType: "sourcecode.swift")
createPackageDescriptionTarget(for: graph.rootPackages[0], manifestFileRef: manifestFileRef)
// Add a group for the overriding .xcconfig file, if we have one.
let xcconfigOverridesFileRef: Xcode.FileReference?
if let xcconfigPath = options.xcconfigOverrides {
// Verify that the xcconfig override file exists
if !fileSystem.exists(xcconfigPath) {
throw ProjectGenerationError.xcconfigOverrideNotFound(path: xcconfigPath)
}
// Create a "Configs" group whose path is the same as the project path.
let xcconfigsGroup = project.mainGroup.addGroup(path: "", name: "Configs")
// Create a file reference for the .xcconfig file (with a path relative
// to the group).
xcconfigOverridesFileRef = xcconfigsGroup.addFileReference(
path: xcconfigPath.relative(to: sourceRootDir).pathString,
name: xcconfigPath.basename)
// We don't assign the file reference as the xcconfig file reference of
// the project's build settings, because if we do, the xcconfig cannot
// override any of the default build settings at the project level. So
// we instead assign it to each target.
// We may instead want to emit all build settings to separate .xcconfig
// files that use `#include` to include the overriding .xcconfig file.
} else {
// Otherwise, we don't create an .xcconfig file reference.
xcconfigOverridesFileRef = nil
}
// Determine the list of external package dependencies, if any.
let externalPackages = graph.packages.filter({ !graph.rootPackages.contains($0) })
// Build a backmap of targets and products to packages.
var packagesByTarget = [ResolvedTarget: ResolvedPackage]()
for package in graph.packages {
for target in package.targets {
packagesByTarget[target] = package
}
}
var packagesByProduct = [ResolvedProduct: ResolvedPackage]()
for package in graph.packages {
for product in package.products {
packagesByProduct[product] = package
}
}
// To avoid creating multiple groups for the same path, we keep a mapping
// of the paths we've seen and the corresponding groups we've created.
var srcPathsToGroups: [AbsolutePath: Xcode.Group] = [:]
// Private helper function to make a group (or return an existing one) for
// a particular path, including any intermediate groups that may be needed.
// A name can be specified, if different from the last path component (any
// custom name does not apply to any intermediate groups).
func makeGroup(for path: AbsolutePath, named name: String? = nil) -> Xcode.Group {
// Check if we already have a group.
if let group = srcPathsToGroups[path] {
// We do, so we just return it without creating anything.
return group
}
// No existing group, so start by making sure we have the parent. Note
// that we don't pass along any custom name for any parent groups.
let parentGroup = makeGroup(for: path.parentDirectory)
// Now we have a parent, so we can create a group, optionally using the
// custom name we were given.
let group = parentGroup.addGroup(path: path.basename, pathBase: .groupDir, name: name ?? path.basename)
// Add the new group to the mapping, so future lookups will find it.
srcPathsToGroups[path] = group
return group
}
// Add a mapping from the project dir to the main group, as a backstop for
// any paths that get that far (which does not happen in standard package
// layout).
srcPathsToGroups[sourceRootDir] = project.mainGroup
// Private helper function that creates a source group for one or more
// targets (which could be regular targets, tests, etc). If there is a
// single target whose source directory's basename is not equal to the
// target name (i.e. the "flat" form of a single-target package), then
// the top-level group will itself represent that target; otherwise, it
// will have one subgroup for each target.
//
// The provided name is always used for the top-level group, whether or
// not it represents a single target or is the parent of a collection of
// targets.
//
// Regardless of the layout case, this function adds a mapping from the
// source directory of each target to the corresponding group, so that
// source files added later will be able to find the right group.
@discardableResult
func createSourceGroup(named groupName: String, for targets: [ResolvedTarget], in parentGroup: Xcode.Group) -> Xcode.Group? {
let targets = targets.sorted { $0.name < $1.name }
// Look for the special case of a single target in a flat layout.
let needsSourcesGroup: Bool
if let target = targets.spm_only {
// FIXME: This is somewhat flaky; packages should have a notion of
// what kind of layout they have. But at least this is just a
// heuristic and won't affect the functioning of the Xcode project.
needsSourcesGroup = (target.sources.root.basename == target.name)
} else {
needsSourcesGroup = true
}
// If we need a sources group, create one.
let sourcesGroup = needsSourcesGroup ?
parentGroup.addGroup(path: "", pathBase: .projectDir, name: groupName) : nil
// Create a group for each target.
for target in targets {
// The sources could be anywhere, so we use a project-relative path.
let path = target.sources.root.relative(to: sourceRootDir).pathString
let name = (sourcesGroup == nil ? groupName : target.name)
let group = (sourcesGroup ?? parentGroup)
.addGroup(path: (path == "." ? "" : path), pathBase: .projectDir, name: name)
// Associate the group with the target's root path.
srcPathsToGroups[target.sources.root] = group
}
return sourcesGroup ?? srcPathsToGroups[targets[0].sources.root]
}
let (rootModules, testModules) = { () -> ([ResolvedTarget], [ResolvedTarget]) in
var targets = graph.rootPackages[0].targets
let secondPartitionIndex = targets.partition(by: { $0.type == .test })
return (Array(targets[..<secondPartitionIndex]), Array(targets[secondPartitionIndex...]))
}()
// Create a `Sources` group for the source targets in the root package.
createSourceGroup(named: "Sources", for: rootModules, in: project.mainGroup)
// Create a `Tests` group for the source targets in the root package.
createSourceGroup(named: "Tests", for: testModules, in: project.mainGroup)
// Determine the set of targets to generate in the project by excluding
// any system targets.
let targets = graph.reachableTargets.filter({ $0.type != .systemModule })
// If we have any external packages, we also add a `Dependencies` group at
// the top level, along with a sources subgroup for each package.
if !externalPackages.isEmpty {
// Create the top-level `Dependencies` group. We cannot count on each
// external package's path, so we don't assign a particular path to the
// `Dependencies` group; each package provides its own project-relative
// path.
let dependenciesGroup = project.mainGroup.addGroup(path: "", pathBase: .groupDir, name: "Dependencies")
// Create set of the targets.
let targetSet = Set(targets)
// Add a subgroup for each external package.
for package in externalPackages {
// Skip if there are no targets in this package that needs to be built.
if targetSet.intersection(package.targets).isEmpty {
continue
}
// TODO: use identity instead
// Construct a group name from the package name and optional version.
var groupName = package.manifest.displayName // TODO: use identity instead?
if let version = package.manifest.version {
groupName += " " + version.description
}
// Create the source group for all the targets in the package.
// FIXME: Eliminate filtering test from here.
let group = createSourceGroup(named: groupName, for: package.targets.filter({ $0.type != .test }), in: dependenciesGroup)
if let group = group {
let manifestPath = package.path.appending(component: "Package.swift")
let manifestFileRef = group.addFileReference(path: manifestPath.pathString, name: "Package.swift", fileType: "sourcecode.swift")
createPackageDescriptionTarget(for: package, manifestFileRef: manifestFileRef)
}
}
}
// Add a `Products` group, to which we'll add references to the outputs of
// the various targets; these references will be added to the link phases.
let productsGroup = project.mainGroup.addGroup(path: "", pathBase: .buildDir, name: "Products")
// Add "blue folders" for any other directories at the top level (note that
// they are not guaranteed to be direct children of the root directory).
for extraDir in extraDirs {
project.mainGroup.addFileReference(path: extraDir.relative(to: sourceRootDir).pathString, pathBase: .projectDir)
}
for extraFile in extraFiles {
let groupOfFile = srcPathsToGroups[extraFile.parentDirectory]
groupOfFile?.addFileReference(path: extraFile.basename)
}
// Set the newly created `Products` group as the official products group of
// the project.
project.productGroup = productsGroup
// We'll need a mapping of targets to the corresponding targets.
var modulesToTargets: [ResolvedTarget: Xcode.Target] = [:]
// Mapping of targets to the path of their modulemap path, if they one.
// It also records if the modulemap is generated by SwiftPM.
var modulesToModuleMap: [ResolvedTarget: (path: AbsolutePath, isGenerated: Bool)] = [:]
// Go through all the targets, creating targets and adding file references
// to the group tree (the specific top-level group under which they are
// added depends on whether or not the target is a test target).
for target in targets.sorted(by: { $0.name < $1.name }) {
// Determine the appropriate product type based on the kind of target.
// FIXME: We should factor this out.
let productType: Xcode.Target.ProductType
switch target.type {
case .executable, .snippet:
productType = .executable
case .library:
productType = .framework
case .test:
productType = .unitTest
case .systemModule, .binary, .plugin:
throw InternalError("\(target.type) not supported")
}
// Warn if the target name is invalid.
if target.type == .library && invalidXcodeModuleNames.contains(target.c99name) {
observabilityScope.emit(
warning: "Target '\(target.name)' conflicts with required framework filenames, rename " + "this target to avoid conflicts."
)
}
// Create a Xcode target for the target.
let package = packagesByTarget[target]!
let xcodeTarget = project.addTarget(
objectID: "\(package.identity)::\(target.name)",
productType: productType, name: target.name)
// Set the product name to the C99-mangled form of the target name.
xcodeTarget.productName = target.c99name
// Configure the target settings based on the target. We set only the
// minimum settings required, because anything we set on the target is
// not overridable by the user-supplied .xcconfig file.
let targetSettings = xcodeTarget.buildSettings
// Set the target's base .xcconfig file to the user-supplied override
// .xcconfig, if we have one. This lets it override project settings.
targetSettings.xcconfigFileRef = xcconfigOverridesFileRef
targetSettings.common.TARGET_NAME = target.name
// Assign the deployment target if the package is using the newer manifest version.
if package.manifest.toolsVersion >= .v5 {
for supportedPlatform in target.platforms.derived {
let version = supportedPlatform.version.versionString
switch supportedPlatform.platform {
case .macOS:
targetSettings.common.MACOSX_DEPLOYMENT_TARGET = version
case .iOS:
targetSettings.common.IPHONEOS_DEPLOYMENT_TARGET = version
case .tvOS:
targetSettings.common.TVOS_DEPLOYMENT_TARGET = version
case .watchOS:
targetSettings.common.WATCHOS_DEPLOYMENT_TARGET = version
case .driverKit:
targetSettings.common.DRIVERKIT_DEPLOYMENT_TARGET = version
default:
break
}
}
}
let infoPlistFilePath = xcodeprojPath.appending(component: target.infoPlistFileName)
targetSettings.common.INFOPLIST_FILE = infoPlistFilePath.relative(to: sourceRootDir).pathString
// The generated Info.plist has $(CURRENT_PROJECT_VERSION) as value for the CFBundleVersion key.
// CFBundleVersion is required for apps to e.g. be submitted to the app store.
// So we need to set it to some valid value in the project settings.
// TODO: Extract version from SPM target (see SR-4265 and SR-12926).
targetSettings.common.CURRENT_PROJECT_VERSION = "1"
if target.type == .test {
targetSettings.common.CLANG_ENABLE_MODULES = "YES"
targetSettings.common.EMBEDDED_CONTENT_CONTAINS_SWIFT = "YES"
targetSettings.common.LD_RUNPATH_SEARCH_PATHS = ["$(inherited)", "@loader_path/../Frameworks", "@loader_path/Frameworks"]
} else {
// We currently force a search path to the toolchain, since we can't
// establish an expected location for the Swift standard libraries.
//
// Note that this means that the built binaries are not suitable for
// distribution, among other things.
targetSettings.common.LD_RUNPATH_SEARCH_PATHS = ["$(inherited)", "$(TOOLCHAIN_DIR)/usr/lib/swift/macosx"]
if target.type == .library {
targetSettings.common.ENABLE_TESTABILITY = "YES"
targetSettings.common.PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"
targetSettings.common.PRODUCT_MODULE_NAME = "$(TARGET_NAME:c99extidentifier)"
targetSettings.common.PRODUCT_BUNDLE_IDENTIFIER = target.c99name.spm_mangledToBundleIdentifier()
targetSettings.common.SKIP_INSTALL = "YES"
} else {
targetSettings.common.SWIFT_FORCE_STATIC_LINK_STDLIB = "NO"
targetSettings.common.SWIFT_FORCE_DYNAMIC_LINK_STDLIB = "YES"
targetSettings.common.LD_RUNPATH_SEARCH_PATHS += ["@executable_path"]
}
}
// Make sure that build settings for C flags, Swift flags, and linker
// flags include any inherited value at the beginning. This is useful
// even if nothing ends up being added, since it's a cue to anyone who
// edits the setting that the inherited value should be preserved.
targetSettings.common.OTHER_CFLAGS = ["$(inherited)"]
targetSettings.common.OTHER_LDFLAGS = ["$(inherited)"]
targetSettings.common.OTHER_SWIFT_FLAGS = ["$(inherited)"]
targetSettings.common.SWIFT_ACTIVE_COMPILATION_CONDITIONS = ["$(inherited)"]
// Set the correct SWIFT_VERSION for the Swift targets.
if case let swiftTarget as SwiftTarget = target.underlyingTarget {
targetSettings.common.SWIFT_VERSION = swiftTarget.swiftVersion.xcodeBuildSettingValue
}
// Add header search paths for any C target on which we depend.
var hdrInclPaths = ["$(inherited)"]
for depModule in try [target] + target.recursiveTargetDependencies() {
// FIXME: Possibly factor this out into a separate protocol; the
// idea would be that we would ask the target how it contributes
// to the overall build environment for client targets, which can
// affect search paths and other flags. This should be done in a
// way that allows SwiftPM to detect incompatibilities.
// FIXME: We don't need SRCROOT macro below but there is an issue with sourcekit.
// See: <rdar://problem/21912068> SourceKit cannot handle relative include paths (working directory)
switch depModule.underlyingTarget {
case let systemTarget as SystemLibraryTarget:
hdrInclPaths.append("$(SRCROOT)/\(systemTarget.path.relative(to: sourceRootDir).pathString)")
for pkgArgs in pkgConfigArgs(for: systemTarget, fileSystem: fileSystem, observabilityScope: observabilityScope) {
targetSettings.common.OTHER_LDFLAGS += pkgArgs.libs
targetSettings.common.OTHER_SWIFT_FLAGS += pkgArgs.cFlags
targetSettings.common.OTHER_CFLAGS += pkgArgs.cFlags
}
case let clangTarget as ClangTarget:
hdrInclPaths.append("$(SRCROOT)/\(clangTarget.includeDir.relative(to: sourceRootDir).pathString)")
default:
continue
}
}
targetSettings.common.HEADER_SEARCH_PATHS = hdrInclPaths
// Add framework search path to build settings.
targetSettings.common.FRAMEWORK_SEARCH_PATHS = ["$(inherited)", "$(PLATFORM_DIR)/Developer/Library/Frameworks"]
// Add a file reference for the target's product.
let productRef = productsGroup.addFileReference(
path: target.productPath.pathString,
pathBase: .buildDir,
objectID: "\(package.identity)::\(target.name)::Product"
)
// Set that file reference as the target's product reference.
xcodeTarget.productReference = productRef
// Add a compile build phase (which Xcode calls "Sources").
let compilePhase = xcodeTarget.addSourcesBuildPhase()
// We don't add dependencies yet — we do so in a separate pass, since
// some dependencies might be on targets that we have not yet created.
// We also don't add the link phase yet, since we'll do so at the same
// time as we set up dependencies.
// Record the target that we created for this target, for later passes.
modulesToTargets[target] = xcodeTarget
// Go through the target source files. As we do, we create groups for
// any path components other than the last one. We also add build files
// to the compile phase of the target we created.
for sourceFile in target.sources.paths {
// Find or make a group for the parent directory of the source file.
// We know that there will always be one, because we created groups
// for the source directories of all the targets.
let group = makeGroup(for: sourceFile.parentDirectory)
// Create a reference for the source file. We don't set its file
// type; rather, we let Xcode determine it based on the suffix.
let srcFileRef = group.addFileReference(path: sourceFile.basename)
// Also add the source file to the compile phase.
compilePhase.addBuildFile(fileRef: srcFileRef)
}
// Set C/C++ language standard.
if case let clangTarget as ClangTarget = target.underlyingTarget {
targetSettings.common.GCC_C_LANGUAGE_STANDARD = clangTarget.cLanguageStandard
targetSettings.common.CLANG_CXX_LANGUAGE_STANDARD = clangTarget.cxxLanguageStandard
}
// Add the `include` group for a library C language target.
if case let clangTarget as ClangTarget = target.underlyingTarget,
clangTarget.type == .library,
fileSystem.isDirectory(clangTarget.includeDir) {
let includeDir = clangTarget.includeDir
let includeGroup = makeGroup(for: includeDir)
// FIXME: Support C++ headers.
for header in try walk(includeDir, fileSystem: fileSystem) where header.extension == "h" {
let group = makeGroup(for: header.parentDirectory)
group.addFileReference(path: header.basename)
}
// Disable defines target for clang target because our clang targets are not proper framework targets.
// Also see: <rdar://problem/29825757>
targetSettings.common.DEFINES_MODULE = "NO"
// Generate a modulemap for clangTarget (if not provided by user) and
// add to the build settings.
var moduleMapPath: AbsolutePath?
// If the modulemap is generated (as opposed to user provided).
var isGenerated = false
// If user provided the modulemap no need to generate.
if case .custom(let path) = clangTarget.moduleMapType {
moduleMapPath = path
} else if includeGroup.subitems.contains(where: { $0.path == clangTarget.c99name + ".h" }) {
// If an umbrella header exists, enable Xcode's builtin module's feature rather than generating
// a custom module map. This increases the compatibility of generated Xcode projects.
let headerPhase = xcodeTarget.addHeadersBuildPhase()
for case let header as Xcode.FileReference in includeGroup.subitems {
let buildFile = headerPhase.addBuildFile(fileRef: header)
buildFile.settings.ATTRIBUTES = ["Public"]
}
targetSettings.common.CLANG_ENABLE_MODULES = "YES"
targetSettings.common.DEFINES_MODULE = "YES"
} else if let generatedModuleMapType = clangTarget.moduleMapType.generatedModuleMapType {
// Generate and drop the modulemap inside the .xcodeproj wrapper.
let path = xcodeprojPath.appending(components: "GeneratedModuleMap", clangTarget.c99name, moduleMapFilename)
try fileSystem.createDirectory(path.parentDirectory, recursive: true)
let moduleMapGenerator = ModuleMapGenerator(targetName: clangTarget.name, moduleName: clangTarget.c99name, publicHeadersDir: clangTarget.includeDir, fileSystem: fileSystem)
try moduleMapGenerator.generateModuleMap(type: generatedModuleMapType, at: path)
moduleMapPath = path
isGenerated = true
}
if let moduleMapPath = moduleMapPath {
includeGroup.addFileReference(path: moduleMapPath.pathString, name: moduleMapPath.basename)
// Save this modulemap path mapped to target so we can later wire it up for its dependencies.
modulesToModuleMap[target] = (moduleMapPath, isGenerated)
}
}
}
// Go through each target and add its build settings.
for (target, xcodeTarget) in modulesToTargets {
for (decl, assignments) in target.underlyingTarget.buildSettings.assignments {
// Process each assignment of a build settings declaration.
for assignment in assignments {
// Skip this assignment if it doesn't contain macOS platform.
if let platformsCondition = assignment.conditions.compactMap({ $0 as? PlatformsCondition }).first {
if !platformsCondition.platforms.contains(.macOS) {
continue
}
}
let config = assignment.conditions.compactMap { $0 as? ConfigurationCondition }.first?.configuration
try appendSetting(assignment.values, forDecl: decl, to: xcodeTarget.buildSettings, config: config)
}
}
}
// Go through all the target/target pairs again, and add target dependencies
// for any target dependencies. As we go, we also add link phases and set
// up the targets to link against the products of the dependencies.
for (target, xcodeTarget) in modulesToTargets {
// Add link build phase (which Xcode calls "Frameworks & Libraries").
// We need to do this whether or not there are dependencies on other
// targets.
let linkPhase = xcodeTarget.addFrameworksBuildPhase()
// For each target on which this one depends, add a target dependency
// and also link against the target's product.
for case .target(let dependency, _) in try target.recursiveDependencies() {
// We should never find ourself in the list of dependencies.
assert(dependency != target)
// Find the target that corresponds to the other target.
guard let otherTarget = modulesToTargets[dependency] else {
// FIXME: We're depending on a target for which we didn't create
// a target. This is unexpected, and we should report this as
// an error.
// FIXME: Or is it? What about system targets, can we depend
// on those? If so, we would just link and not depend, right?
continue
}
// Add a dependency on the other target.
xcodeTarget.addDependency(on: otherTarget)
// If it's a library, we also add want to link against its product.
if dependency.type == .library {
_ = linkPhase.addBuildFile(fileRef: otherTarget.productReference!)
}
// For swift targets, if a clang dependency has a modulemap, add it via -fmodule-map-file.
if let moduleMap = modulesToModuleMap[dependency], target.underlyingTarget is SwiftTarget {
assert(dependency.underlyingTarget is ClangTarget)
xcodeTarget.buildSettings.common.OTHER_SWIFT_FLAGS += [
"-Xcc",
"-fmodule-map-file=$(SRCROOT)/\(moduleMap.path.relative(to: sourceRootDir).pathString)",
]
// Workaround for a interface generation bug. <rdar://problem/30071677>
if moduleMap.isGenerated {
xcodeTarget.buildSettings.common.HEADER_SEARCH_PATHS += [
"$(SRCROOT)/\(moduleMap.path.parentDirectory.relative(to: sourceRootDir).pathString)"
]
}
}
}
}
// Create an aggregate target for every product for which there isn't already
// a target with the same name.
let targetNames: Set<String> = Set(modulesToTargets.values.map({ $0.name }))
for product in graph.reachableProducts {
// Go on to next product if we already have a target with the same name.
if targetNames.contains(product.name) { continue }
// Otherwise, create an aggregate target.
let package = packagesByProduct[product]!
let aggregateTarget = project.addTarget(
objectID: "\(package.identity)::\(product.name)::ProductTarget",
productType: nil, name: product.name
)
// Add dependencies on the targets created for each of the dependencies.
for target in product.targets {
// Find the target that corresponds to the target. There might not
// be one, since we don't create targets for every kind of target
// (such as system targets).
// TODO: We will need to decide how this should best be handled; it
// would make sense to at least emit a warning.
guard let depTarget = modulesToTargets[target] else {
continue
}
// Add a dependency on the dependency target.
aggregateTarget.addDependency(on: depTarget)
}
}
return project
}
extension ResolvedTarget {
var buildableName: String {
return productName
}
var blueprintName: String {
return name
}
}
private extension SupportedLanguageExtension {
var xcodeFileType: String {
switch self {
case .c:
return "sourcecode.c.c"
case .m:
return "sourcecode.c.objc"
case .cxx, .cc, .cpp:
return "sourcecode.cpp.cpp"
case .mm:
return "sourcecode.cpp.objcpp"
case .swift:
return "sourcecode.swift"
case .s, .S:
return "sourcecode.assembly"
}
}
}
private extension ResolvedTarget {
func fileType(forSource source: RelativePath) throws -> String {
switch underlyingTarget {
case is SwiftTarget:
// SwiftModules only has one type of source so just always return this.
return SupportedLanguageExtension.swift.xcodeFileType
case is ClangTarget:
guard let suffix = source.suffix else {
throw InternalError("Source \(source) doesn't have an extension in C family target \(name)")
}
// Suffix includes `.` so drop it.
assert(suffix.hasPrefix("."))
let fileExtension = String(suffix.dropFirst())
guard let ext = SupportedLanguageExtension(rawValue: fileExtension) else {
throw InternalError("Unknown source extension \(source) in C family target \(name)")
}
return ext.xcodeFileType
default:
throw InternalError("unexpected target type")
}
}
}
private extension SwiftLanguageVersion {
/// Returns the build setting value for the given Swift language version.
var xcodeBuildSettingValue: String {
// Swift version setting are represented differently in Xcode:
// 3 -> 3.0, 4 -> 4.0, 4.2 -> 4.2
var swiftVersion = "\(rawValue)"
if !rawValue.contains(".") {
swiftVersion += ".0"
}
return swiftVersion
}
}
func appendSetting(
_ value: [String],
forDecl decl: BuildSettings.Declaration,
to table: Xcode.BuildSettingsTable,
config: BuildConfiguration? = nil
) throws {
switch decl {
// FIXME: This switch case is kind of sad but we need to convert Xcode's
// build model to be of reference type in order to avoid it.
case .SWIFT_ACTIVE_COMPILATION_CONDITIONS:
switch config {
case .debug?:
table.debug.SWIFT_ACTIVE_COMPILATION_CONDITIONS += value
case .release?:
table.release.SWIFT_ACTIVE_COMPILATION_CONDITIONS += value
case nil:
table.common.SWIFT_ACTIVE_COMPILATION_CONDITIONS += value
}
case .OTHER_SWIFT_FLAGS:
switch config {
case .debug?:
table.debug.OTHER_SWIFT_FLAGS += value
case .release?:
table.release.OTHER_SWIFT_FLAGS += value
case nil:
table.common.OTHER_SWIFT_FLAGS += value
}
case .GCC_PREPROCESSOR_DEFINITIONS:
switch config {
case .debug?:
table.debug.GCC_PREPROCESSOR_DEFINITIONS += value
case .release?:
table.release.GCC_PREPROCESSOR_DEFINITIONS += value
case nil:
table.common.GCC_PREPROCESSOR_DEFINITIONS += value
}
case .HEADER_SEARCH_PATHS:
switch config {
case .debug?:
table.debug.HEADER_SEARCH_PATHS += value
case .release?:
table.release.HEADER_SEARCH_PATHS += value
case nil:
table.common.HEADER_SEARCH_PATHS += value
}
case .OTHER_CFLAGS:
switch config {
case .debug?:
table.debug.OTHER_CFLAGS += value
case .release?:
table.release.OTHER_CFLAGS += value
case nil:
table.common.OTHER_CFLAGS += value
}
case .OTHER_CPLUSPLUSFLAGS:
switch config {
case .debug?:
table.debug.OTHER_CPLUSPLUSFLAGS += value
case .release?:
table.release.OTHER_CPLUSPLUSFLAGS += value
case nil:
table.common.OTHER_CPLUSPLUSFLAGS += value
}
case .OTHER_LDFLAGS:
switch config {
case .debug?:
table.debug.OTHER_LDFLAGS += value
case .release?:
table.release.OTHER_LDFLAGS += value
case nil:
table.common.OTHER_LDFLAGS += value
}
case .LINK_LIBRARIES:
let value = value.map({ "-l" + $0 })
switch config {
case .debug?:
table.debug.OTHER_LDFLAGS += value
case .release?:
table.release.OTHER_LDFLAGS += value
case nil:
table.common.OTHER_LDFLAGS += value
}
case .LINK_FRAMEWORKS:
let value = value.flatMap({ ["-framework", $0] })
switch config {
case .debug?:
table.debug.OTHER_LDFLAGS += value
case .release?:
table.release.OTHER_LDFLAGS += value
case nil:
table.common.OTHER_LDFLAGS += value
}
default:
throw InternalError("Unhandled decl \(decl)")
}
}
| 46.660694 | 188 | 0.653979 |
f5a8177d5a49545375fbe92eb2062ab765c21f0a | 5,713 | /*
* Copyright 2019, Undefined Labs
*
* 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 Foundation
import OpenTelemetryApi
/// representation of all data collected by the Span.
public struct SpanData: Equatable {
public struct TimedEvent: Event, Equatable {
public var epochNanos: Int
public var name: String
public var attributes: [String: AttributeValue]
}
public class Link: OpenTelemetryApi.Link {
public var context: SpanContext
public var attributes: [String: AttributeValue]
init(context: SpanContext, attributes: [String: AttributeValue] = [String: AttributeValue]()) {
self.context = context
self.attributes = attributes
}
}
/// The trace id for this span.
public private(set) var traceId: TraceId
/// The span id for this span.
public private(set) var spanId: SpanId
/// The trace flags for this span.
public private(set) var traceFlags: TraceFlags
/// The Tracestate for this span.
public private(set) var tracestate: Tracestate
/// The parent SpanId. If the Span is a root Span, the SpanId
/// returned will be nil.
public private(set) var parentSpanId: SpanId?
/// The resource of this Span.
public private(set) var resource: Resource
/// The instrumentation library specified when creating the tracer which produced this Span
public private(set) var instrumentationLibraryInfo: InstrumentationLibraryInfo
/// The name of this Span.
public private(set) var name: String
/// The kind of this Span.
public private(set) var kind: SpanKind
/// The start epoch timestamp in nanos of this Span.
public private(set) var startEpochNanos: Int
/// The attributes recorded for this Span.
public private(set) var attributes = [String: AttributeValue]()
/// The timed events recorded for this Span.
public private(set) var timedEvents = [TimedEvent]()
/// The links recorded for this Span.
public private(set) var links = [Link]()
/// The Status.
public private(set) var status: Status?
/// The end epoch timestamp in nanos of this Span
public private(set) var endEpochNanos: Int
/// True if the parent is on a different process, false if this is a root span.
public private(set) var hasRemoteParent: Bool
public static func == (lhs: SpanData, rhs: SpanData) -> Bool {
return lhs.traceId == rhs.traceId &&
lhs.spanId == rhs.spanId &&
lhs.traceFlags == rhs.traceFlags &&
lhs.tracestate == rhs.tracestate &&
lhs.parentSpanId == rhs.parentSpanId &&
lhs.name == rhs.name &&
lhs.kind == rhs.kind &&
lhs.status == rhs.status &&
lhs.endEpochNanos == rhs.endEpochNanos &&
lhs.startEpochNanos == rhs.startEpochNanos &&
lhs.hasRemoteParent == rhs.hasRemoteParent &&
lhs.resource == rhs.resource &&
lhs.attributes == rhs.attributes &&
lhs.timedEvents == rhs.timedEvents &&
lhs.links == rhs.links
}
public mutating func settingName(_ name: String) -> SpanData {
self.name = name
return self
}
public mutating func settingTraceId(_ traceId: TraceId) -> SpanData {
self.traceId = traceId
return self
}
public mutating func settingSpanId(_ spanId: SpanId) -> SpanData {
self.spanId = spanId
return self
}
public mutating func settingTraceFlags(_ traceFlags: TraceFlags) -> SpanData {
self.traceFlags = traceFlags
return self
}
public mutating func settingTracestate(_ tracestate: Tracestate) -> SpanData {
self.tracestate = tracestate
return self
}
public mutating func settingAttributes(_ attributes: [String: AttributeValue]) -> SpanData {
self.attributes = attributes
return self
}
public mutating func settingStartEpochNanos(_ nanos: Int) -> SpanData {
startEpochNanos = nanos
return self
}
public mutating func settingEndEpochNanos(_ nanos: Int) -> SpanData {
endEpochNanos = nanos
return self
}
public mutating func settingKind(_ kind: SpanKind) -> SpanData {
self.kind = kind
return self
}
public mutating func settingLinks(_ links: [Link]) -> SpanData {
self.links = links
return self
}
public mutating func settingParentSpanId(_ parentSpanId: SpanId) -> SpanData {
self.parentSpanId = parentSpanId
return self
}
public mutating func settingResource(_ resource: Resource) -> SpanData {
self.resource = resource
return self
}
public mutating func settingStatus(_ status: Status) -> SpanData {
self.status = status
return self
}
public mutating func settingTimedEvents(_ timedEvents: [TimedEvent]) -> SpanData {
self.timedEvents = timedEvents
return self
}
public mutating func settingHasRemoteParent(_ hasRemoteParent: Bool) -> SpanData {
self.hasRemoteParent = hasRemoteParent
return self
}
}
| 31.738889 | 103 | 0.654822 |
72f700561e38b597abed6355759c6b2d8b0b9567 | 3,249 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift %s -module-name SubheadingDeclarationFragmentsTypes -emit-module -emit-module-path %t/
// RUN: %target-swift-symbolgraph-extract -module-name SubheadingDeclarationFragmentsTypes -I %t -pretty-print -output-dir %t
// RUN: %FileCheck %s --input-file %t/SubheadingDeclarationFragmentsTypes.symbols.json --check-prefix=STRUCT
// RUN: %FileCheck %s --input-file %t/SubheadingDeclarationFragmentsTypes.symbols.json --check-prefix=ENUM
// RUN: %FileCheck %s --input-file %t/SubheadingDeclarationFragmentsTypes.symbols.json --check-prefix=PROTOCOL
// RUN: %FileCheck %s --input-file %t/SubheadingDeclarationFragmentsTypes.symbols.json --check-prefix=CLASS
// RUN: %FileCheck %s --input-file %t/SubheadingDeclarationFragmentsTypes.symbols.json --check-prefix=TYPEALIAS
// STRUCT-LABEL: "precise": "s:35SubheadingDeclarationFragmentsTypes6StructV"
// STRUCT: subHeading
// STRUCT-NEXT {
// STRUCT-NEXT "kind": "keyword",
// STRUCT-NEXT "spelling": "struct"
// STRUCT-NEXT }
// STRUCT-NEXT {
// STRUCT-NEXT "kind": "text",
// STRUCT-NEXT "spelling": " "
// STRUCT-NEXT }
// STRUCT-NEXT {
// STRUCT-NEXT "kind": "identifier",
// STRUCT-NEXT "spelling": "Struct"
// STRUCT-NEXT }
public struct Struct<T> where T: Sequence {}
// ENUM-LABEL: "precise": "s:35SubheadingDeclarationFragmentsTypes4EnumO"
// ENUM: subHeading
// ENUM-NEXT: {
// ENUM-NEXT: "kind": "keyword",
// ENUM-NEXT: "spelling": "enum"
// ENUM-NEXT: }
// ENUM-NEXT: {
// ENUM-NEXT: "kind": "text",
// ENUM-NEXT: "spelling": " "
// ENUM-NEXT: }
// ENUM-NEXT: {
// ENUM-NEXT: "kind": "identifier",
// ENUM-NEXT: "spelling": "Enum"
// ENUM-NEXT: }
public enum Enum<T> where T: Sequence {}
// PROTOCOL-LABEL: "precise": "s:35SubheadingDeclarationFragmentsTypes8ProtocolP"
// PROTOCOL: subHeading
// PROTOCOL-NEXT: {
// PROTOCOL-NEXT: "kind": "keyword",
// PROTOCOL-NEXT: "spelling": "protocol"
// PROTOCOL-NEXT: }
// PROTOCOL-NEXT: {
// PROTOCOL-NEXT: "kind": "text",
// PROTOCOL-NEXT: "spelling": " "
// PROTOCOL-NEXT: }
// PROTOCOL-NEXT: {
// PROTOCOL-NEXT: "kind": "identifier",
// PROTOCOL-NEXT: "spelling": "Protocol"
// PROTOCOL-NEXT: }
public protocol Protocol where T: Sequence {
associatedtype T
}
// CLASS-LABEL: "precise": "s:35SubheadingDeclarationFragmentsTypes5ClassC"
// CLASS: subHeading
// CLASS-NEXT {
// CLASS-NEXT "kind": "keyword",
// CLASS-NEXT "spelling": "class"
// CLASS-NEXT },
// CLASS-NEXT {
// CLASS-NEXT "kind": "text",
// CLASS-NEXT "spelling": " "
// CLASS-NEXT },
// CLASS-NEXT {
// CLASS-NEXT "kind": "identifier",
// CLASS-NEXT "spelling": "Class"
// CLASS-NEXT }
public class Class<T> where T: Sequence {}
// TYPEALIAS-LABEL: "precise": "s:35SubheadingDeclarationFragmentsTypes9TypeAliasa"
// TYPEALIAS: subHeading
// TYPEALIAS-NEXT: {
// TYPEALIAS-NEXT: "kind": "keyword",
// TYPEALIAS-NEXT: "spelling": "typealias"
// TYPEALIAS-NEXT: },
// TYPEALIAS-NEXT: {
// TYPEALIAS-NEXT: "kind": "text",
// TYPEALIAS-NEXT: "spelling": " "
// TYPEALIAS-NEXT: },
// TYPEALIAS-NEXT: {
// TYPEALIAS-NEXT: "kind": "identifier",
// TYPEALIAS-NEXT: "spelling": "TypeAlias"
// TYPEALIAS-NEXT: }
public typealias TypeAlias<T> = Struct<T> where T: Collection
| 35.315217 | 125 | 0.680517 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.