├── .gitignore
├── LICENSE
├── Makefile
├── cmd
├── fmt.go
├── package.go
├── root.go
└── template.go
├── go.mod
├── go.sum
├── lib
├── options.go
├── outline.go
├── outline_test.go
├── parser.go
├── parser_test.go
├── scanner.go
└── token.go
├── main.go
└── readme.md
/.gitignore:
--------------------------------------------------------------------------------
1 | .DS_Store
2 | coverage.txt
3 | outline
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | default: build
2 |
3 | build:
4 | go build
5 |
6 | install:
7 | go install
8 |
9 | test:
10 | go test --race --coverprofile=coverage.txt ./...
11 |
12 | coverage:
13 | go tool cover --html=coverage.txt
--------------------------------------------------------------------------------
/cmd/fmt.go:
--------------------------------------------------------------------------------
1 | package cmd
2 |
3 | import (
4 | "fmt"
5 | "os"
6 |
7 | "github.com/b5/outline/lib"
8 | "github.com/spf13/cobra"
9 | )
10 |
11 | // FmtCmd prints present configuration info
12 | var FmtCmd = &cobra.Command{
13 | Use: "fmt",
14 | Short: "format input",
15 | Long: ``,
16 | Run: func(cmd *cobra.Command, args []string) {
17 | var docs lib.Docs
18 | for _, fp := range args {
19 | f, err := os.Open(fp)
20 | if err != nil {
21 | fmt.Println(err.Error())
22 | os.Exit(1)
23 | }
24 |
25 | found, err := lib.Parse(f)
26 | if err != nil {
27 | fmt.Println(err.Error())
28 | os.Exit(1)
29 | }
30 | docs = append(docs, found...)
31 | }
32 |
33 | noSort, err := cmd.Flags().GetBool("no-sort")
34 | if err != nil {
35 | fmt.Println(err)
36 | os.Exit(1)
37 | }
38 | if !noSort {
39 | docs.Sort()
40 | }
41 |
42 | for _, doc := range docs {
43 | data, err := doc.MarshalIndent(0, " ")
44 | if err != nil {
45 | fmt.Println(err.Error())
46 | os.Exit(1)
47 | }
48 |
49 | fmt.Print(string(data) + "\n")
50 | }
51 |
52 | },
53 | }
54 |
55 | func init() {
56 | // FmtCmd.Flags().StringP("export", "e", "config.json", "path to configuration json file")
57 | FmtCmd.Flags().Bool("no-sort", false, "done alpha-sort fields & outline documents")
58 | }
59 |
--------------------------------------------------------------------------------
/cmd/package.go:
--------------------------------------------------------------------------------
1 | package cmd
2 |
3 | import (
4 | "fmt"
5 | "os"
6 | "strings"
7 | "text/template"
8 |
9 | "github.com/b5/outline/lib"
10 | "github.com/spf13/cobra"
11 | parseutil "gopkg.in/src-d/go-parse-utils.v1"
12 | )
13 |
14 | // PackageCmd extracts and execute outline documents from a go package against a template",
15 | var PackageCmd = &cobra.Command{
16 | Use: "package",
17 | Aliases: []string{"pkg"},
18 | Short: "exctract and execute outline documents from a go package against a template",
19 | Long: ``,
20 | Run: func(cmd *cobra.Command, args []string) {
21 | t := template.Must(template.New("mdIndex").Parse(mdIndex))
22 |
23 | str, err := cmd.Flags().GetString("template")
24 | if err != nil {
25 | fmt.Println(err)
26 | os.Exit(1)
27 | }
28 | if str != "" {
29 | t, err = template.ParseFiles(str)
30 | if err != nil {
31 | fmt.Println(err)
32 | os.Exit(1)
33 | }
34 | }
35 |
36 | docs := map[string]*lib.Doc{}
37 | for _, pkg := range args {
38 | pkg, err := parseutil.PackageAST(pkg)
39 | if err != nil {
40 | fmt.Println(err)
41 | os.Exit(1)
42 | }
43 |
44 | for _, f := range pkg.Files {
45 | for _, c := range f.Comments {
46 | buf := strings.NewReader(c.Text())
47 | read, err := lib.Parse(buf)
48 | if err != nil {
49 | fmt.Println(err.Error())
50 | os.Exit(1)
51 | }
52 |
53 | for _, doc := range read {
54 | if found, ok := docs[doc.Name]; ok {
55 | merge(found, doc)
56 | continue
57 | }
58 |
59 | docs[doc.Name] = doc
60 | }
61 | }
62 | }
63 | }
64 |
65 | noSort, err := cmd.Flags().GetBool("no-sort")
66 | if err != nil {
67 | fmt.Println(err)
68 | os.Exit(1)
69 | }
70 |
71 | var list lib.Docs
72 | for _, doc := range docs {
73 | list = append(list, doc)
74 | }
75 |
76 | if !noSort {
77 | list.Sort()
78 | }
79 |
80 | if err := t.Execute(os.Stdout, list); err != nil {
81 | fmt.Println(err.Error())
82 | os.Exit(1)
83 | }
84 | },
85 | }
86 |
87 | func merge(a, b *lib.Doc) {
88 | if a.Description == "" {
89 | a.Description = b.Description
90 | }
91 |
92 | if a.Path == "" {
93 | a.Path = b.Path
94 | }
95 |
96 | a.Types = append(a.Types, b.Types...)
97 | a.Functions = append(a.Functions, b.Functions...)
98 | }
99 |
100 | func init() {
101 | PackageCmd.Flags().StringP("template", "t", "", "template file to load. overrides preset")
102 | PackageCmd.Flags().Bool("no-sort", false, "don't alpha-sort fields & outline documents")
103 | }
104 |
--------------------------------------------------------------------------------
/cmd/root.go:
--------------------------------------------------------------------------------
1 | package cmd
2 |
3 | import (
4 | "fmt"
5 | "os"
6 |
7 | "github.com/sirupsen/logrus"
8 | "github.com/spf13/cobra"
9 | )
10 |
11 | // logger
12 | var log = logrus.New()
13 |
14 | // RootCmd is the walk command
15 | var RootCmd = &cobra.Command{
16 | Short: "outline is a tool for outlining software packages",
17 | PersistentPreRun: func(cmd *cobra.Command, args []string) {
18 | if debug, err := cmd.Flags().GetBool("debug"); err == nil && debug {
19 | logrus.SetLevel(logrus.DebugLevel)
20 | }
21 | },
22 | }
23 |
24 | // Execute adds all child commands to the root command sets flags appropriately.
25 | // This is called by main.main(). It only needs to happen once to the rootCmd.
26 | func Execute() {
27 | if err := RootCmd.Execute(); err != nil {
28 | fmt.Println(err.Error())
29 | os.Exit(1)
30 | }
31 | }
32 |
33 | func init() {
34 | RootCmd.PersistentFlags().Bool("debug", false, "show debug output")
35 | RootCmd.AddCommand(
36 | FmtCmd,
37 | TemplateCmd,
38 | PackageCmd,
39 | )
40 | }
41 |
--------------------------------------------------------------------------------
/cmd/template.go:
--------------------------------------------------------------------------------
1 | package cmd
2 |
3 | import (
4 | "fmt"
5 | "os"
6 | "strings"
7 | "text/template"
8 |
9 | "github.com/b5/outline/lib"
10 | "github.com/spf13/cobra"
11 | )
12 |
13 | // backticks don't work with golang string literals, so use "'" as a stand-in & strings.Replace
14 | var mdIndex = strings.Replace(`{{- define "mdFn" }}
15 | #### '{{ .Signature }}'
16 | {{- if ne .Description "" }}
17 | {{ .Description }}
18 | {{- end -}}
19 | {{- if gt (len .Params) 0 }}
20 |
21 | **parameters:**
22 |
23 | | name | type | description |
24 | |------|------|-------------|
25 | {{ range .Params -}}
26 | | '{{ .Name }}' | '{{ .Type }}' | {{ .Description }} |
27 | {{ end -}}
28 | {{- end -}}
29 | {{- end -}}
30 |
31 | {{- range . -}}
32 | # {{ .Name }}
33 | {{ if ne .Description "" }}{{ .Description }}{{ end }}
34 | {{- if gt (len .Functions) 0 }}
35 |
36 | ## Functions
37 | {{ range .Functions -}}
38 | {{ template "mdFn" . }}
39 | {{ end -}}
40 | {{- end }}
41 | {{ if gt (len .Types) 0 }}
42 | ## Types
43 |
44 | {{ range .Types -}}
45 | ### '{{ .Name }}'
46 | {{ if ne .Description "" }}{{ .Description }}{{ end -}}
47 | {{ if gt (len .Fields) 0 }}
48 |
49 | **Fields**
50 |
51 | | name | type | description |
52 | |------|------|-------------|
53 | {{ range .Fields -}}
54 | | {{ .Name }} | {{ .Type }} | {{ .Description }} |
55 | {{ end -}}
56 | {{ end -}}
57 | {{ if gt (len .Methods) 0 }}
58 | **Methods**
59 | {{- range .Methods -}}
60 | {{ template "mdFn" . }}
61 | {{ end -}}
62 | {{- if gt (len .Operators) 0 }}
63 |
64 | **Operators**
65 |
66 | | operator | description |
67 | |----------|-------------|
68 | {{ range .Operators -}}
69 | | {{ .Opr }} | {{ .Description }} |
70 | {{ end }}
71 | {{ end }}
72 | {{ end }}
73 | {{- end -}}
74 | {{- end -}}
75 | {{ end }}`, "'", "`", -1)
76 |
77 | // TemplateCmd parses outline documents & executes them against a template
78 | var TemplateCmd = &cobra.Command{
79 | Use: "template",
80 | Aliases: []string{"md"},
81 | Short: "execute outline documents against a template",
82 | Long: ``,
83 | Run: func(cmd *cobra.Command, args []string) {
84 | t := template.Must(template.New("mdIndex").Parse(mdIndex))
85 |
86 | str, err := cmd.Flags().GetString("template")
87 | if err != nil {
88 | fmt.Println(err)
89 | os.Exit(1)
90 | }
91 | if str != "" {
92 | t, err = template.ParseFiles(str)
93 | if err != nil {
94 | fmt.Println(err)
95 | os.Exit(1)
96 | }
97 | }
98 |
99 | var options []lib.Option
100 | shouldSort, err := cmd.Flags().GetBool("sort")
101 | if err != nil {
102 | fmt.Println(err)
103 | os.Exit(1)
104 | }
105 | if shouldSort {
106 | options = append(options, lib.AlphaSortFuncs(), lib.AlphaSortTypes())
107 | }
108 |
109 | var docs lib.Docs
110 | for _, fp := range args {
111 | f, err := os.Open(fp)
112 | if err != nil {
113 | fmt.Println(err.Error())
114 | os.Exit(1)
115 | }
116 |
117 | read, err := lib.Parse(f, options...)
118 | if err != nil {
119 | fmt.Println(err.Error())
120 | os.Exit(1)
121 | }
122 | docs = append(docs, read...)
123 | }
124 |
125 | if err := t.Execute(os.Stdout, docs); err != nil {
126 | fmt.Println(err.Error())
127 | os.Exit(1)
128 | }
129 | },
130 | }
131 |
132 | func init() {
133 | TemplateCmd.Flags().StringP("template", "t", "", "template file to load. overrides preset")
134 | TemplateCmd.Flags().Bool("sort", false, "alpha-sort fields & outline documents")
135 | }
136 |
--------------------------------------------------------------------------------
/go.mod:
--------------------------------------------------------------------------------
1 | module github.com/b5/outline
2 |
3 | go 1.12
4 |
5 | require (
6 | github.com/google/go-cmp v0.2.0
7 | github.com/sergi/go-diff v1.0.0
8 | github.com/sirupsen/logrus v1.4.2
9 | github.com/spf13/cobra v0.0.6
10 | github.com/stretchr/testify v1.3.0 // indirect
11 | golang.org/x/net v0.0.0-20200202094626-16171245cfb2 // indirect
12 | golang.org/x/sys v0.0.0-20190626221950-04f50cda93cb // indirect
13 | gopkg.in/src-d/go-parse-utils.v1 v1.1.2
14 | )
15 |
--------------------------------------------------------------------------------
/go.sum:
--------------------------------------------------------------------------------
1 | cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
2 | github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
3 | github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU=
4 | github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
5 | github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=
6 | github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8=
7 | github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q=
8 | github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8=
9 | github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc=
10 | github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
11 | github.com/coreos/bbolt v1.3.2/go.mod h1:iRUV2dpdMOn7Bo10OQBFzIJO9kkE559Wcmn+qkEiiKk=
12 | github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE=
13 | github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk=
14 | github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4=
15 | github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA=
16 | github.com/cpuguy83/go-md2man/v2 v2.0.0/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU=
17 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
18 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
19 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
20 | github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=
21 | github.com/dgryski/go-sip13 v0.0.0-20181026042036-e10d5fee7954/go.mod h1:vAd38F8PWV+bWy6jNmig1y/TA+kYO4g3RSRF0IAv0no=
22 | github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
23 | github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04=
24 | github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as=
25 | github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE=
26 | github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk=
27 | github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
28 | github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ=
29 | github.com/gogo/protobuf v1.2.1/go.mod h1:hp+jE20tsWTFYpLwKvXlhS1hjn+gTNwPg2I6zVXpSg4=
30 | github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b h1:VKtxabqXZkF25pY9ekfRL6a582T4P37/31XEstQ5p58=
31 | github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
32 | github.com/golang/groupcache v0.0.0-20190129154638-5b532d6fd5ef/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
33 | github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
34 | github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
35 | github.com/golang/protobuf v1.3.1 h1:YF8+flBXS5eO826T4nzqPrxfhQThhXl0YzfuUPu4SBg=
36 | github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
37 | github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ=
38 | github.com/google/go-cmp v0.2.0 h1:+dTQ8DZQJz0Mb/HjFlkptS1FeQ4cWSnN941F8aEG4SQ=
39 | github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
40 | github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ=
41 | github.com/grpc-ecosystem/go-grpc-middleware v1.0.0/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs=
42 | github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk=
43 | github.com/grpc-ecosystem/grpc-gateway v1.9.0/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY=
44 | github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ=
45 | github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM=
46 | github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8=
47 | github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo=
48 | github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w=
49 | github.com/kisielk/errcheck v1.1.0/go.mod h1:EZBBE59ingxPouuu3KfxchcWSUPOHkagtvWXihfKN4Q=
50 | github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
51 | github.com/konsorten/go-windows-terminal-sequences v1.0.1 h1:mweAR1A6xJ3oS2pRaGiHgQ4OO8tzTaLawm8vnODuwDk=
52 | github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
53 | github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc=
54 | github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
55 | github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
56 | github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
57 | github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ=
58 | github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
59 | github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=
60 | github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=
61 | github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=
62 | github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U=
63 | github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic=
64 | github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
65 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
66 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
67 | github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw=
68 | github.com/prometheus/client_golang v0.9.3/go.mod h1:/TN21ttK/J9q6uSwhBd54HahCDft0ttaMvbicHlPoso=
69 | github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo=
70 | github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
71 | github.com/prometheus/common v0.0.0-20181113130724-41aa239b4cce/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro=
72 | github.com/prometheus/common v0.4.0/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4=
73 | github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk=
74 | github.com/prometheus/procfs v0.0.0-20190507164030-5867b95ac084/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA=
75 | github.com/prometheus/tsdb v0.7.1/go.mod h1:qhTCs0VvXwvX/y3TZrWD7rabWM+ijKTux40TwIPHuXU=
76 | github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg=
77 | github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
78 | github.com/sergi/go-diff v1.0.0 h1:Kpca3qRNrduNnOQeazBd0ysaKrUJiIuISHxogkT9RPQ=
79 | github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo=
80 | github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc=
81 | github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
82 | github.com/sirupsen/logrus v1.4.2 h1:SPIRibHv4MatM3XXNO2BJeFLZwZ2LvZgfQ5+UNI2im4=
83 | github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE=
84 | github.com/soheilhy/cmux v0.1.4/go.mod h1:IM3LyeVVIOuxMH7sFAkER9+bJ4dT7Ms6E4xg4kGIyLM=
85 | github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA=
86 | github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ=
87 | github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE=
88 | github.com/spf13/cobra v0.0.6 h1:breEStsVwemnKh2/s6gMvSdMEkwW0sK8vGStnlVBMCs=
89 | github.com/spf13/cobra v0.0.6/go.mod h1:/6GTrnGXV9HjY+aR4k0oJ5tcvakLuG6EuKReYlHNrgE=
90 | github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo=
91 | github.com/spf13/pflag v1.0.3 h1:zPAT6CGy6wXeQ7NtTnaTerfKOsV6V6F8agHXFiazDkg=
92 | github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4=
93 | github.com/spf13/viper v1.4.0/go.mod h1:PTJ7Z/lr49W6bUbkmS1V3by4uWynFiR9p7+dSq/yZzE=
94 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
95 | github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
96 | github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
97 | github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q=
98 | github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
99 | github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U=
100 | github.com/ugorji/go v1.1.4/go.mod h1:uQMGLiO92mf5W77hV/PUCpI3pbzQx3CRekS0kk+RGrc=
101 | github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU=
102 | github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77/go.mod h1:aYKd//L2LvnjZzWKhF00oedf4jCCReLcmhLdhm1A27Q=
103 | go.etcd.io/bbolt v1.3.2/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU=
104 | go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE=
105 | go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0=
106 | go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q=
107 | golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
108 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
109 | golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
110 | golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
111 | golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
112 | golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
113 | golang.org/x/net v0.0.0-20181220203305-927f97764cc3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
114 | golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
115 | golang.org/x/net v0.0.0-20190522155817-f3200d17e092/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks=
116 | golang.org/x/net v0.0.0-20200202094626-16171245cfb2 h1:CCH4IOTTfewWjGOlSp+zGcjutRKlBEZQ6wTn8ozI/nI=
117 | golang.org/x/net v0.0.0-20200202094626-16171245cfb2/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
118 | golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
119 | golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
120 | golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
121 | golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
122 | golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
123 | golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
124 | golang.org/x/sys v0.0.0-20181107165924-66b7b1311ac8/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
125 | golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
126 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
127 | golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
128 | golang.org/x/sys v0.0.0-20190626221950-04f50cda93cb h1:fgwFCsaw9buMuxNd6+DQfAuSFqbNiQZpcgJQAgJsK6k=
129 | golang.org/x/sys v0.0.0-20190626221950-04f50cda93cb/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
130 | golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg=
131 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
132 | golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
133 | golang.org/x/tools v0.0.0-20180221164845-07fd8470d635/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
134 | golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
135 | golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
136 | google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
137 | google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8 h1:Nw54tB0rB7hY/N0NQvRW8DG4Yk3Q6T9cu9RcFQDu1tc=
138 | google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
139 | google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
140 | google.golang.org/grpc v1.21.0 h1:G+97AoqBnmZIT91cLG/EkCoK9NSelj64P8bOHHNmGn0=
141 | google.golang.org/grpc v1.21.0/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM=
142 | gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw=
143 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
144 | gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
145 | gopkg.in/resty.v1 v1.12.0/go.mod h1:mDo4pnntr5jdWRML875a/NmxYqAlA73dVijT2AXvQQo=
146 | gopkg.in/src-d/go-parse-utils.v1 v1.1.2 h1:O54LA4vEIHe7U1i57Um3itXx5f7ks94M8ggJMz3vBxA=
147 | gopkg.in/src-d/go-parse-utils.v1 v1.1.2/go.mod h1:OHhBj+ncf7p/gXAcZ+Cgtt+7u1Y4YLxpL8pTlx/Xf2c=
148 | gopkg.in/yaml.v2 v2.0.0-20170812160011-eb3733d160e7/go.mod h1:JAlM8MvJe8wmxCU4Bli9HhUf9+ttbYbLASfIpnQbh74=
149 | gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
150 | gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
151 | honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
152 |
--------------------------------------------------------------------------------
/lib/options.go:
--------------------------------------------------------------------------------
1 | package lib
2 |
3 | type Option interface {
4 | apply(cfg *config) error
5 | }
6 |
7 | type config struct {
8 | alphaSortTypes bool
9 | alphaSortFuncs bool
10 | }
11 |
12 | func AlphaSortTypes() Option { return alphaSortTypes{} }
13 |
14 | type alphaSortTypes struct{}
15 |
16 | func (o alphaSortTypes) apply(cfg *config) error {
17 | cfg.alphaSortTypes = true
18 | return nil
19 | }
20 |
21 | func AlphaSortFuncs() Option { return alphaSortFuncs{} }
22 |
23 | type alphaSortFuncs struct{}
24 |
25 | func (o alphaSortFuncs) apply(cfg *config) error {
26 | cfg.alphaSortFuncs = true
27 | return nil
28 | }
29 |
30 | func parseOptions(opts []Option) (config, error) {
31 | cfg := config{}
32 | for _, opt := range opts {
33 | if err := opt.apply(&cfg); err != nil {
34 | return cfg, err
35 | }
36 | }
37 | return cfg, nil
38 | }
39 |
--------------------------------------------------------------------------------
/lib/outline.go:
--------------------------------------------------------------------------------
1 | // Package lib generates starlark documentation from go code
2 | package lib
3 |
4 | import (
5 | "bytes"
6 | "fmt"
7 | "sort"
8 | "strings"
9 | )
10 |
11 | // Docs is a sortable slice of Doc pointers
12 | type Docs []*Doc
13 |
14 | // Len implements the sort.Sortable interface
15 | func (d Docs) Len() int { return len(d) }
16 |
17 | // Less implements the sort.Sortable interface
18 | func (d Docs) Less(i, j int) bool { return d[i].Path+d[i].Name < d[j].Path+d[j].Name }
19 |
20 | // Swap implements the sort.Sortable interface
21 | func (d Docs) Swap(i, j int) { d[i], d[j] = d[j], d[i] }
22 |
23 | // Sort sorts all sortable fields in all docs, and the docs list itself
24 | func (d Docs) Sort() {
25 | for _, doc := range d {
26 | doc.Sort()
27 | }
28 | sort.Sort(d)
29 | }
30 |
31 | // Doc is is a documentation document
32 | type Doc struct {
33 | cfg config
34 | Name string
35 | Path string
36 | Description string
37 | Functions Functions
38 | Types Types
39 | }
40 |
41 | // Sort sorts all sortable fields in the document
42 | func (d *Doc) Sort() {
43 | if d.cfg.alphaSortFuncs {
44 | sort.Sort(d.Functions)
45 | }
46 | if d.cfg.alphaSortTypes {
47 | sort.Sort(d.Types)
48 | }
49 | }
50 |
51 | // Examples returns a slice of all examples defined in the document
52 | func (d *Doc) Examples() (egs []*Example) {
53 | for _, f := range d.Functions {
54 | if len(f.Examples) > 0 {
55 | egs = append(egs, f.Examples...)
56 | }
57 | }
58 |
59 | for _, t := range d.Types {
60 | for _, m := range t.Methods {
61 | if len(m.Examples) > 0 {
62 | egs = append(egs, m.Examples...)
63 | }
64 | }
65 | }
66 |
67 | return egs
68 | }
69 |
70 | // MarshalIndent writes doc to a string with depth & prefix
71 | func (d *Doc) MarshalIndent(depth int, prefix string) ([]byte, error) {
72 | buf := &bytes.Buffer{}
73 | if d.Name == "" {
74 | buf.WriteString(strings.Repeat(prefix, depth) + DocumentTok.String() + "\n")
75 | } else {
76 | buf.WriteString(fmt.Sprintf("%s%s: %s\n", strings.Repeat(prefix, depth), DocumentTok.String(), d.Name))
77 | }
78 | if d.Path != "" {
79 | depth++
80 | buf.WriteString(strings.Repeat(prefix, depth) + PathTok.String() + ": " + d.Path + "\n")
81 | depth--
82 | }
83 | if d.Description != "" {
84 | depth++
85 | buf.WriteString(strings.Repeat(prefix, depth) + d.Description + "\n")
86 | depth--
87 | }
88 | if d.Functions != nil {
89 | depth++
90 | buf.WriteString(strings.Repeat(prefix, depth) + FunctionsTok.String() + ":\n")
91 | depth++
92 | for _, fn := range d.Functions {
93 | buf.WriteString(strings.Repeat(prefix, depth) + fn.Signature + "\n")
94 | if fn.Description != "" {
95 | for _, p := range strings.Split(fn.Description, "\n") {
96 | buf.WriteString(strings.Repeat(prefix, depth+1) + p + "\n")
97 | }
98 | }
99 | }
100 | depth -= 2
101 | }
102 |
103 | if d.Types != nil {
104 | depth++
105 | buf.WriteString(strings.Repeat(prefix, depth) + TypesTok.String() + ":\n")
106 | depth++
107 | for _, t := range d.Types {
108 | buf.WriteString(strings.Repeat(prefix, depth) + t.Name + "\n")
109 | if t.Description != "" {
110 | depth++
111 | for _, p := range strings.Split(t.Description, "\n") {
112 | buf.WriteString(strings.Repeat(prefix, depth+1) + p + "\n")
113 | }
114 | depth--
115 | }
116 | if len(t.Fields) > 0 {
117 | depth++
118 | buf.WriteString(strings.Repeat(prefix, depth) + FieldsTok.String() + ":\n")
119 | depth++
120 | for _, f := range t.Fields {
121 | buf.WriteString(strings.Repeat(prefix, depth) + f.Name)
122 | if f.Type != "" {
123 | buf.WriteString(" " + f.Type)
124 | }
125 | buf.WriteString("\n")
126 | }
127 | depth -= 2
128 | }
129 | }
130 | depth -= 2
131 | }
132 |
133 | return buf.Bytes(), nil
134 | }
135 |
136 | // Functions is a sortable slice of Function pointers
137 | type Functions []*Function
138 |
139 | // Len implements the sort.Sortable interface
140 | func (f Functions) Len() int { return len(f) }
141 |
142 | // Less implements the sort.Sortable interface
143 | func (f Functions) Less(i, j int) bool { return f[i].Signature < f[j].Signature }
144 |
145 | // Swap implements the sort.Sortable interface
146 | func (f Functions) Swap(i, j int) { f[i], f[j] = f[j], f[i] }
147 |
148 | // Function documents a starlark function
149 | type Function struct {
150 | FuncName string
151 | Receiver string // should be set by parsing context
152 | Signature string
153 | Description string
154 | Params []*Param
155 | Return string
156 | Examples []*Example
157 | }
158 |
159 | // Param is an argument to a function
160 | type Param struct {
161 | Name string
162 | Type string
163 | Optional bool
164 | Description string
165 | }
166 |
167 | // Types is a sortable slice of Type pointers
168 | type Types []*Type
169 |
170 | // Len implements the sort.Sortable interface
171 | func (t Types) Len() int { return len(t) }
172 |
173 | // Less implements the sort.Sortable interface
174 | func (t Types) Less(i, j int) bool { return t[i].Name < t[j].Name }
175 |
176 | // Swap implements the sort.Sortable interface
177 | func (t Types) Swap(i, j int) { t[i], t[j] = t[j], t[i] }
178 |
179 | // Type documents a constructed type
180 | type Type struct {
181 | Name string
182 | Description string
183 | Methods Functions
184 | Fields []*Field
185 | Operators []*Operator
186 | }
187 |
188 | // Sort sorts a Type pointer's Methods
189 | func (t *Type) Sort() {
190 | sort.Sort(t.Methods)
191 | }
192 |
193 | // Field is a property of a constructed Type
194 | type Field struct {
195 | Name string
196 | Type string
197 | Description string
198 | }
199 |
200 | // Operator documents boolean operation on a constructed type
201 | type Operator struct {
202 | Opr string
203 | Description string
204 | }
205 |
206 | type Example struct {
207 | Name string
208 | Description string
209 | Code string
210 | }
211 |
--------------------------------------------------------------------------------
/lib/outline_test.go:
--------------------------------------------------------------------------------
1 | package lib
2 |
3 | import (
4 | "strings"
5 | "testing"
6 |
7 | "github.com/google/go-cmp/cmp"
8 | )
9 |
10 | const unsorted = `
11 | outline: twoFuncs
12 | path: twoFuncs
13 | functions:
14 | difference(a,b int) int
15 | sum(a,b int) int
16 | add two things together
17 |
18 | outline: time
19 | functions:
20 | duration(string) duration
21 | parse a duration
22 | time(string, format=..., location=...) time
23 | parse a time
24 | now() time
25 | new time instance set to current time
26 | implementations are able to make this a constant
27 | zero() time
28 | a constant
29 |
30 | types:
31 | duration
32 | a period of time
33 | methods:
34 | add(d duration) int
35 | params:
36 | d duration
37 | fields:
38 | hours float
39 | minutes float
40 | nanoseconds int
41 | seconds float
42 | operators:
43 | duration - time = duration
44 | duration + time = time
45 | duration == duration = boolean
46 | duration < duration = booleans
47 | time
48 | fields:
49 | operators:
50 | time == time = boolean
51 | time < time = boolean`
52 |
53 | func TestSort(t *testing.T) {
54 | docs, err := Parse(strings.NewReader(unsorted), AlphaSortFuncs(), AlphaSortTypes())
55 | if err != nil {
56 | t.Fatal(err)
57 | }
58 |
59 | docs.Sort()
60 | data, err := docs[0].MarshalIndent(0, "\t")
61 | if err != nil {
62 | t.Fatal(err)
63 | }
64 | if diff := cmp.Diff(expectA, string(data)); diff != "" {
65 | t.Errorf("serialized output mismatch (-want +got):\n%s", diff)
66 | }
67 |
68 | data, err = docs[1].MarshalIndent(0, "\t")
69 | if err != nil {
70 | t.Fatal(err)
71 | }
72 | t.Log(string(data))
73 | if diff := cmp.Diff(expectB, string(data)); diff != "" {
74 | t.Errorf("serialized output mismatch (-want +got):\n%s", diff)
75 | }
76 | }
77 |
78 | const expectA = `outline: time
79 | functions:
80 | duration(string) duration
81 | parse a duration
82 | now() time
83 | new time instance set to current time implementations are able to make this a constant
84 | time(string, format=..., location=...) time
85 | parse a time
86 | zero() time
87 | a constant
88 | types:
89 | duration
90 | a period of time
91 | fields:
92 | hours float
93 | minutes float
94 | nanoseconds int
95 | seconds float
96 | time
97 | `
98 |
99 | const expectB = `outline: twoFuncs
100 | path: twoFuncs
101 | functions:
102 | difference(a,b int) int
103 | sum(a,b int) int
104 | add two things together
105 | `
106 |
--------------------------------------------------------------------------------
/lib/parser.go:
--------------------------------------------------------------------------------
1 | package lib
2 |
3 | import (
4 | "fmt"
5 | "io"
6 | "strings"
7 | )
8 |
9 | // ParseFirst consumes a reader of outline data, creating and returning the first outline document
10 | // it encounters. ParseFirst consumes the entire reader
11 | // TODO(b5): don't consume the entire reader. return after the first complete document
12 | func ParseFirst(r io.Reader, opts ...Option) (doc *Doc, err error) {
13 | docs, err := Parse(r, opts...)
14 | if err != nil {
15 | return nil, err
16 | }
17 |
18 | if len(docs) > 0 {
19 | return docs[0], nil
20 | }
21 | return nil, nil
22 | }
23 |
24 | // Parse consumes a reader of data that contains zero or more outlines
25 | // creating and returning any documents it finds
26 | func Parse(r io.Reader, opts ...Option) (docs Docs, err error) {
27 | cfg, err := parseOptions(opts)
28 | if err != nil {
29 | return docs, err
30 | }
31 | p := parser{s: newScanner(r), cfg: cfg}
32 | for {
33 | doc, err := p.read()
34 | if doc == nil && err == nil {
35 | return docs, nil
36 | }
37 | doc.Sort()
38 | docs = append(docs, doc)
39 | if err != nil {
40 | if err == io.EOF {
41 | docs = append(docs, doc)
42 | return docs, nil
43 | }
44 | return nil, err
45 | }
46 | }
47 | }
48 |
49 | // parser is a state machine for serializing a documentation struct from a byte stream
50 | type parser struct {
51 | s *scanner
52 | cfg config
53 |
54 | buf struct {
55 | tok Token
56 | line, indent int
57 | n int
58 | }
59 |
60 | line int
61 | indent int // indentation level of current line
62 | }
63 |
64 | func (p *parser) scan() (tok Token) {
65 | if p.buf.n > 0 {
66 | tok = p.buf.tok
67 | p.indent = p.buf.indent
68 | p.line = p.buf.line
69 | p.buf.n = 0
70 | return
71 | }
72 |
73 | defer func() {
74 | p.buf.tok = tok
75 | p.buf.line = p.line
76 | p.buf.indent = p.indent
77 | }()
78 |
79 | for {
80 | tok = p.s.Scan()
81 | switch tok.Type {
82 | case NewlineTok:
83 | p.indent = 0
84 | p.line++
85 | case IndentTok:
86 | p.indent++
87 | case eofTok:
88 | return
89 | default:
90 | return
91 | }
92 | }
93 | }
94 |
95 | func (p *parser) unscan() {
96 | p.buf.n = 1
97 | }
98 |
99 | func (p *parser) read() (doc *Doc, err error) {
100 | for {
101 | tok := p.scan()
102 | switch tok.Type {
103 | case DocumentTok:
104 | doc, err = p.readDocument(p.indent)
105 | return
106 | case eofTok:
107 | return
108 | }
109 | }
110 | }
111 |
112 | func (p *parser) readDocument(baseIndent int) (doc *Doc, err error) {
113 | doc = &Doc{cfg: p.cfg}
114 | tok := p.scan()
115 | if tok.Type == TextTok {
116 | doc.Name = tok.Text
117 | } else {
118 | p.unscan()
119 | }
120 |
121 | for {
122 | tok := p.scan()
123 | if p.indent < baseIndent {
124 | p.unscan()
125 | return
126 | }
127 |
128 | switch tok.Type {
129 | case DocumentTok:
130 | if p.indent == baseIndent {
131 | p.unscan()
132 | return
133 | }
134 |
135 | err = fmt.Errorf("outline documents cannot be nested")
136 | return
137 | case PathTok:
138 | if doc.Path, err = p.readMultilineText(p.indent); err != nil {
139 | return
140 | }
141 | case FunctionsTok:
142 | if doc.Functions, err = p.readFunctions(doc.Name, p.indent); err != nil {
143 | return
144 | }
145 | case TypesTok:
146 | if doc.Types, err = p.readTypes(p.indent); err != nil {
147 | return
148 | }
149 | case TextTok:
150 | // only read descriptions when indented
151 | if p.indent > baseIndent {
152 | p.unscan()
153 | text, err := p.readMultilineText(p.indent)
154 | if err != nil {
155 | return doc, err
156 | }
157 | doc.Description = text
158 | }
159 | default:
160 | p.unscan()
161 | return
162 | }
163 | }
164 | }
165 |
166 | func (p *parser) readFunctions(receiver string, baseIndent int) (funcs []*Function, err error) {
167 | for {
168 | var fn *Function
169 | if fn, err = p.readFunction(receiver, baseIndent+1); err != nil || fn == nil {
170 | return
171 | }
172 | funcs = append(funcs, fn)
173 | }
174 | }
175 |
176 | func (p *parser) readFunction(receiver string, baseIndent int) (fn *Function, err error) {
177 | // read signature
178 | tok := p.scan()
179 | if p.indent < baseIndent || tok.Type != TextTok {
180 | p.unscan()
181 | return
182 | }
183 |
184 | funcName := ""
185 | pos := strings.Index(tok.Text, "(")
186 | if pos != -1 {
187 | funcName = tok.Text[:pos]
188 | }
189 |
190 | fn = &Function{FuncName: funcName, Receiver: receiver, Signature: tok.Text}
191 | for {
192 | tok := p.scan()
193 | if p.indent <= baseIndent {
194 | p.unscan()
195 | return
196 | }
197 |
198 | switch tok.Type {
199 | case ParamsTok:
200 | if fn.Params, err = p.readParams(p.indent); err != nil {
201 | return
202 | }
203 | case ReturnTok:
204 | if fn.Return, err = p.readMultilineText(p.indent); err != nil {
205 | return
206 | }
207 | case ExamplesTok:
208 | if fn.Examples, err = p.readExamples(p.indent); err != nil {
209 | return fn, err
210 | }
211 | case TextTok:
212 | p.unscan()
213 | if fn.Description, err = p.readTextBlock(p.indent); err != nil {
214 | return
215 | }
216 | default:
217 | p.unscan()
218 | return
219 | }
220 | }
221 | }
222 |
223 | func (p *parser) readParams(baseIndent int) (params []*Param, err error) {
224 | for {
225 | var param *Param
226 | if param, err = p.readParam(baseIndent + 1); err != nil || param == nil {
227 | return
228 | }
229 | params = append(params, param)
230 | }
231 | }
232 |
233 | func (p *parser) readParam(baseIndent int) (param *Param, err error) {
234 | tok := p.scan()
235 | if p.indent < baseIndent || tok.Type != TextTok {
236 | p.unscan()
237 | return
238 | }
239 |
240 | spl := strings.Split(tok.Text, " ")
241 | switch len(spl) {
242 | default:
243 | param = &Param{Name: tok.Text}
244 | case 2:
245 | param = &Param{
246 | Name: spl[0],
247 | Type: spl[1],
248 | }
249 | }
250 |
251 | param.Description, err = p.readMultilineText(baseIndent + 1)
252 | return
253 | }
254 |
255 | func (p *parser) readTypes(baseIndent int) (types []*Type, err error) {
256 | for {
257 | var t *Type
258 | if t, err = p.readType(baseIndent + 1); err != nil || t == nil {
259 | return
260 | }
261 | types = append(types, t)
262 | }
263 | }
264 |
265 | func (p *parser) readType(baseIndent int) (t *Type, err error) {
266 | // read signature
267 | tok := p.scan()
268 | if p.indent < baseIndent || tok.Type != TextTok {
269 | p.unscan()
270 | return
271 | }
272 |
273 | t = &Type{Name: tok.Text}
274 |
275 | for {
276 | tok = p.scan()
277 | if p.indent <= baseIndent {
278 | p.unscan()
279 | return
280 | }
281 |
282 | switch tok.Type {
283 | case FieldsTok:
284 | if t.Fields, err = p.readFields(p.indent); err != nil {
285 | return
286 | }
287 | case MethodsTok, FunctionsTok:
288 | if t.Methods, err = p.readFunctions(t.Name, p.indent); err != nil {
289 | return
290 | }
291 | case OperatorsTok:
292 | if t.Operators, err = p.readOperators(p.indent); err != nil {
293 | return
294 | }
295 | case TextTok:
296 | p.unscan()
297 | if t.Description, err = p.readTextBlock(p.indent); err != nil {
298 | return
299 | }
300 | default:
301 | err = fmt.Errorf("unexpexted token: %s: %s %d %d", tok.Type, tok.Text, p.indent, baseIndent)
302 | return
303 | }
304 | }
305 | }
306 |
307 | func (p *parser) readFields(baseIndent int) (fields []*Field, err error) {
308 | for {
309 | var f *Field
310 | if f, err = p.readField(baseIndent + 1); err != nil || f == nil {
311 | return
312 | }
313 | fields = append(fields, f)
314 | }
315 | }
316 |
317 | func (p *parser) readField(baseIndent int) (field *Field, err error) {
318 | tok := p.scan()
319 | if p.indent < baseIndent || tok.Type != TextTok {
320 | p.unscan()
321 | return
322 | }
323 |
324 | spl := strings.Split(tok.Text, " ")
325 | switch len(spl) {
326 | case 1:
327 | field = &Field{Name: tok.Text}
328 | case 2:
329 | field = &Field{
330 | Name: spl[0],
331 | Type: spl[1],
332 | }
333 | }
334 |
335 | field.Description, err = p.readMultilineText(baseIndent + 1)
336 | return
337 | }
338 |
339 | func (p *parser) readOperators(baseIndent int) (ops []*Operator, err error) {
340 | for {
341 | var o *Operator
342 | if o, err = p.readOperator(baseIndent + 1); err != nil || o == nil {
343 | return
344 | }
345 | ops = append(ops, o)
346 | }
347 | }
348 |
349 | func (p *parser) readOperator(baseIndent int) (op *Operator, err error) {
350 | tok := p.scan()
351 | if p.indent < baseIndent || tok.Type != TextTok {
352 | p.unscan()
353 | return
354 | }
355 | op = &Operator{Opr: tok.Text}
356 | return
357 | }
358 |
359 | func (p *parser) readMultilineText(baseIndent int) (str string, err error) {
360 | for {
361 | tok := p.scan()
362 | if p.indent < baseIndent || tok.Type != TextTok {
363 | p.unscan()
364 | return
365 | }
366 |
367 | if str == "" {
368 | str = tok.Text
369 | } else {
370 | str += " " + tok.Text
371 | }
372 | }
373 | }
374 |
375 | func (p *parser) readTextBlock(baseIndent int) (str string, err error) {
376 | for {
377 | tok := p.scan()
378 | if p.indent < baseIndent || tok.Type != TextTok {
379 | p.unscan()
380 | return
381 | }
382 |
383 | if str == "" {
384 | str = tok.Text
385 | } else {
386 | str += "\n" + tok.Text
387 | }
388 | }
389 | }
390 |
391 | func (p *parser) readExamples(baseIndent int) (egs []*Example, err error) {
392 | for {
393 | var eg *Example
394 | if eg, err = p.readExample(baseIndent + 1); err != nil || eg == nil {
395 | return egs, err
396 | }
397 | egs = append(egs, eg)
398 | }
399 | }
400 |
401 | func (p *parser) readExample(baseIndent int) (eg *Example, err error) {
402 | // read name
403 | tok := p.scan()
404 | if p.indent < baseIndent || tok.Type != TextTok {
405 | p.unscan()
406 | return nil, nil
407 | }
408 |
409 | eg = &Example{Name: tok.Text}
410 | for {
411 | tok := p.scan()
412 | if p.indent <= baseIndent {
413 | p.unscan()
414 | return
415 | }
416 |
417 | switch tok.Type {
418 | case CodeTok:
419 | if eg.Code, err = p.readTextBlock(p.indent); err != nil {
420 | return eg, err
421 | }
422 | case TextTok:
423 | p.unscan()
424 | if eg.Description, err = p.readTextBlock(p.indent); err != nil {
425 | return eg, err
426 | }
427 | default:
428 | p.unscan()
429 | return eg, nil
430 | }
431 | }
432 | }
433 |
434 | func (p *parser) errorf(format string, args ...interface{}) error {
435 | return fmt.Errorf(format, args...)
436 | }
437 |
--------------------------------------------------------------------------------
/lib/parser_test.go:
--------------------------------------------------------------------------------
1 | package lib
2 |
3 | import (
4 | "bytes"
5 | "testing"
6 |
7 | "github.com/google/go-cmp/cmp"
8 | "github.com/google/go-cmp/cmp/cmpopts"
9 | "github.com/sergi/go-diff/diffmatchpatch"
10 | )
11 |
12 | var differ = diffmatchpatch.New()
13 |
14 | const twoFuncsTabs = `outline: twoFuncs
15 | path: twoFuncs
16 | functions:
17 | difference(a,b int) int
18 | sum(a,b int) int
19 | add two things together`
20 |
21 | const twoFuncsSpaces = `outline: twoFuncs
22 | path: twoFuncs
23 | functions:
24 | difference(a,b int) int
25 | sum(a,b int) int
26 | add two things together`
27 |
28 | var twoFuncs = &Doc{
29 | Name: "twoFuncs",
30 | Path: "twoFuncs",
31 | Functions: []*Function{
32 | {FuncName: "difference",
33 | Signature: "difference(a,b int) int",
34 | Receiver: "twoFuncs",
35 | },
36 | {
37 | FuncName: "sum",
38 | Signature: "sum(a,b int) int",
39 | Description: "add two things together",
40 | Receiver: "twoFuncs",
41 | },
42 | },
43 | }
44 |
45 | const timeSpaces = `here's some leading gak that shouldn't get read into the doc
46 |
47 | outline: time
48 | functions:
49 | duration(string) duration
50 | parse a duration
51 | time(string, format=..., location=...) time
52 | parse a time
53 | now() time
54 | new time instance set to current time
55 | implementations are able to make this a constant
56 | zero() time
57 | a constant
58 |
59 | types:
60 | duration
61 | a period of time
62 | methods:
63 | add(d duration) int
64 | params:
65 | d duration
66 | fields:
67 | hours float
68 | number of hours starting at zero
69 | minutes float
70 | nanoseconds int
71 | seconds
72 | number of seconds starting at zero
73 | operators:
74 | duration - time = duration
75 | duration + time = time
76 | duration == duration = boolean
77 | duration < duration = booleans
78 | time
79 | fields:
80 | operators:
81 | time == time = boolean
82 | time < time = boolean`
83 |
84 | var time = &Doc{
85 | Name: "time",
86 | Functions: []*Function{
87 | {FuncName: "duration",
88 | Signature: "duration(string) duration",
89 | Description: "parse a duration",
90 | Receiver: "time"},
91 | {FuncName: "time",
92 | Signature: "time(string, format=..., location=...) time",
93 | Description: "parse a time",
94 | Receiver: "time"},
95 | {FuncName: "now",
96 | Signature: "now() time",
97 | Description: "new time instance set to current time implementations are able to make this a constant",
98 | Receiver: "time"},
99 | {FuncName: "zero",
100 | Signature: "zero() time",
101 | Description: "a constant",
102 | Receiver: "time"},
103 | },
104 | Types: []*Type{
105 | {Name: "duration",
106 | Description: "a period of time",
107 | Methods: []*Function{
108 | {FuncName: "add",
109 | Receiver: "duration",
110 | Signature: "add(d duration) int",
111 | Params: []*Param{
112 | {Name: "d", Type: "duration"},
113 | },
114 | },
115 | },
116 | Fields: []*Field{
117 | {Name: "hours", Type: "float", Description: "number of hours starting at zero"},
118 | {Name: "minutes", Type: "float"},
119 | {Name: "nanoseconds", Type: "int"},
120 | {Name: "seconds", Description: "number of seconds starting at zero"},
121 | },
122 | Operators: []*Operator{
123 | {Opr: "duration - time = duration"},
124 | {Opr: "duration + time = time"},
125 | {Opr: "duration == duration = boolean"},
126 | {Opr: "duration < duration = booleans"},
127 | },
128 | },
129 | {Name: "time",
130 | Operators: []*Operator{
131 | {Opr: "time == time = boolean"},
132 | {Opr: "time < time = boolean"},
133 | },
134 | },
135 | },
136 | }
137 |
138 | const docWithDescriptionTabs = `outline: doc
139 | this is a document description.
140 | It's written across two lines
141 | functions:
142 | sum(a int, b int) int`
143 |
144 | var docWithDescription = &Doc{
145 | Name: "doc",
146 | Description: "this is a document description. It's written across two lines",
147 | Functions: []*Function{
148 | {FuncName: "sum", Signature: "sum(a int, b int) int", Receiver: "doc"},
149 | },
150 | }
151 |
152 | const huhSpaces = `outline: huh
153 | huh is a package that has no meaning or purpose
154 | functions:
155 | foo(bar string) int
156 | foo a bar, which is to to a bar and remove 'd' from 'food'
157 | params:
158 | bar string
159 | the name of a bar
160 | date() date
161 | make a date`
162 |
163 | var huh = &Doc{
164 | Name: "huh",
165 | Description: "huh is a package that has no meaning or purpose",
166 | Functions: []*Function{
167 | {FuncName: "foo",
168 | Receiver: "huh",
169 | Signature: "foo(bar string) int",
170 | Description: "foo a bar, which is to to a bar and remove 'd' from 'food'",
171 | Params: []*Param{
172 | {Name: "bar", Type: "string", Description: "the name of a bar"},
173 | },
174 | },
175 | {FuncName: "date",
176 | Signature: "date() date",
177 | Description: "make a date",
178 | Receiver: "huh"},
179 | },
180 | }
181 |
182 | const dataframeTabs = `
183 | outline: dataframe
184 | dataframe is a 2d columnar data structure that provides analysis and manipulation tools
185 | path: dataframe
186 | functions:
187 | DataFrame(data, index, columns, dtype) DataFrame
188 | constructs a DataFrame
189 | params:
190 | data any
191 | data for the content of the DataFrame
192 | index
193 | index for the rows of the DataFrame
194 | `
195 |
196 | var dataframe = &Doc{
197 | Name: "dataframe",
198 | Description: "dataframe is a 2d columnar data structure that provides analysis and manipulation tools",
199 | Path: "dataframe",
200 | Functions: []*Function{
201 | {FuncName: "DataFrame",
202 | Signature: "DataFrame(data, index, columns, dtype) DataFrame",
203 | Description: "constructs a DataFrame",
204 | Receiver: "dataframe",
205 | Params: []*Param{
206 | {Name: "data", Type: "any", Description: "data for the content of the DataFrame"},
207 | {Name: "index", Type: "", Description: "index for the rows of the DataFrame"},
208 | },
209 | },
210 | },
211 | }
212 |
213 | const ignoreOuterText = `
214 | /*Package time provides time-related constants and functions. The time module
215 | was upstreamed from starlib into go-Starlark. This package exists to add
216 | documentation. The API is locked to strictly match the Starlark module.
217 | Users are encouraged to import the time package directly via:
218 | go.starlark.net/lib/time
219 |
220 | For source code see
221 | https://github.com/google/starlark-go/tree/master/lib/time
222 |
223 | outline: time
224 | a time package
225 |
226 | */
227 | package time
228 | import "go.starlark.net/lib/time"
229 | `
230 |
231 | var ignoreOuter = &Doc{
232 | Name: "time",
233 | Description: "a time package",
234 | }
235 |
236 | const withExamplesText = `outline: http
237 | functions:
238 | get(url, headers?): Response
239 | params:
240 | url string
241 | headers dict
242 | examples:
243 | simple
244 | do a simple URL fetch
245 | code:
246 | res = http.get("https://example.com")
247 | print(res.status_code) # Output: 200
248 | with headers
249 | fetch, but send custom headers
250 | code:
251 | res = http.get("https://example.com", { "UserAgent": "myAgent" })
252 | print(res.status_code) # Output: 200
253 | `
254 |
255 | var withExamples = &Doc{
256 | Name: "http",
257 | Functions: []*Function{
258 | {FuncName: "get",
259 | Receiver: "http",
260 | Signature: "get(url, headers?): Response",
261 | Params: []*Param{
262 | {Name: "url", Type: "string"},
263 | {Name: "headers", Type: "dict"},
264 | },
265 | Examples: []*Example{
266 | {Name: "simple", Description: "do a simple URL fetch", Code: "res = http.get(\"https://example.com\")\nprint(res.status_code) # Output: 200"},
267 | {Name: "with headers", Description: "fetch, but send custom headers", Code: "res = http.get(\"https://example.com\", { \"UserAgent\": \"myAgent\" })\nprint(res.status_code) # Output: 200"},
268 | },
269 | },
270 | },
271 | }
272 |
273 | func TestParse(t *testing.T) {
274 | cases := []struct {
275 | name string
276 | in string
277 | exp *Doc
278 | err string
279 | }{
280 | {"basic", "outline: foo\n", &Doc{Name: "foo"}, ""},
281 | {"two_funcs_tabs", twoFuncsTabs, twoFuncs, ""},
282 | {"two_funcs_spaces", twoFuncsSpaces, twoFuncs, ""},
283 | {"time", timeSpaces, time, ""},
284 | {"doc_with_description", docWithDescriptionTabs, docWithDescription, ""},
285 | {"huh", huhSpaces, huh, ""},
286 | {"dataframe", dataframeTabs, dataframe, ""},
287 | {"leading_and_trailing", ignoreOuterText, ignoreOuter, ""},
288 | {"examples", withExamplesText, withExamples, ""},
289 | }
290 |
291 | for _, c := range cases {
292 | t.Run(c.name, func(t *testing.T) {
293 | b := bytes.NewBufferString(c.in)
294 | got, err := ParseFirst(b)
295 | if !(err == nil && c.err == "" || err != nil && err.Error() == c.err) {
296 | t.Fatalf("error mismatch. expected: %s, got: %s", c.err, err)
297 | }
298 |
299 | if got == nil {
300 | t.Fatal("doc returned nil")
301 | }
302 |
303 | if diff := cmp.Diff(c.exp, got, cmpopts.IgnoreUnexported(Doc{})); diff != "" {
304 | t.Errorf("result mismatch (-want +got):\n%s", diff)
305 | }
306 |
307 | gotB, _ := got.MarshalIndent(0, " ")
308 | expB, _ := c.exp.MarshalIndent(0, " ")
309 | if diff := cmp.Diff(string(expB), string(gotB)); diff != "" {
310 | t.Errorf("result mismatch (-want +got):\n%s", diff)
311 | }
312 | })
313 | }
314 | }
315 |
--------------------------------------------------------------------------------
/lib/scanner.go:
--------------------------------------------------------------------------------
1 | package lib
2 |
3 | import (
4 | "bufio"
5 | "io"
6 | "strings"
7 | )
8 |
9 | // newScanner allocates a scanner from an io.Reader
10 | func newScanner(r io.Reader) *scanner {
11 | return &scanner{r: bufio.NewReader(r)}
12 | }
13 |
14 | // scanner tokenizes an input stream
15 | // TODO(b5): set position properly for errors
16 | type scanner struct {
17 | r *bufio.Reader
18 |
19 | // scanning state
20 | tok Token
21 | text strings.Builder
22 | line, col, offset int
23 | readNewline bool
24 | err error
25 | }
26 |
27 | // Scan reads one token from the input stream
28 | func (s *scanner) Scan() Token {
29 | inText := false
30 | s.text.Reset()
31 |
32 | if s.readNewline {
33 | s.readNewline = false
34 | return s.newTok(NewlineTok)
35 | }
36 |
37 | for {
38 | ch := s.read()
39 |
40 | switch ch {
41 | case eof:
42 | if inText {
43 | s.readNewline = true
44 | return s.newTok(TextTok)
45 | }
46 | return s.newTok(eofTok)
47 | // ignore line feeds
48 | case '\r':
49 | continue
50 | case '\n':
51 | s.line++
52 | if inText {
53 | s.readNewline = true
54 | return s.newTok(TextTok)
55 | }
56 | return s.newTok(NewlineTok)
57 | case '\t':
58 | return s.newTok(IndentTok)
59 | case ':':
60 | switch s.text.String() {
61 | case "path":
62 | return s.newTok(PathTok)
63 | case "outline":
64 | return s.newTok(DocumentTok)
65 | case "functions":
66 | return s.newTok(FunctionsTok)
67 | case "methods":
68 | return s.newTok(MethodsTok)
69 | case "types":
70 | return s.newTok(TypesTok)
71 | case "fields":
72 | return s.newTok(FieldsTok)
73 | case "operators":
74 | return s.newTok(OperatorsTok)
75 | case "params":
76 | return s.newTok(ParamsTok)
77 | case "return":
78 | return s.newTok(ReturnTok)
79 | case "code":
80 | return s.newTok(CodeTok)
81 | case "examples":
82 | return s.newTok(ExamplesTok)
83 | default:
84 | s.text.WriteRune(':')
85 | }
86 | case ' ':
87 | s.text.WriteRune(' ')
88 | if s.text.String() == " " {
89 | return s.newTok(IndentTok)
90 | }
91 | default:
92 | s.text.WriteRune(ch)
93 | if !inText {
94 | inText = true
95 | }
96 | }
97 | }
98 | }
99 |
100 | // read reads the next rune from the buffered reader.
101 | // Returns the rune(0) if an error occurs (or io.EOF is returned).
102 | func (s *scanner) read() rune {
103 | ch, _, err := s.r.ReadRune()
104 | if err != nil {
105 | return eof
106 | }
107 | return ch
108 | }
109 |
110 | // newTok creates a new token from current scanner state
111 | func (s *scanner) newTok(t TokenType) Token {
112 | return Token{
113 | Type: t,
114 | Text: strings.TrimSpace(s.text.String()),
115 | Pos: Position{Line: s.line, Col: s.col, Offset: s.offset},
116 | }
117 | }
118 |
119 | // eof represents a marker rune for the end of the reader.
120 | var eof = rune(0)
121 |
--------------------------------------------------------------------------------
/lib/token.go:
--------------------------------------------------------------------------------
1 | package lib
2 |
3 | // Position of a token within the scan stream
4 | type Position struct {
5 | Line, Col, Offset int
6 | }
7 |
8 | // Token is a recognized token from the outlineline lexicon
9 | type Token struct {
10 | Type TokenType
11 | Pos Position
12 | Text string
13 | }
14 |
15 | // String implements the stringer interface for token
16 | func (t Token) String() string {
17 | return t.Text
18 | }
19 |
20 | // TokenType enumerates the different types of tokens
21 | type TokenType int
22 |
23 | const (
24 | // IllegalTok is the default for unrecognized tokens
25 | IllegalTok TokenType = iota
26 | eofTok
27 |
28 | // LiteralBegin marks the beginning of literal tokens in the token enumeration
29 | LiteralBegin
30 | // IndentTok is a tab character "\t" or two consecutive spaces" "
31 | IndentTok
32 | // NewlineTok is a line break
33 | NewlineTok
34 | // TextTok is a token for arbitrary text
35 | TextTok
36 | // LiteralEnd marks the end of literal tokens in the token enumeration
37 | LiteralEnd
38 |
39 | // KeywordBegin marks the end of keyword tokens in the token enumeration
40 | KeywordBegin
41 | // CodeTok is the "code:" token
42 | CodeTok
43 | // DocumentTok is the "document:" token
44 | DocumentTok
45 | // ExamplesTok is the "examples:" token
46 | ExamplesTok
47 | // PathTok is the "path:" token
48 | PathTok
49 | // FunctionsTok is the "functions:" token
50 | FunctionsTok
51 | // ParamsTok is the "params:" token
52 | ParamsTok
53 | // ReturnTok is the "return:" token
54 | ReturnTok
55 | // TypesTok is the "types:" token
56 | TypesTok
57 | // FieldsTok is the "fields:" token
58 | FieldsTok
59 | // MethodsTok is the "methods:" token
60 | MethodsTok
61 | // OperatorsTok is the "operators:" token
62 | OperatorsTok
63 | // KeywordEnd marks the end of keyword tokens in the token enumeration
64 | KeywordEnd
65 | )
66 |
67 | func (t TokenType) String() string {
68 | switch t {
69 | case IndentTok:
70 | return "tab"
71 | case NewlineTok:
72 | return "newline"
73 | case TextTok:
74 | return "text"
75 | case DocumentTok:
76 | return "outline"
77 | case PathTok:
78 | return "path"
79 | case MethodsTok:
80 | return "methods"
81 | case ExamplesTok:
82 | return "examples"
83 | case CodeTok:
84 | return "code"
85 | case FunctionsTok:
86 | return "functions"
87 | case TypesTok:
88 | return "types"
89 | case FieldsTok:
90 | return "fields"
91 | case OperatorsTok:
92 | return "operators"
93 | case ParamsTok:
94 | return "params"
95 | case ReturnTok:
96 | return "return"
97 | default:
98 | return "unknown"
99 | }
100 | }
101 |
--------------------------------------------------------------------------------
/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "github.com/b5/outline/cmd"
5 | )
6 |
7 | func main() {
8 | cmd.Execute()
9 | }
10 |
--------------------------------------------------------------------------------
/readme.md:
--------------------------------------------------------------------------------
1 | # outline
2 |
3 | I spend a lot of time sketching out software packages. These sketches are often programming-language agnostic and written in lots of weird places (mainly my own notes, github issues, documentation, and source code). A while back @alandonovan posted what I felt is a clear, concise definition of a package: https://github.com/google/starlark-go/issues/19#issuecomment-336013683. Since reading that package outline I've started to think and write in something like that format.
4 |
5 | While working on a standard library for starlark I ran into the issue of needing a way to embed documentation about a package that's written in go, but targets another language (starlark). I figure with a little rigor it'd be easiest to formalize my preferred outlining format in a way that it can be embedded in a comment, riding with the source code itself. Using the "template" commands we can generate documentation markdown for our website
6 |
7 | ### Project Status
8 | use-at-your-own-risk alpha. I'm working on this with Qri's [rfc](https://github.com/qri-io/rfcs) and [starlib](https://github.com/qri-io/starlib) projects as concrete use-cases to drive development.
9 |
10 | ### Example
11 | ```shell
12 | go install github.com/b5/outline
13 | ```
14 |
15 | make a file: `outline.txt`:
16 | ```
17 | outline: geo
18 | geo defines geographic operations
19 |
20 | functions:
21 | point(lat,lng)
22 | Point constructor takes an x(longitude) and y(latitude) value and returns a Point object
23 | params
24 | lat float
25 | lng float
26 | within(geomA,geomB)
27 | Returns True if geometry A is entirely contained by geometry B
28 | params:
29 | geomA [point,line,polygon]
30 | maybe-inner geometry
31 | geomB [point,line,polygon]
32 | maybe-outer geometery
33 | intersects(geomA,geomB)
34 | Similar to within but part of geometry B can lie outside of geometry A and it will still return True
35 |
36 | types:
37 | point
38 | methods:
39 | buffer(x int)
40 | Generates a buffered region of x units around a point
41 | distance(p2 point)
42 | Euclidian Distance
43 | distanceGeodesic(p2 point)
44 | Distance on the surface of a sphere with the same radius as Earth
45 | KNN()
46 | Given a target point T and an array of other points, return the K nearest points to T
47 | greatCircle(p2 point)
48 | Returns the great circle line segment to point 2
49 | line
50 | methods:
51 | buffer()
52 | length()
53 | geodesicLength()
54 | polygon
55 | ```
56 |
57 | Currently the only thing you can do out-of-the box with outline is parse documents & template them:
58 | ```
59 | outline template ./outline.txt
60 | ```
61 |
62 | This will by default spit out a markdown version of your outline. dope. The real upside of this format is it's designed to survive in weird places. try running the same command against this readme file:
63 | ```
64 | git clone git@github.com:b5/outline.git
65 | cd outline
66 | outline template ./readme.md
67 | ```
68 |
69 | And you'll get the same result. Lovely! You can supply custom templates with the `template` flag. The markdown template is [here](/cmd/template.go).
70 |
71 |
72 | ### Maybe someday...
73 | * `outline fmt` <- "golint" style formatter
74 | * `outline .` <- validate any found outline documents in a given filepath
75 | * `outline require .` <- a command that requires at least one outline document present in the given filepath, useful for integration with CI
76 | * `outline starter --language python .` <- generate starter stub code for a given package based on templates
--------------------------------------------------------------------------------