Skip to content

Commit

Permalink
Run SwiftFormat
Browse files Browse the repository at this point in the history
  • Loading branch information
mattjgalloway committed Oct 13, 2020
1 parent 996d31d commit b890449
Show file tree
Hide file tree
Showing 30 changed files with 347 additions and 296 deletions.
16 changes: 16 additions & 0 deletions .swiftformat
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
--swiftversion 5

--binarygrouping none
--closingparen same-line
--commas inline
--decimalgrouping none
--hexgrouping none
--hexliteralcase lowercase
--indent 2
--maxwidth 120
--octalgrouping none
--operatorfunc spaced
--patternlet inline
--self insert
--stripunusedargs closure-only
--wrapcollections before-first
46 changes: 21 additions & 25 deletions Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -4,28 +4,24 @@
import PackageDescription

let package = Package(
name: "cgtcalc",
products: [
.library(name: "CGTCalcCore", targets: ["CGTCalcCore"]),
.executable(name: "cgtcalc", targets: ["cgtcalc"]),
],
dependencies: [
.package(url: "https://github.com/apple/swift-argument-parser", from: "0.1.0")
],
targets: [
.target(
name: "CGTCalcCore"
),
.target(
name: "cgtcalc",
dependencies: [
"CGTCalcCore",
.product(name: "ArgumentParser", package: "swift-argument-parser")
]
),
.testTarget(
name: "CGTCalcCoreTests",
dependencies: ["CGTCalcCore"]
),
]
)
name: "cgtcalc",
products: [
.library(name: "CGTCalcCore", targets: ["CGTCalcCore"]),
.executable(name: "cgtcalc", targets: ["cgtcalc"])
],
dependencies: [
.package(url: "https://github.com/apple/swift-argument-parser", from: "0.1.0")
],
targets: [
.target(
name: "CGTCalcCore"),
.target(
name: "cgtcalc",
dependencies: [
"CGTCalcCore",
.product(name: "ArgumentParser", package: "swift-argument-parser")
]),
.testTarget(
name: "CGTCalcCoreTests",
dependencies: ["CGTCalcCore"])
])
4 changes: 1 addition & 3 deletions Sources/CGTCalcCore/Calculator/AssetProcessorState.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,7 @@ class AssetProcessorState {
var processedDisposals: [TransactionToMatch] = []
var disposalMatches: [DisposalMatch] = []

var isComplete: Bool {
get { self.pendingDisposals.isEmpty }
}
var isComplete: Bool { self.pendingDisposals.isEmpty }

init(asset: String, acquisitions: [TransactionToMatch], disposals: [TransactionToMatch], assetEvents: [AssetEvent]) {
self.asset = asset
Expand Down
38 changes: 24 additions & 14 deletions Sources/CGTCalcCore/Calculator/Calculator.swift
Original file line number Diff line number Diff line change
Expand Up @@ -35,13 +35,13 @@ public class Calculator {

private func processTransactions() throws -> CalculatorResult {
let transactionsByAsset = self.input.transactions
.reduce(into: [String:[Transaction]]()) { (result, transaction) in
.reduce(into: [String: [Transaction]]()) { result, transaction in
var transactions = result[transaction.asset, default: []]
transactions.append(transaction)
result[transaction.asset] = transactions
}
let assetEventsByAsset = self.input.assetEvents
.reduce(into: [String:[AssetEvent]]()) { (result, assetEvent) in
.reduce(into: [String: [AssetEvent]]()) { result, assetEvent in
var assetEvents = result[assetEvent.asset, default: []]
assetEvents.append(assetEvent)
result[assetEvent.asset] = assetEvents
Expand All @@ -64,11 +64,15 @@ public class Calculator {
}
}
let assetEvents = assetEventsByAsset[asset, default: []].sorted { $0.date < $1.date }
let state = AssetProcessorState(asset: asset, acquisitions: acquisitions, disposals: disposals, assetEvents: assetEvents)
let state = AssetProcessorState(
asset: asset,
acquisitions: acquisitions,
disposals: disposals,
assetEvents: assetEvents)
try self.preprocessAsset(withState: state)
return try processAsset(withState: state)
}
.reduce(into: [DisposalMatch]()) { (disposalMatches, assetResult) in
.reduce(into: [DisposalMatch]()) { disposalMatches, assetResult in
disposalMatches.append(contentsOf: assetResult.disposalMatches)
}

Expand All @@ -79,19 +83,19 @@ public class Calculator {
let initial: ([Transaction], Transaction?) = ([], nil)
return try transactions
.sorted { $0.date < $1.date }
.reduce(into: initial) { (returnValue, transaction) in
.reduce(into: initial) { returnValue, transaction in
guard let groupTransaction = returnValue.1 else {
returnValue.0.append(transaction)
returnValue.1 = transaction
return
}
if groupTransaction.date == transaction.date && groupTransaction.kind == transaction.kind {
if groupTransaction.date == transaction.date, groupTransaction.kind == transaction.kind {
try groupTransaction.groupWith(transaction: transaction)
} else {
returnValue.0.append(transaction)
returnValue.1 = transaction
}
}.0
}.0
}

private func preprocessAsset(withState state: AssetProcessorState) throws {
Expand All @@ -109,7 +113,7 @@ public class Calculator {
// First go over all the capital returns and decrease the price paid for acquisitions.
var acquisitionsIndex = state.pendingAcquisitions.startIndex
var assetEventsIndex = state.assetEvents.startIndex
while assetEventsIndex < state.assetEvents.endIndex && acquisitionsIndex < state.pendingAcquisitions.endIndex {
while assetEventsIndex < state.assetEvents.endIndex, acquisitionsIndex < state.pendingAcquisitions.endIndex {
let assetEvent = state.assetEvents[assetEventsIndex]

let amount: Decimal
Expand All @@ -126,7 +130,7 @@ public class Calculator {
self.logger.debug(" - Processing capital return event: \(assetEvent).")

var amountLeft = amount
while amountLeft > Decimal.zero && acquisitionsIndex < state.pendingAcquisitions.endIndex {
while amountLeft > Decimal.zero, acquisitionsIndex < state.pendingAcquisitions.endIndex {
let acquisition = state.pendingAcquisitions[acquisitionsIndex]
let apportionedValue = value * (acquisition.amount / amount)
self.logger.debug(" - Matching to acquisition \(acquisition), apportioned value of \(apportionedValue).")
Expand All @@ -136,7 +140,8 @@ public class Calculator {
}

if amountLeft != Decimal.zero {
throw CalculatorError.InvalidData("Error pre-processing \(state.asset). Capital return amount doesn't match acquisitions.")
throw CalculatorError
.InvalidData("Error pre-processing \(state.asset). Capital return amount doesn't match acquisitions.")
}

assetEventsIndex += 1
Expand All @@ -162,10 +167,12 @@ public class Calculator {

var amountLeft = amount
var acquisitionsIndex = state.pendingAcquisitions.startIndex
while amountLeft > Decimal.zero && acquisitionsIndex < state.pendingAcquisitions.endIndex {
while amountLeft > Decimal.zero, acquisitionsIndex < state.pendingAcquisitions.endIndex {
let acquisition = state.pendingAcquisitions[acquisitionsIndex]
guard acquisition.date <= assetEvent.date else {
throw CalculatorError.InvalidData("Error pre-processing \(state.asset) while processing dividend events. Went past asset event date while matching acquisitions.")
throw CalculatorError
.InvalidData(
"Error pre-processing \(state.asset) while processing dividend events. Went past asset event date while matching acquisitions.")
}

let apportionedValue = value * (acquisition.amount / amount)
Expand All @@ -176,7 +183,9 @@ public class Calculator {
}

if amountLeft != Decimal.zero {
throw CalculatorError.InvalidData("Error pre-processing \(state.asset) while processing dividend events. Amount doesn't match acquisitions.")
throw CalculatorError
.InvalidData(
"Error pre-processing \(state.asset) while processing dividend events. Amount doesn't match acquisitions.")
}

assetEventsIndex += 1
Expand All @@ -200,7 +209,8 @@ public class Calculator {

self.logger.debug("Tax events for \(state.asset)")
state.disposalMatches.forEach { self.logger.debug(" \($0)") }
self.logger.info("Finished processing transactions for \(state.asset). Created \(state.disposalMatches.count) tax events.")
self.logger
.info("Finished processing transactions for \(state.asset). Created \(state.disposalMatches.count) tax events.")

return AssetResult(asset: state.asset, disposalMatches: state.disposalMatches)
}
Expand Down
18 changes: 13 additions & 5 deletions Sources/CGTCalcCore/Calculator/CalculatorResult.swift
Original file line number Diff line number Diff line change
Expand Up @@ -33,15 +33,15 @@ public struct CalculatorResult {

var carryForwardLoss = Decimal.zero
self.taxYearSummaries = try disposalMatches
.reduce(into: [TaxYear:[DisposalMatch]]()) { (result, disposalMatch) in
.reduce(into: [TaxYear: [DisposalMatch]]()) { result, disposalMatch in
var disposalMatches = result[disposalMatch.taxYear, default: []]
disposalMatches.append(disposalMatch)
result[disposalMatch.taxYear] = disposalMatches
}
.sorted { $0.key < $1.key }
.map { (taxYear, disposalMatches) in
var disposalMatchesByDisposal: [Transaction:[DisposalMatch]] = [:]
var gainByDisposal: [Transaction:Decimal] = [:]
.map { taxYear, disposalMatches in
var disposalMatchesByDisposal: [Transaction: [DisposalMatch]] = [:]
var gainByDisposal: [Transaction: Decimal] = [:]

var totalProceeds = Decimal.zero

Expand Down Expand Up @@ -82,7 +82,15 @@ public struct CalculatorResult {
let basicRateTax = TaxMethods.roundedGain(taxableGain * taxYearRates.basicRate * 0.01)
let higherRateTax = TaxMethods.roundedGain(taxableGain * taxYearRates.higherRate * 0.01)

return TaxYearSummary(taxYear: taxYear, gain: totalGain, proceeds: TaxMethods.roundedGain(totalProceeds), carryForwardLoss: carryForwardLoss, taxableGain: taxableGain, basicRateTax: basicRateTax, higherRateTax: higherRateTax, disposalResults: disposalResults)
return TaxYearSummary(
taxYear: taxYear,
gain: totalGain,
proceeds: TaxMethods.roundedGain(totalProceeds),
carryForwardLoss: carryForwardLoss,
taxableGain: taxableGain,
basicRateTax: basicRateTax,
higherRateTax: higherRateTax,
disposalResults: disposalResults)
}
}
}
23 changes: 16 additions & 7 deletions Sources/CGTCalcCore/Calculator/MatchingProcessor.swift
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,16 @@ class MatchingProcessor {
try self.process(kind: .SameDay)
try self.process(kind: .BedAndBreakfast)

self.logger.info("Finished matching processor. Matched \(self.matchCount) and there are \(self.state.pendingDisposals.count) disposals left.")
self.logger
.info(
"Finished matching processor. Matched \(self.matchCount) and there are \(self.state.pendingDisposals.count) disposals left.")
}

private func process(kind: Kind) throws {
var acquisitionIndex = self.state.pendingAcquisitions.startIndex
var disposalIndex = self.state.pendingDisposals.startIndex
while acquisitionIndex < self.state.pendingAcquisitions.endIndex && disposalIndex < self.state.pendingDisposals.endIndex {
while acquisitionIndex < self.state.pendingAcquisitions.endIndex,
disposalIndex < self.state.pendingDisposals.endIndex {
let acquisition = self.state.pendingAcquisitions[acquisitionIndex]
let disposal = self.state.pendingDisposals[disposalIndex]

Expand All @@ -53,7 +56,7 @@ class MatchingProcessor {
if acquisition.date < disposal.date {
acquisitionIndex += 1
continue
} else if disposal.date.addingTimeInterval(60*60*24*30) < acquisition.date {
} else if disposal.date.addingTimeInterval(60 * 60 * 24 * 30) < acquisition.date {
disposalIndex += 1
continue
}
Expand All @@ -67,10 +70,10 @@ class MatchingProcessor {
currentMultiplier *= m
case .Unsplit(let m):
currentMultiplier /= m
case .CapitalReturn(_, _), .Dividend(_, _):
case .CapitalReturn(_, _), .Dividend:
break
}
}
}
restructureMultiplier = currentMultiplier
}

Expand All @@ -89,9 +92,15 @@ class MatchingProcessor {
let disposalMatch: DisposalMatch
switch kind {
case .SameDay:
disposalMatch = DisposalMatch(kind: .SameDay(acquisition), disposal: disposal, restructureMultiplier: restructureMultiplier)
disposalMatch = DisposalMatch(
kind: .SameDay(acquisition),
disposal: disposal,
restructureMultiplier: restructureMultiplier)
case .BedAndBreakfast:
disposalMatch = DisposalMatch(kind: .BedAndBreakfast(acquisition), disposal: disposal, restructureMultiplier: restructureMultiplier)
disposalMatch = DisposalMatch(
kind: .BedAndBreakfast(acquisition),
disposal: disposal,
restructureMultiplier: restructureMultiplier)
}

self.logger.info("Matched \(disposal) against \(acquisition).")
Expand Down
20 changes: 11 additions & 9 deletions Sources/CGTCalcCore/Calculator/Section104Holding.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,18 +15,18 @@ class Section104Holding {
private(set) var amount: Decimal
private(set) var cost: Decimal
var costBasis: Decimal {
if amount.isZero {
if self.amount.isZero {
return 0
}
return cost / amount
return self.cost / self.amount
}

mutating fileprivate func add(amount: Decimal, cost: Decimal) {
fileprivate mutating func add(amount: Decimal, cost: Decimal) {
self.amount += amount
self.cost += cost
}

mutating fileprivate func remove(amount: Decimal) {
fileprivate mutating func remove(amount: Decimal) {
let costBasis = self.costBasis
self.amount -= amount
self.cost -= amount * costBasis
Expand All @@ -35,11 +35,11 @@ class Section104Holding {
}
}

mutating fileprivate func multiplyAmount(by: Decimal) {
fileprivate mutating func multiplyAmount(by: Decimal) {
self.amount *= by
}

mutating fileprivate func divideAmount(by: Decimal) {
fileprivate mutating func divideAmount(by: Decimal) {
self.amount /= by
}
}
Expand All @@ -61,7 +61,10 @@ class Section104Holding {
throw CalculatorError.InvalidData("Disposing of more than is currently held")
}

let disposalMatch = DisposalMatch(kind: .Section104(self.state.amount, self.state.costBasis), disposal: disposal, restructureMultiplier: Decimal(1))
let disposalMatch = DisposalMatch(
kind: .Section104(self.state.amount, self.state.costBasis),
disposal: disposal,
restructureMultiplier: Decimal(1))

self.state.remove(amount: disposal.amount)
self.logger.debug(" New state: \(self.state)")
Expand All @@ -81,9 +84,8 @@ class Section104Holding {
self.state.divideAmount(by: multiplier)
self.logger.debug(" Rebasing by dividing holding by \(multiplier)")
self.logger.debug(" New state: \(self.state)")
case .CapitalReturn(_, _), .Dividend(_, _):
case .CapitalReturn(_, _), .Dividend:
self.logger.debug(" Nothing to do for this asset event.")
break
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion Sources/CGTCalcCore/Calculator/Section104Processor.swift
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ class Section104Processor {
assetEventDate = .distantFuture
}

if assetEventDate <= acquisitionDate && assetEventDate <= disposal.date {
if assetEventDate <= acquisitionDate, assetEventDate <= disposal.date {
let assetEvent = self.state.assetEvents[assetEventIndex]
section104Holding.process(assetEvent: assetEvent)
assetEventIndex += 1
Expand Down
Loading

0 comments on commit b890449

Please sign in to comment.