Generate class diagrams in one shot with Sourcery + mermaid 🤖

zeero
3 min readMar 27, 2022

GitHub now supports mermaid 🎉
I was trying to use it, and I was thinking, “mermaid can make class diagrams too… I should make class diagrams for those complicated parts of iOS apps…” and then it hit me!
This is a Sourcery case! I thought it could be generated automatically.

So I did it 💪
It still looks buggy, but I’ve gotten it to work, so I’ll publish it.

The source code is voluminous, so I’ll put it on Gist.
https://gist.github.com/zeero/32095f805b89825b32591b195c4bf7e9

Some corrections are made for display in mermaid. Please read README.md for specifications and other notes 🙏🏼

Usage follows:

  1. Install Sourcery
  2. Download source code from Gist
  3. Modify .sourcery.yml to specify the source code for analyzing
    (Sourcery can specify the analysis target by directory or target multiple directories)
  4. Execute sourcery command in the downloaded directory
  5. Display the class_diagram.md file in the same directory with GitHub Issue or other mermaid-compatible tools

Demo

I analyze some OSS libraries by using it.

ReSwift

First, at a moderate scale, ReSwift.

It’s a simple structure, it is easy to understand!

SubscriptionBox seems to have a central role in observing management, because it is composed of Subscription, which has methods related to observing, and StoreSubscriber, which is an observer.

On the right part, the realization line has been drawn on both StoreType and DispatchingStoreType from Store.
StoreType and DispatchingStoreType have an inheritance relationship, so it is really:

Store ..(realization)..> StoreType --(inheritance)--> DispatchingStoreType

But it seemed difficult to resolve in specifications of Sourcery & Stencil… 🤔

RxSwift

RxSwift is too huge to display. lol

RxCocoa

With RxCocoa, it looks like this.

Oooooo… the scale is amazing!
It is no longer visible at all, but I could say that it is a “horizontally wide” library.
It’s a library that adds functionality to each UIKit class.

PKHUD

The last one is PKHUD from the UI library.

Pretty nice display!
UI libraries are focused on a single issue, so they may not have such a complicated class structure.
Each view that inherits from PKHUDSquareBaseView also implements the PKHUDAnimating protocol, so they can display square views to be displayed & animated.

To sum up

I think the visualization will be quite useful to get an overview 💡
And it can also be used as a scaffold. For example, once all the classes have been generated, then only the classes you want can be cut out.
I struggled a lot with Stencil and tried my best to implement relationships, but it was worth it.
If you are interested, please use it 😃

--

--