nitpm: list packages in alphabetical order
[nit.git] / src / nitpm.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 # Nit package manager command line interface
16 module nitpm
17
18 import opts
19 import prompt
20 import ini
21 import curl
22
23 import nitpm_shared
24
25 # Command line action, passed after `nitpm`
26 abstract class Command
27
28 # Short name of the command, specified in the command line
29 fun name: String is abstract
30
31 # Short usage description
32 fun usage: String is abstract
33
34 # Command description
35 fun description: String is abstract
36
37 # Apply this command consiering the `args` that follow
38 fun apply(args: Array[String]) do end
39
40 private var all_commands: Map[String, Command]
41
42 init do all_commands[name] = self
43
44 # Print the help message for this command
45 fun print_local_help
46 do
47 print "usage: {usage}"
48 print ""
49 print " {description}"
50 end
51 end
52
53 # Install a new package
54 class CommandInstall
55 super Command
56
57 redef fun name do return "install"
58 redef fun usage do return "nitpm install [package0[=version] [package1 ...]]"
59 redef fun description do return "Install packages by name, Git repository address or from the local package.ini"
60
61 # Packages installed in this run (identified by the full path)
62 private var installed = new Array[String]
63
64 redef fun apply(args)
65 do
66 if args.not_empty then
67 # Install each package
68 for arg in args do
69 # Parse each arg as an import string, with versions and commas
70 install_packages arg
71 end
72 else
73 # Install packages from local package.ini
74 var ini_path = "package.ini"
75 if not ini_path.file_exists then
76 print_error "Local `package.ini` not found."
77 print_local_help
78 exit 1
79 end
80
81 var ini = new ConfigTree(ini_path)
82 var import_line = ini["package.import"]
83 if import_line == null then
84 print_error "The local `package.ini` declares no external dependencies."
85 exit 0
86 abort
87 end
88
89 install_packages import_line
90 end
91 end
92
93 # Install packages defined by the `import_line`
94 private fun install_packages(import_line: String)
95 do
96 var imports = import_line.parse_import
97 for name, ext_package in imports do
98 install_package(ext_package.id, ext_package.version)
99 end
100 end
101
102 # Install the `package_id` at `version`
103 private fun install_package(package_id: String, version: nullable String)
104 do
105 if package_id.is_package_name then
106 # Ask a centralized server
107 # TODO choose a future safe URL
108 # TODO customizable server list
109 # TODO parse ini file in memory
110
111 var url = "https://xymus.net/nitpm/{package_id}.ini"
112 var ini_path = "/tmp/{package_id}.ini"
113
114 if verbose then print "Looking for a package description at '{url}'"
115
116 var request = new CurlHTTPRequest(url)
117 request.verbose = verbose
118 var response = request.download_to_file(ini_path)
119
120 if response isa CurlResponseFailed then
121 print_error "Failed to contact the remote server at '{url}': {response.error_msg} ({response.error_code})"
122 exit 1
123 end
124
125 assert response isa CurlFileResponseSuccess
126 if response.status_code == 404 then
127 print_error "Package '{package_id}' not found on the server"
128 exit 1
129 else if response.status_code != 200 then
130 print_error "Server side error: {response.status_code}"
131 exit 1
132 end
133
134 if verbose then
135 print "Found a package description:"
136 print ini_path.to_path.read_all
137 end
138
139 var ini = new ConfigTree(ini_path)
140 var git_repo = ini["upstream.git"]
141 if git_repo == null then
142 print_error "Package description invalid, or it does not declare a Git repository"
143 exit 1
144 abort
145 end
146
147 install_from_git(git_repo, package_id, version)
148 else
149 var name = package_id.git_name
150 if name != null and name != "." and not name.is_empty then
151 name = name.to_lower
152 install_from_git(package_id, name, version)
153 else
154 print_error "Failed to infer the package name"
155 exit 1
156 end
157 end
158 end
159
160 private fun install_from_git(git_repo, name: String, version: nullable String)
161 do
162 check_git
163
164 var target_dir = nitpm_lib_dir / name
165 if version != null then target_dir += "=" + version
166 if installed.has(target_dir) then
167 # Ignore packages installed in this run
168 return
169 end
170 installed.add target_dir
171
172 if target_dir.file_exists then
173 # Warn about packages previously installed,
174 # install dependencies anyway in case of a previous error.
175 print_error "Package '{name}' is already installed"
176 else
177 # Actually install it
178 var cmd_branch = ""
179 if version != null then cmd_branch = "--branch '{version}'"
180
181 var cmd = "git clone --depth 1 {cmd_branch} {git_repo.escape_to_sh} {target_dir.escape_to_sh}"
182 if verbose then print "+ {cmd}"
183
184 if "NIT_TESTING".environ == "true" then
185 # Silence git output when testing
186 cmd += " 2> /dev/null"
187 end
188
189 var proc = new Process("sh", "-c", cmd)
190 proc.wait
191
192 if proc.status != 0 then
193 print_error "Install of '{name}' failed"
194 exit 1
195 end
196 end
197
198 # Recursive install
199 var ini = new ConfigTree(target_dir/"package.ini")
200 var import_line = ini["package.import"]
201 if import_line != null then
202 install_packages import_line
203 end
204 end
205 end
206
207 # Upgrade a package
208 class CommandUpgrade
209 super Command
210
211 redef fun name do return "upgrade"
212 redef fun usage do return "nitpm upgrade <package>"
213 redef fun description do return "Upgrade a package"
214
215 redef fun apply(args)
216 do
217 if args.length != 1 then
218 print_local_help
219 exit 1
220 end
221
222 var name = args.first
223 var target_dir = nitpm_lib_dir / name
224
225 if not target_dir.file_exists or not target_dir.to_path.is_dir then
226 print_error "Package not found"
227 exit 1
228 end
229
230 check_git
231
232 var cmd = "cd {target_dir.escape_to_sh}; git pull"
233 if verbose then print "+ {cmd}"
234
235 var proc = new Process("sh", "-c", cmd)
236 proc.wait
237
238 if proc.status != 0 then
239 print_error "Upgrade failed"
240 exit 1
241 end
242 end
243 end
244
245 # Uninstall a package
246 class CommandUninstall
247 super Command
248
249 redef fun name do return "uninstall"
250 redef fun usage do return "nitpm uninstall <package>"
251 redef fun description do return "Uninstall a package"
252
253 redef fun apply(args)
254 do
255 if args.length != 1 then
256 print_local_help
257 exit 1
258 end
259
260 var name = args.first
261 var target_dir = nitpm_lib_dir / name
262
263 if not target_dir.file_exists or not target_dir.to_path.is_dir then
264 print_error "Package not found"
265 exit 1
266 end
267
268 # Ask confirmation
269 var response = prompt("Delete {target_dir.escape_to_sh}? [Y/n] ")
270 var accept = response != null and
271 (response.to_lower == "y" or response.to_lower == "yes" or response == "")
272 if not accept then return
273
274 var cmd = "rm -rf {target_dir.escape_to_sh}"
275 if verbose then print "+ {cmd}"
276
277 var proc = new Process("sh", "-c", cmd)
278 proc.wait
279
280 if proc.status != 0 then
281 print_error "Uninstall failed"
282 exit 1
283 end
284 end
285 end
286
287 # List all installed packages
288 class CommandList
289 super Command
290
291 redef fun name do return "list"
292 redef fun usage do return "nitpm list"
293 redef fun description do return "List installed packages"
294
295 redef fun apply(args)
296 do
297 var files = nitpm_lib_dir.files
298 var name_to_desc = new Map[String, nullable String]
299 var max_name_len = 0
300
301 # Collect package info
302 for file in files do
303 var ini_path = nitpm_lib_dir / file / "package.ini"
304 if verbose then print "- Reading ini file at {ini_path}"
305 var ini = new ConfigTree(ini_path)
306 var tags = ini["package.tags"]
307
308 name_to_desc[file] = tags
309 max_name_len = max_name_len.max(file.length)
310 end
311
312 # Sort in alphabetical order
313 var sorted_names = name_to_desc.keys.to_a
314 alpha_comparator.sort sorted_names
315
316 # Print with clear columns
317 for name in sorted_names do
318 var col0 = name.justify(max_name_len+1, 0.0)
319 var col1 = name_to_desc[name] or else ""
320 var line = col0 + col1
321 print line.trim
322 end
323 end
324 end
325
326 # Show general help or help specific to a command
327 class CommandHelp
328 super Command
329
330 redef fun name do return "help"
331 redef fun usage do return "nitpm help [command]"
332 redef fun description do return "Show general help message or the help for a command"
333
334 redef fun apply(args)
335 do
336 # Try first to help about a valid action
337 if args.length == 1 then
338 var command = commands.get_or_null(args.first)
339 if command != null then
340 command.print_local_help
341 return
342 end
343 end
344
345 print_help
346 end
347 end
348
349 redef class Sys
350
351 # General command line options
352 var opts = new OptionContext
353
354 # Help option
355 var opt_help = new OptionBool("Show this help message", "--help", "-h")
356
357 # Verbose mode option
358 var opt_verbose = new OptionBool("Print more information", "--verbose", "-v")
359 private fun verbose: Bool do return opt_verbose.value
360
361 # All command line actions, mapped to their short `name`
362 var commands = new Map[String, Command]
363
364 private var command_install = new CommandInstall(commands)
365 private var command_list = new CommandList(commands)
366 private var command_update = new CommandUpgrade(commands)
367 private var command_uninstall = new CommandUninstall(commands)
368 private var command_help = new CommandHelp(commands)
369 end
370
371 redef fun nitpm_lib_dir
372 do
373 if "NIT_TESTING".environ == "true" then
374 return "/tmp/nitpm-test-" + "NIT_TESTING_ID".environ
375 else return super
376 end
377
378 # Print the general help message
379 private fun print_help
380 do
381 print "usage: nitpm <command> [options]"
382 print ""
383
384 print "commands:"
385 for command in commands.values do
386 print " {command.name.justify(11, 0.0)} {command.description}"
387 end
388 print ""
389
390 print "options:"
391 opts.usage
392 end
393
394 # Check if `git` is available, exit if not
395 private fun check_git
396 do
397 var proc = new ProcessReader("git", "--version")
398 proc.wait
399 proc.close
400
401 if proc.status != 0 then
402 print_error "Please install `git`"
403 exit 1
404 end
405 end
406
407 # Parse main options
408 opts.add_option(opt_help, opt_verbose)
409 opts.parse
410 var rest = opts.rest
411
412 if opt_help.value then
413 print_help
414 exit 0
415 end
416
417 if opts.errors.not_empty then
418 for error in opts.errors do print error
419 print ""
420 print_help
421 exit 1
422 end
423
424 if rest.is_empty then
425 print_help
426 exit 1
427 end
428
429 # Find and apply action
430 var action_name = rest.shift
431 var action = commands.get_or_null(action_name)
432 if action != null then
433 action.apply rest
434 else
435 print_help
436 exit 1
437 end