nitpackage: generate and check man pages
[nit.git] / src / nitpackage.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 # Helpful features about packages
16 module nitpackage
17
18 import frontend
19 import doc::commands::commands_main
20
21 redef class ToolContext
22 # --expand
23 var opt_expand = new OptionBool("Move singleton packages to their own directory", "--expand")
24
25 # --check-ini
26 var opt_check_ini = new OptionBool("Check package.ini files", "--check-ini")
27
28 # --gen-ini
29 var opt_gen_ini = new OptionBool("Generate package.ini files", "--gen-ini")
30
31 # --force
32 var opt_force = new OptionBool("Force update of existing files", "-f", "--force")
33
34 # --check-makefile
35 var opt_check_makefile = new OptionBool("Check Makefile files", "--check-makefile")
36
37 # --gen-makefile
38 var opt_gen_makefile = new OptionBool("Generate Makefile files", "--gen-makefile")
39
40 # nitpackage phase
41 var nitpackage_phase: Phase = new NitPackagePhase(self, null)
42
43 # --check-man
44 var opt_check_man = new OptionBool("Check manpages files", "--check-man")
45
46 # --gen-man
47 var opt_gen_man = new OptionBool("Generate manpages files", "--gen-man")
48
49 redef init do
50 super
51 option_context.add_option(opt_expand, opt_force)
52 option_context.add_option(opt_check_ini, opt_gen_ini)
53 option_context.add_option(opt_check_makefile, opt_gen_makefile)
54 option_context.add_option(opt_check_man, opt_gen_man)
55 end
56 end
57
58 private class NitPackagePhase
59 super Phase
60
61 redef fun process_mainmodule(mainmodule, mmodules) do
62 var mpackages = extract_mpackages(mmodules)
63 for mpackage in mpackages do
64
65 # Fictive and buggy packages are ignored
66 if not mpackage.has_source then
67 toolcontext.warning(mpackage.location, "no-source",
68 "Warning: `{mpackage}` has no source file")
69 continue
70 end
71
72 # Check package INI files
73 if toolcontext.opt_check_ini.value then
74 mpackage.check_ini(toolcontext)
75 continue
76 end
77
78 # Check package Makefiles
79 if toolcontext.opt_check_makefile.value then
80 mpackage.check_makefile(toolcontext, mainmodule)
81 continue
82 end
83
84 # Check manpages
85 if toolcontext.opt_check_man.value then
86 mpackage.check_man(toolcontext, mainmodule)
87 continue
88 end
89
90 # Expand packages
91 if toolcontext.opt_expand.value and not mpackage.is_expanded then
92 var path = mpackage.expand
93 toolcontext.info("{mpackage} moved to {path}", 0)
94 end
95 if not mpackage.is_expanded then
96 toolcontext.warning(mpackage.location, "no-dir",
97 "Warning: `{mpackage}` has no package directory")
98 continue
99 end
100
101 # Create INI file
102 if toolcontext.opt_gen_ini.value then
103 if not mpackage.has_ini or toolcontext.opt_force.value then
104 var path = mpackage.gen_ini
105 toolcontext.info("generated INI file `{path}`", 0)
106 end
107 end
108
109 # Create Makefile
110 if toolcontext.opt_gen_makefile.value then
111 if not mpackage.has_makefile or toolcontext.opt_force.value then
112 var path = mpackage.gen_makefile(toolcontext.modelbuilder.model, mainmodule)
113 if path != null then
114 toolcontext.info("generated Makefile `{path}`", 0)
115 end
116 end
117 end
118
119 # Create manpages
120 if toolcontext.opt_gen_man.value then
121 mpackage.gen_man(toolcontext, mainmodule)
122 end
123 end
124 end
125
126 # Extract the list of packages from the mmodules passed as arguments
127 fun extract_mpackages(mmodules: Collection[MModule]): Collection[MPackage] do
128 var mpackages = new ArraySet[MPackage]
129 for mmodule in mmodules do
130 var mpackage = mmodule.mpackage
131 if mpackage == null then continue
132 mpackages.add mpackage
133 end
134 return mpackages.to_a
135 end
136 end
137
138 redef class MPackage
139
140 # Expand `self` in its own directory
141 private fun expand: String do
142 assert not is_expanded
143
144 var ori_path = package_path.as(not null)
145 var new_path = ori_path.dirname / name
146
147 new_path.mkdir
148 sys.system "mv {ori_path} {new_path / name}.nit"
149
150 var ini_file = "{new_path}.ini"
151 if ini_file.file_exists then
152 sys.system "mv {new_path}.ini {new_path}/package.ini"
153 end
154
155 return new_path
156 end
157
158 private var maintainer: nullable String is lazy do
159 return git_exec("git shortlog -esn . | head -n 1 | sed 's/\\s*[0-9]*\\s*//'")
160 end
161
162 private var contributors: Array[String] is lazy do
163 var contribs = git_exec("git shortlog -esn . | head -n -1 | " +
164 "sed 's/\\s*[0-9]*\\s*//'")
165 if contribs == null then return new Array[String]
166 return contribs.split("\n")
167 end
168
169 private var git_url: nullable String is lazy do
170 var git = git_exec("git remote get-url origin")
171 if git == null then return null
172 git = git.replace("git@github.com:", "https://github.com/")
173 git = git.replace("git@gitlab.com:", "https://gitlab.com/")
174 return git
175 end
176
177 private var git_dir: nullable String is lazy do
178 return git_exec("git rev-parse --show-prefix")
179 end
180
181 private var browse_url: nullable String is lazy do
182 var git = git_url
183 if git == null then return null
184 var browse = git.replace(".git", "")
185 var dir = git_dir
186 if dir == null or dir.is_empty then return browse
187 return "{browse}/tree/master/{dir}"
188 end
189
190 private var homepage_url: nullable String is lazy do
191 var git = git_url
192 if git == null then return null
193 # Special case for nit files
194 if git.has_suffix("/nit.git") then
195 return "http://nitlanguage.org"
196 end
197 return git.replace(".git", "")
198 end
199
200 private var issues_url: nullable String is lazy do
201 var git = git_url
202 if git == null then return null
203 return "{git.replace(".git", "")}/issues"
204 end
205
206 private var license: nullable String is lazy do
207 var git = git_url
208 if git == null then return null
209 # Special case for nit files
210 if git.has_suffix("/nit.git") then
211 return "Apache-2.0"
212 end
213 return null
214 end
215
216 private fun git_exec(cmd: String): nullable String do
217 var path = package_path
218 if path == null then return null
219 if not is_expanded then path = path.dirname
220 with pr = new ProcessReader("sh", "-c", "cd {path} && {cmd}") do
221 return pr.read_all.trim
222 end
223 end
224
225 private var allowed_ini_keys = [
226 "package.name", "package.desc", "package.tags", "package.license",
227 "package.maintainer", "package.more_contributors",
228 "upstream.browse", "upstream.git", "upstream.git.directory",
229 "upstream.homepage", "upstream.issues"
230 ]
231
232 private fun check_ini(toolcontext: ToolContext) do
233 if not has_ini then
234 toolcontext.error(location, "No `package.ini` file for `{name}`")
235 return
236 end
237
238 var pkg_path = package_path
239 if pkg_path == null then return
240
241 var ini_path = ini_path
242 if ini_path == null then return
243
244 var ini = new ConfigTree(ini_path)
245
246 ini.check_key(toolcontext, self, "package.name", name)
247 ini.check_key(toolcontext, self, "package.desc")
248 ini.check_key(toolcontext, self, "package.tags")
249
250 # FIXME since `git reflog --follow` seems bugged
251 ini.check_key(toolcontext, self, "package.maintainer")
252 # var maint = mpackage.maintainer
253 # if maint != null then
254 # ini.check_key(toolcontext, self, "package.maintainer", maint)
255 # end
256
257 # FIXME since `git reflog --follow` seems bugged
258 # var contribs = mpackage.contributors
259 # if contribs.not_empty then
260 # ini.check_key(toolcontext, self, "package.more_contributors", contribs.join(", "))
261 # end
262
263 ini.check_key(toolcontext, self, "package.license", license)
264 ini.check_key(toolcontext, self, "upstream.browse", browse_url)
265 ini.check_key(toolcontext, self, "upstream.git", git_url)
266 ini.check_key(toolcontext, self, "upstream.git.directory", git_dir)
267 ini.check_key(toolcontext, self, "upstream.homepage", homepage_url)
268 ini.check_key(toolcontext, self, "upstream.issues", issues_url)
269
270 for key in ini.to_map.keys do
271 if not allowed_ini_keys.has(key) then
272 toolcontext.warning(location, "unknown-ini-key",
273 "Warning: ignoring unknown `{key}` key in `{ini.ini_file}`")
274 end
275 end
276 end
277
278 private fun gen_ini: String do
279 var ini_path = self.ini_path.as(not null)
280 var ini = new ConfigTree(ini_path)
281
282 ini.update_value("package.name", name)
283 ini.update_value("package.desc", "")
284 ini.update_value("package.tags", "")
285 ini.update_value("package.maintainer", maintainer)
286 ini.update_value("package.more_contributors", contributors.join(","))
287 ini.update_value("package.license", license or else "")
288
289 ini.update_value("upstream.browse", browse_url)
290 ini.update_value("upstream.git", git_url)
291 ini.update_value("upstream.git.directory", git_dir)
292 ini.update_value("upstream.homepage", homepage_url)
293 ini.update_value("upstream.issues", issues_url)
294
295 ini.save
296 return ini_path
297 end
298
299 # Makefile
300
301 # The path to `self` Makefile
302 fun makefile_path: nullable String do
303 var path = package_path
304 if path == null then return null
305 if not is_expanded then return null
306 return path / "Makefile"
307 end
308
309 # Does `self` have a Makefile?
310 fun has_makefile: Bool do
311 var makefile_path = self.makefile_path
312 if makefile_path == null then return false
313 return makefile_path.file_exists
314 end
315
316 private fun check_makefile(toolcontext: ToolContext, mainmodule: MModule) do
317 var model = toolcontext.modelbuilder.model
318 var filter = new ModelFilter(accept_example = false, accept_test = false)
319 var view = new ModelView(model, mainmodule, filter)
320
321 var cmd_bin = new CmdMains(view, mentity = self)
322 var res_bin = cmd_bin.init_command
323 if not res_bin isa CmdSuccess then return
324
325 for mmodule in cmd_bin.results.as(not null) do
326 if not mmodule isa MModule then continue
327
328 if mmodule.makefile_path == null then
329 toolcontext.warning(location, "missing-makefile",
330 "Warning: no Makefile for executable module `{mmodule.full_name}`")
331 end
332 end
333 end
334
335 private fun gen_makefile(model: Model, mainmodule: MModule): nullable String do
336 var filter = new ModelFilter(accept_example = false, accept_test = false)
337 var view = new ModelView(model, mainmodule, filter)
338
339 var pkg_path = package_path.as(not null)
340 var makefile_path = makefile_path.as(not null)
341
342 var bins = new Array[String]
343 var cmd_bin = new CmdMains(view, mentity = self)
344 var res_bin = cmd_bin.init_command
345 if res_bin isa CmdSuccess then
346 for mmodule in cmd_bin.results.as(not null) do
347 if not mmodule isa MModule then continue
348 var mmodule_makefile = mmodule.makefile_path
349 if mmodule_makefile != null and mmodule_makefile != makefile_path then continue
350
351 var file = mmodule.location.file
352 if file == null then continue
353 # Remove package path prefix
354 var bin_path = file.filename
355 if pkg_path.has_suffix("/") then
356 bin_path = bin_path.replace(pkg_path, "")
357 else
358 bin_path = bin_path.replace("{pkg_path}/", "")
359 end
360 bins.add bin_path
361 end
362 end
363
364 if bins.is_empty then return null
365
366 var make = new NitMakefile(bins)
367 make.render.write_to_file(makefile_path)
368 return makefile_path
369 end
370
371 # Manpages
372
373 # The path to `self` manpage files
374 private fun man_path: nullable String do
375 var path = package_path
376 if path == null then return null
377 if not is_expanded then return null
378 return path / "man"
379 end
380
381 # Does `self` have a manpage files?
382 private fun has_man: Bool do
383 var man_path = self.man_path
384 if man_path == null then return false
385 return man_path.file_exists
386 end
387
388 private fun check_man(toolcontext: ToolContext, mainmodule: MModule) do
389 var model = toolcontext.modelbuilder.model
390 var filter = new ModelFilter(accept_example = false, accept_test = false)
391 var view = new ModelView(model, mainmodule, filter)
392
393 var cmd = new CmdMains(view, mentity = self)
394 var res = cmd.init_command
395 if not res isa CmdSuccess then return
396
397 for mmodule in cmd.results.as(not null) do
398 if not mmodule isa MModule then continue
399 mmodule.check_man(toolcontext)
400 end
401 end
402
403 private fun gen_man(toolcontext: ToolContext, mainmodule: MModule) do
404 var model = toolcontext.modelbuilder.model
405 var filter = new ModelFilter(accept_example = false, accept_test = false)
406 var view = new ModelView(model, mainmodule, filter)
407
408 var cmd = new CmdMains(view, mentity = self)
409 var res = cmd.init_command
410 if not res isa CmdSuccess then return
411
412 var pkg_man = man_path.as(not null)
413 for mmodule in cmd.results.as(not null) do
414 if not mmodule isa MModule then continue
415 if not has_man then pkg_man.mkdir
416 mmodule.gen_man(toolcontext)
417 end
418 end
419 end
420
421 redef class MModule
422 private fun makefile_path: nullable String do
423 var file = location.file
424 if file == null then return null
425
426 var dir = file.filename.dirname
427 var makefile = (dir / "Makefile")
428 if not makefile.file_exists then return null
429
430 for line in makefile.to_path.read_lines do
431 if line.has_prefix("{name}:") then return makefile
432 end
433 return null
434 end
435
436 private fun man_path: nullable String do
437 var mpackage = self.mpackage
438 if mpackage == null then return null
439 var path = mpackage.man_path
440 if path == null then return null
441 return path / "{name}.man"
442 end
443
444 # Does `self` have a manpage?
445 private fun has_man: Bool do
446 var man_path = self.man_path
447 if man_path == null then return false
448 return man_path.file_exists
449 end
450
451 private fun make_module(toolcontext: ToolContext): Bool do
452 var mpackage = self.mpackage
453 if mpackage == null then return false
454 if not mpackage.is_expanded then return false
455
456 var pkg_path = mpackage.package_path
457 if pkg_path == null then return false
458
459 var pr = new ProcessReader("sh", "-c", "cd {pkg_path} && make -Bs bin/{name}")
460 var out = pr.read_all.trim
461 pr.close
462 pr.wait
463 if pr.status > 0 then
464 toolcontext.error(location, "unable to compile `{name}`")
465 print out
466 return false
467 end
468 return true
469 end
470
471 private fun stub_man(toolcontext: ToolContext): nullable String do
472 if not make_module(toolcontext) then return null
473 var mpackage = self.mpackage
474 if mpackage == null then return null
475 if not mpackage.is_expanded then return null
476
477 var pkg_path = mpackage.package_path
478 if pkg_path == null then return null
479
480 var pr = new ProcessReader("{pkg_path}/bin/{name}", "--stub-man")
481 var man = pr.read_all.trim
482 pr.close
483 pr.wait
484 if pr.status > 0 then
485 toolcontext.error(location, "unable to run `{pkg_path}/bin/{name} --stub-man`")
486 print man
487 return null
488 end
489 return man
490 end
491
492 private fun check_man(toolcontext: ToolContext) do
493 if not has_man then
494 toolcontext.error(location, "No manpage for bin {full_name}")
495 return
496 end
497 var man_path = self.man_path.as(not null)
498 var man = stub_man(toolcontext)
499 if man == null or man.is_empty then return
500
501 var old_man = new ManPage.from_file(self, man_path)
502 var new_man = new ManPage.from_string(self, man)
503 old_man.diff(toolcontext, new_man)
504 end
505
506 private fun gen_man(toolcontext: ToolContext) do
507 var man = stub_man(toolcontext)
508 if man == null or man.is_empty then return
509 var man_path = self.man_path
510 if man_path == null then return
511 man.write_to_file(man_path)
512 toolcontext.info("created manpage `{man_path}`", 0)
513 end
514 end
515
516 redef class ConfigTree
517 private fun check_key(toolcontext: ToolContext, mpackage: MPackage, key: String, value: nullable String) do
518 if not has_key(key) then
519 toolcontext.warning(mpackage.location, "missing-ini-key",
520 "Warning: missing `{key}` key in `{ini_file}`")
521 return
522 end
523 if self[key].as(not null).is_empty then
524 toolcontext.warning(mpackage.location, "missing-ini-value",
525 "Warning: empty `{key}` key in `{ini_file}`")
526 return
527 end
528 if value != null and self[key] != value then
529 toolcontext.warning(mpackage.location, "wrong-ini-value",
530 "Warning: wrong value for `{key}` in `{ini_file}`. " +
531 "Expected `{value}`, got `{self[key] or else ""}`")
532 end
533 end
534
535 private fun update_value(key: String, value: nullable String) do
536 if value == null then return
537 if not has_key(key) then
538 self[key] = value
539 else
540 var old_value = self[key]
541 if not value.is_empty and old_value != value then
542 self[key] = value
543 end
544 end
545 end
546 end
547
548 # A Makefile for the Nit project
549 class NitMakefile
550
551 # Nit files to compile
552 var nit_files: Array[String]
553
554 # List of rules to add in the Makefile
555 fun rules: Array[MakeRule] do
556 var rules = new Array[MakeRule]
557
558 var rule_all = new MakeRule("all", is_phony = true)
559 rules.add rule_all
560
561 for file in nit_files do
562 var bin = file.basename.strip_extension
563
564 rule_all.deps.add "bin/{bin}"
565
566 var rule = new MakeRule("bin/{bin}")
567 rule.deps.add "$(shell $(NITLS) -M {file})"
568 rule.lines.add "mkdir -p bin/"
569 rule.lines.add "$(NITC) {file} -o bin/{bin}"
570 rules.add rule
571 end
572
573 var rule_check = new MakeRule("check", is_phony = true)
574 rule_check.lines.add "$(NITUNIT) ."
575 rules.add rule_check
576
577 var rule_doc = new MakeRule("doc", is_phony = true)
578 rule_doc.lines.add "$(NITDOC) . -o doc/"
579 rules.add rule_doc
580
581 var rule_clean = new MakeRule("clean", is_phony = true)
582 if nit_files.not_empty then
583 rule_clean.lines.add "rm -rf bin/"
584 end
585 rule_clean.lines.add "rm -rf doc/"
586 rules.add rule_clean
587
588 return rules
589 end
590
591 # Render `self`
592 fun render: Writable do
593 var tpl = new Template
594 tpl.addn """
595 # This file is part of NIT ( http://www.nitlanguage.org ).
596 #
597 # Licensed under the Apache License, Version 2.0 (the "License");
598 # you may not use this file except in compliance with the License.
599 # You may obtain a copy of the License at
600 #
601 # http://www.apache.org/licenses/LICENSE-2.0
602 #
603 # Unless required by applicable law or agreed to in writing, software
604 # distributed under the License is distributed on an "AS IS" BASIS,
605 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
606 # See the License for the specific language governing permissions and
607 # limitations under the License.\n"""
608
609 if nit_files.not_empty then
610 tpl.addn "NITC ?= nitc"
611 tpl.addn "NITLS ?= nitls"
612 end
613 tpl.addn "NITUNIT ?= nitunit"
614 tpl.addn "NITDOC ?= nitdoc"
615
616 for rule in rules do
617 tpl.add "\n{rule.render.write_to_string}"
618 end
619
620 return tpl
621 end
622 end
623
624 # A rule that goes into a Makefile
625 class MakeRule
626
627 # Rule name
628 var name: String
629
630 # Is this rule a `.PHONY` one?
631 var is_phony: Bool = false is optional
632
633 # Rule dependencies
634 var deps = new Array[String]
635
636 # Rule lines
637 var lines = new Array[String]
638
639 # Render `self`
640 fun render: Writable do
641 var tpl = new Template
642 if is_phony then
643 tpl.addn ".PHONY: {name}"
644 end
645 tpl.add "{name}:"
646 if deps.not_empty then
647 tpl.add " {deps.join(" ")}"
648 end
649 tpl.add "\n"
650 for line in lines do
651 tpl.addn "\t{line}"
652 end
653 return tpl
654 end
655 end
656
657 private class ManPage
658 var mmodule: MModule
659 var name: nullable String is noinit
660 var synopsis: nullable String is noinit
661 var options = new HashMap[Array[String], String]
662
663 init from_file(mmodule: MModule, file: String) do
664 from_lines(mmodule, file.to_path.read_lines)
665 end
666
667 init from_string(mmodule: MModule, string: String) do
668 from_lines(mmodule, string.split("\n"))
669 end
670
671 init from_lines(mmodule: MModule, lines: Array[String]) do
672 init mmodule
673
674 var section = null
675 for i in [0..lines.length[ do
676 var line = lines[i]
677 if line.is_empty then continue
678
679 if line == "# NAME" then
680 section = "name"
681 continue
682 end
683 if line == "# SYNOPSIS" then
684 section = "synopsis"
685 continue
686 end
687 if line == "# OPTIONS" then
688 section = "options"
689 continue
690 end
691
692 if section == "name" and name == null then
693 name = line.trim
694 end
695 if section == "synopsis" and synopsis == null then
696 synopsis = line.trim
697 end
698 if section == "options" and line.has_prefix("###") then
699 var opts = new Array[String]
700 for opt in line.substring(3, line.length).trim.replace("`", "").split(",") do
701 opts.add opt.trim
702 end
703 var desc = ""
704 if i < lines.length - 1 then
705 desc = lines[i + 1].trim
706 end
707 options[opts] = desc
708 end
709 end
710 end
711
712 fun diff(toolcontext: ToolContext, ref: ManPage) do
713 if name != ref.name then
714 toolcontext.warning(mmodule.location, "diff-man",
715 "Warning: outdated man description. " +
716 "Expected `{ref.name or else ""}` got `{name or else ""}`.")
717 end
718 if synopsis != ref.synopsis then
719 toolcontext.warning(mmodule.location, "diff-man",
720 "Warning: outdated man synopsis. " +
721 "Expected `{ref.synopsis or else ""}` got `{synopsis or else ""}`.")
722 end
723 for name, desc in options do
724 if not ref.options.has_key(name) then
725 toolcontext.warning(mmodule.location, "diff-man",
726 "Warning: unknown man option `{name}`.`")
727 continue
728 end
729 var ref_desc = ref.options[name]
730 if desc != ref_desc then
731 toolcontext.warning(mmodule.location, "diff-man",
732 "Warning: outdated man option description. Expected `{ref_desc}` got `{desc}`.")
733 end
734 end
735 for ref_name, ref_desc in ref.options do
736 if not options.has_key(ref_name) then
737 toolcontext.warning(mmodule.location, "diff-man",
738 "Warning: missing man option `{ref_name}`.`")
739 end
740 end
741 end
742
743 redef fun to_s do
744 var tpl = new Template
745 tpl.addn "# NAME"
746 tpl.addn name or else ""
747 tpl.addn "# SYNOPSIS"
748 tpl.addn synopsis or else ""
749 tpl.addn "# OPTIONS"
750 for name, desc in options do
751 tpl.addn " * {name}: {desc}"
752 end
753 return tpl.write_to_string
754 end
755 end
756
757 # build toolcontext
758 var toolcontext = new ToolContext
759 var tpl = new Template
760 tpl.add "Usage: nitpackage [OPTION]... <file.nit>...\n"
761 tpl.add "Helpful features about packages."
762 toolcontext.tooldescription = tpl.write_to_string
763
764 # process options
765 toolcontext.process_options(args)
766 var arguments = toolcontext.option_context.rest
767
768 # build model
769 var model = new Model
770 var mbuilder = new ModelBuilder(model, toolcontext)
771 var mmodules = mbuilder.parse_full(arguments)
772
773 # process
774 if mmodules.is_empty then return
775 mbuilder.run_phases
776 toolcontext.run_global_phases(mmodules)