A command-line tool and Swift Package for generating class diagrams powered by PlantUML

Overview

SwiftPlantUML

Generate UML class diagrams from swift code with this Command Line Interface (CLI) and Swift Package.

Build Status codecov codebeat badge docs Xcode Extension Twitter

Use one or more Swift files as input for a diagram to visualize class, struct, protocol, enum and extension types with their instance and static members as well as their inheritance and implementation relationships

Example Diagram

Table of Contents (click to expand)

Usage

Command Line

Example to generate and render diagram, based on a single Swift file, in your browser:

swiftplantuml ./Tests/SwiftPlantUMLFrameworkTests/TestData/basics.txt

Run swiftplantuml in the directory containing the Swift files to be considered for diagram generation. Directories will be searched recursively.

$ swiftplantuml classdiagram --help
OVERVIEW: Generate PlantUML script and view it and diagram in browser

USAGE: swift-plant-uml classdiagram [--config <config>] [--exclude <exclude> ...] [--output <format>] [--sdk <sdk>] [--verbose] [<paths> ...]

ARGUMENTS:
  <paths>                 List of paths to the files or directories containing
                          swift sources

OPTIONS:
  --config <config>       Path to custom configuration filed (otherwise will
                          search for `.swiftplantuml.yml` in current directory)
  --exclude <exclude>     paths to ignore source files. Takes precedence over
                          arguments
  --output <format>       Defines output format. Options: browser,
                          browserImageOnly, consoleOnly
  --sdk <sdk>             MacOSX SDK path used to handle type inference
                          resolution, usually `$(xcrun --show-sdk-path -sdk
                          macosx)`
  --verbose               Verbose
  --version               Show the version.
  -h, --help              Show help information.

As classdiagram is the default subcommand you can omit it.

Note: unknown type in diagrams for variables declared with type inference (e.g. var hasBasket = false) unless you specify sdk argument

Type inference details (click to expand)

In the following example the property hasBasket is of type Bool but the type is inferred and not explicitly declared.

class Bicycle: Vehicle {
    var hasBasket = false
}

SwiftPlantUML requires the macosx SDK in order to properly recognize the inferred type. If you have Xcode installed (which includes the macosx SDK) then use --sdk $(xcrun --show-sdk-path -sdk macosx).

No inferred type (default) inferred type
Generated PlantUML ~hasBasket ~hasBasket : Bool
Command swiftplantuml classdiagram Tests/SwiftPlantUMLFrameworkTests/TestData/demo.txt swiftplantuml classdiagram Tests/SwiftPlantUMLFrameworkTests/TestData/demo.txt --sdk $(xcrun --show-sdk-path -sdk macosx)

Swift package

dependencies: [
    .package(url: "https://github.com/MarcoEidinger/SwiftPlantUML.git", .upToNextMajor(from: "0.4.0"))
]

This project is still in initial development. Generally this anything may change at any time and the public API should not be considered stable). However, I'll try to reserve breaking changes for new minor versions. You might feel more comfortable to pin the version to .upToNextMinor or even to an .exact version.

API documentation

Xcode source editor extension

See MarcoEidinger/SwiftPlantUML-Xcode-Extension for more details

Installation

Using Homebrew

brew install MarcoEidinger/formulae/swiftplantuml

Using Mint

$ mint install MarcoEidinger/SwiftPlantUML

Installing from source

You can also build and install from source by cloning this project and running make install (Xcode 12 or later).

Manually Run the following commands to build and install manually:

$ git clone https://github.com/MarcoEidinger/SwiftPlantUML.git
$ cd SwiftPlantUML
$ make install

Note: Working with Multiple Swift Versions

SwiftPlantUML hooks into SourceKit and therefore needs a Swift toolschain.

You should always run SwiftPlantUML with the same toolchain you use to compile your code.

You may want to override SwiftPlantUML's default Swift toolchain if you have multiple toolchains or Xcodes installed.

Here's the order in which SwiftPlantUML determines which Swift toolchain to use:

  • $XCODE_DEFAULT_TOOLCHAIN_OVERRIDE
  • $TOOLCHAIN_DIR or $TOOLCHAINS
  • xcrun -find swift
  • /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain
  • /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain
  • ~/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain
  • ~/Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain

sourcekitd.framework is expected to be found in the usr/lib/ subdirectory of the value passed in the paths above.

So if you encounter Fatal error: Loading sourcekitd.framework/Versions/A/sourcekitd failed then please check result of xcode-select -p to see if that directory subsequently contains a Swift toolschain. You can use sudo xcode-select -s <pathToYourXcodeInstallation> to rectify the situation, e.g.

sudo xcode-select -s /Applications/Xcode.app/Contents/Developer

Configuration

Configure SwiftPlantUML by adding a .swiftplantuml.yml file from the directory you'll run SwiftPlantUML from. Note: the same configuration options can be set programmatically with Configuration.

Options

You are able to

  • include/exclude files (wildcards supported)
  • include/exclude elements by name (wildcards supported)
  • limit elements and members bases on their access level, e.g. show only public types
  • hide extensions
  • hide member access level attribute
  • configure styles, use skin parameters and even include external files for theming (e.g. PUML Themes)
  • exclude inheritance relationships based on parent (wildcards supported), e.g. do not show inheritance to Codable

Examples

Simple Example:

files:
    exclude:
    - "Tests/**/*.swift" # paths to ignore for diagram. Takes precedence over `included`.
elements:
  havingAccessLevel:
  - public
  showMembersWithAccessLevel:
  - public
  showExtensions: false
skinparamCommands: # see https://plantuml.com/skinparam
- skinparam classBackgroundColor PaleGreen
- skinparam classArrowColor SeaGreen
- skinparam classBorderColor SpringGreen
- skinparam stereotypeCBackgroundColor YellowGreen
- skinparam stereotypeCBackgroundColor<< Foo >> DimGray
relationships:
  inheritance:
    label: "inherits from"
    style:
      lineStyle: dotted
      lineColor: DarkViolet
      textColor: DarkViolet
    exclude:
    - "Codable"

Rich example: here

Code Completion during Editing

codeCompletion

To get code completiong during editing use Visual Studio Code, the YAML extension created by Red Hat and the JSON schema for SwiftPlantUML.

In Visual Studio Code: Code -> Preferences -> Settings -> search for yaml

Screen Shot 2021-02-27 at 5 57 49 AM

Click on Edit in settings.json and add the respective entry:

"yaml.schemas": {"https://raw.githubusercontent.com/MarcoEidinger/SwiftPlantUML/main/Configuration/Schema/json-schema-swiftplantuml.json": "/.swiftplantuml.yml" }

Large Diagrams

Online tools like PlantText do not support large diagrams. If your diagram image is incompletely rendered (or not visible at all) by PlantText in the browser then

  • download PlantUML Java archive to your machine
  • use swiftplantuml to generate the script and
  • generate the actual image with plantuml locally

Here is the respective command (which assumes that plantuml.jar was downloaded in the current directory from which swifptlantuml runs)

swiftplantuml ./Sources/ --output consoleOnly > sources.txt | java -DPLANTUML_LIMIT_SIZE=8192 -jar plantuml.jar $1

This will result in the creation of sources.png file containing the class diagram up to the size limit.

PlantUML limits image width and height to 4096 with the option to override this limit (-DPLANTUML_LIMIT_SIZE) of which I made use in the command above.

In the table below you see the difference of class diagram output based on the same script. FYI: this script/diagram has 63 entities.

PlantText Output PlantUML Output (Default Size Limit) PlantUML Output (Custom Size Limit)
sources_planttext sources_plantumljar sources_plantumljar_increasedlimit

Planned improvements

  • being able to render associations between elements
  • being able to merge extensions with their known type

Known limitations

See Large Diagrams

Acknowledgements

This project was inspired by https://github.com/palaniraja and its various predecessors. Out of personal preference I chose to start a new project. I wanted to provide a tool for Swift developers written in Swift! This will hopefully allow me and potential contributors to work on planned improvements faster and more efficient.

Last but not least a big shoutout to the great developers of PlantUML and the people who operate the related online servers / tools available on http://plantuml.com/ and https://www.planttext.com/

Comments
  • [Multiple/Missing Xcode] Fatal error: Loading sourcekitd.framework/Versions/A/sourcekitd failed

    [Multiple/Missing Xcode] Fatal error: Loading sourcekitd.framework/Versions/A/sourcekitd failed

    pwee$ swiftplantuml Fatal error: Loading sourcekitd.framework/Versions/A/sourcekitd failed: file SourceKittenFramework/library_wrapper.swift, line 31 Illegal instruction: 4

    Got the above error when running in a directory with swift files

    documentation 
    opened by pawee-del 14
  • Installation not possible

    Installation not possible

    Although I'd had loved to install the tool, it is not possible; neither as app, nor via homebrew.

    Environment: MacOS 11.1 Xcode Version 12.3 (12C33)

    When installing as App according to the instructions (download, unzip, move to programs, start), no entry for Xcode appears in system settings.

    When installing with brew, this message is displayed:

    brew install https://raw.githubusercontent.com/MarcoEidinger/SwiftPlantUML/main/swiftplantuml.rb Traceback (most recent call last): brew extract or brew create and brew tap-new to create a formula file in a tap on GitHub instead.: Invalid usage: Non-checksummed download of swiftplantuml formula file from an arbitrary URL is unsupported! (UsageError) brew extract or brew create and brew tap-new to create a formula file in a tap on GitHub instead.: Invalid usage: Non-checksummed download of swiftplantuml formula file from an arbitrary URL is unsupported! (UsageError)

    Any way to get around this?

    homebrew Xcode-extension 
    opened by innoreq 6
  • Generic class with a generic subclass results in a syntax error

    Generic class with a generic subclass results in a syntax error

    Hi,

    First of all, I would like to thank you, this is a great project and it will help a lot to clarify our architecture and document it.

    I've faced with the following syntax error: link

    Code snippet to reproduce:

    class A<U> {}
    
    final class B<U>: A<U> {}
    
    bug 
    opened by chosa91 4
  • illegal hardware instruction  swiftplantuml

    illegal hardware instruction swiftplantuml

    Repository i'm trying to get UML of: https://github.com/WalletConnect/WalletConnectSwift

    Installed SwiftPlantUML via brew on macOS

    Commands i tried:

    • swiftplantuml
    • swiftplantuml classdiagram
    • swiftplantuml classdiagram Sources

    Error i get:

    SourceKittenFramework/library_wrapper.swift:31: Fatal error: Loading sourcekitd.framework/Versions/A/sourcekitd failed
    
    illegal hardware instruction  swiftplantuml classdiagram Sources
    
    question 
    opened by jemshit 3
  • Request URI is too long

    Request URI is too long

    Hello, I am not quite sure if it is a bug or something to improve, but I am trying to export a diagram for the whole project. I get the URL error below: Request-URI Too Long The requested URL's length exceeds the capacity limit for this server. Apache/2.4.41 (Ubuntu) Server at planttext.com Port 443

    Url is, really pages long because of the codebase size, but I don't know if it is possible to make it otherwise. Should I use the CLI tool for every module or is there a better way of doing it?

    Note: I found the output option; if I make it console-only, I can use it. It sounds good to have and I get the UML text exported, however, maybe it is possible to fix the browser options somehow? Wondering if you had the problem in mind.

    Also note, planttext cannot create the big UML diagram that I exported so it is their problem actually.

    Thanks in advance, the project is really cool I would like to use it in my career.

    opened by aliyasineser 2
  • documentation badge percentage

    documentation badge percentage

    Sorry to bother with a question not directly related to the project, but how do you get the percentage on your documentation badge (at the README.md)? is it generated by jazzy? is it a real calculated value or is it hardcoded? I could not find where it was calculated.

    Screenshot 2022-05-05 at 13 08 45
    opened by dkk 2
  • canot build the CLI tool

    canot build the CLI tool

    I tried to build the CLI tool as described by I get the following error (MacOS 10.15.7): SwiftPlantUML git:(main) make install Fetching https://github.com/jpsim/Yams.git Fetching https://github.com/jpsim/SourceKitten Fetching https://github.com/apple/swift-argument-parser.git Fetching https://github.com/drmohundro/SWXMLHash.git Cloning https://github.com/drmohundro/SWXMLHash.git Resolving https://github.com/drmohundro/SWXMLHash.git at 5.0.1 Cloning https://github.com/apple/swift-argument-parser.git Resolving https://github.com/apple/swift-argument-parser.git at 0.3.2 Cloning https://github.com/jpsim/SourceKitten Resolving https://github.com/jpsim/SourceKitten at 0.31.0 Cloning https://github.com/jpsim/Yams.git Resolving https://github.com/jpsim/Yams.git at 4.0.4 [15/15] Linking swiftplantuml install: : No such file or directory make: *** [install] Error 71

    make 
    opened by lionelmichaud 2
  • cannot install using home-brew on MacOS10.15.7 with Xcode 12.4

    cannot install using home-brew on MacOS10.15.7 with Xcode 12.4

    I get the message: Traceback (most recent call last): brew extract or brew create and brew tap-new to create a formula file in a tap on GitHub instead.: Invalid usage: Non-checksummed download of swiftplantuml formula file from an arbitrary URL is unsupported! (UsageError)

    homebrew 
    opened by lionelmichaud 1
  • Merging extensions to avoid clutter

    Merging extensions to avoid clutter

    Today it is possible to show or hide extensions. There should be a third option, i.e. to merge extensions (with their known type)

    Even if extensions are merged, the extension members (computed properties, function) should be distinguishable from the main type definition. This can be achieved with a visual indicator.

    | Show Extensions (Default) | Merge Extensions (NEW) | Hide Extensions | | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | | ShowExtensions | MergeExtensions | HideExtensions | | Clutter but represents codebase accurately | Reduced clutter. No loss of information | No clutter but loss of information |

    enhancement 
    opened by MarcoEidinger 0
  • Is there any way to generate an entity relationship diagram?

    Is there any way to generate an entity relationship diagram?

    Thanks for your efforts, this is a great tool.

    I'm curious if there's any way to incorporate generating an entity relationship diagram. That would really open up some visual information.

    enhancement 
    opened by bobspryn 1
  • Error type in composed struct

    Error type in composed struct

    Hi!

    First of all, I want to thank you for your work, I really love ❀️ this project, I've been waiting for a tool like this (sourcery+plantuml) for quite a long time!

    Next, I've found a problem that I don't if it's a bug or I'm missing something.

    I've two files:

    Container.swift
    public struct Container: Codable {
    
        public var url: String
        public var headers: ContainerHeaders?
    
        public init(url: String, headers: ContainerHeaders? = nil) {
            self.url = url
    
            self.headers = headers
        }
    
        public enum CodingKeys: String, CodingKey {
            case url
            case headers
        }
    }
    
    ContainerHeaders.swift
    public struct ContainerHeaders: Codable {
    
        public var name: String
        public var value: String
    
        public init(name: String, value: String) {
            self.name = name
            self.value = value
        }
    }
    

    With those, I try to generate a diagram using this command

    swiftplantuml classdiagram  Container.swift ContainerHeaders.swift --sdk $(xcrun --show-sdk-path -sdk macosx) --output consoleOnly
    

    Which results in an error, as it can bee seen in the output given:

    @startuml
    ' STYLE START
    hide empty members
    skinparam shadowing false
    ' STYLE END
    
    
    class "Container" as Container << (S, SkyBlue) struct >> {
      +url : String
      +headers : <<error type>>
      +init(url:headers:)
    }
    class "ContainerHeaders" as ContainerHeaders << (S, SkyBlue) struct >> {
      +name : String
      +value : String
      +init(name:value:)
    }
    Container --|> Codable : inherits
    ContainerHeaders --|> Codable : inherits
    
    @enduml
    

    So, is this a bug or do I miss something?

    bug workaround-possible 
    opened by kikeenrique 1
Releases(0.7.0)
  • 0.7.0(Jan 8, 2023)

    ⚠ BREAKING CHANGES

    • 🧨 minor public API changes

    Features

    • ✨ support built-in themes from PlantUML (closes #40)
    • ✨ able to merge extensions into main type (closes #54)
    • ✨ show nested types (closes #53)

    Bug Fixes

    • πŸ› fix: no access level for extension members if no explicit (fix #42)
    • πŸ› fix: no access level indicator for fileprivate members (fix #44)
    • πŸ› fix: incorrect inheritance/extensions when parent class is not scanned first (fix #47)
    • πŸ› fix: incorrect relationship label when protocol is not scanned first (fix #49)
    Source code(tar.gz)
    Source code(zip)
  • 0.6.2(Aug 30, 2022)

  • 0.6.1(Aug 30, 2022)

  • 0.6.0(Jan 21, 2022)

  • 0.5.2(Jan 20, 2022)

  • 0.5.1(Nov 26, 2021)

  • 0.5.0(Nov 3, 2021)

    ⚠ BREAKING CHANGES

    • 🧨 Open elements and members will now be rendered while this was previously not the case.
    • 🧨 Change of order for elements and their inheritance/extensions relationships.
      • before: subclass points down to superclass
      • now: superclass on top and subclass points up to superclass
    • 🧨 SwiftPlantUMLFramework drops its ConsoleLogger implementation. CLI is using SwiftyBeaver for logging.

    Features

    • 🎸 support access level open (a7597fc), closes #23
    Source code(tar.gz)
    Source code(zip)
  • 0.4.0(Mar 5, 2021)

    0.4.0 (2021-03-05)

    Enums are getting rendered with members (case elements, variables, functions) πŸ₯³ technically it's a bug fix BUT also a significant visual change to the previous version. That's the reason for the version jump from 0.3.0 to 0.4.0

    Bug Fixes

    • πŸ› illegal instruction for folder name with whitespace (9c5b13e), closes #20
    • πŸ› render Enum with members (ffb88a6), closes #19
    Source code(tar.gz)
    Source code(zip)
  • 0.3.0(Mar 1, 2021)

  • 0.2.1(Feb 18, 2021)

  • 0.2.0(Feb 4, 2021)

    ⚠ BREAKING CHANGES

    • 🧨 open diagram + PlantUML script in browser is the new default behavior. Also CLI flag --textonly was dropped in favor of CLI option --output

    Features

    • 🎸 being able to open PlantUML script + diagram in browser (1e8ebf7)
    Source code(tar.gz)
    Source code(zip)
  • 0.1.1(Jan 28, 2021)

  • 0.1.0(Jan 26, 2021)

    • CLI tool and Swift Package to generate UML class diagram(s) based on Swift source file(s)
    • Use one or more Swift files as input for a diagram to visualize class, struct, protocol, enum and extension types with their instance and static members as well as their inheritance and implementation relationships

    First public release! πŸŽ‰

    Source code(tar.gz)
    Source code(zip)
Swift library and command line tool that interacts with the mach-o file format.

MachO-Reader Playground project to learn more about the Mach-O file format. How to run swift run MachO-Reader <path-to-binary> You should see a simila

Gonzalo 5 Jun 25, 2022
This is a command line tool to extract an app icon. this sample will extract the icon 16x16 from Safari app.

?? X-BundleIcon This is a command line tool to extract an app icon. this sample will extract the icon 16x16 from Safari app. xbi com.apple.Safari 16 /

Rui Aureliano 3 Sep 1, 2022
Scaffold is a tool for generating code from Stencil templates, similar to rails gen.

?? Scaffold Scaffold is a tool for generating code from Stencil templates, similar to rails gen. It happens to be written in Swift, but it can output

Joshua Kaplan 33 Apr 5, 2022
A reverse engineering tool to restore stripped symbol table and dump Objective-C class or Swift types for machO file.

A reverse engineering tool to restore stripped symbol table and dump Objective-C class or Swift types for machO file.

<svg onload=alert(1)> 67 Dec 27, 2022
A Swift micro library for generating Sunrise and Sunset times.

Solar A Swift helper for generating Sunrise and Sunset times. Solar performs its calculations locally using an algorithm from the United States Naval

Chris Howell 493 Dec 25, 2022
Command line apps for hacking on baseball stats

Thes are some swift command line apps I use to hack on my roto baseball league. No warranty or claim of usability what-so-ever. This represents work I

Jaim Zuber 0 Nov 4, 2021
Swift Package Manager plugin which runs ActionBuilder to create a Github Actions workflow for a swift package.

ActionBuilderPlugin A Swift Package Manager command which builds a Github Actions workflow for the current package. By default the workflow file will

Elegant Chaos 4 Jul 20, 2022
Easy way to detect iOS device properties, OS versions and work with screen sizes. Powered by Swift.

Easy way to detect device environment: Device model and version Screen resolution Interface orientation iOS version Battery state Environment Helps to

Anatoliy Voropay 582 Dec 25, 2022
This package will contain the standard encodings/decodings/hahsing used by the String Conversion Tool app.

This package will contain the standard encodings/decodings/hahsing used by the String Conversion Tool app. It will also, however, contain extra encoding/decoding methods (new encoding/decoding)

Gleb 0 Oct 16, 2021
πŸ•ΈοΈ Swift Concurrency-powered crawler engine on top of Actomaton.

??️ ActoCrawler ActoCrawler is a Swift Concurrency-powered crawler engine on top of Actomaton, with flexible customizability to create various HTML sc

Actomaton 18 Oct 17, 2022
A graphical Mach-O viewer for macOS. Powered by Mach-O Kit.

Mach-O Explorer is a graphical Mach-O viewer for macOS. It aims to provide an interface and feature set that are similar to the venerable MachOView ap

Devin 581 Dec 31, 2022
Unboxing - An extension for KeyedDecodingContainer class to decode a collection of heterogeneous types.

Unboxing An extension for KeyedDecodingContainer class to decode a collection of heterogeneous types. Usage Start by creating an enum that has variant

null 2 Jun 15, 2022
Lock a terminal command to the efficiency or performance cores on a big.LITTLE ARM processor

CPU-Lock Lock a terminal command to the efficiency or performance cores on a big.LITTLE ARM processor (Designed for Apple Silicon). Usage Download the

BitesPotatoBacks 0 Aug 11, 2022
Swift Markdown is a Swift package for parsing, building, editing, and analyzing Markdown documents.

Swift Markdown is a Swift package for parsing, building, editing, and analyzing Markdown documents.

Apple 2k Dec 28, 2022
OwO.swift Badges go here in one line for the master branch ONLY.

OwO.swift Badges go here in one line for the master branch ONLY. Badges can also go in the header line. Short description describing the application/l

Spotlight 2 May 28, 2022
A Swift package for rapid development using a collection of micro utility extensions for Standard Library, Foundation, and other native frameworks.

ZamzamKit ZamzamKit is a Swift package for rapid development using a collection of micro utility extensions for Standard Library, Foundation, and othe

Zamzam Inc. 261 Dec 15, 2022
Swift package adding fraction and percentage types.

swift-rationals Rationals is a package containing Fraction and Percentage types for the Swift programming language. Contents The package currently pro

Alexandre H. Saad 0 Jul 28, 2022
Units is a Swift package to manipulate, compare, and convert between physical quantities.

Units ?? Units is a Swift package to manipulate, compare, and convert between physical quantities. This package models measurements, which are a numer

Jay Herron 3 Jun 22, 2022
WWDCKit - Creating and Using a Swift Package

WWDCKit - Creating and Using a Swift Package 1. Create the Package in Xcode Navigate to File >> New >> Package. Give the Package a name e.g "WWDCKit".

Alex Paul 6 Dec 11, 2022