]> git.proxmox.com Git - pve-esxi-import-tools.git/commit
listvms: add arg parser, context manager for connections, fetch helper
authorMax Carrara <m.carrara@proxmox.com>
Fri, 22 Mar 2024 18:06:21 +0000 (19:06 +0100)
committerWolfgang Bumiller <w.bumiller@proxmox.com>
Wed, 27 Mar 2024 09:22:45 +0000 (10:22 +0100)
commit5f6e1d5bfbbea385e6d54cf908e26b6d14ec09b9
tree8b9e128985226a245be6d6b47426c595c18ce849
parentcda87e27dfcac216e841f4c0d1de3ff861133723
listvms: add arg parser, context manager for connections, fetch helper

In order to make the CLI interface more friendly to humans, Python's
`argparse` [0] module from the standard library is used to parse the
arguments provided to the script. Each option and positional argument
also contain a short help text that is shown when running the script
with either "-h" or "--help".

Additionally, this commit also adds a context manager [1] for
establishing connections to an ESXi host. The context manager ensures
that the connection is closed in its inner `finally` block.

The inner part of the VM-data-fetching loop in `main()` is factored
out into a separate helper function, which now raises a `RuntimeError`
if the datacenter of a VM cannot be looked up.

In general, should any exception be thrown inside the loop, its output
is subsequently logged to stderr. The loop then just continues like
before.

Any exception that is not caught inside of `main()` is now printed to
stderr, followed by exiting with `1`.

Overall, the script's behaviour and output on successful operations
remains the same, except regarding unsuccessful argument parsing and
displaying error messages. In other words, invocations prior to this
patch should result in the same JSON output (if successful).

This was tested by piping the outputs of this script before and after
this commit through `jq` and then comparing the outputs with `diff`.

[0]: https://docs.python.org/3.11/library/argparse.html
[1]: https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager

Signed-off-by: Max Carrara <m.carrara@proxmox.com>
listvms.py