├── .gitignore ├── .travis.yml ├── CHANGELOG.md ├── LICENSE ├── README.md ├── build.sbt ├── patchless-circe └── src │ ├── main │ └── scala │ │ └── patchless │ │ └── circe │ │ ├── extras │ │ └── package.scala │ │ └── package.scala │ └── test │ └── scala │ └── patchless │ └── circe │ ├── PatchJsonSpec.scala │ └── extras │ └── ConfigurablePatchJsonSpec.scala ├── patchless-core └── src │ ├── main │ └── scala │ │ └── patchless │ │ ├── Patch.scala │ │ └── Patchable.scala │ └── test │ └── scala │ └── patchless │ └── PatchSpec.scala ├── project ├── build.properties └── plugins.sbt └── version.sbt /.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | .idea 3 | .DS_Store 4 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: false 2 | 3 | language: scala 4 | 5 | scala: 6 | - 2.11.12 7 | - 2.12.10 8 | - 2.13.1 9 | 10 | jdk: 11 | - oraclejdk9 12 | 13 | cache: 14 | directories: 15 | - $HOME/.ivy2/cache 16 | - $HOME/.sbt/boot/ 17 | 18 | script: 19 | - sbt clean +test 20 | 21 | before_cache: 22 | - find $HOME/.ivy2 -name "ivydata-*.properties" -delete 23 | - find $HOME/.sbt -name "*.lock" -delete 24 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Change Log 2 | All notable changes to this project will be documented in this file. 3 | This project adheres to [Semantic Versioning](http://semver.org/). 4 | 5 | ## 1.0.7 - 2020-02-05 6 | * Added Scala 2.13.1 build 7 | * Updated circe to 0.12.12 (except for Scala 2.11) 8 | 9 | ## 1.0.6 - 2020-02-05 10 | * Updated circe to 0.11.2 11 | * Updated scala 2.12 to 2.12.10 12 | 13 | ## 1.0.5 - 2018-03-27 14 | * Updated circe to 0.9.0 15 | * Updated Scala 2.12 to 2.12.4 16 | 17 | ## 1.0.4 - 2017-04-20 18 | * Updated circe to 0.7.1 19 | * Updated Scala to 2.11.11 and 2.12.2 20 | 21 | ## 1.0.3 - 2016-11-29 22 | * Added `equals` implementation for `Patch` 23 | * Added Scala 2.12 support 24 | 25 | ## 1.0.2 - 2016-11-28 26 | * Add apply syntax for `Patch` 27 | 28 | ## 1.0.1 - 2016-11-28 29 | * Minor cleanup 30 | 31 | ## 1.0.0 - 2016-11-27 32 | * Initial release 33 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # patchless 2 | [![Build Status](https://travis-ci.org/jeremyrsmith/patchless.svg?branch=master)](https://travis-ci.org/jeremyrsmith/patchless) 3 | [![Maven Central](https://maven-badges.herokuapp.com/maven-central/io.github.jeremyrsmith/patchless_2.11/badge.svg?style=plastic)](https://maven-badges.herokuapp.com/maven-central/io.github.jeremyrsmith/patchless_2.11) 4 | 5 | 6 | 7 | **patchless** is a tiny Scala library which provides: 8 | 9 | * A data type `Patch[T]`, which extends `T => T` and encapsulates a set of updates to be performed to values of type `T`. 10 | * A typeclass `Patchable[T]`, which supports the data type above. 11 | 12 | It uses [shapeless](https://github.com/milessabin/shapeless) to derive `Patchable[T]` for any case class. 13 | 14 | ## Dependency 15 | 16 | Patchless is published to Maven Central – put this in your build.sbt: 17 | 18 | ```scala 19 | libraryDependencies += "io.github.jeremyrsmith" %% "patchless" % "1.0.4" 20 | ``` 21 | 22 | ## Usage 23 | The core of patchless provides only two simple way to create a `Patch[T]` for any given `T`: 24 | 25 | * The `apply` syntax (macro-driven): 26 | 27 | ```scala 28 | import patchless.Patch 29 | case class Foo(a: String, b: Int, c: Boolean) 30 | val patch = Patch[Foo](b = 22) 31 | ``` 32 | 33 | * The `Patch.diff[T]` static method: 34 | 35 | ```scala 36 | case class Foo(a: String, b: Int, c: Boolean) 37 | val a = Foo("test", 22, true) 38 | val b = Foo("patched", 22, true) 39 | val patch = Patch.diff(a, b) 40 | patch(a) // Foo("patched", 22, true) 41 | patch(Foo("wibble", 44, false)) // Foo("patched", 44, false) 42 | ``` 43 | 44 | Additionally, the `patchless-circe` module provides decoders directly from JSON to `Patch[T]`. See 45 | [below](#patchless-circe) for details. 46 | 47 | ### Using the patch fields 48 | The primary advantage of `Patch[T]` over simply `T => T` is that the updated fields can be accessed as a shapeless 49 | `Record` of `Option`s. Each field retains the name from the original case class `T`, but its value type is lifted to 50 | an `Option` of the original type within the case class. 51 | 52 | The `Record` is accessible in two ways. The first is simply by the `updates` member of the `Patch` value: 53 | 54 | ```scala 55 | println(patch) // Some("patched") :: None :: None :: HNil 56 | ``` 57 | 58 | This alone doesn't turn out to be all that useful from a typelevel standpoint - Scala doesn't inherently know the type 59 | of the `updates` field, so your options there are limited. 60 | 61 | So patchless does some additional type voodoo to allow you to recover a statically known `Record` for a `Patch[T]` of a 62 | concrete, statically known type `T`. This is done with the implicit enrichment method `patchUpdates`, which allows you 63 | to do typelevel things like mapping over the updates `HList` or summoning typeclasses for it: 64 | 65 | ```scala 66 | object mapUpdates extends Poly1 { 67 | implicit def cases[K <: Symbol, T](implicit 68 | name: Witness.Aux[K] 69 | ) = at[FieldType[K, T]] { 70 | field => name.value.name -> field.toString 71 | } 72 | } 73 | patch.patchUpdates.map(mapUpdates).toList 74 | // List(("a", "Some(patched)"), ("b", "None"), ("c", "None")) 75 | ``` 76 | 77 | Please note that this only works for a concrete `T`. If `T` is abstract (such as in a polymorphic method over `Patch` 78 | types) then you'll still have to parameterize over various `HList` types and require various implicit shapeless `Aux` 79 | typeclasses over them as usual – starting with `Patchable.Aux[T, U]` where `U` will be inferred to the type of the 80 | `Updates` record for `T`. 81 | 82 | ```scala 83 | def doPatchyStuff[T, U <: HList, A <: HList](patch: Patch[T])(implicit 84 | patchable: Patchable.Aux[T, U], 85 | liftAll: LiftAll.Aux[MyTC, U, A], 86 | toList: ToList[A, Any] 87 | ) = ??? 88 | ``` 89 | 90 | Also, be aware that `patchUpdates` involves a typecast; it's assumed that the `Updates` of the `Patch[T]` value has the 91 | same type as the `Patchable[T]` that is in implicit scope. This is usually a safe assumption, but it's not *guaranteed* 92 | to be safe. In an effort to make it as close as possible to a guarantee, `Patchable` is defined as `sealed`, which means 93 | that only the blessed derivations can ever be used to create it; these ought to be deterministic for a particular `T`, 94 | but Scala provides no way to express this and thus a typecast is still necessary. 95 | 96 | ## patchless-circe 97 | 98 | Derived decoders and encoders are provided in the `patchless-circe` module. 99 | 100 | In build.sbt: 101 | 102 | ```scala 103 | libraryDependencies += "io.github.jeremyrsmith" %% "patchless-circe" % "1.0.2" 104 | ``` 105 | 106 | There are two different imports, depending on how you're using circe. You need to have at least `circe-generic`, and 107 | you can also optionally use `circe-generic-extras` (which is marked as a provided dependency in case you don't use it). 108 | 109 | You also need to be using automatic derivation for this to be of any use; it's not possible to derive a `Patch[T]` decoder 110 | for a semiauto or manual decoder of `T`. 111 | 112 | For vanilla automatic derivation: 113 | 114 | ```scala 115 | import io.circe.generic.auto._ 116 | import patchless.circe._ 117 | import cats.syntax.either._ // for working with results 118 | 119 | case class Foo(aString: String, bInt: Int) 120 | val parsed = io.circe.parser.parse("""{"aString": "patched"}""") 121 | parsed.valueOr(throw _).as[Patch[Foo]].valueOr(throw _) 122 | parsed.updates // Some("patched") :: None :: HNil 123 | parsed(Foo("blah", 22)) // Foo("patched", 22) 124 | ``` 125 | 126 | Configurable derivation is the same, but import `patchless.circe.extras._` instead; your implicit `Configuration` will 127 | be used to derive the decoders for `Patch` types. 128 | 129 | Encoders work the same way, but be aware that the JSON output depends on the printer used – in particular, you'll 130 | typically want to `dropNullKeys` if you're outputting `Patch` values to JSON. 131 | 132 | ## License 133 | 134 | Licensed under the **[Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0)** (the "License"); 135 | you may not use this software except in compliance with the License. 136 | 137 | Unless required by applicable law or agreed to in writing, software 138 | distributed under the License is distributed on an "AS IS" BASIS, 139 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 140 | See the License for the specific language governing permissions and 141 | limitations under the License. 142 | 143 | ## Code of Conduct 144 | The patchless project supports the [Typelevel Code of Conduct](http://typelevel.org/conduct.html) and wants all its channels 145 | to be welcoming environments for everyone. 146 | -------------------------------------------------------------------------------- /build.sbt: -------------------------------------------------------------------------------- 1 | val versions = new { 2 | val circe211 = "0.11.2" 3 | val circe = "0.12.2" 4 | val shapeless = "2.3.3" 5 | val scalatest = "3.1.0" 6 | val scalacheck = "1.14.1" 7 | } 8 | 9 | val circeVersion = settingKey[String]("Circe version for the target Scala binary version") 10 | 11 | inThisBuild(List( 12 | scalaVersion := "2.11.12", 13 | crossScalaVersions := Seq("2.11.12","2.12.10","2.13.1"), 14 | organization := "io.github.jeremyrsmith", 15 | libraryDependencies ++= Seq( 16 | "org.scalatest" %% "scalatest" % versions.scalatest % "test", 17 | "org.scalacheck" %% "scalacheck" % versions.scalacheck % "test" 18 | ), 19 | licenses := Seq("Apache-2.0" -> url("http://www.apache.org/licenses/LICENSE-2.0")), 20 | homepage := Some(url("https://github.com/jeremyrsmith/patchless")), 21 | scmInfo := Some( 22 | ScmInfo( 23 | url("https://github.com/jeremyrsmith/patchless"), 24 | "scm:git:git@github.com:jeremyrsmith/patchless.git" 25 | ) 26 | ), 27 | pomExtra := { 28 | 29 | 30 | jeremyrsmith 31 | Jeremy Smith 32 | https://github.com/jeremyrsmith 33 | 34 | 35 | } 36 | )) 37 | 38 | val `patchless-core` = project.settings( 39 | name := "patchless-core", 40 | publishTo := sonatypePublishToBundle.value, 41 | libraryDependencies ++= Seq( 42 | "com.chuusai" %% "shapeless" % versions.shapeless, 43 | "org.scala-lang" % "scala-reflect" % scalaVersion.value % "provided" 44 | ) 45 | ) 46 | 47 | val `patchless-circe` = project.settings( 48 | name := "patchless-circe", 49 | publishTo := sonatypePublishToBundle.value, 50 | circeVersion := (if (scalaBinaryVersion.value == "2.11") versions.circe211 else versions.circe), 51 | libraryDependencies ++= Seq( 52 | "io.circe" %% "circe-generic" % circeVersion.value, 53 | "io.circe" %% "circe-generic-extras" % circeVersion.value % "provided,test", 54 | "io.circe" %% "circe-parser" % circeVersion.value % "test" 55 | ) 56 | ).dependsOn(`patchless-core`) 57 | 58 | val `patchless` = (project in file(".")). 59 | settings( 60 | name := "patchless", 61 | publishArtifact := false, 62 | publish := {}, 63 | publishLocal := {}, 64 | skip in publish := true 65 | ). 66 | aggregate(`patchless-core`, `patchless-circe`) 67 | 68 | -------------------------------------------------------------------------------- /patchless-circe/src/main/scala/patchless/circe/extras/package.scala: -------------------------------------------------------------------------------- 1 | package patchless.circe 2 | 3 | import cats.syntax.either._ 4 | import io.circe.{Decoder, HCursor, Json, JsonObject} 5 | import io.circe.generic.decoding.DerivedDecoder 6 | import io.circe.generic.extras.decoding.ReprDecoder 7 | import io.circe.generic.encoding.DerivedObjectEncoder 8 | import io.circe.generic.extras.Configuration 9 | import io.circe.generic.extras.encoding.ReprObjectEncoder 10 | import io.circe.generic.extras.util.RecordToMap 11 | import patchless.{Patch, Patchable} 12 | import shapeless.{Default, HList, Lazy} 13 | 14 | package object extras { 15 | 16 | /** 17 | * This is necessary to allow patching optional fields: https://github.com/circe/circe/issues/304 18 | */ 19 | implicit def decodeOptionOption[T]( 20 | implicit decodeOpt: Decoder[Option[T]] 21 | ) : Decoder[Option[Option[T]]] = 22 | Decoder.withReattempt { 23 | c => if (c.succeeded) c.as[Option[T]].map(Some(_)) else Right(None) 24 | } 25 | 26 | implicit def decodePatch[T, U <: HList, D <: HList](implicit 27 | patchable: Patchable.Aux[T, U], 28 | decodeU: Lazy[ReprDecoder[U]], 29 | defaults: Default.AsRecord.Aux[T, D], 30 | defaultMapper: RecordToMap[D], 31 | config: Configuration 32 | ): DerivedDecoder[Patch[T]] = new DerivedDecoder[Patch[T]] { 33 | def apply(c: HCursor): Decoder.Result[Patch[T]] = decodeU.value.configuredDecode(c)( 34 | config.transformMemberNames, 35 | config.transformConstructorNames, 36 | if(config.useDefaults) defaultMapper(defaults()) else Map.empty, 37 | config.discriminator 38 | ).map { 39 | updates => 40 | Patch.ofUpdates[T, U](updates) 41 | } 42 | } 43 | 44 | implicit def encodePatch[T, U <: HList](implicit 45 | patchable: Patchable.Aux[T, U], 46 | encodeU: Lazy[ReprObjectEncoder[U]], 47 | config: Configuration 48 | ): DerivedObjectEncoder[Patch[T]] = new DerivedObjectEncoder[Patch[T]] { 49 | def encodeObject(a: Patch[T]): JsonObject = encodeU.value.configuredEncodeObject(a.patchUpdates)( 50 | config.transformMemberNames, 51 | config.transformConstructorNames, 52 | config.discriminator 53 | ) 54 | } 55 | 56 | } 57 | -------------------------------------------------------------------------------- /patchless-circe/src/main/scala/patchless/circe/package.scala: -------------------------------------------------------------------------------- 1 | package patchless 2 | 3 | import cats.syntax.either._ 4 | import io.circe.Decoder.Result 5 | import io.circe.{Decoder, HCursor, Json, JsonObject} 6 | import io.circe.generic.decoding.{DerivedDecoder, ReprDecoder} 7 | import io.circe.generic.encoding.{DerivedObjectEncoder, ReprObjectEncoder} 8 | import shapeless.{HList, LabelledGeneric} 9 | 10 | package object circe { 11 | 12 | /** 13 | * This is necessary to allow patching optional fields: https://github.com/circe/circe/issues/304 14 | */ 15 | implicit def decodeOptionOption[T]( 16 | implicit decodeOpt: Decoder[Option[T]] 17 | ) : Decoder[Option[Option[T]]] = { 18 | Decoder.instance { 19 | cursor => if(cursor.focus == Json.Null) { 20 | Right(Some(None)) 21 | } else decodeOpt.apply(cursor).map(Some(_)) 22 | } 23 | } 24 | 25 | implicit def decodePatch[T, U <: HList](implicit 26 | patchable: Patchable.Aux[T, U], 27 | decodeU: ReprDecoder[U] 28 | ): DerivedDecoder[Patch[T]] = new DerivedDecoder[Patch[T]] { 29 | def apply(c: HCursor): Result[Patch[T]] = decodeU(c).map { 30 | updates => 31 | Patch.ofUpdates[T, U](updates) 32 | } 33 | } 34 | 35 | implicit def encodePatch[T, U <: HList](implicit 36 | patchable: Patchable.Aux[T, U], 37 | encodeU: ReprObjectEncoder[U] 38 | ): DerivedObjectEncoder[Patch[T]] = new DerivedObjectEncoder[Patch[T]] { 39 | def encodeObject(a: Patch[T]): JsonObject = encodeU.encodeObject(a.patchUpdates) 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /patchless-circe/src/test/scala/patchless/circe/PatchJsonSpec.scala: -------------------------------------------------------------------------------- 1 | package patchless.circe 2 | 3 | import cats.syntax.either._ 4 | import org.scalatest.{FreeSpec, Matchers} 5 | import io.circe.parser.parse 6 | import patchless.Patch 7 | import shapeless.record.Record 8 | import io.circe.generic.auto._ 9 | 10 | class PatchJsonSpec extends FreeSpec with Matchers { 11 | 12 | "Decoder" - { 13 | 14 | "Auto" in { 15 | case class Foo(aString: String, bInt: Int, cBoolean: Boolean) 16 | 17 | def parsePatch(str: String) = 18 | parse(str).valueOr(throw _).as[Patch[Foo]].valueOr(throw _) 19 | 20 | val aPatched = parsePatch("""{"aString": "patched"}""") 21 | val bPatched = parsePatch("""{"bInt": 22}""") 22 | val cPatched = parsePatch("""{"cBoolean": false}""") 23 | 24 | aPatched.updates shouldEqual Record(aString = Some("patched"), bInt = None, cBoolean = None) 25 | bPatched.updates shouldEqual Record(aString = None, bInt = Some(22), cBoolean = None) 26 | cPatched.updates shouldEqual Record(aString = None, bInt = None, cBoolean = Some(false)) 27 | } 28 | 29 | "Options" in { 30 | case class Foo(aString: Option[String]) 31 | def parsePatch(str: String) = 32 | parse(str).valueOr(throw _).as[Patch[Foo]].valueOr(throw _) 33 | 34 | val aPatchedSome = parsePatch("""{"aString": "patched"}""") 35 | val aPatchedNone = parsePatch("""{"aString": null}""") 36 | 37 | aPatchedSome.updates shouldEqual Record(aString = Some(Some("patched"))) 38 | aPatchedNone.updates shouldEqual Record(aString = Some(None)) 39 | } 40 | 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /patchless-circe/src/test/scala/patchless/circe/extras/ConfigurablePatchJsonSpec.scala: -------------------------------------------------------------------------------- 1 | package patchless.circe.extras 2 | 3 | import cats.syntax.either._ 4 | import io.circe.generic.extras.Configuration 5 | import io.circe.generic.extras.auto._ 6 | import io.circe.parser.parse 7 | import org.scalatest.{FreeSpec, Matchers} 8 | import patchless.Patch 9 | import shapeless.record.Record 10 | 11 | class ConfigurablePatchJsonSpec extends FreeSpec with Matchers { 12 | 13 | 14 | "Configurable decoder" - { 15 | "Normal" in { 16 | import io.circe.generic.extras.defaults._ 17 | case class Foo(aString: String, bInt: Int, cBoolean: Boolean) 18 | 19 | def parsePatch(str: String) = 20 | parse(str).valueOr(throw _).as[Patch[Foo]].valueOr(throw _) 21 | 22 | val aPatched = parsePatch("""{"aString": "patched"}""") 23 | val bPatched = parsePatch("""{"bInt": 22}""") 24 | val cPatched = parsePatch("""{"cBoolean": false}""") 25 | 26 | aPatched.updates shouldEqual Record(aString = Some("patched"), bInt = None, cBoolean = None) 27 | bPatched.updates shouldEqual Record(aString = None, bInt = Some(22), cBoolean = None) 28 | cPatched.updates shouldEqual Record(aString = None, bInt = None, cBoolean = Some(false)) 29 | } 30 | 31 | "Snake case" in { 32 | implicit val configuration = Configuration.default.withSnakeCaseMemberNames 33 | case class Foo(aString: String, bInt: Int, cBoolean: Boolean) 34 | 35 | def parsePatch(str: String) = 36 | parse(str).valueOr(throw _).as[Patch[Foo]].valueOr(throw _) 37 | 38 | val aPatched = parsePatch("""{"a_string": "patched"}""") 39 | val bPatched = parsePatch("""{"b_int": 22}""") 40 | val cPatched = parsePatch("""{"c_boolean": false}""") 41 | 42 | aPatched.updates shouldEqual Record(aString = Some("patched"), bInt = None, cBoolean = None) 43 | bPatched.updates shouldEqual Record(aString = None, bInt = Some(22), cBoolean = None) 44 | cPatched.updates shouldEqual Record(aString = None, bInt = None, cBoolean = Some(false)) 45 | } 46 | 47 | "Options" in { 48 | import io.circe.generic.extras.defaults._ 49 | case class Foo(aString: Option[String]) 50 | def parsePatch(str: String) = 51 | parse(str).valueOr(throw _).as[Patch[Foo]].valueOr(throw _) 52 | 53 | val aPatchedSome = parsePatch("""{"aString": "patched"}""") 54 | val aPatchedNone = parsePatch("""{"aString": null}""") 55 | 56 | aPatchedSome.updates shouldEqual Record(aString = Some(Some("patched"))) 57 | aPatchedNone.updates shouldEqual Record(aString = Some(None)) 58 | } 59 | 60 | } 61 | 62 | } 63 | -------------------------------------------------------------------------------- /patchless-core/src/main/scala/patchless/Patch.scala: -------------------------------------------------------------------------------- 1 | package patchless 2 | 3 | import scala.annotation.tailrec 4 | 5 | import shapeless.labelled.{FieldType, field} 6 | import shapeless.ops.hlist.{Mapper, Zip} 7 | import shapeless._ 8 | import scala.language.experimental.macros 9 | import scala.language.dynamics 10 | 11 | abstract class Patch[T] extends (T => T) { 12 | type Updates <: HList 13 | def updates: Updates 14 | 15 | override def equals(obj: scala.Any): Boolean = obj match { 16 | case patch: Patch[_] => patch.updates == updates 17 | case _ => false 18 | } 19 | } 20 | 21 | object Patch extends Dynamic { 22 | 23 | type Aux[T, U <: HList] = Patch[T] { type Updates = U } 24 | 25 | def applyDynamicNamed[T](method: String)(rec: Any*): Patch[T] = macro PatchMacros.mkPatchImpl[T] 26 | 27 | def ofUpdates[T, U <: HList](up: U)(implicit 28 | patchable: Patchable.Aux[T, U] 29 | ): Aux[T, U] = new Patch[T] { 30 | type Updates = U 31 | val updates: U = up 32 | def apply(t: T): T = patchable(t, up) 33 | } 34 | 35 | def diff[T, L <: HList, Z <: HList, U <: HList](a: T, b: T)(implicit 36 | gen: LabelledGeneric.Aux[T, L], 37 | zip: Zip.Aux[L :: L :: HNil, Z], 38 | patchable: Patchable.Aux[T, U], 39 | mapper: Mapper.Aux[differences.type, Z, U] 40 | ): Aux[T, U] = ofUpdates[T, U](mapper(zip(gen.to(a) :: gen.to(b) :: HNil))) 41 | 42 | 43 | object differences extends Poly1 { 44 | implicit def cases[K <: Symbol, V] = at[(FieldType[K, V], FieldType[K, V])] { 45 | case (a, b) => if(a == b) 46 | field[K](None: Option[V]) 47 | else 48 | field[K](Some(b): Option[V]) 49 | } 50 | } 51 | 52 | abstract class Updates[T, U <: HList] { 53 | type Updates = U 54 | } 55 | 56 | implicit class ConcretePatchOps[T, U <: HList](val patch: Patch[T])(implicit 57 | patchable: Patchable.Aux[T, U] 58 | ) { 59 | def patchUpdates: U = patch.updates.asInstanceOf[U] 60 | } 61 | 62 | } 63 | 64 | // Macros to support patch Apply syntax 65 | class PatchMacros(ctx: scala.reflect.macros.whitebox.Context) extends RecordMacros(ctx) { 66 | import c.universe._ 67 | def mkPatchImpl[T: WeakTypeTag](method: c.Expr[String])(rec: Tree*): Tree = { 68 | val T = weakTypeOf[T] 69 | val patchable = c.inferImplicitValue( 70 | appliedType(weakTypeOf[Patchable[_]].typeConstructor, T), 71 | silent = false 72 | ) 73 | val typ = patchable.tpe.typeArgs.lastOption.getOrElse { 74 | c.abort(c.enclosingPosition, s"No Updates type found for $T") 75 | } 76 | 77 | val args = rec.map { 78 | case q"(${Literal(Constant(name: String))}, $arg)" => 79 | name -> arg 80 | }.toMap 81 | 82 | val result = c.typecheck(mkUpdates(T, typ, args)) 83 | q"_root_.patchless.Patch.ofUpdates[$T, $typ]($result)" 84 | } 85 | 86 | private val FieldTypeSym = symbolOf[FieldType[_, _]] 87 | private val AtAtSym = symbolOf[shapeless.tag.@@[_, _]] 88 | 89 | @tailrec 90 | final def mkUpdates(T: Type, typ: Type, args: Map[String, Tree], current: List[Tree] = Nil): Tree = { 91 | typ match { 92 | case TypeRef(_, _, List(head, tail)) => 93 | val (field, key, value) = head match { 94 | case TypeRef(_, _, List(f @ RefinedType(List(_, TypeRef(_, _, List(ConstantType(Constant(k: String))))), _), v)) => 95 | (f, k, v) 96 | case TypeRef(_, FieldTypeSym, List(f @ TypeRef(_, AtAtSym, args), v)) => 97 | val k = args.collectFirst { 98 | case ConstantType(Constant(k: String)) => k 99 | }.getOrElse(c.abort(c.enclosingPosition, s"Couldn't find literal string type in $f (expected a string with the field name to tag the value in the record)")) 100 | (f, k, v) 101 | case typ => 102 | val t = typ 103 | c.abort(c.enclosingPosition, s"Couldn't make an update field for $typ (is it a field type?)") 104 | } 105 | 106 | args.get(key) match { 107 | case Some(tree) => mkUpdates(T, tail, args - key, c.typecheck(q"_root_.shapeless.labelled.field[$field].apply(Some($tree):$value)") :: current) 108 | case None => mkUpdates(T, tail, args, c.typecheck(q"_root_.shapeless.labelled.field[$field].apply(None:$value)") :: current) 109 | } 110 | 111 | case t if t <:< weakTypeOf[shapeless.HNil] => 112 | args.headOption.foreach { 113 | case (name, arg) => c.abort(arg.pos, s"$T has no field $name") 114 | } 115 | current.foldLeft(q"_root_.shapeless.HNil":Tree) { 116 | (accum, next) => q"_root_.shapeless.::($next, $accum)" 117 | } 118 | case typ => 119 | c.abort(c.enclosingPosition, s"Couldn't make updates for type $typ (is it an HList of field types?)") 120 | } 121 | } 122 | } 123 | -------------------------------------------------------------------------------- /patchless-core/src/main/scala/patchless/Patchable.scala: -------------------------------------------------------------------------------- 1 | package patchless 2 | 3 | import shapeless.labelled.{FieldType, field} 4 | import shapeless._ 5 | 6 | sealed trait Patchable[T] { 7 | type Updates <: HList 8 | def apply(t: T, updates: Updates): T 9 | } 10 | 11 | object Patchable { 12 | type Aux[T, U <: HList] = Patchable[T] { type Updates = U } 13 | 14 | def apply[T](implicit patchable: Patchable[T]): Aux[T, patchable.Updates] = patchable 15 | 16 | implicit val hnil: Aux[HNil, HNil] = new Patchable[HNil] { 17 | final type Updates = HNil 18 | def apply(t: HNil, updates: HNil): HNil = HNil 19 | } 20 | 21 | implicit def hcons[K <: Symbol, H, T <: HList, TU <: HList](implicit 22 | patchTail: Aux[T, TU] 23 | ): Aux[FieldType[K, H] :: T, FieldType[K, Option[H]] :: TU] = new Patchable[FieldType[K, H] :: T] { 24 | final type Updates = FieldType[K, Option[H]] :: TU 25 | def apply(t: FieldType[K, H] :: T, updates: FieldType[K, Option[H]] :: TU) = 26 | field[K](updates.head.getOrElse(t.head)) :: patchTail(t.tail, updates.tail) 27 | } 28 | 29 | implicit def generic[T, L <: HList, U <: HList](implicit 30 | gen: LabelledGeneric.Aux[T, L], 31 | patchL: Aux[L, U] 32 | ): Aux[T, U] = new Patchable[T] { 33 | final type Updates = U 34 | def apply(t: T, updates: U) = gen.from(patchL(gen.to(t), updates)) 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /patchless-core/src/test/scala/patchless/PatchSpec.scala: -------------------------------------------------------------------------------- 1 | package patchless 2 | 3 | import org.scalatest.{FreeSpec, Matchers} 4 | import shapeless._ 5 | import shapeless.labelled.FieldType 6 | import shapeless.record.Record 7 | 8 | class PatchSpec extends FreeSpec with Matchers { 9 | 10 | "Case classes" - { 11 | 12 | case class Foo(a: String, b: Int, c: Boolean) 13 | 14 | val patchable = Patchable[Foo] 15 | 16 | "apply syntax" in { 17 | val patch = Patch[Foo](a = "patched") 18 | patch.patchUpdates shouldEqual Record(a = Some("patched"), b = None, c = None) 19 | 20 | //val fail = Patch[Foo](nonExisting = "foo") // does not compile (correctly) 21 | } 22 | 23 | "diff" in { 24 | val diff = Patch.diff( 25 | Foo("test", 22, true), 26 | Foo("test1", 22, true) 27 | ) 28 | diff.patchUpdates shouldEqual Record(a = Some("test1"):Option[String], b = None:Option[Int], c = None:Option[Boolean]) 29 | diff(Foo("a", 33, false)) shouldEqual Foo("test1", 33, false) 30 | } 31 | 32 | "concrete patch type should be known to compiler" - { 33 | 34 | "can map with a poly using witness" in { 35 | object testMap extends Poly1 { 36 | implicit def cases[K <: Symbol, V](implicit name: Witness.Aux[K]) = at[FieldType[K, Option[V]]] { 37 | v => name.value.name -> (v: Option[V]) 38 | } 39 | } 40 | 41 | def fooUpdates(patch: Patch[Foo]) = { 42 | patch.patchUpdates.map(testMap).toList 43 | } 44 | 45 | val diff = Patch.diff( 46 | Foo("test", 22, true), 47 | Foo("test1", 22, true) 48 | ) 49 | 50 | fooUpdates(diff) shouldEqual List("a" -> Some("test1"), "b" -> None, "c" -> None) 51 | } 52 | 53 | "can summon typeclasses" in { 54 | 55 | trait SomeTypeclass[T] { 56 | def wibble(t: T): String 57 | } 58 | 59 | object SomeTypeclass { 60 | implicit val string: SomeTypeclass[String] = new SomeTypeclass[String] { 61 | def wibble(s: String) = s"String $s" 62 | } 63 | 64 | implicit val int: SomeTypeclass[Int] = new SomeTypeclass[Int] { 65 | def wibble(i: Int) = s"Int $i" 66 | } 67 | 68 | implicit val boolean: SomeTypeclass[Boolean] = new SomeTypeclass[Boolean] { 69 | def wibble(b: Boolean) = s"Boolean $b" 70 | } 71 | 72 | implicit def opt[T](implicit tc: SomeTypeclass[T]): SomeTypeclass[Option[T]] = new SomeTypeclass[Option[T]] { 73 | def wibble(o: Option[T]) = o.map(tc.wibble).getOrElse("") 74 | } 75 | 76 | implicit def labelled[K <: Symbol, V](implicit tc: SomeTypeclass[V]): SomeTypeclass[FieldType[K, V]] = new SomeTypeclass[FieldType[K, V]] { 77 | def wibble(v: FieldType[K, V]) = tc.wibble(v) 78 | } 79 | 80 | implicit val hnil: SomeTypeclass[HNil] = new SomeTypeclass[HNil] { 81 | def wibble(hnil: HNil) = "" 82 | } 83 | 84 | implicit def hcons[H, T <: HList](implicit tcHead: SomeTypeclass[H], tcTail: SomeTypeclass[T]): SomeTypeclass[H :: T] = new SomeTypeclass[H :: T] { 85 | def wibble(l: H :: T) = List(Option(tcHead.wibble(l.head)).filter(_.nonEmpty), Option(tcTail.wibble(l.tail)).filter(_.nonEmpty)).flatten.mkString(" :: ") 86 | } 87 | } 88 | 89 | implicit class SomeTypeclassOps[T: SomeTypeclass](val self: T) { 90 | def wibble = implicitly[SomeTypeclass[T]].wibble(self) 91 | } 92 | 93 | def fooWibble(patch: Patch[Foo]) = { 94 | patch.patchUpdates.wibble 95 | } 96 | 97 | val diff = Patch.diff( 98 | Foo("test", 22, true), 99 | Foo("test1", 22, true) 100 | ) 101 | 102 | fooWibble(diff) shouldEqual "String test1" 103 | 104 | diff.patchUpdates.wibble shouldEqual "String test1" 105 | } 106 | } 107 | 108 | } 109 | 110 | "comparison" in { 111 | case class Foo(a: Int, b: String) 112 | Patch[Foo](a = 10) shouldEqual Patch[Foo](a = 10) 113 | Patch[Foo](a = 10) shouldNot equal (Patch[Foo](a = 11)) 114 | } 115 | 116 | 117 | } 118 | -------------------------------------------------------------------------------- /project/build.properties: -------------------------------------------------------------------------------- 1 | sbt.version = 1.3.8 2 | -------------------------------------------------------------------------------- /project/plugins.sbt: -------------------------------------------------------------------------------- 1 | logLevel := Level.Warn 2 | addSbtPlugin("org.xerial.sbt" % "sbt-sonatype" % "3.8.1") 3 | addSbtPlugin("com.jsuereth" % "sbt-pgp" % "1.1.0") 4 | -------------------------------------------------------------------------------- /version.sbt: -------------------------------------------------------------------------------- 1 | version in ThisBuild := "1.0.7" 2 | --------------------------------------------------------------------------------