blob: 603cfd471906a9439baa89cf0d092aa7442aa136 [file] [log] [blame]
Michal Vasko2e79f262021-10-19 14:29:07 +02001/**
2 * @file cmd_feature.c
3 * @author Michal Vasko <mvasko@cesnet.cz>
4 * @brief 'feature' command of the libyang's yanglint tool.
5 *
6 * Copyright (c) 2015-2021 CESNET, z.s.p.o.
7 *
8 * This source code is licensed under BSD 3-Clause License (the "License").
9 * You may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
11 *
12 * https://opensource.org/licenses/BSD-3-Clause
13 */
14
15#define _GNU_SOURCE
16
17#include "cmd.h"
18
19#include <getopt.h>
20#include <stdint.h>
21#include <stdio.h>
22
23#include "libyang.h"
24
25#include "common.h"
26
27void
28cmd_feature_help(void)
29{
30 printf("Usage: feature [-h] <module> [<module>]*\n"
31 " Print features of all the module with state of each one.\n");
32}
33
34int
35collect_features(const struct lys_module *mod, struct ly_set *set)
36{
37 struct lysp_feature *f = NULL;
38 uint32_t idx = 0;
39
40 while ((f = lysp_feature_next(f, mod->parsed, &idx))) {
41 if (ly_set_add(set, (void *)f->name, 1, NULL)) {
42 YLMSG_E("Memory allocation failed.\n");
43 ly_set_erase(set, NULL);
44 return 1;
45 }
46 }
47
48 return 0;
49}
50
51void
52cmd_feature(struct ly_ctx **ctx, const char *cmdline)
53{
54 int argc = 0;
55 char **argv = NULL;
56 int opt, opt_index, i;
57 struct option options[] = {
58 {"help", no_argument, NULL, 'h'},
59 {NULL, 0, NULL, 0}
60 };
61 struct ly_set set = {0};
62 size_t max_len;
63 uint32_t j;
64 const char *name;
65
66 if (parse_cmdline(cmdline, &argc, &argv)) {
67 goto cleanup;
68 }
69
70 while ((opt = getopt_long(argc, argv, "h", options, &opt_index)) != -1) {
71 switch (opt) {
72 case 'h':
73 cmd_feature_help();
74 goto cleanup;
75 default:
76 YLMSG_E("Unknown option.\n");
77 goto cleanup;
78 }
79 }
80
81 if (argc == optind) {
82 YLMSG_E("Missing modules to print.\n");
83 goto cleanup;
84 }
85
86 for (i = 0; i < argc - optind; i++) {
87 const struct lys_module *mod = ly_ctx_get_module_latest(*ctx, argv[optind + i]);
88 if (!mod) {
89 YLMSG_E("Module \"%s\" not found.\n", argv[optind + i]);
90 goto cleanup;
91 }
92
93 /* collect features of the module */
94 if (collect_features(mod, &set)) {
95 goto cleanup;
96 }
97
98 /* header */
99 printf("%s features:\n", mod->name);
100
101 if (set.count) {
102 /* get max len */
103 max_len = 0;
104 for (j = 0; j < set.count; ++j) {
105 name = set.objs[j];
106 if (strlen(name) > max_len) {
107 max_len = strlen(name);
108 }
109 }
110
111 /* print features */
112 for (j = 0; j < set.count; ++j) {
113 name = set.objs[j];
114 printf("\t%-*s (%s)\n", (int)max_len, name, lys_feature_value(mod, name) ? "off" : "on");
115 }
116
117 ly_set_erase(&set, NULL);
118 } else {
119 printf("\t(none)\n");
120 }
121 }
122
123cleanup:
124 free_cmdline(argv);
125}