yard-md 0.1.0 → 1.0.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: f4f3e9d517be738972f09d0b90a31ab26b84f8eed6c8736b5abc05a795003368
4
- data.tar.gz: f2f8856420c1dcc9751d2cb16bbc35b80a6c4f5a58ea95e6bff2aa495b41e718
3
+ metadata.gz: 7c22ac4f517b7e0c411f2028ee67a707b13a6bee87e9c5295234a034c738a2b1
4
+ data.tar.gz: b16a80c1a02dd3fc586b84a513c582f09d5e2679373bc486e8831337bc5afdd5
5
5
  SHA512:
6
- metadata.gz: 767f5c0be2a8f990ea5d55ca777d359eaed7b4f7566c1651aaf41fe822ae13b2c101cb8b5f966970dab9023a9c998431a83ac94821f873e308abbe4bd49438a1
7
- data.tar.gz: 4880d52d3861e8c51f6215d90f4f9841639d997883aa4518e21d3a6b8ccdb09fe480ff53b8cdfac828dd8cf87c9477526fde8c17bf3cec65db4338c2de271755
6
+ metadata.gz: 97227e30d53769099e98c2f2aff4ca63614961db497601e73fefc1f979694515ab17187f1090cea90eda8306f8c27d1e3616297683eb0111860a91b936c68ad4
7
+ data.tar.gz: f59a706d327b2071106a0c5d6e25ed9360057b8d93e085fb1ade764da9ca4b7bd88ee20d9c5a79006b497197b70ff6a2ec27a4095df89069c3ee557ee1e891e4
data/README.md CHANGED
@@ -13,16 +13,51 @@ Coding agents write code against a gem from what they remember of it, not from t
13
13
  ```sh
14
14
  gem install yard-md
15
15
  cd my-project
16
- yard-md ~/.cache/gem-docs
16
+ yard-md
17
17
  ```
18
18
 
19
- Run in a project, yard-md documents every gem Bundler resolves for it on this platform, each into `<output dir>/<gem>-<version>/`. A gem whose directory already exists is skipped, so a second run writes nothing and the output directory is the cache, shared by every project that points at it.
19
+ Run in a project, yard-md documents every gem Bundler resolves for it on this platform, each into `<output dir>/<gem>-<version>/`. The bundle is resolved by the project's own Ruby through `mise exec` where mise is installed, otherwise by the `ruby` on the PATH; with mise, one install of yard-md serves projects on any Ruby. The output directory is `$XDG_CACHE_HOME/gem-docs`, or `~/.cache/gem-docs` when that is unset, empty or relative, unless given as the argument: `yard-md docs`. A gem whose directory already exists is skipped, so a second run writes nothing and the output directory is the cache, shared by every project. `yard-md --force` rebuilds the project's gems whose directories exist, for when a newer yard-md writes them differently, and leaves other projects' gems alone.
20
20
 
21
21
  Each gem's directory holds:
22
22
 
23
23
  - a page per class and module YARD documents, at YARD's own paths (`ActiveRecord/FinderMethods.md`): the public API, plus whatever visibility the gem's `.yardopts` asks for, without `@private` and `@api private`;
24
24
  - its README and the files its `.yardopts` names, as they are;
25
- - its `doc/`, `docs/`, `examples/`, `example/`, `samples/` and `sample/` directories, copied whole.
25
+ - its `doc/`, `docs/`, `examples/`, `example/`, `samples/` and `sample/` directories, copied whole;
26
+ - `.index.json`, the index `mdri` reads.
27
+
28
+ `yard-md --help` says the same in short.
29
+
30
+ ## Reading
31
+
32
+ ```sh
33
+ mdri Faraday # its documentation, then its constants, classes, modules and methods
34
+ mdri Faraday::Connection#run_request # that instance method's documentation
35
+ mdri Faraday.new # that class method's documentation
36
+ mdri Faraday::VERSION # that constant's value and documentation
37
+ ```
38
+
39
+ A class or module answers with its own documentation, then its list, and each line of the list says what lies behind it, so the next call goes where it should. `mdri YardMd`:
40
+
41
+ ```
42
+ The documentation of installed gems as plain Markdown.
43
+
44
+ YardMd::CACHE = File.join(cache_home, "gem-docs")
45
+ YardMd::VERSION = "0.1.0"
46
+ YardMd::Bundle — class, 3 methods
47
+ YardMd::Error — class
48
+ ```
49
+
50
+ A constant shows its value, or its size when longer than a line of 80 characters; a class or module, its kind and how many constants, modules, classes and methods it holds; a method, its summary, the first sentence of its documentation, as YARD's own index shows it. A class or module with nothing to list answers with its documentation, then its kind and the gems it is in.
51
+
52
+ Run in the same project, `mdri` answers from the documentation yard-md wrote for its bundle, at the versions its `Gemfile.lock` locks, addressed by constant as YARD's `yri` is. It reads the lockfile with Bundler's own parser and starts no process, so neither a call nor a page of a long answer waits on the project's Ruby. Every gem in the bundle answers: a namespace several gems add to (`Rails`) lists them all, and a class a gem reopens (`String`, by activesupport) answers with that gem's methods. It reads the output directory yard-md writes, or the one given after the constant, and writes nothing. It answers from an index yard-md writes beside each gem's pages, so a gem documented by an earlier yard-md does not answer until `yard-md --force` documents it again. `mdri --help` says the same in short.
53
+
54
+ An answer is read whole, so `mdri` keeps it from flooding the reader's context: it cuts each answer to 100 lines, each line to 100 words and each word to 200 characters, marking every cut where it happens (`… [+340 words]`, `… [+12000 chars]`). An answer cut by lines ends with its total and, while lines remain, the command for the next ones:
55
+
56
+ ```
57
+ [Showing lines 1–100 of 304. mdri RuboCop::Cop::Style --from 101 for the next.]
58
+ ```
59
+
60
+ `--from N` starts an answer at line N.
26
61
 
27
62
  Docstrings written in RDoc markup (`+code+`, `<tt>`, `*bold*`, `_em_`, `= Heading`, labelled lists) come out in Markdown; code examples are left as they are.
28
63
 
data/exe/mdri ADDED
@@ -0,0 +1,73 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require "optparse"
5
+ require "shellwords"
6
+ require "yard_md"
7
+
8
+ parser = OptionParser.new(<<~HELP)
9
+ Reads the documentation yard-md wrote for a project's gems, by constant.
10
+
11
+ Usage: mdri [--from N] <Constant>[#method|.method] [output dir]
12
+
13
+ Run in a project. Reads the documentation yard-md wrote into <output dir>
14
+ for the gems its bundle locks in Gemfile.lock, at those versions:
15
+
16
+ mdri Faraday its documentation, then its constants,
17
+ classes, modules and methods
18
+ mdri Faraday::Connection#run_request that instance method's documentation
19
+ mdri Faraday.new that class method's documentation
20
+ mdri Faraday::VERSION that constant's value and documentation
21
+
22
+ Each line of a list says what lies behind it: a constant's value, or its
23
+ size when longer than a line of 80 characters; a class's or module's kind
24
+ and how many constants, modules, classes and methods it holds; a method's
25
+ summary. A class or module with nothing to list answers with its
26
+ documentation, then its kind and the gems it is in.
27
+
28
+ Every gem in the bundle answers, so a namespace several gems add to lists
29
+ them all, and a class a gem reopens, such as String, answers for that gem.
30
+
31
+ The output directory defaults to gem-docs/ in XDG_CACHE_HOME, or in ~/.cache
32
+ when that is unset, empty or relative: here, #{YardMd::CACHE}.
33
+
34
+ Prints the answer and writes nothing. When nothing in the bundle documents
35
+ what it is asked, says so on stderr and exits non-zero. A gem answers once
36
+ yard-md has documented it; one documented by yard-md 0.1.0 answers after
37
+ yard-md --force documents it again.
38
+
39
+ Cuts each answer to #{YardMd::Excerpt::LINES} lines, each line to #{YardMd::Excerpt::WORDS} words and each word
40
+ to #{YardMd::Excerpt::CHARS} characters, marking every cut where it happens: … [+340 words],
41
+ … [+12000 chars]. An answer cut by lines ends with its total and, while
42
+ lines remain, the command for the next ones.
43
+
44
+ Options:
45
+ HELP
46
+ parser.version = YardMd::VERSION
47
+ parser.on("--from N", Integer, "starts the answer at line N") do |line|
48
+ line.positive? ? line : raise(OptionParser::InvalidArgument, line.to_s)
49
+ end
50
+ parser.on_tail("-h", "--help", "shows this") do
51
+ puts parser.help
52
+ exit
53
+ end
54
+ parser.on_tail("-v", "--version", "prints the version") do
55
+ puts parser.ver
56
+ exit
57
+ end
58
+
59
+ trap("INT") { exit 130 }
60
+
61
+ begin
62
+ options = {}
63
+ address, *output = parser.parse(ARGV, into: options)
64
+ abort parser.help unless address && output.size <= 1
65
+ answer = YardMd::Bundle.new(*output).read(address)
66
+ abort "mdri: nothing in the bundle documents #{address}" unless answer
67
+ from = options.fetch(:from, 1)
68
+ excerpt = YardMd::Excerpt.new(answer, from).page(Shellwords.join(["mdri", address, *output.map { |directory| File.expand_path(directory) }]))
69
+ abort "mdri: the answer has #{answer.lines.size} lines, fewer than --from #{from}" unless excerpt
70
+ print excerpt
71
+ rescue OptionParser::ParseError, YardMd::Error, SystemCallError
72
+ parser.abort
73
+ end
data/exe/yard-md CHANGED
@@ -1,12 +1,50 @@
1
1
  #!/usr/bin/env ruby
2
2
  # frozen_string_literal: true
3
3
 
4
+ require "optparse"
4
5
  require "yard_md"
5
6
 
6
- abort "usage: yard-md <output dir>" unless ARGV.size == 1
7
+ parser = OptionParser.new(<<~HELP)
8
+ Documents a project's gems as Markdown, for people and coding agents to read.
9
+
10
+ Usage: yard-md [--force] [output dir]
11
+
12
+ Run in a project. Documents every gem its bundle resolves on this platform
13
+ as Markdown, each into <output dir>/<gem>-<version>/: a page per class and
14
+ module, the index mdri reads, the README and the files its .yardopts
15
+ names, and its doc/, docs/, example(s)/ and sample(s)/ directories. A gem
16
+ whose directory exists is skipped, so the output directory is a cache several
17
+ projects can share; --force rebuilds such a gem, and leaves other projects'
18
+ gems alone.
19
+
20
+ The output directory defaults to gem-docs/ in XDG_CACHE_HOME, or in ~/.cache
21
+ when that is unset, empty or relative: here, #{YardMd::CACHE}.
22
+
23
+ Prints each gem it documents. A gem it cannot document is reported on stderr
24
+ and the rest go on; the exit status says whether every gem is documented.
25
+ What YARD could not process in a gem is reported on stderr under its name,
26
+ and the gem still counts as documented.
27
+
28
+ Options:
29
+ HELP
30
+ parser.version = YardMd::VERSION
31
+ parser.on("--force", "rebuilds the bundle's gems whose directories exist")
32
+ parser.on_tail("-h", "--help", "shows this") do
33
+ puts parser.help
34
+ exit
35
+ end
36
+ parser.on_tail("-v", "--version", "prints the version") do
37
+ puts parser.ver
38
+ exit
39
+ end
40
+
41
+ trap("INT") { exit 130 }
7
42
 
8
43
  begin
9
- exit YardMd::Bundle.new(ARGV.first).document
10
- rescue Bundler::BundlerError => error
11
- abort "yard-md: #{error.message}"
44
+ options = {}
45
+ arguments = parser.parse(ARGV, into: options)
46
+ abort parser.help if arguments.size > 1
47
+ exit YardMd::Bundle.new(*arguments, **options).document
48
+ rescue OptionParser::ParseError, YardMd::Error, SystemCallError
49
+ parser.abort
12
50
  end
@@ -4,40 +4,245 @@ module YardMd
4
4
  # The documentation of every gem the current project's bundle resolves on
5
5
  # this platform, written as Markdown into one directory per gem version.
6
6
  #
7
+ # {#document} has the bundle resolved by the project's own Ruby through
8
+ # <tt>mise exec</tt> where mise is installed, otherwise by the +ruby+ on the
9
+ # PATH, so it need not be the Ruby yard-md runs on. mise installs no missing
10
+ # tool for it. {#read} takes the versions from the project's lockfile alone.
11
+ #
7
12
  # The output directory is a cache: a gem whose <tt><gem>-<version></tt> directory
8
- # exists is skipped, and a directory appears only once its gem is fully
9
- # documented, so an interrupted or concurrent run leaves no partial one.
10
- # Several projects can share it.
13
+ # exists is skipped unless forced, and a directory appears only once its gem
14
+ # is fully documented, so an interrupted or concurrent run leaves no partial
15
+ # one; what a run killed on this machine left half-written, the next run
16
+ # removes. Several projects can share it.
11
17
  #
12
18
  # @example
13
- # YardMd::Bundle.new("~/.cache/gem-docs").document
19
+ # YardMd::Bundle.new.document
20
+ # YardMd::Bundle.new.read("YARD::Registry.at")
14
21
  class Bundle
15
- # @param output [String] the directory to write into; created when missing
16
- def initialize(output)
22
+ # A gem at its version; resolved, also its code under +root+, all of it or
23
+ # only +files+, and its own directory at +path+.
24
+ # @api private
25
+ Spec = Data.define(:name, :version, :path, :root, :files) do
26
+ def initialize(name:, version:, path:, root: path, files: [])
27
+ super
28
+ end
29
+ end
30
+
31
+ # @api private
32
+ Namespace = Struct.new(:kind, :constants, :methods, :gems) do
33
+ def initialize(kind:, constants: {}, methods: {}, gems: [])
34
+ super
35
+ end
36
+ end
37
+
38
+ # @api private
39
+ SCRATCH = ".yard-md-"
40
+
41
+ # @api private
42
+ NOUNS = {"constant" => "constants", "module" => "modules", "class" => "classes", "method" => "methods"}.freeze
43
+
44
+ # Run by the project's Ruby, it writes into the file named by its argument
45
+ # the bundle's {Spec}s, or Bundler's error, as JSON; what the Gemfile
46
+ # prints goes wherever it goes.
47
+ # @api private
48
+ RESOLVER = <<~RUBY
49
+ require "bundler"
50
+ require "json"
51
+
52
+ Bundler.ui = Bundler::UI::Silent.new
53
+ lib = RbConfig::CONFIG["rubylibdir"]
54
+ result = begin
55
+ specs = Bundler.definition.specs.map do |spec|
56
+ entry = {name: spec.name, version: spec.version.to_s, path: spec.full_gem_path}
57
+ next entry unless spec.default_gem?
58
+
59
+ files = spec.files.filter_map do |file|
60
+ file = file.delete_prefix("lib/")
61
+ file if file.end_with?(".rb") && File.file?(File.join(lib, file))
62
+ end
63
+ entry.merge(root: lib, files: files)
64
+ end
65
+ {specs: specs}
66
+ rescue Bundler::BundlerError => error
67
+ {error: error.message}
68
+ end
69
+ File.write(ARGV.fetch(0), JSON.generate(result))
70
+ RUBY
71
+
72
+ # @param output [String] the directory to write into, created when missing,
73
+ # and read from
74
+ # @param force [Boolean] rebuild the bundle's gems whose directories exist,
75
+ # replacing each only once its rebuild succeeds; other directories in
76
+ # +output+ are left alone
77
+ def initialize(output = CACHE, force: false)
17
78
  @output = File.expand_path(output)
79
+ @force = force
18
80
  end
19
81
 
20
- # Documents each gem not documented yet, printing its <tt><gem>-<version></tt> to
21
- # stdout. A gem that fails is reported on stderr and skipped; the rest go on.
82
+ # Documents each gem not documented yet, or every gem when forced, printing
83
+ # its <tt><gem>-<version></tt> to stdout. A gem that fails is reported on
84
+ # stderr and skipped; the rest go on. The code YARD could not process in a
85
+ # gem is reported on stderr under the gem's name, without YARD's stack
86
+ # traces; the gem still counts as documented.
22
87
  #
23
88
  # @return [Boolean] whether every gem is documented
24
- # @raise [Bundler::BundlerError] when the bundle cannot be resolved, e.g.
25
- # a gem in it is not installed
89
+ # @raise [Error] when the bundle cannot be resolved, e.g. a gem in it is not
90
+ # installed
26
91
  def document
27
- Bundler.ui = Bundler::UI::Silent.new
92
+ resolved = specs
28
93
  FileUtils.mkdir_p(@output)
29
- Bundler.definition.specs.map { |spec| build(spec) }.all?
94
+ sweep
95
+ resolved.map { |spec| build(spec) }.all?
96
+ end
97
+
98
+ # Answers from the documentation {#document} wrote for the bundle's gems, at
99
+ # the versions the project's lockfile locks, found as Bundler finds it, plus
100
+ # the bundler gem at its <tt>BUNDLED WITH</tt> version, gem by gem in name
101
+ # order. A gem not documented yet, or documented by yard-md 0.1.0, which
102
+ # wrote no index, does not answer.
103
+ #
104
+ # @param address [String] a constant, or a method of one:
105
+ # <tt>Faraday</tt>, <tt>Faraday::VERSION</tt>,
106
+ # <tt>Faraday::Connection#run_request</tt>, <tt>Faraday.new</tt>; an
107
+ # empty constant is the top-level namespace: <tt>""</tt>, <tt>#puts</tt>
108
+ # @return [String] for a class or module, its own documentation from every
109
+ # gem that documents it, then its list: one line per constant, class or
110
+ # module, and method in it, from every gem that has them, each with what
111
+ # lies behind it (a constant's value, a class's or module's kind and
112
+ # counts, a method's summary), or, when it has nothing to list, one line
113
+ # with its kind and gems
114
+ # @return [String] for a value constant or a method, its block of the page,
115
+ # from every gem that documents it
116
+ # @return [nil] when no gem documents it
117
+ # @raise [Error] when the project has no Gemfile or lockfile, or Bundler
118
+ # cannot read the lockfile
119
+ def read(address)
120
+ constant, method = address.match(/\A([^#.]*)(.*)\z/m).captures
121
+ indexes = locked.filter_map do |spec|
122
+ file = File.join(directory(spec), INDEX)
123
+ index = JSON.parse(File.read(file)) if File.exist?(file)
124
+ [spec, index] if index&.dig("", "kind")
125
+ end
126
+ return blocks(indexes, constant, "methods", method) unless method.empty?
127
+
128
+ namespace, _, name = constant.rpartition("::")
129
+ list = listing(indexes, constant)
130
+ return blocks(indexes, namespace, "constants", name) unless list
131
+
132
+ [*indexes.filter_map { |spec, index| slice(spec, index, constant, index.dig(constant, "docs", "lines")) }, list].join("\n")
30
133
  end
31
134
 
32
135
  private
33
136
 
137
+ def specs
138
+ Tempfile.create("yard-md-bundle") do |answer|
139
+ _, err, = ruby("-e", RESOLVER, answer.path)
140
+ raise Error, err.strip if answer.size.zero?
141
+
142
+ result = JSON.parse(answer.read, symbolize_names: true)
143
+ raise Error, result[:error] if result[:error]
144
+
145
+ result[:specs].map { |spec| Spec.new(**spec) }
146
+ end
147
+ end
148
+
149
+ def locked
150
+ lockfile = Bundler.default_lockfile
151
+ raise Error, "Could not locate #{lockfile.basename}" unless lockfile.file?
152
+
153
+ parser = Bundler::LockfileParser.new(Bundler.read_file(lockfile))
154
+ versions = parser.specs.map { |spec| [spec.name, spec.version.to_s] }
155
+ versions << ["bundler", parser.bundler_version.to_s] if parser.bundler_version
156
+ versions.uniq.sort.map { |name, version| Spec.new(name: name, version: version, path: nil) }
157
+ rescue Bundler::BundlerError => error
158
+ raise Error, error.message
159
+ end
160
+
161
+ def ruby(*args)
162
+ Open3.capture3({"MISE_EXEC_AUTO_INSTALL" => "false"}, "mise", "exec", "--", "ruby", *args)
163
+ rescue Errno::ENOENT
164
+ Open3.capture3("ruby", *args)
165
+ end
166
+
167
+ def directory(spec)
168
+ File.join(@output, "#{spec.name}-#{spec.version}")
169
+ end
170
+
171
+ def listing(indexes, constant)
172
+ namespaces = namespaces(indexes, constant)
173
+ namespace = namespaces[constant]
174
+ children = namespaces.keys.select { |path| inside?(path, constant) }.sort
175
+ return unless namespace || children.any?
176
+
177
+ held = held(namespaces)
178
+ lines = [
179
+ *namespace&.constants&.sort&.map { |name, detail| constant_line(qualified(constant, name), detail) },
180
+ *children.map { |path| [path, [namespaces[path].kind, *counts(held[path])].join(", ")].join(" — ") },
181
+ *namespace&.methods&.map { |name, detail| [name, detail["summary"]].compact.join(" — ") }
182
+ ]
183
+ return lines.map { |line| "#{line}\n" }.join if lines.any?
184
+
185
+ "#{constant} — #{namespace.kind} in #{namespace.gems.join(", ")}, with no constants, classes or methods\n"
186
+ end
187
+
188
+ def held(namespaces)
189
+ namespaces.each_with_object(Hash.new { |held, path| held[path] = Hash.new(0) }) do |(path, namespace), held|
190
+ held[path]["constant"] += namespace.constants.size
191
+ held[path]["method"] += namespace.methods.size
192
+ held[parent(path)][namespace.kind] += 1 unless path.empty?
193
+ end
194
+ end
195
+
196
+ def namespaces(indexes, constant)
197
+ indexes.each_with_object({}) do |(spec, index), namespaces|
198
+ index.each do |path, entry|
199
+ next unless path == constant || inside?(path, constant) || inside?(parent(path), constant)
200
+
201
+ namespace = namespaces[path] ||= Namespace.new(kind: entry["kind"])
202
+ namespace.constants = entry.fetch("constants", {}).merge(namespace.constants)
203
+ namespace.methods = namespace.methods.merge(entry.fetch("methods", {})) { |_, first, _| first }
204
+ namespace.gems << "#{spec.name} #{spec.version}"
205
+ end
206
+ end
207
+ end
208
+
209
+ def counts(held)
210
+ NOUNS.filter_map { |noun, plural| "#{held[noun]} #{(held[noun] == 1) ? noun : plural}" if held[noun].positive? }
211
+ end
212
+
213
+ def constant_line(path, detail)
214
+ detail.key?("value") ? "#{path} = #{detail["value"]}" : "#{path} — #{detail["size"]}"
215
+ end
216
+
217
+ def blocks(indexes, namespace, group, name)
218
+ blocks = indexes.filter_map { |spec, index| slice(spec, index, namespace, index.dig(namespace, group, name, "lines")) }
219
+ blocks.join("\n") unless blocks.empty?
220
+ end
221
+
222
+ def slice(spec, index, namespace, lines)
223
+ first, last = lines
224
+ File.readlines(File.join(directory(spec), index.dig(namespace, "page")))[(first - 1)...last].join if first
225
+ end
226
+
227
+ def inside?(path, namespace)
228
+ path != namespace && parent(path) == namespace
229
+ end
230
+
231
+ def parent(path)
232
+ path.rpartition("::").first
233
+ end
234
+
235
+ def qualified(namespace, name)
236
+ namespace.empty? ? name : "#{namespace}::#{name}"
237
+ end
238
+
34
239
  def build(spec)
35
- name = "#{spec.name}-#{spec.version}"
36
- target = File.join(@output, name)
37
- return true if File.exist?(target)
240
+ target = directory(spec)
241
+ name = File.basename(target)
242
+ return true if !@force && File.exist?(target)
38
243
 
39
- staging = Dir.mktmpdir(".#{name}-", @output)
40
- return false unless write(spec, staging)
244
+ staging = Dir.mktmpdir(scratch(name), @output)
245
+ return false unless write(spec, name, staging)
41
246
 
42
247
  publish(staging, target)
43
248
  puts name
@@ -46,23 +251,52 @@ module YardMd
46
251
  FileUtils.rm_rf(staging) if staging
47
252
  end
48
253
 
49
- def write(spec, staging)
254
+ def write(spec, name, staging)
50
255
  # YARD's registry, tag library and logger are process-wide, and a gem's
51
256
  # .yardopts changes them; a process per gem keeps one gem out of the next.
257
+ log = StringIO.new
52
258
  pid = fork do
53
- GemDocs.new(spec).write(staging)
259
+ GemDocs.new(spec).write(staging, log)
260
+ warn "yard-md: #{name}:", *log.string.lines unless log.string.empty?
54
261
  exit!(true)
55
262
  rescue => error
56
- warn "yard-md: #{spec.name}-#{spec.version}: #{error.class}: #{error.message}"
263
+ warn "yard-md: #{name}: #{error.class}: #{error.message}", *log.string.lines
57
264
  exit!(false)
58
265
  end
59
266
  Process.wait2(pid).last.success?
60
267
  end
61
268
 
62
269
  def publish(staging, target)
270
+ retire(target) if @force && File.exist?(target)
63
271
  File.rename(staging, target)
64
272
  rescue Errno::EEXIST, Errno::ENOTEMPTY
65
273
  nil
66
274
  end
275
+
276
+ def retire(target)
277
+ Dir.mktmpdir(scratch(File.basename(target)), @output) do |retired|
278
+ File.rename(target, File.join(retired, "docs"))
279
+ rescue Errno::ENOENT
280
+ nil
281
+ end
282
+ end
283
+
284
+ def scratch(name)
285
+ "#{SCRATCH}#{Process.pid}-#{name}-"
286
+ end
287
+
288
+ def sweep
289
+ Dir.glob("#{SCRATCH}*", base: @output).each do |entry|
290
+ FileUtils.rm_rf(File.join(@output, entry)) unless alive?(entry.delete_prefix(SCRATCH).to_i)
291
+ end
292
+ end
293
+
294
+ def alive?(pid)
295
+ Process.kill(0, pid)
296
+ rescue Errno::ESRCH
297
+ false
298
+ rescue Errno::EPERM
299
+ true
300
+ end
67
301
  end
68
302
  end
@@ -0,0 +1,39 @@
1
+ # frozen_string_literal: true
2
+
3
+ module YardMd
4
+ # @api private
5
+ class Excerpt
6
+ LINES = 100
7
+ WORDS = 100
8
+ CHARS = 200
9
+ KEPT_WORDS = /\A\s*(?:\S+\s+){#{WORDS - 1}}\S+/
10
+ LONG_WORD = /\S{#{CHARS + 1},}/
11
+
12
+ def initialize(text, from = 1)
13
+ @lines = text.lines
14
+ @from = from
15
+ end
16
+
17
+ def page(command)
18
+ return if @from > @lines.size
19
+
20
+ shown = @lines[@from - 1, LINES]
21
+ last = @from + shown.size - 1
22
+ text = shown.map { |line| cut(line) }.join
23
+ return text if @from == 1 && last == @lines.size
24
+
25
+ more = " #{command} --from #{last + 1} for the next." if last < @lines.size
26
+ "#{text.chomp}\n[Showing lines #{@from}–#{last} of #{@lines.size}.#{more}]\n"
27
+ end
28
+
29
+ private
30
+
31
+ def cut(line)
32
+ text = line.chomp
33
+ count = text.scan(/\S+/).size
34
+ text = "#{text[KEPT_WORDS]} … [+#{count - WORDS} words]" if count > WORDS
35
+ text = text.gsub(LONG_WORD) { |word| "#{word[0, CHARS]}… [+#{word.size - CHARS} chars]" }
36
+ "#{text}#{line[line.chomp.size..]}"
37
+ end
38
+ end
39
+ end
@@ -10,10 +10,10 @@ module YardMd
10
10
  @spec = spec
11
11
  end
12
12
 
13
- def write(output)
13
+ def write(output, log = $stderr)
14
14
  output = File.expand_path(output)
15
- Dir.chdir(source_root) do
16
- yardoc = parse
15
+ Dir.chdir(@spec.root) do
16
+ yardoc = parse(log)
17
17
  pages(yardoc, output)
18
18
  extra_files(yardoc.options.files, output)
19
19
  end
@@ -22,30 +22,29 @@ module YardMd
22
22
 
23
23
  private
24
24
 
25
- def source_root
26
- @spec.default_gem? ? RbConfig::CONFIG["rubylibdir"] : @spec.full_gem_path
27
- end
28
-
29
- def sources
30
- return [] unless @spec.default_gem?
31
-
32
- @spec.files.filter_map { |file| file.delete_prefix("lib/") if file.start_with?("lib/") && file.end_with?(".rb") }
33
- end
34
-
35
- def parse
25
+ def parse(log)
36
26
  YARD::Config.options[:safe_mode] = true
37
- YARD::Logger.instance.io = $stderr
27
+ YARD::Logger.instance.io = log
38
28
  YARD::Registry.clear
39
- YARD::CLI::Yardoc.new.tap { |yardoc| yardoc.run(*YARDOC_ARGS, *sources) }
29
+ YARD::CLI::Yardoc.new.tap do |yardoc|
30
+ yardoc.parse_arguments(*YARDOC_ARGS, *@spec.files)
31
+ YARD::Logger.instance.show_backtraces = false
32
+ yardoc.run(nil)
33
+ end
40
34
  end
41
35
 
42
36
  def pages(yardoc, output)
43
37
  serializer = YARD::Serializers::FileSystemSerializer.new(basepath: output, extension: "md")
44
38
  prose = Prose.new(yardoc.options.markup)
45
- yardoc.options.verifier.run(yardoc.all_objects).each do |object|
46
- page = Page.new(object, yardoc.options.verifier, prose).to_s
47
- serializer.serialize(object, page) if page
39
+ index = yardoc.options.verifier.run(yardoc.all_objects).to_h do |object|
40
+ page = Page.new(object, yardoc.options.verifier, prose)
41
+ markdown = page.to_s
42
+ next [object.path, {kind: object.type}] unless markdown
43
+
44
+ serializer.serialize(object, markdown)
45
+ [object.path, {kind: object.type, page: serializer.serialized_path(object), **page.members}]
48
46
  end
47
+ File.write(File.join(output, INDEX), JSON.generate(index))
49
48
  end
50
49
 
51
50
  def extra_files(files, output)
@@ -56,7 +55,7 @@ module YardMd
56
55
  end
57
56
 
58
57
  def directories(output)
59
- DIRECTORIES.map { |directory| File.join(@spec.full_gem_path, directory) }.each do |directory|
58
+ DIRECTORIES.map { |directory| File.join(@spec.path, directory) }.each do |directory|
60
59
  FileUtils.cp_r(directory, output) if File.directory?(directory) && !output.start_with?("#{directory}/")
61
60
  end
62
61
  end
data/lib/yard_md/page.rb CHANGED
@@ -7,6 +7,15 @@ module YardMd
7
7
  include YARD::Templates::Helpers::MethodHelper
8
8
 
9
9
  SCOPES = {class: ".", instance: "#"}.freeze
10
+ SEPARATOR = "\n\n"
11
+ INLINE = 80
12
+ CALL_SEQ = /\A\s*:call-seq:.*?(?:\n[ \t]*\n|\z)/m
13
+
14
+ Entry = Data.define(:text, :group, :names, :detail) do
15
+ def initialize(text:, group: nil, names: [], detail: {})
16
+ super
17
+ end
18
+ end
10
19
 
11
20
  def initialize(object, verifier, prose)
12
21
  @object = object
@@ -15,15 +24,34 @@ module YardMd
15
24
  end
16
25
 
17
26
  def to_s
18
- sections = [constants, *SCOPES.keys.map { |scope| attributes(scope) }, *SCOPES.keys.map { |scope| methods(scope) }].compact
19
- body = [docs(@object, 1), *sections].reject(&:empty?)
20
- return if body.empty?
27
+ entries.map(&:text).join(SEPARATOR) + "\n" unless entries.empty?
28
+ end
21
29
 
22
- [header, *body].join("\n\n") + "\n"
30
+ def members
31
+ first = 1
32
+ entries.each_with_object({constants: {}, methods: {}}) do |entry, members|
33
+ last = first + entry.text.count("\n")
34
+ members[:docs] = {lines: [first, last]} if entry.group == :docs
35
+ entry.names.each { |name| members[entry.group][name] = {lines: [first, last], **entry.detail} }
36
+ first = last + SEPARATOR.count("\n")
37
+ end
23
38
  end
24
39
 
25
40
  private
26
41
 
42
+ def entries
43
+ @entries ||= begin
44
+ docs = docs(@object, 1)
45
+ body = [
46
+ *(Entry.new(text: docs, group: :docs) unless docs.empty?),
47
+ *constants,
48
+ *SCOPES.keys.flat_map { |scope| attributes(scope) },
49
+ *SCOPES.keys.flat_map { |scope| methods(scope) }
50
+ ]
51
+ body.empty? ? [] : [Entry.new(text: header), *body]
52
+ end
53
+ end
54
+
27
55
  def header
28
56
  title = @object.root? ? "# Top-level namespace" : "# #{@object.type} #{@object.path}"
29
57
  title += " < #{@object.superclass.path}" if @object.is_a?(YARD::CodeObjects::ClassObject) && @object.superclass && @object.superclass.path != "Object"
@@ -47,7 +75,20 @@ module YardMd
47
75
  def constant_entry(constant)
48
76
  value = constant.value.to_s
49
77
  heading = value.include?("\n") ? "### #{constant.name}\n\n```ruby\n#{constant.name} = #{value}\n```" : "### #{constant.name} = #{value}"
50
- [heading, docs(constant, 3)].reject(&:empty?).join("\n\n")
78
+ Entry.new(
79
+ text: [heading, docs(constant, 3)].reject(&:empty?).join(SEPARATOR),
80
+ group: :constants,
81
+ names: (constant.type == :constant) ? [constant.name.to_s] : [],
82
+ detail: shown(value)
83
+ )
84
+ end
85
+
86
+ def shown(value)
87
+ lines = value.lines.size
88
+ if lines > 1 then {size: "#{lines} lines"}
89
+ elsif value.size > INLINE then {size: "#{value.size} characters"}
90
+ else {value: value}
91
+ end
51
92
  end
52
93
 
53
94
  def attributes(scope)
@@ -59,7 +100,7 @@ module YardMd
59
100
  elsif reader then " (read-only)"
60
101
  else " (write-only)"
61
102
  end
62
- ["### #{SCOPES[scope]}#{name}#{access}", docs(reader || writer, 3), aliases([reader, writer].compact)].compact.reject(&:empty?).join("\n\n")
103
+ named_entry([reader, writer].compact, ["### #{SCOPES[scope]}#{name}#{access}", docs(reader || writer, 3)])
63
104
  end
64
105
  section("#{scope.capitalize} attributes", entries)
65
106
  end
@@ -76,15 +117,33 @@ module YardMd
76
117
  block = format_block(method)
77
118
  heading += " #{block}" unless block.empty?
78
119
  heading += " (#{method.visibility})" unless method.visibility == :public
79
- [heading, docs(method, 3), aliases([method])].compact.reject(&:empty?).join("\n\n")
80
- end
81
-
82
- def aliases(methods)
83
- list("Also known as", @verifier.run(methods.flat_map(&:aliases)).map(&:name))
120
+ named_entry([method], [heading, docs(method, 3)])
121
+ end
122
+
123
+ def named_entry(methods, parts)
124
+ aliases = @verifier.run(methods.flat_map(&:aliases))
125
+ summary = summary(methods.first)
126
+ Entry.new(
127
+ text: [*parts, list("Also known as", aliases.map(&:name))].compact.reject(&:empty?).join(SEPARATOR),
128
+ group: :methods,
129
+ names: (methods + aliases).map { |method| "#{SCOPES[method.scope]}#{method.name}" },
130
+ detail: summary.empty? ? {} : {summary: summary}
131
+ )
132
+ end
133
+
134
+ def summary(method)
135
+ overloads = method.tags(:overload)
136
+ docstring = (overloads.one? && method.docstring.empty?) ? overloads.first.docstring : method.docstring
137
+ docstring = YARD::Docstring.new(docstring.sub(CALL_SEQ, "")) if docstring.match?(CALL_SEQ)
138
+ returns = method.tags(:return)
139
+ if docstring.summary.empty? && returns.one? && returns.first.text
140
+ docstring = YARD::Docstring.new(returns.first.text.sub(/\A[a-z]/, &:upcase).strip)
141
+ end
142
+ @prose.call(docstring.summary, method, 4).strip.gsub(/\s*\n\s*/, " ")
84
143
  end
85
144
 
86
145
  def section(title, entries)
87
- "## #{title}\n\n#{entries.join("\n\n")}" if entries.any?
146
+ entries.empty? ? [] : [Entry.new(text: "## #{title}"), *entries]
88
147
  end
89
148
 
90
149
  def docs(object, level)
@@ -97,7 +156,7 @@ module YardMd
97
156
  next if tags.empty? || (name == :return && returns_nothing?(object, tags))
98
157
 
99
158
  case name
100
- when :example then tags.map { |tag| example(tag) }.join("\n\n")
159
+ when :example then tags.map { |tag| example(object, tag) }.join("\n\n")
101
160
  when :overload then tags.map { |tag| overload(tag, level) }.join("\n\n")
102
161
  else listing(YARD::Tags::Library.labels[name], tags, object)
103
162
  end
@@ -143,8 +202,8 @@ module YardMd
143
202
  @prose.call(tag.text, object, 4).strip.gsub("\n", "\n ")
144
203
  end
145
204
 
146
- def example(tag)
147
- title = tag.name.to_s.empty? ? "Example:" : "Example: #{tag.name}"
205
+ def example(object, tag)
206
+ title = tag.name.to_s.empty? ? "Example:" : "Example: #{@prose.call(tag.name, object, 4).strip}"
148
207
  "#{title}\n\n```ruby\n#{tag.text.sub(/\A\n+/, "").rstrip}\n```"
149
208
  end
150
209
 
data/lib/yard_md/prose.rb CHANGED
@@ -3,7 +3,13 @@
3
3
  module YardMd
4
4
  # @api private
5
5
  class Prose
6
- DIRECTIVE = /\A[ \t]*:(?:markup|include|nodoc|doc|stopdoc|startdoc|enddoc|title|section|category):/
6
+ DIRECTIVE = /\A[ \t]*:(?:markup|include|nodoc|doc|stopdoc|startdoc|enddoc|title|section|category|call-seq):/
7
+ REFERENCES = [
8
+ [/\{([^{}]+)\}\[rdoc-ref:[^\]]+\]/, "\\1"],
9
+ [/\[([^\]]+)\]\(rdoc-ref:[^)]+\)/, "\\1"],
10
+ [/(`[^`\n]*`|\w+)\[rdoc-ref:[^\]]+\]/, "\\1"]
11
+ ].freeze
12
+ CODE = /`[^`]*`/
7
13
  FILE_MARKUP = /^\s*#\s*:markup:\s*(\w+)/
8
14
  LINK = /(\\|!)?\{(?!\})(\S+?)(?:\s([^}]*?\S))?\}/
9
15
  URL = %r{\A(?:\w+://|mailto:)}
@@ -16,6 +22,12 @@ module YardMd
16
22
  rules.inject(text) { |result, (pattern, replacement)| result.gsub(pattern, replacement) }
17
23
  end
18
24
 
25
+ def self.references(text)
26
+ literals = []
27
+ masked = text.gsub(CODE) { |code| code.include?("rdoc-ref:") ? "\0#{(literals << code).size - 1}\0" : code }
28
+ substitute(masked, REFERENCES).gsub(/\0(\d+)\0/) { literals[$1.to_i] }
29
+ end
30
+
19
31
  def initialize(markup)
20
32
  @markup = markup.to_sym
21
33
  @file_markups = {}
@@ -54,7 +66,7 @@ module YardMd
54
66
  next line if fenced || line.start_with?(" ", "\t")
55
67
  next if line.match?(DIRECTIVE)
56
68
 
57
- html = Prose.substitute(line.gsub(RDocMarkup::TELETYPE, "`\\2`"), RDocMarkup::HTML_EMPHASIS)
69
+ html = Prose.references(Prose.substitute(line.gsub(RDocMarkup::TELETYPE, "`\\2`"), RDocMarkup::HTML_EMPHASIS))
58
70
  Prose.outside_code(html) do |part|
59
71
  part.gsub(LINK) { ($1) ? $~[0][1..] : link($2, $3) }
60
72
  end
@@ -13,10 +13,9 @@ module YardMd
13
13
  INLINE = [
14
14
  [/(?<![\w*])\*([^\s*]+)\*(?![\w*])/, "**\\1**"],
15
15
  [/(?<![\w_])_([^\s_](?:\S*[^\s_])?)_(?!\w)/, "*\\1*"],
16
- [/\{([^{}]+)\}\[rdoc-ref:[^\]]+\]/, "\\1"],
17
16
  [/\{([^{}]+)\}\[((?:https?|mailto|ftp):[^\]]+)\]/, "[\\1](\\2)"],
18
17
  [/(\w+)\[((?:https?|mailto|ftp):[^\]]+)\]/, "[\\1](\\2)"],
19
- [/rdoc-ref:(\S+)/, "`\\1`"],
18
+ [/(?<![(\[])rdoc-ref:(\S+)/, "`\\1`"],
20
19
  [/\\(?=[A-Z#:+*_<])/, ""]
21
20
  ].freeze
22
21
 
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module YardMd
4
- VERSION = "0.1.0"
4
+ VERSION = "1.0.0"
5
5
  end
data/lib/yard_md.rb CHANGED
@@ -2,6 +2,10 @@
2
2
 
3
3
  require "bundler"
4
4
  require "fileutils"
5
+ require "json"
6
+ require "open3"
7
+ require "stringio"
8
+ require "tempfile"
5
9
  require "tmpdir"
6
10
  require "yard"
7
11
 
@@ -10,8 +14,23 @@ require_relative "yard_md/rdoc_markup"
10
14
  require_relative "yard_md/prose"
11
15
  require_relative "yard_md/page"
12
16
  require_relative "yard_md/gem_docs"
17
+ require_relative "yard_md/excerpt"
13
18
  require_relative "yard_md/bundle"
14
19
 
15
20
  # The documentation of installed gems as plain Markdown.
16
21
  module YardMd
22
+ cache_home = Gem.cache_home
23
+ cache_home = File.join(Gem.user_home, ".cache") unless File.absolute_path?(cache_home)
24
+
25
+ # Where the documentation goes unless told otherwise.
26
+ CACHE = File.join(cache_home, "gem-docs")
27
+
28
+ # The bundle cannot be resolved, or its lockfile read; the message says why,
29
+ # in the words of the project's Ruby, mise or Bundler where they gave one.
30
+ class Error < StandardError; end
31
+
32
+ # The file in each gem's directory that {Bundle#read} answers from, beside
33
+ # the pages it indexes.
34
+ # @api private
35
+ INDEX = ".index.json"
17
36
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: yard-md
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.0
4
+ version: 1.0.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Yevhenii Hurin
@@ -29,16 +29,19 @@ description: Reads a gem's own documentation with YARD — its source comments a
29
29
  email:
30
30
  - evgeny.gurin@gmail.com
31
31
  executables:
32
+ - mdri
32
33
  - yard-md
33
34
  extensions: []
34
35
  extra_rdoc_files: []
35
36
  files:
36
37
  - LICENSE
37
38
  - README.md
39
+ - exe/mdri
38
40
  - exe/yard-md
39
41
  - lib/yard-md.rb
40
42
  - lib/yard_md.rb
41
43
  - lib/yard_md/bundle.rb
44
+ - lib/yard_md/excerpt.rb
42
45
  - lib/yard_md/gem_docs.rb
43
46
  - lib/yard_md/page.rb
44
47
  - lib/yard_md/prose.rb