LoginSignup
38
23

More than 1 year has passed since last update.

この記事について

ドメイン固有言語(DSL: Domain-Specific Language)の1つであり、Declarative Diagrammingの略であるD2言語の環境構築、および簡単な作図例を示したものです。

D2とは

2022年11月22日にオープンソースとなったドメイン固有言語です。MPL-2.0ライセンスの元公開されています。

Mermaid, Graphviz, PlantUMLとの比較を行えるサイトもD2の開発元であるTerrastructによって公開されています。

一部抜粋したものが次の表になります。
他のText to Diagramツールと比較して、D2では様々な機能が追加されていることが分かります。

特徴 D2 PlantUML MermaidJS GraphViz
エラーメッセージ 
ただ単に"syntax error"とだけ表示しない
× × ×
メンテナンスの継続性 サポートは限定的で終了する可能性
図とアイコンの挿入 どのURLでも使用可能 × FontAwesome
imgタグ
×
シーケンス図 試験的 ×
SQLテーブル
ER図への対応
×
マークダウン記法 × × ×
コードスニペット × × ×
オートフォーマット × × ×

特にD2におけるエラーメッセージは非常に分かりやすく、
次のように図形に表示する語句を空白にしたままコンパイルを行うと

in.d2
test: 

このようにエラーの発生する箇所を行数及び行頭からの文字数、また具体的なエラーの内容まで教えてくれます。

$ d2 --watch in.d2
[11:11:49] success: listening on http://127.0.0.1:50817
[11:11:49] info: compiling in.d2...
[11:11:49] err: failed to compile: 1:5: missing value after colon

このエラーの内容は複数個所存在する場合は一度に表示してくれます。

in.d2
test1: 
test2:
[11:18:29] err: failed to recompile: 1:6: missing value after colon
[11:18:29] err: 2:6: missing value after colon

環境構築

2022年11月28日時点では、Windows向けの環境構築方法の公開、及びDocker Imageの公式配布はありません。

2022年12月7日にリリースされたv0.1.0にてWindowsへのサポートが対応されました!

今回は2通りの環境構築を行っていますが、作図例で用いた環境は次の通りです。

  • Windows 11 Home 22H2
  • Git Bash
  • D2 v0.1.1

WSL2でのインストール

WSL2の環境構築に関しては他の方の記事を参考にしてください。

インストール自体は次のコマンドで行えます。

$ curl -fsSL https://d2lang.com/install.sh | sh -s --

インストールの挙動が気になる方はdry-runを行ってみても良いでしょう。

$ curl -fsSL https://d2lang.com/install.sh | sh -s -- --dry-run

インストールされたか確認

$ d2 --version
v0.1.1

バージョン情報が表示されればインストール成功です。

Git Bashでのインストール

2022年12月7日にリリースされたv0.1.0にてサポートされました!

Git Bashのインストールに関しては他の方の記事を参考にしてください。

今回は2022年12月8日にリリースされたv0.1.1を用いてみます。
こちらから環境に適したアセットをダウンロードしましょう。

適当なディレクトリに配置しtarコマンドで解凍します。

$ ls
d2-v0.1.1-windows-amd64.tar.gz

$ tar -zxvf d2-v0.1.1-windows-amd64.tar.gz
d2-v0.1.1/
d2-v0.1.1/man/
d2-v0.1.1/bin/
d2-v0.1.1/Makefile
d2-v0.1.1/README.md
d2-v0.1.1/scripts/
d2-v0.1.1/LICENSE.txt
d2-v0.1.1/scripts/uninstall.sh
d2-v0.1.1/scripts/install.sh
d2-v0.1.1/scripts/lib.sh
d2-v0.1.1/bin/d2.exe
d2-v0.1.1/man/d2.1

あとはbinディレクトリに対してpathを通してあげれば完了です。

インストールされたか確認

$ d2 --version
v0.1.1

バージョン情報が表示されればインストール成功です。

動かしてみる

公式でチュートリアルが用意されています。
次のコマンドを叩くことで、自動的にブラウザが立ち上がりsvgが表示されます。

$ echo 'x -> y -> z' > in.d2
$ d2 --watch in.d2 out.svg
out.svg

今回はd2ファイルに対してコマンドを挿入して、out.svgとして出力しましたが、

$ d2 --watch input.d2

とした上で、input.d2ファイルを編集することで、自動的に図を作成、表示までしてくれます。

VSCodeで動かしてみる

2022年12月14日現在、シンタックスハイライトのみサポートされています

またVSCodeでは公式から拡張機能が提供されています。
拡張機能のパネルから、d2と入力しTerrastructが出しているものをインストールしましょう。
d2-extension.png
ターミナルを起動し先ほどと同じようにd2 --watch input.d2を叩くことで、input.d2ファイルを更新する度にブラウザに表示される図が更新されていきます。
image.png

図形の種類

D2ではデフォルトで様々な形の図形が用意されています。

図形の指定は図形を定義したうえで、shapeフィールドを指定します。

object: 長方形 # objectという名前の図形を定義し「長方形」と表示する
object.shape: rectangle # objectの形をrectangle(長方形)として指定

ただしデフォルトで長方形が指定されているため、長方形を用いる場合は指定する必要はありません。
公式ドキュメントでは一部のみ掲載されているため、利用可能な全種類の図形を表示しておきます。

長方形

rect: rectangle
rect.shape: rectangle

image.png

正方形

squa: square
squa.shape: square

square.png

ページ

page: page
page.shape: page

page.png

平行四辺形

paral: parallelogram
paral.shape: parallelogram

parallelogram.png

ドキュメント

docu: document
docu.shape: document

document.png

円柱(縦)

cyli: cylinder
cyli.shape: cylinder

cylinder.png

円柱(横)

que: queue
que.shape: queue

queue.png

パッケージ

pack: package
pack.shape: package

package.png

ステップ

step: step
step.shape: step

step.png

吹き出し

call: callout
call.shape: callout

callout.png

データストア

stdt: stored_data
stdt.shape: stored_data

stored_data.png

人型

pers: person
pers.shape: person

person.png

ひし形

dia: diamond
dia.shape: diamond

diamond.png

楕円

oval: oval
oval.shape: oval

oval.png

circ: circle
circ.shape: circle

circle.png

六角形

hex: hexagon
hex.shape: hexagon

hexagon.png

クラウド

cloud: cloud
cloud.shape: cloud

cloud.png

その他

このほかにも特殊な図形として

  1. text: md形式で文章を追加可能
  2. code: md形式をコードブロックに変換して配置可能
  3. class: UML図を記述することが可能
  4. sql_table: ER図を記述することが可能
  5. image: アイコンや画像の挿入が可能
  6. sequence_diagram: シーケンス図を記述することが可能

が定義されています。

v0.1.0にてシーケンス図が試験的に導入されました!

作図例

フローチャート

まずは簡単なフローチャートを作図してみました。
直感的で分かりやすく記述することが可能ですね。

start: 開始
start.shape: oval
if: 条件
if.shape: diamond
process: 処理
process.shape: rectangle
exception: 例外処理
exception.shape: rectangle
end: 終了
end.shape: oval

start -> if
if -> process: true
if -> exception: false
process -> end
exception -> end

flow.png

UML図

次にUML図に加え、D2内で使用可能なmarkdownでの文章の記述と、コードブロックでのコードの記述も試してみました。

SuperClass: {
    shape: class

    -testStatus: String
    \#testId: String

    +getStatus(String): String
}

SubClass: {
    shape: class

    \#piyo: String

    \#getHoge(int): Class<?>
    setHuga(T)
}

SuperClass <- SubClass

SuperClassExplanation: |md
    # test
    - If you write in English, it will display nicely.
    - In v0.0.13, the background of here is black due to the dark mode. This problem will be fixed next release.
    - [render: consistent md render regardless of system dark mode](https://github.com/terrastruct/d2/pull/211)
| {
    near: SuperClass
}

JapaneseExplanation: |md
    日本語のテストです、現時点だと欠けちゃいます
|{ 
    near: SubClass
}

SubClassCode: |java
    public class SubClass extends SuperClass {
        protected String piyo;

        protected Class<?> getHoge(int aaa) {

        }

        private void setHuga(T) {

        }
    }
| {
    near: SubClass
}

UML2.png

v0.1.0となり'near'はTALAレイアウトエンジンでのみ動作する記述が追加されました
他のレイアウトエンジンでも動作するよう開発中だそうです

執筆時点でissueへの投稿は見られませんでしたが、
日本語で記述した部分に関しては見切れてしまうようです

ER図

次のER図は公式ドキュメントで用意されているサンプルになります。
先に紹介した図形と併用して利用することも可能です。

cloud: {
  disks: {
    shape: sql_table
    id: int {constraint: primary_key}
  }
  blocks: {
    shape: sql_table
    id: int {constraint: primary_key}
    disk: int {constraint: foreign_key}
    blob: blob
  }
  blocks.disk -> disks.id

  AWS S3 Vancouver -> disks
}

ER.png

シーケンス図

次のシーケンス図は公式ドキュメントで用意されているサンプルになります。
実線や点線のカスタマイズも容易に行えますね。

shape: sequence_diagram
scorer: { shape: person }
scorer.t -> itemResponse.t: getItem()
scorer.t <- itemResponse.t: item {
    stroke-dash: 5
}

scorer.t -> item.t1: getRubric()
scorer.t <- item.t1: rubric {
    stroke-dash: 5
}

scorer.t -> essayRubric.t: applyTo(essayResp)
itemResponse -> essayRubric.t.c
essayRubric.t.c -> concept.t: match(essayResponse)
scorer <- essayRubric.t: score {
    stroke-dash: 5
}

scorer.t -> itemOutcome.t1: new
scorer.t -> item.t2: getNormalMinimum()
scorer.t -> item.t3: getNormalMaximum()

scorer.t -> itemOutcome.t2: setScore(score)
scorer.t -> itemOutcome.t3: setFeedback(missingConcepts)

SequenceDiagram.png

終わりに

D2はv0.1.0からWindowsでも容易に利用可能になり、現在も活発に開発されている言語です。
執筆中もリリースが行われ、バグ修正が行われていました。
言語としては直感的で分かりやすく、利用シーンは多々ありそうですね。
最後までお読みいただきありがとうございました。

38
23
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
38
23