xref: /llvm-project/llvm/utils/TableGen/jupyter/tablegen_kernel/install.py (revision 535693f8f74d539a4b34f2d226cdef8d71405d47)
1# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
2# See https://llvm.org/LICENSE.txt for license information.
3# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
4
5import os
6import json
7import sys
8import argparse
9from tempfile import TemporaryDirectory
10from jupyter_client.kernelspec import KernelSpecManager
11
12
13def install_my_kernel_spec(user=True, prefix=None):
14    """Install the kernel spec for user in given prefix."""
15    print("Installing llvm-tblgen IPython kernel spec")
16
17    kernel_json = {
18        "argv": [
19            sys.executable, "-m", "tablegen_kernel", "-f", "{connection_file}"
20        ],
21        "display_name": "LLVM TableGen",
22        "language": "tablegen",
23        "language_info": {
24            "name": "tablegen",
25            "codemirror_mode": "tablegen",
26            "mimetype": "text/x-tablegen",
27            "file_extension": ".td",
28            "pygments_lexer": "text"
29        }
30    }
31
32    with TemporaryDirectory() as tmpdir:
33      json_path = os.path.join(tmpdir, "kernel.json")
34      with open(json_path, 'w') as json_file:
35        json.dump(kernel_json, json_file)
36      KernelSpecManager().install_kernel_spec(
37          tmpdir, "tablegen", user=user, prefix=prefix
38      )
39
40
41def _is_root():
42    """Returns whether the current user is root."""
43    try:
44        return os.geteuid() == 0
45    except AttributeError:
46        # Return false wherever unknown.
47        return False
48
49
50def main(argv=None):
51    parser = argparse.ArgumentParser(
52        description="Install KernelSpec for LLVM TableGen Kernel"
53    )
54    prefix_locations = parser.add_mutually_exclusive_group()
55
56    prefix_locations.add_argument(
57        "--user", help="Install in user home directory", action="store_true"
58    )
59    prefix_locations.add_argument(
60        "--prefix", help="Install directory prefix", default=None
61    )
62
63    args = parser.parse_args(argv)
64
65    user = args.user or not _is_root()
66    prefix = args.prefix
67
68    install_my_kernel_spec(user=user, prefix=prefix)
69
70
71if __name__ == "__main__":
72    main()
73