plank

1.6

A tool for generating immutable model objects
pinterest/plank

What's New

v1.6 - Schema updates, improved Java support, Objective-C optimizations and dependency graph analysis

2020-01-07T19:52:02Z

Updates

General

Nested object definitions.

Previously it was required to create a new file for each schema. Now we support declaring types within types which can be useful for ones that only make sense in a certain scope or are fairly minimal.

Example schema declaration:

{
    "some_property" : {
        "type": "object",
        "title": "nested",
        "properties": {
            "id": { "type": "integer" },
            "name": { "type": "string" }
        }
    }
}

JSON dependency graph output

The behavior of the --print_deps output has changed to be JSON by default. This allows for tooling to be built to visualize or analyze dependency graph of your schemas.

Given this command using our example schemas:

plank --print_deps Examples/PDK/pin.json                                                                                                                                                     

You'll get an output with it's dependencies and any inherited types (via extends keyword)

{
  "pin" : [
    "image",
    "board",
    "user"
  ]
}

CI

We've migrated our CI entirely to Github Actions which will make it easier for contributors to analyze logs and build failures.

Objective-C

  • Optimizations around memory footprint of properties
  • Test updates for equality methods

Java

  • Removed AutoValue as a dependency
  • Support for tracking properties which are set
  • ADT, equality and nullability support
  • TypeAdapters derived from Schema definitions

Changes

8ee84c2 Mention nested object types in the documentation (#258)
2346a29 Support nested object type definitions (#256)
85e802f Mark generated files using 'linguist-generated' (#257)
e4e5e72 Remove trailing space after integer-based enums (#255)
9e5c65f Missing @SerializedName annotation on integer-based enums (#253)
fbcd34f Convert deps command output to produce JSON (#252)
c232819 Java model potentially missing import for types contained in maps and lists (#251)
921c98f Upgrade swiftformat and swiftlint (#250)
979e358 Java ADT partial implementation (#249)
41c25a8 Migrate CI to Github CI/CD (#239)
eeb4918 Support configurable URI types for Java (#245)
618acaa Optionally log unknown properties in TypeAdapter.read (#243)
9d367a5 Java equals() should evaluate primitives first (#244)
a27b144 Check _bits directly in internal calls (#242)
f650f01 Order modifiers according to the Java spec (#241)
42a168b Make generated TypeAdapter classes private (#240)
690a266 Only allocate _bits when necessary (#238)
55b0a25 Use transitiveProperties to gather Java imports (#237)
fa2e15e Only import the necessary set of types (#235)
920dcee Stop importing java.lang.annotation.Retention{Policy} (#234)
01cf3e9 Stop importing com.google.gson.JsonElement (#233)
6253078 Add the Plank project URL to the file comment header (#232)
4c794b2 Java model property annotations should be sorted deterministically (#231)
bf771de Java model TypeAdapter write method should not use delegateAdapter. (#227)
730f8e1 Add more nullability annotations to Java models (#228)
f683102 Java model TypeAdapter should not not instantiate its inner TypeAdapters until needed (#226)
102d645 Java models should not include null fields when serialized into Json (#225)
faadfa9 Java Model Builder.build method should be annotated with NonNull (#223)
7b054be Java model - _bits field should be deserialized if it's present in the JSON (#221)
bc8c8fd Java Model Decorators (beta) (#217)
738fb3e Builder property variables should not have @SerializedName annotation (#220)
d4a714d Emit BOOL properties as bitfields (#208)
47fb542 Add equality tests for ObjC (#219)
c7fe044 Missing call to set tracking isSet-bit in Java model merging (#218)
d3c6322 Use smaller enum types to reduce object sizes. (#207)
ef88906 Use a boolean[] array for tracking set-bits so we can accommodate models with more than 32 fields (fixes integer overflow) (#216)
32f2fe5 Add option to generate Java private setters (#212)
8d23c9b Fix invalid call to Builder-setter from Java TypeAdapter (#211)
427edd4 Add support for androidx Nullability annotations (#204)
f368cd1 Add a static TYPE variable to java models (#201)
bdd00b0 Toolchain updates (#196)
a8e91d3 Remove local shadow variable self.properties should be used for clarity. (#202)
a2d1022 Fix archive command to work also with Swift 5 (#200)
d467436 Avoid use of reflection-based deserialization in Java model (#194)
02d18ba Add linter for making sure linux main is kept up to date (#192)
5e5ed22 Don't use ObjectiveC-based handling of reserved keywords for Java (#187)
2dd9ed8 Add missing check for null json token (#188)
06925b8 Use standard Java enum types for enum properties (#184)
e63f15c For Boolean, Double and Integer properties, getters should be NonNull (#178)
efe3c84 Build Java sources during integration tests (#176)
47ad603 Add custom TypeAdapter for Java models that will allow for setting _bits field (#177)
f38aa84 Fix missing comma in Java model constructor (#175)
3cb4722 Update docs to reflect that plank is for more than Objective-C (#173)
7d17623 Remove AutoValue from Java generated models (#159)
4372837 Update variable name substitution logic (#157)
fd4dea5 Remove unused CI directory
1d44870 Add swiftlint / swiftformat in Package.swift, fix issues (#168)

Plank logo

Plank

Build Status

Plank is a command-line tool for generating robust immutable models from JSON Schemas. It will save you time writing boilerplate and eliminate model errors as your application scales in complexity.

We currently support the following languages:

Schema-defined

Models are defined in JSON, a well-defined, extensible and language-independent specification.

Immutable Classes

Model classes are generated to be immutable. Each class provides a “Builder” class to handle mutation.

Type safe

Based on the type information specified in the schema definition, each class provides type validation and null reference checks to ensure model integrity.

Installation

MacOS

$ brew install plank

Linux

Plank supports building in Ubuntu Linux via Docker. The Dockerfile in the repository will fetch the most recent release of plank and build dependencies including the Swift snapshot.

$ docker build -t plank .

Build from source

Plank is built using the Swift Package Manager. Although you’ll be able to build Plank using swift build directly, for distribution of the binary we’d recommend using the commands in the Makefile since they will pass the necessary flags to bundle the Swift runtime.

$ make archive

Getting Started

Keep reading to learn about Plank’s features or get your try it yourself with the tutorial.

Defining a schema

Plank takes a schema file as an input. Schemas are based on JSON, a well-defined, extensible and language-independent specification. Defining schemas in JSON allowed us to avoid writing unnecessary parser code and opened up the possibility of generating code from the same type system used on the server.

{
    "id": "pin.json",
    "title": "pin",
    "description" : "Schema definition of a Pin",
    "$schema": "http://json-schema.org/schema#",
    "type": "object",
    "properties": {
        "id": { "type": "string" },
        "link": { "type": "string", "format": "uri"}
    }
}

You’ll notice we specify the name of the model and a list of its properties. Note that link specifies an additional format attribute which tells Plank to use a more concrete type like NSURL or NSDate.

Generating a model

Generate a schema file (pin.json) using Plank using the format plank [options] file1 file2 file3 ...

$ plank pin.json

This will generate files (Pin.h, Pin.m) in the current directory:

$ ls
pin.json Pin.h Pin.m

Learn more about usage on the installation page.

Generated Output

Plank will generate the necessary header and implementation file for your schema definition. Here is the output of the Pin.h header.

@interface Pin
@property (nonatomic, copy, readonly) NSString *identifier;
@property (nonatomic, strong, readonly) NSURL *link;
@end

All properties are readonly, as this makes the class immutable. Populating instances of your model with values is performed by builder classes.

Mutations through builders

Model mutations are performed through a builder class. The builder class is a separate type which contains readwrite properties and a build method that will create a new object. Here is the header of the builder that Plank generated for the Pin model:

@interface PinBuilder
@property (nonatomic, copy, readwrite) NSString *identifier;
@property (nonatomic, strong, readwrite) NSURL *link;
- (Pin *)build;
@end

@interface Pin (BuilderAdditions)
- (instancetype)initWithBuilder:(PinBuilder *)builder;
@end

JSON parsing

Plank will create an initializer method called initWithModelDictionary: that handles parsing NSDictionary objects that conform to your schema. The generated implementation will perform validation checks based on the schema’s types, avoiding the dreaded [NSNull null] showing up in your objects:

@interface Pin (JSON)
- (instancetype)initWithModelDictionary:(NSDictionary *)dictionary;
@end

Serialization

All Plank generated models implement methods to conform to NSSecureCoding, providing native serialization support out of the box.

+ (BOOL)supportsSecureCoding {
    return YES;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    if (!(self = [super init])) { return self; }
    _identifier = [aDecoder decodeObjectOfClass:[NSString class] forKey:@"identifier"];
    _link = [aDecoder decodeObjectOfClass:[NSURL class] forKey:@"link"];
    return self;
}

- (void)encodeWithCoder:(NSCoder *)aCoder {
    [aCoder encodeObject:self.identifier forKey:@"identifier"];
    [aCoder encodeObject:self.link forKey:@"link"];
}

With this implementation objects are serialized using NSKeyedArchiver:

// Create a pin from a server response
Pin *pin = [[Pin alloc] initWithModelDictionary:/* server response */];
// Cache the pin
[NSKeyedArchiver archiveRootObject:pin toFile:/* cached pin path */];
// App goes on, terminates, restarts...
// Load the cached object
Pin *cachedPin = [NSKeyedUnarchiver unarchiveObjectWithFile:/* cached pin path */];

Model merging and partial data

Plank models support merging and partial object materialization through a conventional “last writer wins” approach. By calling the mergeWithModel: on a generated model with a newer instance, the properties set on the newer instance will be preserved. To know which properties are set, the information is tracked internally within the model during initialization or through any mutation methods. In this example, an identifier property is used as a primary key for object equality:

static inline id valueOrNil(NSDictionary *dict, NSString *key);
struct PinSetProperties {
  unsigned int Identifier:1;
  unsigned int Link:1;
};
- (instancetype)initWithModelDictionary:(NSDictionary *)modelDictionary {
  [modelDictionary enumerateKeysAndObjectsUsingBlock:^(NSString *  _Nonnull key, id obj, BOOL *stop){
    if ([key isEqualToString:@"identifier"]) {
        // ... Set self.identifier
        self->_pinSetProperties.Identifier = 1;
    }
    if ([key isEqualToString:@"link"]) {
        // ... Set self.link
        self->_pinSetProperties.Link = 1;
    }
  }];
  // Post notification
  [[NSNotificationCenter defaultCenter] postNotificationName:@"kPlankModelDidInitializeNotification" object:self];
}

With immutable models, you have to think through how data flows through your application and how to keep a consistent state. At the end of every model class initializer, there’s a notification posted with the updated model. This is useful for integrating with your data consistency framework. With this you can track whenever a model has updated and can use internal tracking to merge the new model.

@implementation Pin(ModelMerge)
- (instancetype)mergeWithModel:(Pin *)modelObject {
    PinBuilder *builder = [[PinBuilder alloc] initWithModelObject:self];
    if (modelObject.pinSetProperties.Identifier) {
        builder.identifier = modelObject.identifier;
    }
    if (modelObject.pinSetProperties.Link) {
        builder.link = modelObject.link;
    }
    return [builder build];
}
@end

Algebraic data types

Plank provides support for specifying multiple model types in a single property, commonly referred to as an Algebraic Data Type (ADT). In this example, the Pin schema receives an attribution property that will be either a User, Board, or Interest. Assume we have separate schemas defined in files user.json, board.json and interest.json, respectively.

{
    "title": "pin",
    "properties": {
        "identifier": { "type": "string" },
        "link": { "type": "string", "format": "uri"},
        "attribution": {
          "oneOf": [
            { "$ref": "user.json" },
            { "$ref": "board.json" },
            { "$ref": "interest.json" }
          ]
        }
    }
}

Plank takes this definition of attribution and creates the necessary boilerplate code to handle each possibility. It also provides additional type-safety by generating a new class to represent your ADT.

@interface PinAttribution : NSObject<NSCopying, NSSecureCoding>
+ (instancetype)objectWithUser:(User *)user;
+ (instancetype)objectWithBoard:(Board *)board;
+ (instancetype)objectWithInterest:(Interest *)interest;
- (void)matchUser:(void (^)(User * pin))userMatchHandler
          orBoard:(void (^)(Board * board))boardMatchHandler
       orInterest:(void (^)(Interest * interest))interestMatchHandler;
@end

Note there’s a “match” function declared in the header. This is how you extract the true underlying value of your ADT instance. This approach guarantees at compile-time you have explicitly handled every possible case preventing bugs and reducing the needs to use runtime reflection which hinders performance. The example below shows how you’d use this match function.

PinAttribution *attribution;
[attribution matchUser:^(User *user) {
   // Do something with "user"
} orBoard:^(Board *board) {
   // Do something with "board"
} orInterest:^(Interest *interest) {
   // Do something with "interest"
}];

Contributing

Pull requests for bug fixes and features welcomed.

License

Copyright 2019 Pinterest, 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.

Description

  • Swift Tools 5.0.0
View More Packages from this Author

Dependencies

Last updated: Thu Apr 09 2026 00:44:07 GMT-0900 (Hawaii-Aleutian Daylight Time)