xref: /linux/tools/net/ynl/pyynl/lib/specdir.py (revision 91ec2035134982b98fab0609a9fd8480e8217dc1)
1# SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause
2
3"""
4Locating YNL spec and schema files on disk.
5
6Resolves the directory holding the YAML specs (preferring an in-tree copy
7over the installed system path) and maps family names to spec files.
8"""
9
10import os
11
12SYS_SCHEMA_DIR='/usr/share/ynl'
13RELATIVE_SCHEMA_DIR='../../../../../Documentation/netlink'
14
15
16def schema_dir():
17    """
18    Return the effective schema directory, preferring in-tree before
19    system schema directory.
20    """
21    script_dir = os.path.dirname(os.path.abspath(__file__))
22    schema_dir_ = os.path.abspath(f"{script_dir}/{RELATIVE_SCHEMA_DIR}")
23    if not os.path.isdir(schema_dir_):
24        schema_dir_ = SYS_SCHEMA_DIR
25    if not os.path.isdir(schema_dir_):
26        raise FileNotFoundError(f"Schema directory {schema_dir_} does not exist")
27    return schema_dir_
28
29def spec_dir():
30    """
31    Return the effective spec directory, relative to the effective
32    schema directory.
33    """
34    spec_dir_ = schema_dir() + '/specs'
35    if not os.path.isdir(spec_dir_):
36        raise FileNotFoundError(f"Spec directory {spec_dir_} does not exist")
37    return spec_dir_
38
39
40def find_spec(family):
41    """ Return the path to the YAML spec file for a family by name. """
42    spec = f"{spec_dir()}/{family}.yaml"
43    if not os.path.isfile(spec):
44        raise FileNotFoundError(f"Spec for family '{family}' not found at {spec}")
45    return spec
46
47
48def list_families():
49    """ Return the sorted names of all families with an installed spec. """
50    return sorted(f.removesuffix('.yaml')
51                  for f in os.listdir(spec_dir()) if f.endswith('.yaml'))
52