auto-platform-guide 0.1.0 → 0.3.0

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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 5ccccab1be99709c35e9851337b7f95f722124a4f23368de67c76c7e6539f6c5
4
- data.tar.gz: cebdb9082d0502cd57550a0c567809bfee9beeb606faf7800b898dfa049da294
3
+ metadata.gz: 6a0f92f354b138123f8bb9195f00fe36761bb28a71076101409eb1202e85a7cd
4
+ data.tar.gz: 4e8933ef7687c1b6cbc1e26c8acd6f2cb0f105853b258a3140caf840e5aa8d82
5
5
  SHA512:
6
- metadata.gz: 797fdaf7358ada5c81bf394f57f38490e2734c1bb9d269676d3d0c51e9b0513f7f9d1db9386a409c453f41f80f2951ddae076936e092967b58fd8db702e350fd
7
- data.tar.gz: 6f6b428ebf18973783dc42b5ca427a41a8ab0b91bdffd9fad9ed972f8e617e13b7d784f5c499da9d2eacdc6dcdc8aaee0d380d672570aad39d0ec74a95c6e899
6
+ metadata.gz: 44d659d32d930bacc31e42b4c23732508d56e4680a63188ed733d7931165e883f3aaa7126e30e4e5ae38e79e72f6731bb7d73353c1040514a931f0f7b9204518
7
+ data.tar.gz: ffd5c19017221d77f4910d606338dd36313b9c51587632b3c68c6c66b1fc9c55b8d857dd2730e33da52d03cf06d9ecda9fde9af1181c68a7ac2f965f63de6829
data/CHANGELOG.md CHANGED
@@ -8,6 +8,52 @@ and this project adheres to
8
8
 
9
9
  ## [Unreleased]
10
10
 
11
+ ## [0.3.0] - 2026-11-12
12
+
13
+ ### Added
14
+
15
+ - `AutoPlatformGuide::TableOfContents`: reads the `toc.yml` the generator writes
16
+ next to each README (`toc.<locale>.yml` for translated runs) and returns the
17
+ guides around an id as `{ previous:, next: }`, so a host app can build
18
+ previous/next navigation without parsing the README or reading specs at runtime.
19
+
20
+ ### Changed
21
+
22
+ - `check` also reports a missing or outdated `toc.yml` next to the README.
23
+
24
+ ## [0.2.0] - 2026-10-29
25
+
26
+ ### Added
27
+
28
+ - `locales` configuration: translated guides from per-spec `<spec>.<locale>.yml`
29
+ files, a localized README, locale-specific screenshot directories (`DOC_LOCALE`),
30
+ and a `check` that notices missing, mismatched or outdated translations.
31
+ - `localized_readme` configuration and an optional `category:` in translation
32
+ files, so the translated README has translated texts, category names and
33
+ diagram.
34
+
35
+ ### Changed
36
+
37
+ - `Document#title` and breadcrumbs use the guide's first heading, falling back to
38
+ the file name, so `EVENTS.pt-BR.md` no longer shows as "Events.Pt Br".
39
+ - `generate` now fails when a screenshot spec run fails, and shows that run's
40
+ output, instead of silently ignoring the failure.
41
+
42
+ ### Added
43
+
44
+ - `app/assets/stylesheets/auto_platform_guide/docs.css`, a minimal stylesheet
45
+ for the docs pages, plus a styling guide covering the class contract and
46
+ theming.
47
+ - `rails generate auto_platform_guide:styles`, which copies that stylesheet into
48
+ the host app.
49
+ - Theme-aware `<picture>` images, so one image can follow the reader's colour
50
+ scheme.
51
+
52
+ ### Fixed
53
+
54
+ - A blockquote that followed a callout was rendered inside it, because Redcarpet
55
+ folds blank-line-separated quotes into one callback.
56
+
11
57
  ## [0.1.0] - 2026-10-26
12
58
 
13
59
  Initial release: spec-driven doc generator, `doc_screenshot` helper, configurable
@@ -40,5 +86,7 @@ browser driver wiring, and markdown docs viewer.
40
86
 
41
87
  - `bin/generate-docs`; use `auto_platform_guide:generate` instead.
42
88
 
43
- [Unreleased]: https://github.com/mauriciozaffari/auto-platform-guide/compare/v0.1.0...HEAD
89
+ [Unreleased]: https://github.com/mauriciozaffari/auto-platform-guide/compare/v0.3.0...HEAD
90
+ [0.3.0]: https://github.com/mauriciozaffari/auto-platform-guide/compare/v0.2.0...v0.3.0
91
+ [0.2.0]: https://github.com/mauriciozaffari/auto-platform-guide/compare/v0.1.0...v0.2.0
44
92
  [0.1.0]: https://github.com/mauriciozaffari/auto-platform-guide/releases/tag/v0.1.0
data/README.md CHANGED
@@ -2,12 +2,26 @@
2
2
 
3
3
  Generate in-app documentation from system specs.
4
4
 
5
+ <picture>
6
+ <source media="(prefers-color-scheme: dark)" srcset="docs/images/docs-dark.png">
7
+ <img alt="A rendered guide page with a title, breadcrumb, table, highlighted code, callouts, a diagram and a screenshot" src="docs/images/docs-light.png">
8
+ </picture>
9
+
5
10
  The gem documents itself: `docs/platform-guide/` is generated from
6
11
  `spec/docs/` by `rake auto_platform_guide:render` and checked in CI.
7
12
 
8
13
  - `AutoPlatformGuide::Generator` renders markdown guides from `# =` doc comments in
9
14
  system specs into `generated_docs_dir`, with an ordered README TOC grouped by
10
15
  `@category`/`@order` directives.
16
+ - `AutoPlatformGuide::TableOfContents` reads the `toc.yml` the generator writes next
17
+ to the README (`toc.<locale>.yml` for a translated run), so a host app can build
18
+ previous/next navigation from generated data, without parsing the README or
19
+ reading specs at runtime:
20
+
21
+ ```ruby
22
+ AutoPlatformGuide::TableOfContents.neighbours('EVENTS', locale: I18n.locale)
23
+ # => { previous: #<data Entry id="DELIVERIES", title="Deliveries">, next: #<data Entry ...> }
24
+ ```
11
25
  - `AutoPlatformGuide.setup_rspec(config)` wires system-spec screenshot support:
12
26
  `doc_screenshot('name')` captures to `screenshots_dir` when `SCREENSHOTS=true`,
13
27
  and specs run on `rack_test` unless they need a browser (`:js` tag or
@@ -32,7 +46,8 @@ The gem documents itself: `docs/platform-guide/` is generated from
32
46
  needs no host helpers, partials or assets. Links are built from `docs_path`, so
33
47
  set it to the path you mount (default `/docs`). Mermaid fenced blocks render
34
48
  when a global `mermaid` is present and stay readable as source otherwise.
35
- Override the template in the host app to change the surrounding chrome.
49
+ Override the template in the host app to change the surrounding chrome; see
50
+ [Styling](#styling) for the stylesheet and class contract.
36
51
 
37
52
  ## Installation
38
53
 
@@ -69,6 +84,49 @@ contents; `nil` keeps `AutoPlatformGuide::Generator::README_PREAMBLE`. Note:
69
84
  `:selenium` support is unit-tested with mocked drivers — no CI job boots a real
70
85
  browser under either driver.
71
86
 
87
+ ### Translated guides
88
+
89
+ The English `# =` comments in a spec stay the source. To add a language, list it
90
+ and put one translation file next to each documented spec:
91
+
92
+ ```ruby
93
+ config.locales = ['pt-BR']
94
+ ```
95
+
96
+ ```yaml
97
+ # spec/system/orders_spec.pt-BR.yml
98
+ source_digest: 1a2b3c4d5e6f # printed by the error when it is missing or outdated
99
+ sections: # same order and count as the `# =` / `# ==` headings
100
+ - title: Pedidos
101
+ body: |
102
+ Crie e acompanhe pedidos de clientes.
103
+ - title: Criar um pedido
104
+ body: Escolha um cliente, adicione itens e salve.
105
+ ```
106
+
107
+ Add `category: Pedidos` at the top level of the file to translate the spec's
108
+ `@category` in the README, and set the README's fixed texts per locale (anything
109
+ left out stays English):
110
+
111
+ ```ruby
112
+ config.localized_readme = {
113
+ 'pt-BR' => { 'preamble' => "<h1 id=\"guia\">Guia</h1>\n\nTexto...\n", 'contents' => 'Índice' }
114
+ }
115
+ ```
116
+
117
+ Guide titles and breadcrumbs come from the guide's first heading, so translated
118
+ guides show their translated title.
119
+
120
+ `rake auto_platform_guide:generate` writes `ORDERS.pt-BR.md` and `README.pt-BR.md`
121
+ beside the English files, and `auto_platform_guide:check` fails when a translation
122
+ is missing, has a different section count, or its `source_digest` no longer matches
123
+ the English comments (that is how a changed English paragraph is noticed).
124
+
125
+ Screenshots are captured once more per locale, with `DOC_LOCALE=<locale>` set and
126
+ `I18n.locale` switched by `setup_rspec`, and saved under `screenshots_dir/<locale>/`.
127
+ A host that does not use `setup_rspec` must switch its own locale from `DOC_LOCALE`.
128
+ Serving the right file for the visitor's locale is up to the host.
129
+
72
130
  ```ruby
73
131
  # spec/rails_helper.rb
74
132
  require 'auto_platform_guide/rspec'
@@ -78,6 +136,25 @@ RSpec.configure do |config|
78
136
  end
79
137
  ```
80
138
 
139
+ ## Styling
140
+
141
+ The gem ships plain markup and one optional stylesheet. Generate it into the
142
+ app and import it:
143
+
144
+ ```bash
145
+ bin/rails generate auto_platform_guide:styles
146
+ ```
147
+
148
+ ```css
149
+ @import "docs";
150
+ ```
151
+
152
+ Every rule is scoped to the classes the gem emits, so it will not leak. Colours,
153
+ fonts and radii are `--apg-*` custom properties on `:root`; dark mode follows
154
+ `prefers-color-scheme`. Code blocks stay dark in both schemes because Rouge
155
+ writes token colours inline. See [Styling](docs/platform-guide/STYLING.md) for
156
+ the class contract and how to change the code block theme.
157
+
81
158
  ## Writing a documented spec
82
159
 
83
160
  Doc comments are parsed from the files matched by `specs_glob`. A spec file is
@@ -0,0 +1,292 @@
1
+ /* Minimal docs styling for auto-platform-guide.
2
+ *
3
+ * The gem ships plain markup and no stylesheet, so nothing here is loaded
4
+ * automatically. Copy this file into the host app and import it, or replace it
5
+ * wholesale with your own design system.
6
+ *
7
+ * Every rule is scoped to the classes the gem emits, so it will not leak into
8
+ * the rest of the application. Only the `.content-header` block touches chrome
9
+ * the host app may already style; drop it if so.
10
+ */
11
+
12
+ :root {
13
+ --apg-font: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
14
+ --apg-font-mono: ui-monospace, SFMono-Regular, "SF Mono", Menlo, monospace;
15
+ --apg-fg: #1f2328;
16
+ --apg-muted: #656d76;
17
+ --apg-surface: #ffffff;
18
+ --apg-surface-muted: #f6f8fa;
19
+ --apg-border: #d0d7de;
20
+ --apg-accent: #0969da;
21
+ --apg-radius: 6px;
22
+ --apg-callout-note: #0969da;
23
+ --apg-callout-tip: #1a7f37;
24
+ --apg-callout-important: #8250df;
25
+ --apg-callout-warning: #9a6700;
26
+ --apg-callout-caution: #cf222e;
27
+ /* Rouge highlights inline with GitHub's dark token colours, so the block
28
+ behind them stays dark in both colour schemes. */
29
+ --apg-code-bg: #161b22;
30
+ --apg-code-fg: #c9d1d9;
31
+ }
32
+
33
+ @media (prefers-color-scheme: dark) {
34
+ :root {
35
+ --apg-fg: #e6edf3;
36
+ --apg-muted: #8b949e;
37
+ --apg-surface: #161b22;
38
+ --apg-surface-muted: #1f242c;
39
+ --apg-border: #30363d;
40
+ --apg-accent: #4493f8;
41
+ --apg-code-bg: #0d1117;
42
+ }
43
+ }
44
+
45
+ /* Page chrome: title and breadcrumb, outside `.documentation`.
46
+ * Both sit on the host page background rather than the gem's surface, so they
47
+ * inherit its text colour and never assume a colour scheme. */
48
+
49
+ .content-header h1 {
50
+ margin: 0 0 0.5rem;
51
+ font-family: var(--apg-font);
52
+ font-size: 1.5rem;
53
+ font-weight: 600;
54
+ line-height: 1.25;
55
+ }
56
+
57
+ .content-header .breadcrumb {
58
+ display: flex;
59
+ flex-wrap: wrap;
60
+ gap: 0.5rem;
61
+ margin: 0 0 1.5rem;
62
+ padding: 0;
63
+ font-family: var(--apg-font);
64
+ font-size: 0.875rem;
65
+ list-style: none;
66
+ opacity: 0.75;
67
+ }
68
+
69
+ .content-header .breadcrumb li + li::before {
70
+ margin-right: 0.5rem;
71
+ color: var(--apg-border);
72
+ content: "/";
73
+ }
74
+
75
+ .content-header .breadcrumb a {
76
+ color: var(--apg-accent);
77
+ text-decoration: none;
78
+ }
79
+
80
+ .content-header .breadcrumb a:hover {
81
+ text-decoration: underline;
82
+ }
83
+
84
+ /* Rendered markdown. */
85
+
86
+ .documentation {
87
+ font-family: var(--apg-font);
88
+ font-size: 1rem;
89
+ line-height: 1.6;
90
+ color: var(--apg-fg);
91
+ }
92
+
93
+ .documentation .box {
94
+ background: var(--apg-surface);
95
+ border: 1px solid var(--apg-border);
96
+ border-radius: var(--apg-radius);
97
+ }
98
+
99
+ .documentation .box-body {
100
+ padding: 1.5rem;
101
+ }
102
+
103
+ .documentation .box-body > :first-child {
104
+ margin-top: 0;
105
+ }
106
+
107
+ .documentation .box-body > :last-child {
108
+ margin-bottom: 0;
109
+ }
110
+
111
+ .documentation h1,
112
+ .documentation h2,
113
+ .documentation h3,
114
+ .documentation h4 {
115
+ margin: 2rem 0 0.75rem;
116
+ font-weight: 600;
117
+ line-height: 1.25;
118
+ }
119
+
120
+ .documentation h1 {
121
+ font-size: 1.5rem;
122
+ }
123
+
124
+ .documentation h2 {
125
+ padding-bottom: 0.3rem;
126
+ font-size: 1.25rem;
127
+ border-bottom: 1px solid var(--apg-border);
128
+ }
129
+
130
+ .documentation h3 {
131
+ font-size: 1.1rem;
132
+ }
133
+
134
+ .documentation h4 {
135
+ font-size: 1rem;
136
+ }
137
+
138
+ .documentation p,
139
+ .documentation ul,
140
+ .documentation ol {
141
+ margin: 0 0 1rem;
142
+ }
143
+
144
+ .documentation ul,
145
+ .documentation ol {
146
+ padding-left: 1.5rem;
147
+ }
148
+
149
+ .documentation li + li {
150
+ margin-top: 0.25rem;
151
+ }
152
+
153
+ .documentation a {
154
+ color: var(--apg-accent);
155
+ }
156
+
157
+ .documentation hr {
158
+ height: 1px;
159
+ margin: 2rem 0;
160
+ background: var(--apg-border);
161
+ border: 0;
162
+ }
163
+
164
+ /* Inline code only; fenced blocks are handled below. */
165
+
166
+ .documentation :not(pre) > code {
167
+ padding: 0.15em 0.35em;
168
+ font-family: var(--apg-font-mono);
169
+ font-size: 0.875em;
170
+ background: var(--apg-surface-muted);
171
+ border: 1px solid var(--apg-border);
172
+ border-radius: 4px;
173
+ }
174
+
175
+ .documentation pre.code-block {
176
+ margin: 0 0 1rem;
177
+ padding: 1rem;
178
+ overflow-x: auto;
179
+ font-family: var(--apg-font-mono);
180
+ font-size: 0.875rem;
181
+ line-height: 1.5;
182
+ color: var(--apg-code-fg);
183
+ background: var(--apg-code-bg);
184
+ border-radius: var(--apg-radius);
185
+ }
186
+
187
+ .documentation pre.code-block code {
188
+ padding: 0;
189
+ font: inherit;
190
+ color: inherit;
191
+ background: none;
192
+ border: 0;
193
+ }
194
+
195
+ /* Diagram source until mermaid.js replaces it, then the rendered SVG. */
196
+
197
+ .documentation pre.mermaid {
198
+ margin: 0 0 1rem;
199
+ padding: 1rem;
200
+ overflow-x: auto;
201
+ font-family: var(--apg-font-mono);
202
+ font-size: 0.875rem;
203
+ background: var(--apg-surface-muted);
204
+ border: 1px solid var(--apg-border);
205
+ border-radius: var(--apg-radius);
206
+ }
207
+
208
+ .documentation pre.mermaid[data-processed="true"] {
209
+ text-align: center;
210
+ background: none;
211
+ border: 0;
212
+ }
213
+
214
+ /* Plain blockquotes, then the five callouts the renderer emits. */
215
+
216
+ .documentation blockquote {
217
+ margin: 0 0 1rem;
218
+ padding: 0 1rem;
219
+ color: var(--apg-muted);
220
+ border-left: 3px solid var(--apg-border);
221
+ }
222
+
223
+ .documentation .callout {
224
+ padding: 0.75rem 1rem;
225
+ color: var(--apg-fg);
226
+ background: color-mix(in srgb, var(--apg-callout-color, var(--apg-border)) 8%, transparent);
227
+ border-left: 4px solid var(--apg-callout-color, var(--apg-border));
228
+ border-radius: 0 var(--apg-radius) var(--apg-radius) 0;
229
+ }
230
+
231
+ .documentation .callout > :last-child {
232
+ margin-bottom: 0;
233
+ }
234
+
235
+ .documentation .callout-title {
236
+ margin: 0 0 0.25rem;
237
+ font-weight: 600;
238
+ color: var(--apg-callout-color, var(--apg-fg));
239
+ }
240
+
241
+ /* The icon is Font Awesome; without it the element collapses harmlessly. */
242
+
243
+ .documentation .callout-title i {
244
+ margin-right: 0.25rem;
245
+ }
246
+
247
+ .documentation .callout-note {
248
+ --apg-callout-color: var(--apg-callout-note);
249
+ }
250
+
251
+ .documentation .callout-tip {
252
+ --apg-callout-color: var(--apg-callout-tip);
253
+ }
254
+
255
+ .documentation .callout-important {
256
+ --apg-callout-color: var(--apg-callout-important);
257
+ }
258
+
259
+ .documentation .callout-warning {
260
+ --apg-callout-color: var(--apg-callout-warning);
261
+ }
262
+
263
+ .documentation .callout-caution {
264
+ --apg-callout-color: var(--apg-callout-caution);
265
+ }
266
+
267
+ .documentation table {
268
+ width: 100%;
269
+ margin: 0 0 1rem;
270
+ font-size: 0.9375rem;
271
+ border-collapse: collapse;
272
+ }
273
+
274
+ .documentation th,
275
+ .documentation td {
276
+ padding: 0.5rem 0.75rem;
277
+ text-align: left;
278
+ vertical-align: top;
279
+ border: 1px solid var(--apg-border);
280
+ }
281
+
282
+ .documentation th {
283
+ font-weight: 600;
284
+ background: var(--apg-surface-muted);
285
+ }
286
+
287
+ .documentation .img-responsive {
288
+ max-width: 100%;
289
+ height: auto;
290
+ border: 1px solid var(--apg-border);
291
+ border-radius: var(--apg-radius);
292
+ }
@@ -17,6 +17,12 @@ module AutoPlatformGuide
17
17
  # Markdown written above the generated README table of contents. Defaults to
18
18
  # Generator::README_PREAMBLE when nil.
19
19
  attr_accessor :readme_preamble
20
+ # Extra locales to generate beside the English doc comments, e.g. ['pt-BR'].
21
+ # Each documented spec then needs a `<spec>.<locale>.yml` next to it.
22
+ attr_accessor :locales
23
+ # Fixed README texts per locale, e.g. { 'pt-BR' => { 'preamble' => '...', 'contents' => 'Índice' } }.
24
+ # Anything left out stays in English.
25
+ attr_accessor :localized_readme
20
26
  # URL prefix where the docs viewer is mounted. Links, breadcrumbs and
21
27
  # wikilinks are built from it, so it must match the host's route.
22
28
  attr_reader :docs_path
@@ -28,6 +34,8 @@ module AutoPlatformGuide
28
34
  @specs_glob = 'spec/system/**/*_spec.rb'
29
35
  @browser_driver = :playwright
30
36
  @readme_preamble = nil
37
+ @locales = []
38
+ @localized_readme = {}
31
39
  @docs_path = '/docs'
32
40
  end
33
41
 
@@ -18,6 +18,7 @@ module AutoPlatformGuide
18
18
  class RecordNotFound < StandardError; end
19
19
 
20
20
  FOLDER_INDEX_NAMES = ['README', '00 - Index'].freeze
21
+ H1 = %r{\A\s*<h1[^>]*>(.*?)</h1>}
21
22
 
22
23
  class Renderer < Redcarpet::Render::HTML
23
24
  include ActionView::Helpers::TagHelper
@@ -34,9 +35,11 @@ module AutoPlatformGuide
34
35
  'caution' => 'ban'
35
36
  }.freeze
36
37
 
37
- # Redcarpet merges adjacent blockquotes into one callback, so split the
38
- # quote at each callout marker and render them separately.
39
- CALLOUT_SPLIT = /(?=<p>\[!(?:NOTE|TIP|IMPORTANT|WARNING|CAUTION)\])/i
38
+ # Redcarpet folds blockquotes separated by a blank line into a single
39
+ # block_quote callback, so a plain quote after a callout lands inside it.
40
+ # A comment between adjacent quote groups forces the break; the final
41
+ # sanitize strips the comment.
42
+ QUOTE_SEPARATOR = '<!--apg:quote-separator-->'
40
43
 
41
44
  def self.render(path, base_dir: nil)
42
45
  new(base_dir:).render(path)
@@ -49,8 +52,9 @@ module AutoPlatformGuide
49
52
  end
50
53
 
51
54
  def sanitize(html)
52
- tags = ActionView::Base.sanitized_allowed_tags + %w[table thead tbody th tr td img i]
53
- attributes = ActionView::Base.sanitized_allowed_attributes + %w[style colspan src alt id class aria-hidden]
55
+ tags = ActionView::Base.sanitized_allowed_tags + %w[table thead tbody th tr td img i picture source]
56
+ attributes = ActionView::Base.sanitized_allowed_attributes +
57
+ %w[style colspan src alt id class aria-hidden media srcset sizes type]
54
58
  super(html, tags:, attributes:)
55
59
  end
56
60
 
@@ -68,10 +72,10 @@ module AutoPlatformGuide
68
72
  sanitize(markdown.render(File.read(path)))
69
73
  end
70
74
 
71
- # Convert Obsidian wikilinks to markdown links before parsing, leaving any
72
- # text inside fenced or inline code untouched.
75
+ # Normalise wikilinks and <picture> blocks before parsing, leaving fenced
76
+ # and inline code untouched.
73
77
  def preprocess(document)
74
- replace_wikilinks(document)
78
+ separate_blockquotes(replace_wikilinks(collapse_pictures(document)))
75
79
  end
76
80
 
77
81
  def block_code(code, language)
@@ -93,38 +97,86 @@ module AutoPlatformGuide
93
97
  end
94
98
 
95
99
  def block_quote(quote)
96
- quote.split(CALLOUT_SPLIT).reject(&:empty?).map { |segment| render_quote(segment) }.join("\n")
97
- end
98
-
99
- private
100
-
101
- def render_quote(segment)
102
- callout = segment.match(CALLOUT)
103
- return %(<blockquote>#{segment}</blockquote>) unless callout
100
+ callout = quote.match(CALLOUT)
101
+ return %(<blockquote>#{quote}</blockquote>) unless callout
104
102
 
105
103
  type = callout[1].downcase
106
- body = segment.sub(CALLOUT, '<p>')
104
+ body = quote.sub(CALLOUT, '<p>')
107
105
  icon = tag.i(class: "fa fa-#{CALLOUT_ICONS.fetch(type)}", aria: { hidden: true })
108
106
  title = %(<p class="callout-title">#{icon} #{type.titleize}</p>)
109
107
 
110
108
  %(<blockquote class="callout callout-#{type}">#{title}\n#{body}</blockquote>)
111
109
  end
112
110
 
113
- def replace_wikilinks(document)
111
+ private
112
+
113
+ # Insert a separator between adjacent quote groups so Redcarpet emits one
114
+ # block_quote callback per quote. Fenced code is left untouched.
115
+ def separate_blockquotes(document)
116
+ lines = document.lines
117
+ in_fence = false
118
+
119
+ lines.each_with_index.flat_map do |line, index|
120
+ in_fence = !in_fence if line.start_with?('```')
121
+ next [line] unless !in_fence && blank_line?(line) && quote_group?(lines, index)
122
+
123
+ [line, "#{QUOTE_SEPARATOR}\n"]
124
+ end.join
125
+ end
126
+
127
+ # A blank line sits between two quote groups when the nearest non-blank
128
+ # line on each side starts with `>`.
129
+ def quote_group?(lines, index)
130
+ quote_line?(nearest_line(lines[0...index].reverse)) &&
131
+ quote_line?(nearest_line(lines[(index + 1)..]))
132
+ end
133
+
134
+ def nearest_line(candidates)
135
+ candidates.find { |line| !blank_line?(line) }
136
+ end
137
+
138
+ def quote_line?(line)
139
+ line.to_s.lstrip.start_with?('>')
140
+ end
141
+
142
+ def blank_line?(line)
143
+ line.strip.empty?
144
+ end
145
+
146
+ # Redcarpet predates <picture> and treats it as inline HTML, so hard_wrap
147
+ # would turn the block's newlines into <br>. Collapse it onto one line.
148
+ def collapse_pictures(document)
149
+ outside_fences(document) { |text| collapse_picture_blocks(text) }
150
+ end
151
+
152
+ def collapse_picture_blocks(text)
153
+ text.gsub(%r{<picture\b.*?</picture>}mi) { |block| block.split(/\s*\n\s*/).join(' ') }
154
+ end
155
+
156
+ # Yields each stretch of the document that sits outside fenced code.
157
+ def outside_fences(document)
114
158
  in_fence = false
115
159
 
116
- document.each_line.map do |line|
117
- if line.start_with?('```')
160
+ document.split(/^([ \t]*```.*)$/).map do |segment|
161
+ if segment.match?(/\A[ \t]*```/)
118
162
  in_fence = !in_fence
119
- line
163
+ segment
120
164
  elsif in_fence
121
- line
165
+ segment
122
166
  else
123
- replace_wikilinks_in_line(line)
167
+ yield(segment)
124
168
  end
125
169
  end.join
126
170
  end
127
171
 
172
+ def replace_wikilinks(document)
173
+ outside_fences(document) { |text| replace_wikilinks_in_text(text) }
174
+ end
175
+
176
+ def replace_wikilinks_in_text(text)
177
+ text.each_line.map { |line| replace_wikilinks_in_line(line) }.join
178
+ end
179
+
128
180
  def replace_wikilinks_in_line(line)
129
181
  line.split(/(`[^`]*`)/).map do |part|
130
182
  if part.start_with?('`')
@@ -204,15 +256,17 @@ module AutoPlatformGuide
204
256
  Renderer.render(path, base_dir: dir == '.' ? nil : dir)
205
257
  end
206
258
 
259
+ # The guide's first heading (already translated in localized guides), else the file name.
207
260
  def title
208
- name.titleize
261
+ heading = File.file?(path) ? File.foreach(path, encoding: 'UTF-8').filter_map { |line| line[H1, 1] }.first : nil
262
+ heading.presence || name.titleize
209
263
  end
210
264
 
211
265
  def breadcrumbs
212
266
  parts = id.split('/')
213
267
 
214
268
  parts.each_with_index.map do |part, i|
215
- { name: part.titleize, path: "#{self.class.docs_path}/#{parts[0..i].join('/')}" }
269
+ { name: i == parts.size - 1 ? title : part.titleize, path: "#{self.class.docs_path}/#{parts[0..i].join('/')}" }
216
270
  end
217
271
  end
218
272
  end
@@ -10,6 +10,9 @@ module AutoPlatformGuide
10
10
 
11
11
  rake_tasks do
12
12
  require 'auto_platform_guide/rake_tasks'
13
+ %w[generate check readme render].each do |name|
14
+ Rake::Task["auto_platform_guide:#{name}"].enhance(['environment'])
15
+ end
13
16
  end
14
17
  end
15
18
  end
@@ -1,7 +1,9 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require 'fileutils'
4
+ require 'stringio'
4
5
  require 'pathname'
6
+ require 'yaml'
5
7
 
6
8
  module AutoPlatformGuide
7
9
  # Generates markdown guides from system specs with doc comments, plus the
@@ -9,6 +11,9 @@ module AutoPlatformGuide
9
11
  # files; `doc_screenshot('name')` calls reference PNGs captured during a
10
12
  # SCREENSHOTS=true run.
11
13
  class Generator
14
+ include LocalizedGeneration
15
+ include ReadmeGeneration
16
+
12
17
  # Fallbacks for specs that omit the directives below. Specs with no
13
18
  # `@category` collect under DEFAULT_CATEGORY; specs with no `@order` sort
14
19
  # after numbered ones. Both defaults push such docs to the end of the TOC.
@@ -34,7 +39,14 @@ module AutoPlatformGuide
34
39
  spec_files = argv - FLAGS
35
40
  generator = new(spec_files.empty? ? nil : spec_files)
36
41
 
37
- case FLAGS.find { |flag| argv.include?(flag) }
42
+ run_mode(generator, FLAGS.find { |flag| argv.include?(flag) })
43
+ rescue ArgumentError => e
44
+ warn "✗ #{e.message}"
45
+ 1
46
+ end
47
+
48
+ def self.run_mode(generator, flag)
49
+ case flag
38
50
  when '--check'
39
51
  # Verify docs without running specs; used by CI.
40
52
  generator.up_to_date? ? 0 : 1
@@ -66,12 +78,14 @@ module AutoPlatformGuide
66
78
  return
67
79
  end
68
80
 
81
+ validate_translations
69
82
  @spec_files.each do |spec_file|
70
83
  puts "\nGenerating documentation for #{spec_file}..."
71
84
  process_spec(spec_file, run_specs:)
72
85
  end
73
86
 
74
87
  generate_readme
88
+ config.locales.each { |locale| generate_translation(locale) }
75
89
 
76
90
  puts "\n✓ Documentation generation complete!"
77
91
  puts " Generated #{@spec_files.size} documentation file(s) in #{config.generated_docs_dir}/"
@@ -83,30 +97,39 @@ module AutoPlatformGuide
83
97
  # the committed markdown, ignoring the generation timestamp and the
84
98
  # screenshot binaries themselves. Returns true when everything is up to date.
85
99
  def up_to_date?
86
- stale = find_documented_specs.select { |spec_file| doc_stale?(spec_file) }
87
-
88
- if stale.empty?
100
+ stale = find_documented_specs.select { |spec_file| doc_stale?(spec_file) || translations_stale?(spec_file) }
101
+ readme_stale = stale.empty? && (readmes_stale? || tocs_stale?)
102
+ unless stale.any? || readme_stale
89
103
  puts '✓ Platform-guide docs are up to date.'
90
104
  return true
91
105
  end
92
106
 
93
- warn "✗ Platform-guide docs are out of date for #{stale.size} spec(s):"
94
- stale.each { |spec_file| warn " - #{spec_file} -> #{generate_output_filename(spec_file)}" }
95
- warn ''
96
- warn 'Regenerate the affected guide(s) and commit the result:'
97
- stale.each { |spec_file| warn %( rake "auto_platform_guide:generate[#{spec_file}]") }
107
+ warn '✗ Generated README or toc is out of date; run rake auto_platform_guide:readme' if readme_stale
108
+ report_stale(stale)
98
109
  false
99
110
  end
100
111
 
101
112
  # Rebuild only the README table of contents from the committed docs and
102
113
  # their spec `@category`/`@order` directives, without running any specs.
103
114
  def regenerate_readme
115
+ validate_translations
104
116
  generate_readme
117
+ config.locales.each { |locale| write_readme(locale) }
105
118
  puts '✓ Regenerated README.md table of contents.'
106
119
  end
107
120
 
108
121
  private
109
122
 
123
+ def report_stale(stale)
124
+ return if stale.empty?
125
+
126
+ warn "✗ Platform-guide docs are out of date for #{stale.size} spec(s):"
127
+ stale.each { |spec_file| warn " - #{spec_file} -> #{generate_output_filename(spec_file)}" }
128
+ warn ''
129
+ warn 'Regenerate the affected guide(s) and commit the result:'
130
+ stale.each { |spec_file| warn %( rake "auto_platform_guide:generate[#{spec_file}]") }
131
+ end
132
+
110
133
  def doc_stale?(spec_file)
111
134
  output_file = generate_output_filename(spec_file)
112
135
  return true unless File.exist?(output_file)
@@ -150,8 +173,18 @@ module AutoPlatformGuide
150
173
  def run_spec_with_screenshots(spec_file)
151
174
  FileUtils.mkdir_p(config.screenshots_dir)
152
175
 
153
- command = "SCREENSHOTS=true bundle exec rspec --format documentation #{spec_file}"
154
- system(command, err: File::NULL)
176
+ # Only the examples that take screenshots run in the browser; the rest of
177
+ # the file would otherwise be forced through it too (SCREENSHOTS=true).
178
+ lines = spec(spec_file).screenshot_calls.pluck(:line_number).uniq
179
+ return if lines.empty?
180
+
181
+ command = ['bundle', 'exec', 'rspec', '--format', 'documentation', *lines.map { |line| "#{spec_file}:#{line}" }]
182
+ raise "Screenshot capture failed: #{spec_file}" unless system({ 'SCREENSHOTS' => 'true' }, *command)
183
+
184
+ config.locales.each do |locale|
185
+ env = { 'SCREENSHOTS' => 'true', 'DOC_LOCALE' => locale.to_s }
186
+ raise "Screenshot capture failed: #{spec_file} (#{locale})" unless system(env, *command)
187
+ end
155
188
  end
156
189
 
157
190
  def generate_output_filename(spec_file)
@@ -176,7 +209,7 @@ module AutoPlatformGuide
176
209
  # Render the markdown body (everything after the timestamp header) from a
177
210
  # spec's doc comments and screenshot calls. Shared by generation and --check
178
211
  # so both produce byte-identical output for the same spec.
179
- def render_doc_body(doc_comments, screenshot_calls)
212
+ def render_doc_body(doc_comments, screenshot_calls, locale: nil)
180
213
  body = +''
181
214
 
182
215
  doc_comments.each_with_index do |comment, index|
@@ -190,7 +223,7 @@ module AutoPlatformGuide
190
223
  next_comment_line = doc_comments[index + 1]&.dig(:line_number) || Float::INFINITY
191
224
  screenshots = find_related_screenshots(comment[:line_number], next_comment_line, screenshot_calls)
192
225
  screenshots.each do |screenshot|
193
- rendered = render_screenshot(screenshot[:path])
226
+ rendered = render_screenshot(screenshot[:path], locale:)
194
227
  body << rendered if rendered
195
228
  end
196
229
  end
@@ -205,12 +238,11 @@ module AutoPlatformGuide
205
238
  end
206
239
  end
207
240
 
208
- def render_screenshot(screenshot_path)
209
- # Only embed screenshots whose generated file exists on disk. Image URLs
210
- # mirror screenshots_dir so a customized dir keeps working links.
211
- return unless File.exist?(File.join(config.screenshots_dir, "#{screenshot_path}.png"))
241
+ def render_screenshot(screenshot_path, locale: nil)
242
+ directory = [config.screenshots_dir, locale].compact.join('/')
243
+ return unless File.exist?(File.join(directory, "#{screenshot_path}.png"))
212
244
 
213
- prefix = "/#{config.screenshots_dir.sub(%r{\A/+}, '').sub(%r{/+\z}, '')}"
245
+ prefix = "/#{directory.sub(%r{\A/+}, '').sub(%r{/+\z}, '')}"
214
246
  "![#{screenshot_path}](#{prefix}/#{screenshot_path}.png)\n\n"
215
247
  end
216
248
 
@@ -220,81 +252,5 @@ module AutoPlatformGuide
220
252
  .gsub(/\s+/, '-').squeeze('-')
221
253
  .gsub(/^-|-$/, '')
222
254
  end
223
-
224
- # Writes the README table of contents grouped by `@category` and ordered by
225
- # `@order`. Called at the end of a full/partial generation run and standalone
226
- # via `regenerate_readme` (the `--readme-only` mode).
227
- def generate_readme
228
- readme_path = File.join(config.generated_docs_dir, 'README.md')
229
-
230
- File.open(readme_path, 'w') do |f|
231
- f.puts '<!--'
232
- f.puts "Generated: #{generated_at}"
233
- f.puts '-->'
234
- f.puts
235
-
236
- f.write(config.readme_preamble || README_PREAMBLE)
237
-
238
- # Build the TOC from every documented spec (not just the ones regenerated
239
- # in this run) so running for a subset of specs doesn't drop other
240
- # entries. Group by `@category` and order by `@order`.
241
- groups = toc_groups
242
-
243
- f.puts category_workflow_diagram(groups.map(&:first))
244
- f.puts
245
- f.puts '<h2 id="table-of-contents">Table of Contents</h2>'
246
-
247
- groups.each do |category, entries|
248
- f.puts
249
- f.puts %(<h3 id="#{slugify(category)}">#{category}</h3>)
250
- f.puts
251
- entries.each do |entry|
252
- f.puts "- [#{entry[:title]}](#{entry[:file]})"
253
- end
254
- end
255
- end
256
- end
257
-
258
- # A Mermaid flowchart of the guide categories in workflow order, rendered by
259
- # the in-app docs viewer. Derived from the same ordered categories as the TOC,
260
- # so it never drifts from the actual guides.
261
- def category_workflow_diagram(categories)
262
- return '' if categories.empty?
263
-
264
- nodes = categories.each_with_index.map { |category, index| %(c#{index}["#{category}"]) }
265
- <<~DIAGRAM.chomp
266
-
267
- ```mermaid
268
- flowchart LR
269
- #{nodes.join(' --> ')}
270
- ```
271
- DIAGRAM
272
- end
273
-
274
- # Returns the TOC as an ordered list of [category, entries] pairs.
275
- # Category order is derived entirely from the specs: categories are
276
- # listed in ascending order of the smallest `@order` they contain (ties broken
277
- # alphabetically), and entries within a category are ordered by `@order` then
278
- # title. Only specs whose generated doc actually exists on disk are linked.
279
- def toc_groups
280
- entries = find_documented_specs.filter_map do |spec_file|
281
- file = File.basename(generate_output_filename(spec_file))
282
- next unless File.exist?(File.join(config.generated_docs_dir, file))
283
-
284
- parsed = spec(spec_file)
285
- directives = parsed.directives
286
- {
287
- file:,
288
- title: parsed.title,
289
- category: directives[:category] || DEFAULT_CATEGORY,
290
- order: directives[:order] || DEFAULT_ORDER
291
- }
292
- end
293
-
294
- entries
295
- .group_by { |entry| entry[:category] }
296
- .sort_by { |category, group| [group.map { |entry| entry[:order] }.min, category] }
297
- .map { |category, group| [category, group.sort_by { |entry| [entry[:order], entry[:title]] }] }
298
- end
299
255
  end
300
256
  end
@@ -0,0 +1,78 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AutoPlatformGuide
4
+ # Localized counterparts for generated guides: `<spec>.<locale>.yml` holds the
5
+ # translated sections and `SOME-GUIDE.<locale>.md` is what gets generated.
6
+ module LocalizedGeneration
7
+ private
8
+
9
+ def translations_stale?(spec_file)
10
+ config.locales.any? { |locale| translation_stale?(spec_file, locale) }
11
+ end
12
+
13
+ def translation_stale?(spec_file, locale)
14
+ path = translated_filename(spec_file, locale)
15
+ return true unless File.file?(path)
16
+
17
+ parsed = spec(spec_file)
18
+ expected = "#{render_doc_body(parsed.translated_comments(locale), parsed.screenshot_calls, locale:).rstrip}\n"
19
+ strip_timestamp_header(File.read(path, encoding: 'UTF-8')) != expected
20
+ rescue ArgumentError
21
+ true
22
+ end
23
+
24
+ def readmes_stale?
25
+ config.locales.any? { |locale| readme_stale?(locale) }
26
+ end
27
+
28
+ # The generated toc files drive host-app navigation, so a stale or missing
29
+ # one is as stale as the docs themselves.
30
+ def tocs_stale?
31
+ ([nil] + config.locales).any? { |locale| table_of_contents(locale).stale? }
32
+ end
33
+
34
+ def readme_stale?(locale)
35
+ committed = strip_timestamp_header(File.read(readme_path(locale), encoding: 'UTF-8'))
36
+ committed != readme_body(locale)
37
+ rescue Errno::ENOENT
38
+ true
39
+ end
40
+
41
+ # Fail before writing anything when a translation is missing or outdated.
42
+ def validate_translations
43
+ find_documented_specs.product(config.locales).each do |spec_file, locale|
44
+ spec(spec_file).translated_comments(locale)
45
+ end
46
+ end
47
+
48
+ def translated_filename(spec_file, locale)
49
+ generate_output_filename(spec_file).sub(/\.md\z/, ".#{locale}.md")
50
+ end
51
+
52
+ def generate_translation(locale)
53
+ @spec_files.each do |file|
54
+ parsed = spec(file)
55
+ body = render_doc_body(parsed.translated_comments(locale), parsed.screenshot_calls, locale:)
56
+ File.write(translated_filename(file, locale), "#{timestamp_header}#{body.rstrip}\n")
57
+ end
58
+ write_readme(locale)
59
+ end
60
+
61
+ def toc_entry(spec_file, file, locale)
62
+ parsed = spec(spec_file)
63
+ directives = parsed.directives
64
+ {
65
+ id: file.delete_suffix('.md'),
66
+ title: locale ? parsed.translated_comments(locale).first.fetch(:title) : parsed.title,
67
+ category: directives[:category] || Generator::DEFAULT_CATEGORY,
68
+ translated_category: locale ? parsed.translated_category(locale) : nil,
69
+ order: directives[:order] || Generator::DEFAULT_ORDER
70
+ }
71
+ end
72
+
73
+ # Group name: the first translated `category:` of its guides, else the English one.
74
+ def localized_category(group, category)
75
+ group.filter_map { |entry| entry[:translated_category] }.first || category
76
+ end
77
+ end
78
+ end
@@ -0,0 +1,101 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AutoPlatformGuide
4
+ # Writes the README table of contents and the machine-readable toc files the
5
+ # docs viewer navigation reads, for the English run and every locale.
6
+ module ReadmeGeneration
7
+ private
8
+
9
+ # Writes the README table of contents grouped by `@category` and ordered by
10
+ # `@order`. Called at the end of a full/partial generation run and standalone
11
+ # via `regenerate_readme` (the `--readme-only` mode).
12
+ def generate_readme
13
+ write_readme(nil)
14
+ end
15
+
16
+ # The ordered guides of a locale. The README sections and the generated
17
+ # `toc.yml` are both rendered from it, so navigation cannot drift from the
18
+ # index, and host apps read the toc instead of parsing the README.
19
+ def table_of_contents(locale = nil)
20
+ entries = toc_groups(locale).flat_map { |category, group| guides(category, group) }
21
+ TableOfContents.new(entries, locale:)
22
+ end
23
+
24
+ def write_readme(locale)
25
+ table_of_contents(locale).write
26
+ File.write(readme_path(locale), "#{timestamp_header}#{readme_body(locale)}")
27
+ end
28
+
29
+ def readme_path(locale)
30
+ File.join(config.generated_docs_dir, locale ? "README.#{locale}.md" : 'README.md')
31
+ end
32
+
33
+ def guides(category, entries)
34
+ entries.map { |entry| TableOfContents::Entry.new(id: entry[:id], title: entry[:title], category:) }
35
+ end
36
+
37
+ # The README markdown after the timestamp header. With a locale it uses the
38
+ # translated titles and category names, and `localized_readme[locale]`
39
+ # (`'preamble'`, `'contents'`) for the fixed texts, falling back to English.
40
+ def readme_body(locale = nil)
41
+ texts = config.localized_readme.fetch(locale.to_s, {})
42
+ out = StringIO.new
43
+
44
+ out.write(texts['preamble'] || config.readme_preamble || Generator::README_PREAMBLE)
45
+
46
+ # Build the TOC from every documented spec (not just the ones regenerated
47
+ # in this run) so running for a subset of specs doesn't drop other
48
+ # entries. Group by `@category` and order by `@order`.
49
+ groups = table_of_contents(locale).groups
50
+
51
+ out.puts category_workflow_diagram(groups.keys)
52
+ out.puts
53
+ out.puts %(<h2 id="table-of-contents">#{texts['contents'] || 'Table of Contents'}</h2>)
54
+
55
+ groups.each { |category, entries| out.write(toc_section(category, entries, locale)) }
56
+
57
+ out.string
58
+ end
59
+
60
+ def toc_section(category, entries, locale)
61
+ suffix = locale ? ".#{locale}.md" : '.md'
62
+ links = entries.map { |entry| "- [#{entry.title}](#{entry.id}#{suffix})\n" }.join
63
+ %(\n<h3 id="#{slugify(category)}">#{category}</h3>\n\n#{links})
64
+ end
65
+
66
+ # A Mermaid flowchart of the guide categories in workflow order, rendered by
67
+ # the in-app docs viewer. Derived from the same ordered categories as the TOC,
68
+ # so it never drifts from the actual guides.
69
+ def category_workflow_diagram(categories)
70
+ return '' if categories.empty?
71
+
72
+ nodes = categories.each_with_index.map { |category, index| %(c#{index}["#{category}"]) }
73
+ <<~DIAGRAM.chomp
74
+
75
+ ```mermaid
76
+ flowchart LR
77
+ #{nodes.join(' --> ')}
78
+ ```
79
+ DIAGRAM
80
+ end
81
+
82
+ # Returns the TOC as an ordered list of [category, entries] pairs.
83
+ # Category order is derived entirely from the specs: categories are
84
+ # listed in ascending order of the smallest `@order` they contain (ties broken
85
+ # alphabetically), and entries within a category are ordered by `@order` then
86
+ # title. Only specs whose generated doc actually exists on disk are linked.
87
+ def toc_groups(locale = nil)
88
+ entries = find_documented_specs.filter_map do |spec_file|
89
+ file = File.basename(generate_output_filename(spec_file))
90
+ next unless File.exist?(File.join(config.generated_docs_dir, file))
91
+
92
+ toc_entry(spec_file, file, locale)
93
+ end
94
+
95
+ entries.sort_by { |entry| [entry[:order], entry[:title]] }
96
+ .group_by { |entry| entry[:category] }
97
+ .sort_by { |category, group| [group.first[:order], category] }
98
+ .map { |category, group| [localized_category(group, category), group] }
99
+ end
100
+ end
101
+ end
@@ -20,7 +20,9 @@ module AutoPlatformGuide
20
20
  return unless AutoPlatformGuide.screenshots_enabled?
21
21
 
22
22
  sleep 0.5 # Allow time for animations to complete
23
- save_screenshot(Rails.root.join(AutoPlatformGuide.configuration.screenshots_dir, "#{filename}.png")) # rubocop:disable Lint/Debugger
23
+ directory = AutoPlatformGuide.configuration.screenshots_dir
24
+ directory = File.join(directory, ENV['DOC_LOCALE']) if ENV['DOC_LOCALE'].present?
25
+ save_screenshot(Rails.root.join(directory, "#{filename}.png")) # rubocop:disable Lint/Debugger
24
26
  end
25
27
  end
26
28
 
@@ -53,8 +55,14 @@ module AutoPlatformGuide
53
55
  end
54
56
  end
55
57
 
58
+ def self.apply_doc_locale
59
+ locale = ENV.fetch('DOC_LOCALE', nil)
60
+ I18n.locale = locale if locale.present?
61
+ end
62
+
56
63
  def self.prepare_system_example(example, max_wait_time, screen_size, browser_options)
57
64
  Capybara.default_max_wait_time = max_wait_time
65
+ apply_doc_locale
58
66
 
59
67
  if screenshots_enabled?
60
68
  drive_with_browser(example, screen_size:, options: browser_options)
@@ -1,5 +1,8 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require 'digest'
4
+ require 'yaml'
5
+
3
6
  module AutoPlatformGuide
4
7
  # A system spec file carrying `# = Heading` doc comments and
5
8
  # `doc_screenshot('name')` calls. Parses it once and exposes what the
@@ -35,6 +38,26 @@ module AutoPlatformGuide
35
38
  @doc_comments ||= parse_doc_comments
36
39
  end
37
40
 
41
+ # Short fingerprint of the English doc comments. A translation file records it
42
+ # as `source_digest`, so editing the English text flags the translation stale.
43
+ def source_digest
44
+ Digest::SHA256.hexdigest(doc_comments.map { |c| [c[:title], *c[:content]].join("\n") }.join("\n\n"))[0, 12]
45
+ end
46
+
47
+ # Translate each section while retaining its source line for screenshot placement.
48
+ def translated_comments(locale)
49
+ sections = translation(locale)['sections']
50
+
51
+ doc_comments.zip(sections).map do |source, translated|
52
+ source.merge(title: translated.fetch('title'), content: translated.fetch('body').lines.map(&:chomp))
53
+ end
54
+ end
55
+
56
+ # The optional `category:` of a translation file, shown instead of `@category`.
57
+ def translated_category(locale)
58
+ translation(locale)['category']
59
+ end
60
+
38
61
  # `{ path:, line_number: }` for every `doc_screenshot('...')` call.
39
62
  def screenshot_calls
40
63
  @screenshot_calls ||= parse_screenshot_calls
@@ -58,6 +81,31 @@ module AutoPlatformGuide
58
81
  @lines ||= File.readlines(@path, encoding: 'UTF-8')
59
82
  end
60
83
 
84
+ # The parsed and validated `<spec>.<locale>.yml`.
85
+ def translation(locale)
86
+ path = @path.sub(/\.rb\z/, ".#{locale}.yml")
87
+ raise ArgumentError, "Missing translation file #{path}" unless File.file?(path)
88
+
89
+ data = YAML.safe_load_file(path)
90
+ sections = data.is_a?(Hash) ? data['sections'] : nil
91
+ raise ArgumentError, "#{path} needs a `sections` list" unless sections.is_a?(Array)
92
+ unless sections.size == doc_comments.size
93
+ raise ArgumentError,
94
+ "#{path} has #{sections.size} sections, #{@path} has #{doc_comments.size}"
95
+ end
96
+ unless data['source_digest'] == source_digest
97
+ raise ArgumentError,
98
+ "#{path} is out of date: set `source_digest: #{source_digest}` after updating it"
99
+ end
100
+ unless sections.all? do |section|
101
+ section.is_a?(Hash) && section['title'].is_a?(String) && section['body'].is_a?(String)
102
+ end
103
+ raise ArgumentError, "#{path} sections need a title and body"
104
+ end
105
+
106
+ data
107
+ end
108
+
61
109
  def first_match(pattern)
62
110
  lines.filter_map { |line| line.match(pattern)&.[](1) }.first
63
111
  end
@@ -0,0 +1,81 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'yaml'
4
+
5
+ module AutoPlatformGuide
6
+ # The ordered guides of one locale. The generator builds one from the spec
7
+ # directives and writes it as `toc.yml`; a host app loads the committed file to
8
+ # navigate between guides, and the README sections are rendered from `#groups`.
9
+ class TableOfContents
10
+ # One guide in the table of contents.
11
+ class Entry
12
+ attr_reader :id, :title, :category
13
+
14
+ def initialize(id:, title:, category:)
15
+ @id = id
16
+ @title = title
17
+ @category = category
18
+ end
19
+
20
+ def to_h
21
+ { 'id' => id, 'title' => title, 'category' => category }
22
+ end
23
+ end
24
+
25
+ # Reads the committed toc for a locale, falling back to English when the
26
+ # locale has none.
27
+ def self.load(locale: nil)
28
+ path = path_for(locale)
29
+ path = path_for(nil) unless File.exist?(path)
30
+ entries = YAML.load_file(path).map do |entry|
31
+ Entry.new(id: entry['id'], title: entry['title'], category: entry['category'])
32
+ end
33
+ new(entries, locale:)
34
+ end
35
+
36
+ # Where a locale's toc is written.
37
+ def self.path_for(locale)
38
+ File.join(AutoPlatformGuide.configuration.generated_docs_dir, locale ? "toc.#{locale}.yml" : 'toc.yml')
39
+ end
40
+
41
+ def initialize(entries, locale: nil)
42
+ @entries = entries
43
+ @locale = locale
44
+ end
45
+
46
+ attr_reader :entries, :locale
47
+
48
+ # Guides by category, in the order the categories first appear.
49
+ def groups
50
+ entries.group_by(&:category)
51
+ end
52
+
53
+ # The guides either side of `id`, e.g. `{ previous: Entry, next: Entry }`.
54
+ # Omits a side that has no neighbour and returns `{}` for an unknown guide.
55
+ def neighbours(id)
56
+ sequence[id] || {}
57
+ end
58
+
59
+ def write
60
+ File.write(self.class.path_for(locale), to_yaml)
61
+ end
62
+
63
+ def stale?
64
+ File.read(self.class.path_for(locale), encoding: 'UTF-8') != to_yaml
65
+ rescue Errno::ENOENT
66
+ true
67
+ end
68
+
69
+ def to_yaml
70
+ entries.map(&:to_h).to_yaml
71
+ end
72
+
73
+ private
74
+
75
+ def sequence
76
+ @sequence ||= [nil, *entries, nil].each_cons(3).to_h do |previous, entry, following|
77
+ [entry.id, { previous:, next: following }.compact]
78
+ end
79
+ end
80
+ end
81
+ end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module AutoPlatformGuide
4
- VERSION = '0.1.0'
4
+ VERSION = '0.3.0'
5
5
  end
@@ -4,7 +4,10 @@ require 'auto_platform_guide/version'
4
4
  require 'auto_platform_guide/configuration'
5
5
  require 'auto_platform_guide/spec_file'
6
6
  require 'auto_platform_guide/document'
7
+ require 'auto_platform_guide/localized_generation'
8
+ require 'auto_platform_guide/readme_generation'
7
9
  require 'auto_platform_guide/generator'
10
+ require 'auto_platform_guide/table_of_contents'
8
11
  require 'auto_platform_guide/docs_controller_actions'
9
12
 
10
13
  module AutoPlatformGuide
@@ -0,0 +1,19 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'rails/generators'
4
+
5
+ module AutoPlatformGuide
6
+ module Generators
7
+ # Copies the minimal docs stylesheet into the host app.
8
+ class StylesGenerator < Rails::Generators::Base
9
+ source_root File.expand_path('../../../..', __dir__)
10
+
11
+ desc 'Copy the auto-platform-guide stylesheet into app/assets/stylesheets.'
12
+
13
+ def copy_stylesheet
14
+ copy_file 'app/assets/stylesheets/auto_platform_guide/docs.css',
15
+ 'app/assets/stylesheets/docs.css'
16
+ end
17
+ end
18
+ end
19
+ end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: auto-platform-guide
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.0
4
+ version: 0.3.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Mauricio Zaffari
@@ -119,6 +119,7 @@ files:
119
119
  - CHANGELOG.md
120
120
  - LICENSE.txt
121
121
  - README.md
122
+ - app/assets/stylesheets/auto_platform_guide/docs.css
122
123
  - app/views/docs/show.html.erb
123
124
  - lib/auto-platform-guide.rb
124
125
  - lib/auto_platform_guide.rb
@@ -127,10 +128,14 @@ files:
127
128
  - lib/auto_platform_guide/document.rb
128
129
  - lib/auto_platform_guide/engine.rb
129
130
  - lib/auto_platform_guide/generator.rb
131
+ - lib/auto_platform_guide/localized_generation.rb
130
132
  - lib/auto_platform_guide/rake_tasks.rb
133
+ - lib/auto_platform_guide/readme_generation.rb
131
134
  - lib/auto_platform_guide/rspec.rb
132
135
  - lib/auto_platform_guide/spec_file.rb
136
+ - lib/auto_platform_guide/table_of_contents.rb
133
137
  - lib/auto_platform_guide/version.rb
138
+ - lib/generators/auto_platform_guide/styles/styles_generator.rb
134
139
  homepage: https://github.com/mauriciozaffari/auto-platform-guide
135
140
  licenses:
136
141
  - MIT