sargasso 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: e993c1b7af47b4e9924c31ca18f9f8eab56235a3c35fc1b58509bf899e6e4a6c
4
+ data.tar.gz: 7be2a0c6a1ba3646b6428dbc8503dd0f0be774d4e5855a0ed70d1282720b553e
5
+ SHA512:
6
+ metadata.gz: 96efae4db9533a137da49cbfc928261ede6d8ed7ed852fc00cc6c56e0299fcdf08b557eb8e0ff2b214212c60bb4f3397b7f9d12cbbbcdc22b6323035443f0992
7
+ data.tar.gz: 4e7a7cec1fdf01bdb7f7ac241b8efdaaa3fa80cc50bdb067dc21307e5e92dba5346647da3a97b95b89f060db472542d33692ccf26fe8b0ddb718b8b5c66babcf
data/CHANGELOG.md ADDED
@@ -0,0 +1,24 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [Unreleased]
9
+
10
+ ### Changed
11
+
12
+ - Minimum Ruby version raised to 3.3.0 (the development toolchain requires it)
13
+
14
+ ## [0.0.1] - 2026-09-03
15
+
16
+ ### Added
17
+
18
+ - Initial release
19
+ - `Sargasso.convert(plantuml_string)` converts PlantUML source to Mermaid source
20
+ - Sequence diagram support: messages, participant aliases, dashed/return arrows, `alt`/`else` blocks
21
+ - Diagram-agnostic AST (`Parser` -> `AST` -> `Emitters::Mermaid`) so more diagram types and emitters can be added later
22
+ - CLI (`sargasso`) with file argument, stdin via `-`, `--quiet`, and `--strict`
23
+ - Unsupported PlantUML constructs are reported as warnings by default, or raise `Sargasso::UnsupportedConstructError` under `--strict`
24
+ - Minitest suite with golden-file fixtures (`.puml` / `.mmd` pairs)
@@ -0,0 +1,83 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, caste, color, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or advances of any kind
22
+ * Trolling, insulting or derogatory comments, and personal or political attacks
23
+ * Public or private harassment
24
+ * Publishing others' private information, such as a physical or email address, without their explicit permission
25
+ * Other conduct which could reasonably be considered inappropriate in a professional setting
26
+
27
+ ## Enforcement Responsibilities
28
+
29
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
30
+
31
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
32
+
33
+ ## Scope
34
+
35
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
36
+
37
+ ## Enforcement
38
+
39
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at **kerrizor@kerrizor.com**. All complaints will be reviewed and investigated promptly and fairly.
40
+
41
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
42
+
43
+ ## Enforcement Guidelines
44
+
45
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
46
+
47
+ ### 1. Correction
48
+
49
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
50
+
51
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
52
+
53
+ ### 2. Warning
54
+
55
+ **Community Impact**: A violation through a single incident or series of actions.
56
+
57
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
58
+
59
+ ### 3. Temporary Ban
60
+
61
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
62
+
63
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
64
+
65
+ ### 4. Permanent Ban
66
+
67
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
68
+
69
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
70
+
71
+ ## Attribution
72
+
73
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.1, available at [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
74
+
75
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
76
+
77
+ For answers to common questions about this code of conduct, see the FAQ at [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at [https://www.contributor-covenant.org/translations][translations].
78
+
79
+ [homepage]: https://www.contributor-covenant.org
80
+ [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
81
+ [Mozilla CoC]: https://github.com/mozilla/diversity
82
+ [FAQ]: https://www.contributor-covenant.org/faq
83
+ [translations]: https://www.contributor-covenant.org/translations
data/CONTRIBUTING.md ADDED
@@ -0,0 +1,113 @@
1
+ # Contributing to Sargasso
2
+
3
+ Thanks for your interest in contributing to Sargasso! This document covers how to get started.
4
+
5
+ ## Development Setup
6
+
7
+ ```bash
8
+ git clone https://github.com/kerrizor/sargasso.git
9
+ cd sargasso
10
+ bundle install
11
+ ```
12
+
13
+ ## Running Tests
14
+
15
+ ```bash
16
+ bundle exec rake test
17
+ ```
18
+
19
+ Or run the full default task (tests plus RuboCop):
20
+
21
+ ```bash
22
+ bundle exec rake
23
+ ```
24
+
25
+ All tests must pass and RuboCop must be clean before submitting a PR.
26
+
27
+ ## Code Style
28
+
29
+ - Use `frozen_string_literal: true` at the top of all Ruby files
30
+ - Follow standard Ruby conventions (enforced by RuboCop)
31
+ - Keep methods small and focused
32
+ - Add tests for new functionality
33
+ - No em-dashes in prose (use commas, parentheses, or restructure)
34
+
35
+ ## Architecture
36
+
37
+ Sargasso converts diagrams through a three-stage pipeline:
38
+
39
+ ```
40
+ PlantUML source -> Sargasso::Parser -> Sargasso::AST -> Sargasso::Emitters::Mermaid -> Mermaid source
41
+ ```
42
+
43
+ - **`Sargasso::Parser`** turns PlantUML source into AST nodes.
44
+ - **`Sargasso::AST`** is a diagram-agnostic set of structs (`Diagram`, `Participant`, `Message`, `Alt`, `Branch`, `Unsupported`). It knows nothing about PlantUML or Mermaid syntax.
45
+ - **`Sargasso::Emitters::Mermaid`** turns AST nodes into Mermaid source.
46
+
47
+ Keeping the AST neutral is what lets new diagram types and new emitters (for example draw.io or graphviz) slot in without a rewrite. When you add support for a construct, add the AST node first, then teach the parser to produce it and the emitter to render it.
48
+
49
+ ## Adding Support for a New Construct
50
+
51
+ The most common contribution is teaching Sargasso a PlantUML construct it does not yet understand (currently these become `AST::Unsupported` and produce a warning). Each addition is three coordinated changes plus a fixture pair.
52
+
53
+ ### 1. Add or reuse an AST node
54
+
55
+ If the construct needs new structure, add a struct to `lib/sargasso/ast.rb`. Keep it source-agnostic and target-agnostic. For example, a note might be:
56
+
57
+ ```ruby
58
+ # A note attached to one or more participants.
59
+ #
60
+ # position is a neutral placement: :left, :right, or :over.
61
+ #
62
+ Note = Struct.new(:position, :participants, :text, keyword_init: true)
63
+ ```
64
+
65
+ ### 2. Teach the parser to produce it
66
+
67
+ In `lib/sargasso/parser.rb`, match the PlantUML line and build the AST node instead of falling through to `AST::Unsupported`.
68
+
69
+ ### 3. Teach the emitter to render it
70
+
71
+ In `lib/sargasso/emitters/mermaid.rb`, handle the new node type and emit the equivalent Mermaid syntax. If Mermaid has no equivalent, record a warning (or raise `Sargasso::UnsupportedConstructError` under strict mode) rather than dropping it silently.
72
+
73
+ ### 4. Add a golden-file fixture pair
74
+
75
+ Add a matching pair under `test/fixtures/`:
76
+
77
+ - `test/fixtures/my_construct.puml` (the PlantUML input)
78
+ - `test/fixtures/my_construct.mmd` (the expected Mermaid output)
79
+
80
+ Then assert the conversion in `test/test_sargasso.rb`:
81
+
82
+ ```ruby
83
+ def test_my_construct
84
+ assert_fixture_converts("my_construct")
85
+ end
86
+ ```
87
+
88
+ ### 5. Update documentation
89
+
90
+ - Update the feature/feasibility table in `README.md` if coverage changed
91
+ - Add a changelog entry under `[Unreleased]`
92
+
93
+ ## Adding a New Diagram Type
94
+
95
+ Sequence diagrams are the only supported type in v1. Adding another type (class, state, ER, and so on) follows the same pattern at a larger scale: add the AST nodes it needs, add a parser path that recognizes the diagram's opening syntax, and add emitter cases that render it. See the feasibility ranking in the README and in the idea doc for which types map cleanly to Mermaid.
96
+
97
+ ## Pull Request Process
98
+
99
+ 1. **Branch naming**: Use `your-username/description` (for example `kerrizor/support-notes`)
100
+
101
+ 2. **Changelog**: Add an entry to `CHANGELOG.md` under `[Unreleased]`:
102
+ ```markdown
103
+ ### Added
104
+ - **Notes** - `note left/right/over` now converts to Mermaid notes
105
+ ```
106
+
107
+ 3. **Tests**: Ensure `bundle exec rake` passes (tests plus RuboCop)
108
+
109
+ 4. **PR description**: Explain what the change does and why
110
+
111
+ ## Questions?
112
+
113
+ Open an issue if you have questions or want to discuss a feature before implementing it.
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2026 Kerri Miller
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,142 @@
1
+ # Sargasso 🌊
2
+
3
+ **PlantUML goes in, Mermaid comes out.**
4
+
5
+ The Sargasso Sea is the one stretch of ocean defined by its seaweed rather than
6
+ its shores, a floating tangle that catches whatever drifts through. This gem is
7
+ that tangle for your diagrams: feed it PlantUML and it hands back the equivalent
8
+ Mermaid, so your old diagrams wash up somewhere they can actually be rendered.
9
+
10
+ ```
11
+ 🧜 PlantUML sequence diagrams -> Mermaid, in pure Ruby
12
+ 🪸 Parser -> AST -> Emitter, so new diagram types can grow on the reef
13
+ 🐚 Nothing dropped silently: unknown syntax warns, or raises under --strict
14
+ ```
15
+
16
+ It also fills a genuine gap: no Ruby gem does this today, and the wider
17
+ ecosystem is thin (a couple of JavaScript tools, some hosted web apps).
18
+
19
+ Named for the free-floating *Sargassum* seaweed of the Sargasso Sea.
20
+
21
+ ## Why parse the source directly (the no-clean-bridge rationale)
22
+
23
+ PlantUML never exports a neutral, re-serializable semantic model. Its native
24
+ exports are renders (PNG, SVG, PDF), and its structured exports are narrow and
25
+ lossy (SCXML for state diagrams only, XMI for class diagrams only). There is no
26
+ reliable intermediate format to lean on, so Sargasso parses PlantUML source
27
+ directly and emits Mermaid.
28
+
29
+ ## Installation
30
+
31
+ Install the gem from RubyGems (once published):
32
+
33
+ ```bash
34
+ gem install sargasso
35
+ ```
36
+
37
+ Or add it to a Gemfile:
38
+
39
+ ```ruby
40
+ gem "sargasso"
41
+ ```
42
+
43
+ Sargasso is pure Ruby with no Node or JavaScript runtime dependency.
44
+
45
+ ## Usage
46
+
47
+ ```ruby
48
+ require "sargasso"
49
+
50
+ plantuml = <<~PUML
51
+ @startuml
52
+ Alice -> Bob: Hello
53
+ Bob --> Alice: Hi back
54
+ @enduml
55
+ PUML
56
+
57
+ puts Sargasso.convert(plantuml)
58
+ ```
59
+
60
+ Output:
61
+
62
+ ```
63
+ sequenceDiagram
64
+ Alice->>Bob: Hello
65
+ Bob-->>Alice: Hi back
66
+ ```
67
+
68
+ PlantUML `->` maps to Mermaid's solid arrow (`->>`), and `-->` maps to the
69
+ dashed arrow (`-->>`). The `@startuml` and `@enduml` markers are stripped, and
70
+ message lines are indented under `sequenceDiagram`.
71
+
72
+ ### Unsupported constructs
73
+
74
+ By default, a construct Sargasso does not understand produces a warning and is
75
+ skipped rather than silently dropped. You can collect those warnings, or opt
76
+ into strict mode to raise instead:
77
+
78
+ ```ruby
79
+ warnings = []
80
+ Sargasso.convert(plantuml, warnings: warnings) # warnings gathered here
81
+
82
+ Sargasso.convert(plantuml, strict: true) # raises on the first unsupported construct
83
+ ```
84
+
85
+ ## CLI
86
+
87
+ ```bash
88
+ sargasso path/to/diagram.puml # convert a file, write Mermaid to stdout
89
+ cat diagram.puml | sargasso - # read from stdin, write to stdout
90
+ sargasso --quiet diagram.puml # suppress warnings
91
+ sargasso --strict diagram.puml # exit non-zero on any unsupported construct
92
+ ```
93
+
94
+ ## Scope: v1 supports sequence diagrams only
95
+
96
+ Sequence is the best-covered diagram type across every existing tool, so it is
97
+ the v1 target. Other diagram types are not yet supported. The feasibility table
98
+ below cross-references the design notes in the idea doc.
99
+
100
+ | PlantUML diagram | Mermaid target | Feasibility | Status |
101
+ |------------------|---------------------|-----------------------------------|---------------|
102
+ | Sequence | `sequenceDiagram` | High (proven by pu2mm) | v1 (this gem) |
103
+ | Class | `classDiagram` | Medium (partial in other tools) | planned (v2) |
104
+ | State | `stateDiagram-v2` | Medium (SCXML path possible) | planned (v2) |
105
+ | Activity (beta) | `flowchart` | Low/Medium (structural mismatch) | not planned |
106
+ | Component | `flowchart`/`graph` | Low (approximate only) | not planned |
107
+ | Use case | `flowchart` | Low (no native Mermaid use-case) | not planned |
108
+ | ER | `erDiagram` | Medium | maybe |
109
+ | Gantt | `gantt` | Medium | maybe |
110
+
111
+ The pipeline is structured as `Parser -> AST -> Emitter` so additional diagram
112
+ types and additional emitters (for example draw.io) can be added later without
113
+ a rewrite.
114
+
115
+ ## Development
116
+
117
+ After checking out the repo, run `bin/setup` to install dependencies. Then run
118
+ `rake test` to run the tests and `rake rubocop` to lint. You can also run
119
+ `bin/console` for an interactive prompt.
120
+
121
+ Tests use golden-file fixtures: each pair `test/fixtures/<name>.puml` and
122
+ `test/fixtures/<name>.mmd` asserts that converting the PlantUML input produces
123
+ the expected Mermaid output.
124
+
125
+ ## Changelog
126
+
127
+ See [CHANGELOG.md](CHANGELOG.md) for a list of notable changes to each release.
128
+
129
+ ## Contributing
130
+
131
+ Bug reports and pull requests are welcome on GitHub at
132
+ https://github.com/kerrizor/sargasso. See [CONTRIBUTING.md](CONTRIBUTING.md) for
133
+ development setup, the `Parser -> AST -> Emitter` architecture, and how to add
134
+ support for a new construct or diagram type.
135
+
136
+ Everyone interacting in the Sargasso project is expected to follow the
137
+ [Code of Conduct](CODE_OF_CONDUCT.md).
138
+
139
+ ## License
140
+
141
+ Available as open source under the terms of the
142
+ [MIT License](https://opensource.org/licenses/MIT).
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "minitest/test_task"
5
+
6
+ Minitest::TestTask.create
7
+
8
+ require "rubocop/rake_task"
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[test rubocop]
data/exe/sargasso ADDED
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require "sargasso/cli"
5
+
6
+ exit Sargasso::CLI.new(ARGV).run
@@ -0,0 +1,56 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Sargasso
4
+ # Diagram-agnostic AST nodes.
5
+ #
6
+ # These structs describe the semantic content of a diagram independent of any
7
+ # source (PlantUML) or target (Mermaid) syntax. Parsers build them; emitters
8
+ # consume them. Keeping this layer neutral is what lets a future grammar or a
9
+ # future emitter (draw.io, graphviz) slot in without a rewrite.
10
+ #
11
+ module AST
12
+ # The root of a parsed diagram. For v1, kind is always :sequence.
13
+ #
14
+ Diagram = Struct.new(:kind, :nodes, keyword_init: true) do
15
+ def initialize(kind:, nodes: [])
16
+ super
17
+ end
18
+ end
19
+
20
+ # A declared participant or actor, with an optional display label.
21
+ #
22
+ # id is the identifier used in messages. label is the human display name
23
+ # (nil when the declaration had no alias).
24
+ #
25
+ Participant = Struct.new(:id, :label, keyword_init: true)
26
+
27
+ # A message from one participant to another.
28
+ #
29
+ # arrow is the neutral arrow kind: :solid or :dashed. The emitter decides
30
+ # the concrete target syntax.
31
+ #
32
+ Message = Struct.new(:from, :to, :text, :arrow, keyword_init: true)
33
+
34
+ # An alt/else group. branches is an array of Branch nodes.
35
+ #
36
+ Alt = Struct.new(:branches, keyword_init: true) do
37
+ def initialize(branches: [])
38
+ super
39
+ end
40
+ end
41
+
42
+ # One branch of a group (the alt label, or an else label).
43
+ #
44
+ Branch = Struct.new(:label, :nodes, keyword_init: true) do
45
+ def initialize(label:, nodes: [])
46
+ super
47
+ end
48
+ end
49
+
50
+ # A construct sargasso does not yet understand. Kept in the tree so the
51
+ # emitter can warn (or, under strict mode, raise) rather than silently
52
+ # dropping input.
53
+ #
54
+ Unsupported = Struct.new(:source, keyword_init: true)
55
+ end
56
+ end
@@ -0,0 +1,80 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "optparse"
4
+ require_relative "../sargasso"
5
+
6
+ module Sargasso
7
+ # Command-line entry point.
8
+ #
9
+ # sargasso path/to/diagram.puml # -> stdout Mermaid
10
+ # cat diagram.puml | sargasso - # stdin -> stdout
11
+ # sargasso --quiet ... # suppress warnings
12
+ # sargasso --strict ... # fail on any unsupported construct
13
+ #
14
+ class CLI
15
+ def initialize(argv, stdin: $stdin, stdout: $stdout, stderr: $stderr)
16
+ @argv = argv
17
+ @stdin = stdin
18
+ @stdout = stdout
19
+ @stderr = stderr
20
+ @options = { quiet: false, strict: false }
21
+ end
22
+
23
+ # Returns a process exit status (0 success, non-zero failure).
24
+ #
25
+ def run
26
+ paths = parse_options
27
+ return 0 if @help
28
+
29
+ source = read_source(paths)
30
+ return 1 if source.nil?
31
+
32
+ convert_and_emit(source)
33
+ rescue Sargasso::UnsupportedConstructError => e
34
+ @stderr.puts("sargasso: #{e.message}")
35
+ 1
36
+ end
37
+
38
+ private
39
+
40
+ def convert_and_emit(source)
41
+ warnings = []
42
+ output = Sargasso.convert(source, strict: @options[:strict], warnings: warnings)
43
+ @stdout.puts(output)
44
+ report_warnings(warnings)
45
+ 0
46
+ end
47
+
48
+ def parse_options
49
+ parser = OptionParser.new do |opts|
50
+ opts.banner = "Usage: sargasso [options] FILE|-"
51
+ opts.on("--quiet", "Suppress warnings") { @options[:quiet] = true }
52
+ opts.on("--strict", "Fail on any unsupported construct") { @options[:strict] = true }
53
+ opts.on("-h", "--help", "Show this help") do
54
+ @stdout.puts(opts)
55
+ @help = true
56
+ end
57
+ end
58
+ parser.parse(@argv)
59
+ end
60
+
61
+ def read_source(paths)
62
+ path = paths.first
63
+ if path.nil?
64
+ @stderr.puts("sargasso: no input file given (use '-' for stdin)")
65
+ return nil
66
+ end
67
+
68
+ path == "-" ? @stdin.read : File.read(path)
69
+ rescue Errno::ENOENT
70
+ @stderr.puts("sargasso: no such file: #{path}")
71
+ nil
72
+ end
73
+
74
+ def report_warnings(warnings)
75
+ return if @options[:quiet]
76
+
77
+ warnings.each { |w| @stderr.puts("sargasso: warning: #{w}") }
78
+ end
79
+ end
80
+ end
@@ -0,0 +1,75 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../ast"
4
+
5
+ module Sargasso
6
+ module Emitters
7
+ # Emits Mermaid sequenceDiagram source from a Sargasso::AST::Diagram.
8
+ #
9
+ # Each message line is indented one level (4 spaces) under the
10
+ # "sequenceDiagram" header. Nested groups (alt/else) add further indentation.
11
+ #
12
+ class Mermaid
13
+ ARROWS = { solid: "->>", dashed: "-->>" }.freeze
14
+ INDENT = " "
15
+
16
+ # warnings collects human-readable messages about unsupported constructs.
17
+ # In strict mode the first unsupported construct raises instead.
18
+ #
19
+ attr_reader :warnings
20
+
21
+ def initialize(strict: false)
22
+ @strict = strict
23
+ @warnings = []
24
+ end
25
+
26
+ def emit(diagram)
27
+ lines = ["sequenceDiagram"]
28
+ emit_nodes(diagram.nodes, lines, 1)
29
+ "#{lines.join("\n")}\n"
30
+ end
31
+
32
+ private
33
+
34
+ def emit_nodes(nodes, lines, depth)
35
+ nodes.each { |node| emit_node(node, lines, depth) }
36
+ end
37
+
38
+ def emit_node(node, lines, depth)
39
+ case node
40
+ when AST::Participant then lines << participant_line(node, depth)
41
+ when AST::Message then lines << message_line(node, depth)
42
+ when AST::Alt then emit_alt(node, lines, depth)
43
+ when AST::Unsupported then handle_unsupported(node)
44
+ end
45
+ end
46
+
47
+ def participant_line(node, depth)
48
+ line = "#{INDENT * depth}participant #{node.id}"
49
+ line += " as #{node.label}" if node.label
50
+ line
51
+ end
52
+
53
+ def message_line(node, depth)
54
+ "#{INDENT * depth}#{node.from}#{ARROWS.fetch(node.arrow)}#{node.to}: #{node.text}"
55
+ end
56
+
57
+ def emit_alt(alt, lines, depth)
58
+ alt.branches.each_with_index do |branch, index|
59
+ keyword = index.zero? ? "alt" : "else"
60
+ label = branch.label.empty? ? keyword : "#{keyword} #{branch.label}"
61
+ lines << "#{INDENT * depth}#{label}"
62
+ emit_nodes(branch.nodes, lines, depth + 1)
63
+ end
64
+ lines << "#{INDENT * depth}end"
65
+ end
66
+
67
+ def handle_unsupported(node)
68
+ message = "unsupported construct: #{node.source.inspect}"
69
+ raise Sargasso::UnsupportedConstructError, message if @strict
70
+
71
+ @warnings << message
72
+ end
73
+ end
74
+ end
75
+ end
@@ -0,0 +1,131 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "ast"
4
+
5
+ module Sargasso
6
+ # Parses PlantUML sequence-diagram source into Sargasso::AST nodes.
7
+ #
8
+ # v1 is deliberately line-oriented: PlantUML sequence syntax is largely
9
+ # line-based, so a set of per-line matchers gets us a useful walking skeleton
10
+ # fast. The AST layer sits between this and the emitter so a real grammar can
11
+ # replace this parser later without touching emitters.
12
+ #
13
+ class Parser
14
+ # Matches a message line: "A -> B: text" or "A --> B : text".
15
+ # Group 1: source, 2: arrow, 3: target, 4: optional text.
16
+ #
17
+ MESSAGE = /\A(\S+)\s*(-+>+)\s*(\S+)\s*(?::\s*(.*))?\z/
18
+
19
+ # Matches a participant/actor declaration, with optional quoted label and
20
+ # "as" alias:
21
+ # participant Bob
22
+ # participant "Bob B." as B
23
+ # actor Alice
24
+ # Group 1: keyword, 2: quoted name (optional), 3: bare name (optional),
25
+ # 4: alias (optional).
26
+ #
27
+ PARTICIPANT = /\A(participant|actor)\s+(?:"([^"]+)"|(\S+))(?:\s+as\s+(\S+))?\z/i
28
+
29
+ ALT = /\Aalt\b\s*(.*)\z/i
30
+ ELSE = /\Aelse\b\s*(.*)\z/i
31
+ END_GROUP = /\Aend\b\z/i
32
+
33
+ def initialize(source)
34
+ @source = source
35
+ end
36
+
37
+ def parse
38
+ diagram = AST::Diagram.new(kind: :sequence)
39
+ # Stack of node lists; the top is where new nodes are appended. Groups
40
+ # (alt/else) push a new branch's node list onto this stack.
41
+ #
42
+ @stack = [diagram.nodes]
43
+
44
+ each_significant_line do |line|
45
+ parse_line(line)
46
+ end
47
+
48
+ diagram
49
+ end
50
+
51
+ private
52
+
53
+ def each_significant_line
54
+ @source.each_line do |raw|
55
+ line = raw.strip
56
+ next if line.empty?
57
+ next if line.start_with?("@startuml", "@enduml")
58
+ next if line.start_with?("'") # PlantUML single-line comment
59
+
60
+ yield line
61
+ end
62
+ end
63
+
64
+ def parse_line(line)
65
+ case line
66
+ when ALT then start_alt(Regexp.last_match(1))
67
+ when ELSE then start_else(Regexp.last_match(1))
68
+ when END_GROUP then end_group
69
+ when PARTICIPANT then push_participant(Regexp.last_match)
70
+ when MESSAGE then push_message(Regexp.last_match)
71
+ else current << AST::Unsupported.new(source: line)
72
+ end
73
+ end
74
+
75
+ def push_participant(match)
76
+ quoted = match[2]
77
+ bare = match[3]
78
+ alias_name = match[4]
79
+
80
+ # With an alias, the alias is the id and the name is the label. Without
81
+ # one, the name (quoted or bare) is the id and there is no separate label.
82
+ #
83
+ participant = if alias_name
84
+ AST::Participant.new(id: alias_name, label: quoted || bare)
85
+ else
86
+ AST::Participant.new(id: quoted || bare, label: nil)
87
+ end
88
+
89
+ current << participant
90
+ end
91
+
92
+ def push_message(match)
93
+ arrow = match[2].include?("--") ? :dashed : :solid
94
+ current << AST::Message.new(
95
+ from: match[1],
96
+ to: match[3],
97
+ text: match[4].to_s.strip,
98
+ arrow: arrow
99
+ )
100
+ end
101
+
102
+ def start_alt(label)
103
+ alt = AST::Alt.new
104
+ branch = AST::Branch.new(label: label.strip)
105
+ alt.branches << branch
106
+ current << alt
107
+ @open_alts ||= []
108
+ @open_alts << alt
109
+ @stack.push(branch.nodes)
110
+ end
111
+
112
+ def start_else(label)
113
+ # Replace the current branch's node list with a new else branch.
114
+ #
115
+ @stack.pop
116
+ alt = @open_alts.last
117
+ branch = AST::Branch.new(label: label.strip)
118
+ alt.branches << branch
119
+ @stack.push(branch.nodes)
120
+ end
121
+
122
+ def end_group
123
+ @stack.pop
124
+ @open_alts&.pop
125
+ end
126
+
127
+ def current
128
+ @stack.last
129
+ end
130
+ end
131
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Sargasso
4
+ VERSION = "0.0.1"
5
+ end
data/lib/sargasso.rb ADDED
@@ -0,0 +1,34 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "sargasso/version"
4
+ require_relative "sargasso/ast"
5
+ require_relative "sargasso/parser"
6
+ require_relative "sargasso/emitters/mermaid"
7
+
8
+ # Sargasso converts PlantUML diagram source into equivalent Mermaid source.
9
+ #
10
+ # v1 supports sequence diagrams only. The pipeline is:
11
+ # PlantUML source -> Sargasso::Parser -> Sargasso::AST -> Emitters::Mermaid
12
+ #
13
+ module Sargasso
14
+ class Error < StandardError; end
15
+
16
+ # Raised when strict mode encounters a construct sargasso cannot convert.
17
+ #
18
+ class UnsupportedConstructError < Error; end
19
+
20
+ module_function
21
+
22
+ # Convert PlantUML source into Mermaid source.
23
+ #
24
+ # strict: raise UnsupportedConstructError on any unsupported construct.
25
+ # warnings: an optional array that collected warnings are appended to.
26
+ #
27
+ def convert(plantuml_string, strict: false, warnings: nil)
28
+ diagram = Parser.new(plantuml_string).parse
29
+ emitter = Emitters::Mermaid.new(strict: strict)
30
+ output = emitter.emit(diagram)
31
+ warnings&.concat(emitter.warnings)
32
+ output
33
+ end
34
+ end
data/sig/sargasso.rbs ADDED
@@ -0,0 +1,4 @@
1
+ module Sargasso
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
metadata ADDED
@@ -0,0 +1,61 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: sargasso
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.1
5
+ platform: ruby
6
+ authors:
7
+ - Kerri Miller
8
+ bindir: exe
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies: []
12
+ description: Sargasso parses PlantUML source directly and emits Mermaid diagram source.
13
+ v1 supports sequence diagrams. Pure Ruby, no Node or JavaScript runtime dependency.
14
+ email:
15
+ - kerrizor@kerrizor.com
16
+ executables:
17
+ - sargasso
18
+ extensions: []
19
+ extra_rdoc_files: []
20
+ files:
21
+ - CHANGELOG.md
22
+ - CODE_OF_CONDUCT.md
23
+ - CONTRIBUTING.md
24
+ - LICENSE.txt
25
+ - README.md
26
+ - Rakefile
27
+ - exe/sargasso
28
+ - lib/sargasso.rb
29
+ - lib/sargasso/ast.rb
30
+ - lib/sargasso/cli.rb
31
+ - lib/sargasso/emitters/mermaid.rb
32
+ - lib/sargasso/parser.rb
33
+ - lib/sargasso/version.rb
34
+ - sig/sargasso.rbs
35
+ homepage: https://github.com/kerrizor/sargasso
36
+ licenses:
37
+ - MIT
38
+ metadata:
39
+ homepage_uri: https://github.com/kerrizor/sargasso
40
+ source_code_uri: https://github.com/kerrizor/sargasso/tree/main
41
+ changelog_uri: https://github.com/kerrizor/sargasso/blob/main/CHANGELOG.md
42
+ bug_tracker_uri: https://github.com/kerrizor/sargasso/issues
43
+ rubygems_mfa_required: 'true'
44
+ rdoc_options: []
45
+ require_paths:
46
+ - lib
47
+ required_ruby_version: !ruby/object:Gem::Requirement
48
+ requirements:
49
+ - - ">="
50
+ - !ruby/object:Gem::Version
51
+ version: 3.3.0
52
+ required_rubygems_version: !ruby/object:Gem::Requirement
53
+ requirements:
54
+ - - ">="
55
+ - !ruby/object:Gem::Version
56
+ version: '0'
57
+ requirements: []
58
+ rubygems_version: 4.0.10
59
+ specification_version: 4
60
+ summary: Convert PlantUML diagram source into equivalent Mermaid source.
61
+ test_files: []