Swiftpack.co - Package - krzysztofzablocki/Sourcery

CircleCI codecov docs Version License Platform

Sourcery is a code generator for Swift language, built on top of Apple's own SourceKit. It extends the language abstractions to allow you to generate boilerplate code automatically.

It's used in over 6000 projects on both iOS and macOS and it powers some of the most popular and critically-acclaimed apps you have used. Its massive community adoption was one of the factors that pushed Apple to implement derived Equality and automatic Codable conformance. Sourcery is maintained by a growing community of contributors.

Try Sourcery for your next project or add it to an existing one -- you'll save a lot of time and be happy you did!

TL;DR

Sourcery allows you to get rid of repetitive tasks. An example might be implementing Equatable, without Sourcery you need to implement stuff like this:

extension Person: Equatable {
    static func ==(lhs: Person, rhs: Person) -> Bool {
        guard lhs.firstName == rhs.firstName else { return false }
        guard lhs.lastName == rhs.lastName else { return false }
        guard lhs.birthDate == rhs.birthDate else { return false }
        return true
    }
}

This is trivial code but imagine doing this across ten types. Across fifty. How many structs and classes are in your project?

Sourcery removes the need to write this code. And if you refactor or add properties, the equality code will be automatically updated for you, eliminating possible human errors.

Sourcery automation can be applied to many more domains, e.g.

  • Equality & Hashing
  • Enum cases & Counts
  • Lenses
  • Mocks & Stubs
  • LinuxMain
  • Decorators
  • JSON coding
  • NSCoding and Codable

It's trivial to write new templates to remove boilerplate that is specific to your projects.

How To Get Started

There are plenty of tutorials for different uses of Sourcery:

Installation

  • Binary form

    Downloadthe latest release with the prebuilt binary from release tab. Unzip the archive into the desired destination and run bin/sourcery

  • CocoaPods

    Add pod 'Sourcery' to your Podfile and run pod update Sourcery. This will download the latest release binary and will put it in your project's CocoaPods path so you will run it with $PODS_ROOT/Sourcery/bin/sourcery

  • Mint

    Run mint run krzysztofzablocki/Sourcery.

    Note: Constraints of SPM (see below) apply.

  • Building from source

    Download the latest release source code from the release tab or clone the repository and build Sourcery manually.

    • Building with Swift Package Manager

      Run swift build -c release in the root folder. This will create a .build/release folder and will put the binary there. Move the whole .build/release folder to your desired destination and run with path_to_release_folder/sourcery

      Note: Swift and JS templates are not supported when building with SPM yet.

    • Building with Xcode

      Open Sourcery.xcworkspace and build with Sourcery-Release scheme. This will create Sourcery.app in the Derived Data folder. You can copy it to your desired destination and run with path_to_sourcery_app/Sourcery.app/Contents/MacOS/Sourcery

Documentation

Full documentation is available here.

Usage

Sourcery is a command line tool, you can either run it manually or in a custom build phase using the following command:

$ ./sourcery --sources <sources path> --templates <templates path> --output <output path>

Note: this command may be different depending on the way in which you installed Sourcery (see Installing)

Command line options

  • --sources - Path to a source swift files. You can provide multiple paths using multiple --sources option.
  • --templates - Path to templates. File or Directory. You can provide multiple paths using multiple --templates options.
  • --force-parse - File extensions of Sourcery generated file you want to parse. You can provide multiple extension using multiple --force-parse options. (i.e. file.toparse.swift will be parsed even if generated by Sourcery if --force-parse toparse). Useful when trying to implement a multiple phases generation.
  • --output [default: current path] - Path to output. File or Directory.
  • --config [default: current path] - Path to config file. Directory. See Configuration file.
  • --args - Additional arguments to pass to templates. Each argument can have an explicit value or will have implicit true value. Arguments should be separated with , without spaces (i.e. --args arg1=value,arg2). Arguments are accessible in templates via argument.name
  • --watch [default: false] - Watch both code and template folders for changes and regenerate automatically.
  • --verbose [default: false] - Turn on verbose logging
  • --quiet [default: false] - Turn off any logging, only emit errors
  • --disableCache [default: false] - Turn off caching of parsed data
  • --prune [default: false] - Prune empty generated files
  • --version - Display the current version of Sourcery
  • --help - Display help information

Configuration file

You can also provide arguments using .sourcery.yml file in project's root directory, like this:

sources:
  - <sources path>
  - <sources path>
templates:
  - <templates path>
  - <templates path>
force-parse:
  - <string value>
  - <string value>
output:
  <output path>
args:
  <name>: <value>

You can exlude some sources or templates using include and exclude keys:

sources:
  include:
    - <sources path to include>
    - <sources path to include>
  exclude:
    - <sources path to exclude>
    - <sources path to exclude>
templates:
  include:
    - <templates path to include>
    - <templates path to include>
  exclude:
    - <templates path to exclude>
    - <templates path to exclude>

You can provide either sources paths or targets to scan:

project:
  file:
    <path to xcodeproj file>
  root:
    <path to project sources root>
  target:
    name: <target name>
    module: <module name> //required if different from target name

You can use several project or target objects to scan multiple targets from one project or to scan multiple projects.

Note: Paths in configuration files are by default relative to configuration file path. If you want to specify absolute paths start it with /.

Contributing

Contributions to Sourcery are welcomed and encouraged!

It is easy to get involved. Please see the Contributing guide for more details.

A list of contributors is available through GitHub.

To give clarity of what is expected of our community, Sourcery has adopted the code of conduct defined by the Contributor Covenant. This document is used across many open source communities, and I think it articulates my values well. For more, see the Code of Conduct.

License

Sourcery is available under the MIT license. See LICENSE for more information.

Attributions

This tool is powered by

Thank you! for:

  • Mariusz Ostrowski for creating the logo.
  • Artsy Eidolon team, because we use their codebase as a stub data for performance testing the parser.
  • Olivier Halligon for showing me his setup scripts for CLI tools which are powering our rakefile.

Other Libraries / Tools

If you want to generate code for asset related data like .xib, .storyboards etc. use SwiftGen. SwiftGen and Sourcery are complementary tools.

Make sure to check my other libraries and tools, especially:

  • KZPlayground - Powerful playgrounds for Swift and Objective-C
  • KZFileWatchers - Daemon for observing local and remote file changes, used for building other developer tools (Sourcery uses it)

You can follow me on Twitter for news/updates about other projects I am creating.

Github

link
Stars: 2935
Help us keep the lights on

Releases

0.10.0 - Dec 11, 2017

New Features

  • Added test for count Stencil filter
  • Added new reversed Stencil filter
  • Added new isEmpty Stencil filter
  • Added new sorted and sortedDescending Stencil filters. This can sort arrays by calling e.g. protocol.allVariables|sorted:"name"
  • Added new toArray Stencil filter
  • Added a console warning when a yaml is available but any parameter between 'sources', templates', 'forceParse', 'output' are provided

Internal changes

  • Add release to Homebrew rake task
  • Fixed Swiftlint warnings
  • Fixed per file generation if there is long (approx. 150KB) output inside sourcery:file annotation
  • Do not generate default.profraw
  • Remove filters in favor of same filters from StencilSwiftKit

0.9.0 - Sep 22, 2017

New Features

  • Added support for file paths in config parameter
  • Added isDeinitializer property for methods
  • Improved config file validation and error reporting
  • Various improvements for AutoMockable template:
    • support methods with reserved keywords name
    • support methods that throws
    • improved generated declarations names

Bug fixes

  • Fixed single file generation not skipping writing the file when there is no generated content

Internal changes

  • Updated dependencies for Swift 4
  • Update internal ruby dependencies

0.8.0 - Aug 12, 2017

New Features

  • Added support in AutoHashable for static variables, [Hashable] array and [Hashable: Hashable] dictionary
  • Added definedInType property for Method and Variable
  • Added extensions filter for stencil template
  • Added include support in Swift templates
  • Swift templates now can throw errors. You can also throw just string literals.
  • Added support for TypeName in string filters (except filters from StencilSwiftKit).

Bug fixes

  • Fixed linker issue when using Swift templates
  • Updated AutoMockable to exclude generated code collisions
  • Fixed parsing of default values for variables that also have a body (e.g. for didSet)
  • Fixed line number display when an error occur while parsing a Swift template
  • Fixed rsync issue on SourceryRuntime.framework when using Swift templates
  • Fixed auto:inline for nested types (this concerns the first time the code is inserted)

Internal changes

  • Fix link for template in docs
  • Fix running Sourcery in the example app
  • Add step to update internal boilerplate code during the release

0.7.2 - Jun 16, 2017

Internal changes

  • Add Version.swift to represent CLI tool version

0.7.1 - Jun 14, 2017

Bug fixes

  • Fixed regression in parsing templates from config file
  • Removed meaningless isMutating property for Variable

Internal changes

  • Improvements in release script
  • Updated boilerplate code to reflect latest changes