nitpackage: move package path services up to `model/mpackage.nit`
[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
20 redef class ToolContext
21 # --expand
22 var opt_expand = new OptionBool("Move singleton packages to their own directory", "--expand")
23
24 # README handling phase
25 var readme_phase: Phase = new ReadmePhase(self, null)
26
27 redef init do
28 super
29 option_context.add_option(opt_expand)
30 end
31 end
32
33 private class ReadmePhase
34 super Phase
35
36 redef fun process_mainmodule(mainmodule, mmodules) do
37 var expand_packages = toolcontext.opt_expand.value
38 var model = toolcontext.modelbuilder.model
39
40 for mpackage in model.mpackages do
41
42 # Fictive and buggy packages are ignored
43 if not mpackage.has_source then
44 toolcontext.warning(mpackage.location, "no-source",
45 "Warning: `{mpackage}` has no source file")
46 continue
47 end
48
49 # Expand packages
50 if not mpackage.is_expanded then
51 if expand_packages then
52 var path = mpackage.expand
53 toolcontext.info("{mpackage} moved to {path}", 0)
54 else
55 toolcontext.warning(mpackage.location, "no-dir",
56 "Warning: `{mpackage}` has no package directory")
57 continue
58 end
59 end
60 end
61 end
62 end
63
64 redef class MPackage
65
66 # Expand `self` in its own directory
67 private fun expand: String do
68 assert not is_expanded
69
70 var ori_path = package_path.as(not null)
71 var new_path = ori_path.dirname / name
72
73 new_path.mkdir
74 sys.system "mv {ori_path} {new_path / name}.nit"
75
76 var ini_file = "{new_path}.ini"
77 if ini_file.file_exists then
78 sys.system "mv {new_path}.ini {new_path}/package.ini"
79 end
80
81 return new_path
82 end
83 end
84
85 # build toolcontext
86 var toolcontext = new ToolContext
87 var tpl = new Template
88 tpl.add "Usage: nitpackage [OPTION]... <file.nit>...\n"
89 tpl.add "Helpful features about packages."
90 toolcontext.tooldescription = tpl.write_to_string
91
92 # process options
93 toolcontext.process_options(args)
94 var arguments = toolcontext.option_context.rest
95
96 # build model
97 var model = new Model
98 var mbuilder = new ModelBuilder(model, toolcontext)
99 var mmodules = mbuilder.parse_full(arguments)
100
101 # process
102 if mmodules.is_empty then return
103 mbuilder.run_phases
104 toolcontext.run_global_phases(mmodules)