yanglint REFACTOR reflect changes in libyang 2.0 in yanglint
diff --git a/tools/lint/CMakeLists.txt b/tools/lint/CMakeLists.txt
index 0467a1d..e4ad069 100644
--- a/tools/lint/CMakeLists.txt
+++ b/tools/lint/CMakeLists.txt
@@ -3,7 +3,15 @@
set(lintsrc
main.c
main_ni.c
- commands.c
+ cmd.c
+ cmd_add.c
+ cmd_clear.c
+ cmd_data.c
+ cmd_list.c
+ cmd_load.c
+ cmd_print.c
+ cmd_searchpath.c
+ common.c
completion.c
configuration.c
linenoise/linenoise.c)
diff --git a/tools/lint/cmd.c b/tools/lint/cmd.c
new file mode 100644
index 0000000..576743d
--- /dev/null
+++ b/tools/lint/cmd.c
@@ -0,0 +1,269 @@
+/**
+ * @file cmd.c
+ * @author Michal Vasko <mvasko@cesnet.cz>
+ * @author Radek Krejci <rkrejci@cesnet.cz>
+ * @brief libyang's yanglint tool general commands
+ *
+ * Copyright (c) 2015-2020 CESNET, z.s.p.o.
+ *
+ * This source code is licensed under BSD 3-Clause License (the "License").
+ * You may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://opensource.org/licenses/BSD-3-Clause
+ */
+
+#define _GNU_SOURCE
+
+#include "cmd.h"
+
+#include <getopt.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <string.h>
+#include <strings.h>
+
+#include "common.h"
+#include "compat.h"
+#include "libyang.h"
+
+COMMAND commands[];
+extern int done;
+
+#ifndef NDEBUG
+
+void
+cmd_debug_help(void)
+{
+ printf("Usage: debug (dict | yang | yin | xpath | diff)+\n");
+}
+
+void
+cmd_debug(struct ly_ctx **UNUSED(ctx), const char *cmdline)
+{
+ int argc = 0;
+ char **argv = NULL;
+ int opt, opt_index;
+ struct option options[] = {
+ {"help", no_argument, NULL, 'h'},
+ {NULL, 0, NULL, 0}
+ };
+ uint32_t dbg_groups = 0;
+
+ if (parse_cmdline(cmdline, &argc, &argv)) {
+ goto cleanup;
+ }
+
+ while ((opt = getopt_long(argc, argv, "h", options, &opt_index)) != -1) {
+ switch (opt) {
+ case 'h':
+ cmd_debug_help();
+ goto cleanup;
+ default:
+ YLMSG_E("Unknown option.\n");
+ goto cleanup;
+ }
+ }
+ if (argc == optind) {
+ /* no argument */
+ cmd_debug_help();
+ goto cleanup;
+ }
+
+ for (int i = 0; i < argc - optind; i++) {
+ if (!strcasecmp("dict", argv[optind + i])) {
+ dbg_groups |= LY_LDGDICT;
+ } else if (!strcasecmp("yang", argv[optind + i])) {
+ dbg_groups |= LY_LDGYANG;
+ } else if (!strcasecmp("yin", argv[optind + i])) {
+ dbg_groups |= LY_LDGYIN;
+ } else if (!strcasecmp("xpath", argv[optind + i])) {
+ dbg_groups |= LY_LDGXPATH;
+ } else if (!strcasecmp("diff", argv[optind + i])) {
+ dbg_groups |= LY_LDGDIFF;
+ } else {
+ YLMSG_E("Unknown debug group \"%s\"\n", argv[optind + 1]);
+ goto cleanup;
+ }
+ }
+
+ ly_log_dbg_groups(dbg_groups);
+
+cleanup:
+ free_cmdline(argv);
+}
+
+#endif
+
+void
+cmd_verb_help(void)
+{
+ printf("Usage: verb (error | warning | verbose | debug)\n");
+}
+
+void
+cmd_verb(struct ly_ctx **UNUSED(ctx), const char *cmdline)
+{
+ int argc = 0;
+ char **argv = NULL;
+ int opt, opt_index;
+ struct option options[] = {
+ {"help", no_argument, NULL, 'h'},
+ {NULL, 0, NULL, 0}
+ };
+
+ if (parse_cmdline(cmdline, &argc, &argv)) {
+ goto cleanup;
+ }
+
+ while ((opt = getopt_long(argc, argv, "h", options, &opt_index)) != -1) {
+ switch (opt) {
+ case 'h':
+ cmd_verb_help();
+ goto cleanup;
+ default:
+ YLMSG_E("Unknown option.\n");
+ goto cleanup;
+ }
+ }
+
+ if (argc - optind > 1) {
+ YLMSG_E("Only a single verbosity level can be set.\n");
+ cmd_verb_help();
+ goto cleanup;
+ } else if (argc == optind) {
+ /* no argument - print current value */
+ LY_LOG_LEVEL level = ly_log_level(LY_LLCUR);
+ printf("Current verbosity level: ");
+ if (level == LY_LLERR) {
+ printf("error\n");
+ } else if (level == LY_LLWRN) {
+ printf("warning\n");
+ } else if (level == LY_LLVRB) {
+ printf("verbose\n");
+ } else if (level == LY_LLDBG) {
+ printf("debug\n");
+ }
+ goto cleanup;
+ }
+
+ if (!strcasecmp("error", argv[optind]) || !strcmp("0", argv[optind])) {
+ ly_log_level(LY_LLERR);
+ } else if (!strcasecmp("warning", argv[optind]) || !strcmp("1", argv[optind])) {
+ ly_log_level(LY_LLWRN);
+ } else if (!strcasecmp("verbose", argv[optind]) || !strcmp("2", argv[optind])) {
+ ly_log_level(LY_LLVRB);
+ } else if (!strcasecmp("debug", argv[optind]) || !strcmp("3", argv[optind])) {
+ ly_log_level(LY_LLDBG);
+ } else {
+ YLMSG_E("Unknown verbosity \"%s\"\n", argv[optind]);
+ goto cleanup;
+ }
+
+#ifndef NDEBUG
+ if (ly_log_level(LY_LLCUR) == LY_LLDBG) {
+ ly_log_dbg_groups(LY_LDGDICT | LY_LDGYANG | LY_LDGYIN | LY_LDGXPATH | LY_LDGDIFF);
+ } else {
+ ly_log_dbg_groups(0);
+ }
+#endif
+
+cleanup:
+ free_cmdline(argv);
+}
+
+void
+cmd_quit(struct ly_ctx **UNUSED(ctx), const char *UNUSED(cmdline))
+{
+ done = 1;
+ return;
+}
+
+void
+cmd_help_help(void)
+{
+ printf("Usage: help [cmd ...]\n");
+}
+
+void
+cmd_help(struct ly_ctx **UNUSED(ctx), const char *cmdline)
+{
+ int argc = 0;
+ char **argv = NULL;
+ int opt, opt_index;
+ struct option options[] = {
+ {"help", no_argument, NULL, 'h'},
+ {NULL, 0, NULL, 0}
+ };
+
+ if (parse_cmdline(cmdline, &argc, &argv)) {
+ goto cleanup;
+ }
+
+ while ((opt = getopt_long(argc, argv, "h", options, &opt_index)) != -1) {
+ switch (opt) {
+ case 'h':
+ cmd_help_help();
+ goto cleanup;
+ default:
+ YLMSG_E("Unknown option.\n");
+ goto cleanup;
+ }
+ }
+
+ if (argc == optind) {
+generic_help:
+ printf("Available commands:\n");
+ for (uint16_t i = 0; commands[i].name; i++) {
+ if (commands[i].helpstring != NULL) {
+ printf(" %-15s %s\n", commands[i].name, commands[i].helpstring);
+ }
+ }
+ } else {
+ /* print specific help for the selected command(s) */
+
+ for (int c = 0; c < argc - optind; ++c) {
+ int8_t match = 0;
+ /* get the command of the specified name */
+ for (uint16_t i = 0; commands[i].name; i++) {
+ if (strcmp(argv[optind + c], commands[i].name) == 0) {
+ match = 1;
+ if (commands[i].help_func != NULL) {
+ commands[i].help_func();
+ } else {
+ printf("%s: %s\n", argv[optind + c], commands[i].helpstring);
+ }
+ break;
+ }
+ }
+ if (!match) {
+ /* if unknown command specified, print the list of commands */
+ printf("Unknown command \'%s\'\n", argv[optind + c]);
+ goto generic_help;
+ }
+ }
+ }
+
+cleanup:
+ free_cmdline(argv);
+}
+
+COMMAND commands[] = {
+ {"help", cmd_help, cmd_help_help, "Display commands description"},
+ {"add", cmd_add, cmd_add_help, "Add a new module from a specific file"},
+ {"load", cmd_load, cmd_load_help, "Load a new model from the searchdirs"},
+ {"print", cmd_print, cmd_print_help, "Print a schema module"},
+ {"data", cmd_data, cmd_data_help, "Load, validate and optionally print instance data"},
+ {"list", cmd_list, cmd_list_help, "List all the loaded models"},
+ {"searchpath", cmd_searchpath, cmd_searchpath_help, "Print/set the search path(s) for models"},
+ {"clear", cmd_clear, cmd_clear_help, "Clear the context - remove all the loaded models"},
+ {"verb", cmd_verb, cmd_verb_help, "Change verbosity"},
+#ifndef NDEBUG
+ {"debug", cmd_debug, cmd_debug_help, "Display specific debug message groups"},
+#endif
+ {"quit", cmd_quit, NULL, "Quit the program"},
+ /* synonyms for previous commands */
+ {"?", cmd_help, NULL, "Display commands description"},
+ {"exit", cmd_quit, NULL, "Quit the program"},
+ {NULL, NULL, NULL, NULL}
+};
diff --git a/tools/lint/cmd.h b/tools/lint/cmd.h
new file mode 100644
index 0000000..185c50e
--- /dev/null
+++ b/tools/lint/cmd.h
@@ -0,0 +1,64 @@
+/**
+ * @file cmd.h
+ * @author Michal Vasko <mvasko@cesnet.cz>
+ * @author Radek Krejci <rkrejci@cesnet.cz>
+ * @brief libyang's yanglint tool commands header
+ *
+ * Copyright (c) 2015-2020 CESNET, z.s.p.o.
+ *
+ * This source code is licensed under BSD 3-Clause License (the "License").
+ * You may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://opensource.org/licenses/BSD-3-Clause
+ */
+
+#ifndef COMMANDS_H_
+#define COMMANDS_H_
+
+#include "libyang.h"
+
+/**
+ * @brief command information
+ */
+typedef struct {
+ char *name; /* User printable name of the function. */
+ void (*func)(struct ly_ctx **ctx, const char *); /* Function to call to do the command. */
+ void (*help_func)(void); /* Display command help. */
+ char *helpstring; /* Documentation for this function. */
+} COMMAND;
+
+/**
+ * @brief The list of available commands.
+ */
+extern COMMAND commands[];
+
+/* cmd_add.c */
+void cmd_add(struct ly_ctx **ctx, const char *cmdline);
+void cmd_add_help(void);
+
+/* cmd_clear.c */
+void cmd_clear(struct ly_ctx **ctx, const char *cmdline);
+void cmd_clear_help(void);
+
+/* cmd_data.c */
+void cmd_data(struct ly_ctx **ctx, const char *cmdline);
+void cmd_data_help(void);
+
+/* cmd_list.c */
+void cmd_list(struct ly_ctx **ctx, const char *cmdline);
+void cmd_list_help(void);
+
+/* cmd_load.c */
+void cmd_load(struct ly_ctx **ctx, const char *cmdline);
+void cmd_load_help(void);
+
+/* cmd_print.c */
+void cmd_print(struct ly_ctx **ctx, const char *cmdline);
+void cmd_print_help(void);
+
+/* cmd_searchpath.c */
+void cmd_searchpath(struct ly_ctx **ctx, const char *cmdline);
+void cmd_searchpath_help(void);
+
+#endif /* COMMANDS_H_ */
diff --git a/tools/lint/cmd_add.c b/tools/lint/cmd_add.c
new file mode 100644
index 0000000..aebb2a6
--- /dev/null
+++ b/tools/lint/cmd_add.c
@@ -0,0 +1,166 @@
+/**
+ * @file cmd_add.c
+ * @author Michal Vasko <mvasko@cesnet.cz>
+ * @author Radek Krejci <rkrejci@cesnet.cz>
+ * @brief 'add' command of the libyang's yanglint tool.
+ *
+ * Copyright (c) 2015-2020 CESNET, z.s.p.o.
+ *
+ * This source code is licensed under BSD 3-Clause License (the "License").
+ * You may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://opensource.org/licenses/BSD-3-Clause
+ */
+
+#define _GNU_SOURCE
+
+#include "cmd.h"
+
+#include <getopt.h>
+#include <libgen.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+
+#include "libyang.h"
+
+#include "common.h"
+
+void
+cmd_add_help(void)
+{
+ printf("Usage: add [-iD] <schema1> [<schema2> ...]\n"
+ " Add a new module from a specific file.\n\n"
+ " -D, --disable-searchdir\n"
+ " Do not implicitly search in current working directory for\n"
+ " the import schema modules. If specified a second time, do not\n"
+ " even search in the module directory (all modules must be \n"
+ " explicitly specified).\n"
+ " -F FEATURES, --features=FEATURES\n"
+ " Features to support, default all.\n"
+ " <modname>:[<feature>,]*\n"
+ " -i, --makeimplemented\n"
+ " Make the imported modules \"referenced\" from any loaded\n"
+ " <schema> module also implemented. If specified a second time,\n"
+ " all the modules are set implemented.\n");
+}
+
+void
+cmd_add(struct ly_ctx **ctx, const char *cmdline)
+{
+
+ int argc = 0;
+ char **argv = NULL;
+ int opt, opt_index;
+ struct option options[] = {
+ {"disable-searchdir", no_argument, NULL, 'D'},
+ {"features", required_argument, NULL, 'F'},
+ {"help", no_argument, NULL, 'h'},
+ {"makeimplemented", no_argument, NULL, 'i'},
+ {NULL, 0, NULL, 0}
+ };
+ uint16_t options_ctx = 0;
+ struct ly_set fset = {0};
+
+ if (parse_cmdline(cmdline, &argc, &argv)) {
+ goto cleanup;
+ }
+
+ while ((opt = getopt_long(argc, argv, "D:F:hi", options, &opt_index)) != -1) {
+ switch (opt) {
+ case 'D': /* --disable--search */
+ if (options_ctx & LY_CTX_DISABLE_SEARCHDIRS) {
+ YLMSG_W("The -D option specified too many times.\n");
+ }
+ if (options_ctx & LY_CTX_DISABLE_SEARCHDIR_CWD) {
+ options_ctx &= ~LY_CTX_DISABLE_SEARCHDIR_CWD;
+ options_ctx |= LY_CTX_DISABLE_SEARCHDIRS;
+ } else {
+ options_ctx |= LY_CTX_DISABLE_SEARCHDIR_CWD;
+ }
+ break;
+
+ case 'F': /* --features */
+ if (parse_features(optarg, &fset)) {
+ goto cleanup;
+ }
+ break;
+
+ case 'h':
+ cmd_add_help();
+ goto cleanup;
+
+ case 'i': /* --makeimplemented */
+ if (options_ctx & LY_CTX_REF_IMPLEMENTED) {
+ options_ctx &= ~LY_CTX_REF_IMPLEMENTED;
+ options_ctx |= LY_CTX_ALL_IMPLEMENTED;
+ } else {
+ options_ctx |= LY_CTX_REF_IMPLEMENTED;
+ }
+ break;
+
+ default:
+ YLMSG_E("Unknown option.\n");
+ goto cleanup;
+ }
+ }
+
+ if (argc == optind) {
+ /* no argument */
+ cmd_add_help();
+ goto cleanup;
+ }
+
+ if (options_ctx) {
+ ly_ctx_set_options(*ctx, options_ctx);
+ }
+
+ for (int i = 0; i < argc - optind; i++) {
+ /* process the schema module files */
+ LY_ERR ret;
+ uint8_t path_unset = 1; /* flag to unset the path from the searchpaths list (if not already present) */
+ char *dir, *module;
+ const char **features = NULL;
+ struct ly_in *in = NULL;
+
+ if (parse_schema_path(argv[optind + i], &dir, &module)) {
+ goto cleanup;
+ }
+
+ /* add temporarily also the path of the module itself */
+ if (ly_ctx_set_searchdir(*ctx, dirname(dir)) == LY_EEXIST) {
+ path_unset = 0;
+ }
+
+ /* get features list for this module */
+ get_features(&fset, module, &features);
+
+ /* temporary cleanup */
+ free(dir);
+ free(module);
+
+ /* prepare input handler */
+ ret = ly_in_new_filepath(argv[optind + i], 0, &in);
+ if (ret) {
+ goto cleanup;
+ }
+
+ /* parse the file */
+ ret = lys_parse(*ctx, in, LYS_IN_UNKNOWN, features, NULL);
+ ly_in_free(in, 1);
+ ly_ctx_unset_searchdir_last(*ctx, path_unset);
+
+ if (ret) {
+ /* libyang printed the error messages */
+ goto cleanup;
+ }
+ }
+
+cleanup:
+ if (options_ctx) {
+ ly_ctx_unset_options(*ctx, options_ctx);
+ }
+ ly_set_erase(&fset, free_features);
+ free_cmdline(argv);
+}
diff --git a/tools/lint/cmd_clear.c b/tools/lint/cmd_clear.c
new file mode 100644
index 0000000..5cece3a
--- /dev/null
+++ b/tools/lint/cmd_clear.c
@@ -0,0 +1,91 @@
+/**
+ * @file cmd_clear.c
+ * @author Michal Vasko <mvasko@cesnet.cz>
+ * @author Radek Krejci <rkrejci@cesnet.cz>
+ * @brief 'clear' command of the libyang's yanglint tool.
+ *
+ * Copyright (c) 2015-2020 CESNET, z.s.p.o.
+ *
+ * This source code is licensed under BSD 3-Clause License (the "License").
+ * You may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://opensource.org/licenses/BSD-3-Clause
+ */
+
+#define _GNU_SOURCE
+
+#include "cmd.h"
+
+#include <getopt.h>
+#include <stdint.h>
+#include <stdio.h>
+
+#include "libyang.h"
+
+#include "common.h"
+
+void
+cmd_clear_help(void)
+{
+ printf("Usage: clear [<yang-library-data> | --external]\n"
+ " Replace the current context with an empty one, searchpaths\n"
+ " are not kept.\n"
+ " If <yang-library-data> path specified, load the modules\n"
+ " according to the provided yang library data.\n"
+ " -e, --external-yl\n"
+ " When creating the new context, do not load the internal\n"
+ " ietf-yang-library and let user to load ietf-yang-library from\n"
+ " file. Note, that until a compatible ietf-yang-library loaded,\n"
+ " the 'list' command does not work.\n");
+}
+
+void
+cmd_clear(struct ly_ctx **ctx, const char *cmdline)
+{
+ int argc = 0;
+ char **argv = NULL;
+ int opt, opt_index;
+ struct option options[] = {
+ {"external-yl", no_argument, NULL, 'e'},
+ {"help", no_argument, NULL, 'h'},
+ {NULL, 0, NULL, 0}
+ };
+ uint16_t options_ctx = 0;
+ struct ly_ctx *ctx_new;
+
+ if (parse_cmdline(cmdline, &argc, &argv)) {
+ goto cleanup;
+ }
+
+ while ((opt = getopt_long(argc, argv, "eh", options, &opt_index)) != -1) {
+ switch (opt) {
+ case 'e':
+ options_ctx |= LY_CTX_NO_YANGLIBRARY;
+ break;
+ case 'h':
+ cmd_clear_help();
+ goto cleanup;
+ default:
+ YLMSG_E("Unknown option.\n");
+ goto cleanup;
+ }
+ }
+
+ /* TODO ietf-yang-library support */
+ if (argc != optind) {
+ YLMSG_E("Creating context following the ietf-yang-library data is not yet supported.\n");
+ goto cleanup;
+ }
+
+ if (ly_ctx_new(NULL, options_ctx, &ctx_new)) {
+ YLMSG_W("Failed to create context.\n");
+ goto cleanup;
+ }
+
+ ly_ctx_destroy(*ctx, NULL);
+ *ctx = ctx_new;
+
+cleanup:
+ free_cmdline(argv);
+}
diff --git a/tools/lint/cmd_data.c b/tools/lint/cmd_data.c
new file mode 100644
index 0000000..e5987ad
--- /dev/null
+++ b/tools/lint/cmd_data.c
@@ -0,0 +1,384 @@
+/**
+ * @file cmd_data.c
+ * @author Michal Vasko <mvasko@cesnet.cz>
+ * @author Radek Krejci <rkrejci@cesnet.cz>
+ * @brief 'data' command of the libyang's yanglint tool.
+ *
+ * Copyright (c) 2015-2020 CESNET, z.s.p.o.
+ *
+ * This source code is licensed under BSD 3-Clause License (the "License").
+ * You may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://opensource.org/licenses/BSD-3-Clause
+ */
+
+#define _GNU_SOURCE
+
+#include "cmd.h"
+
+#include <errno.h>
+#include <getopt.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <string.h>
+#include <strings.h>
+
+#include "libyang.h"
+
+#include "common.h"
+
+void
+cmd_data_help(void)
+{
+ printf("Usage: data [-ems] [-t TYPE]\n"
+ " [-f FORMAT] [-d DEFAULTS] [-o OUTFILE] <data1> ...\n"
+ " data [-s] -t (rpc | notif) [-O FILE]\n"
+ " [-f FORMAT] [-d DEFAULTS] [-o OUTFILE] <data1> ...\n"
+ " data [-s] -t reply -r <request-file> [-O FILE]\n"
+ " [-f FORMAT] [-d DEFAULTS] [-o OUTFILE] <data1> ...\n"
+ " data [-s] -t reply [-O FILE]\n"
+ " [-f FORMAT] [-d DEFAULTS] [-o OUTFILE] <data1> <request1> ...\n"
+ " data [-es] [-t TYPE] -x XPATH [-o OUTFILE] <data1> ...\n"
+ " Parse, validate and optionaly print data instances\n\n"
+
+ " -t TYPE, --type=TYPE\n"
+ " Specify data tree type in the input data file(s):\n"
+ " data - Complete datastore with status data (default type).\n"
+ " config - Configuration datastore (without status data).\n"
+ " get - Result of the NETCONF <get> operation.\n"
+ " getconfig - Result of the NETCONF <get-config> operation.\n"
+ " edit - Content of the NETCONF <edit-config> operation.\n"
+ " rpc - Content of the NETCONF <rpc> message, defined as YANG's\n"
+ " RPC/Action input statement.\n"
+ " reply - Reply to the RPC/Action. Besides the reply itself,\n"
+ " yanglint(1) requires information about the request for\n"
+ " the reply. The request (RPC/Action) can be provide as\n"
+ " the --request option or as another input data <file>\n"
+ " provided right after the reply data <file> and\n"
+ " containing complete RPC/Action for the reply.\n"
+ " notif - Notification instance (content of the <notification>\n"
+ " element without <eventTime>).\n\n"
+
+ " -e, --present Validate only with the schema modules whose data actually\n"
+ " exist in the provided input data files. Takes effect only\n"
+ " with the 'data' or 'config' TYPEs. Used to avoid requiring\n"
+ " mandatory nodes from modules which data are not present in the\n"
+ " provided input data files.\n"
+ " -m, --merge Merge input data files into a single tree and validate at\n"
+ " once.The option has effect only for 'data' and 'config' TYPEs.\n"
+ " In case of using -x option, the data are always merged.\n"
+ " -s, --strict Strict data parsing (do not skip unknown data), has no effect\n"
+ " for schemas.\n"
+ " -r PATH, --request=PATH\n"
+ " The alternative way of providing request information for the\n"
+ " '--type=reply'. The PATH is the XPath subset described in\n"
+ " documentation as Path format. It is required to point to the\n"
+ " RPC or Action in the schema which is supposed to be a request\n"
+ " for the reply(ies) being parsed from the input data files.\n"
+ " In case of multiple input data files, the 'request' option can\n"
+ " be set once for all the replies or multiple times each for the\n"
+ " respective input data file.\n"
+ " -O FILE, --operational=FILE\n"
+ " Provide optional data to extend validation of the 'rpc',\n"
+ " 'reply' or 'notif' TYPEs. The FILE is supposed to contain\n"
+ " the :running configuration datastore and state data\n"
+ " (operational datastore) referenced from the RPC/Notification.\n\n"
+
+ " -f FORMAT, --format=FORMAT\n"
+ " Print the data in one of the following formats:\n"
+ " xml, json, lyb\n"
+ " Note that the LYB format requires the -o option specified.\n"
+ " -d MODE, --default=MODE\n"
+ " Print data with default values, according to the MODE\n"
+ " (to print attributes, ietf-netconf-with-defaults model\n"
+ " must be loaded):\n"
+ " all - Add missing default nodes.\n"
+ " all-tagged - Add missing default nodes and mark all the default\n"
+ " nodes with the attribute.\n"
+ " trim - Remove all nodes with a default value.\n"
+ " implicit-tagged - Add missing nodes and mark them with the attribute.\n"
+ " -o OUTFILE, --output=OUTFILE\n"
+ " Write the output to OUTFILE instead of stdout.\n\n"
+
+ " -x XPATH, --xpath=XPATH\n"
+ " Evaluate XPATH expression and print the nodes satysfying the.\n"
+ " expression. The output format is specific and the option cannot\n"
+ " be combined with the -f and -d options. Also all the data\n"
+ " inputs are merged into a single data tree where the expression\n"
+ " is evaluated, so the -m option is always set implicitly.\n\n");
+
+}
+
+static int
+prepare_inputs(int argc, char *argv[], struct ly_set *requests, struct ly_set *inputs)
+{
+ struct ly_in *in;
+ uint8_t request_expected = 0;
+
+ for (int i = 0; i < argc - optind; i++) {
+ LYD_FORMAT format = LYD_UNKNOWN;
+ struct cmdline_file *rec;
+
+ if (get_input(argv[optind + i], NULL, &format, &in)) {
+ return -1;
+ }
+
+ if (request_expected) {
+ if (fill_cmdline_file(requests, in, argv[optind + i], format)) {
+ ly_in_free(in, 1);
+ return -1;
+ }
+
+ request_expected = 0;
+ } else {
+ rec = fill_cmdline_file(inputs, in, argv[optind + i], format);
+ if (!rec) {
+ ly_in_free(in, 1);
+ return -1;
+ }
+
+ if (requests) {
+ /* requests for the replies are expected in another input file */
+ if (++i == argc - optind) {
+ /* there is no such file */
+ YLMSG_E("Missing request input file for the reply input file %s.\n", rec->path);
+ return -1;
+ }
+
+ request_expected = 1;
+ }
+ }
+ }
+
+ if (request_expected) {
+ YLMSG_E("Missing request input file for the reply input file %s.\n", argv[argc - optind - 1]);
+ return -1;
+ }
+
+ return 0;
+}
+
+void
+cmd_data(struct ly_ctx **ctx, const char *cmdline)
+{
+ int argc = 0;
+ char **argv = NULL;
+ int opt, opt_index;
+ struct option options[] = {
+ {"defaults", required_argument, NULL, 'd'},
+ {"present", no_argument, NULL, 'e'},
+ {"format", required_argument, NULL, 'f'},
+ {"help", no_argument, NULL, 'h'},
+ {"merge", no_argument, NULL, 'm'},
+ {"output", required_argument, NULL, 'o'},
+ {"operational", required_argument, NULL, 'O'},
+ {"request", required_argument, NULL, 'r'},
+ {"strict", no_argument, NULL, 's'},
+ {"type", required_argument, NULL, 't'},
+ {"xpath", required_argument, NULL, 'x'},
+ {NULL, 0, NULL, 0}
+ };
+
+ uint8_t data_merge = 0;
+ uint32_t options_print = 0;
+ uint32_t options_parse = 0;
+ uint32_t options_validate = 0;
+ uint8_t data_type = 0;
+ uint8_t data_type_set = 0;
+ LYD_FORMAT format = LYD_UNKNOWN;
+ struct ly_out *out = NULL;
+ struct cmdline_file *operational = NULL;
+ struct ly_set inputs = {0};
+ struct ly_set requests = {0};
+ struct ly_set request_paths = {0};
+ struct ly_set xpaths = {0};
+
+ if (parse_cmdline(cmdline, &argc, &argv)) {
+ goto cleanup;
+ }
+
+ while ((opt = getopt_long(argc, argv, "d:ef:hmo:O:r:st:x:", options, &opt_index)) != -1) {
+ switch (opt) {
+ case 'd': /* --default */
+ if (!strcasecmp(optarg, "all")) {
+ options_print = (options_print & ~LYD_PRINT_WD_MASK) | LYD_PRINT_WD_ALL;
+ } else if (!strcasecmp(optarg, "all-tagged")) {
+ options_print = (options_print & ~LYD_PRINT_WD_MASK) | LYD_PRINT_WD_ALL_TAG;
+ } else if (!strcasecmp(optarg, "trim")) {
+ options_print = (options_print & ~LYD_PRINT_WD_MASK) | LYD_PRINT_WD_TRIM;
+ } else if (!strcasecmp(optarg, "implicit-tagged")) {
+ options_print = (options_print & ~LYD_PRINT_WD_MASK) | LYD_PRINT_WD_IMPL_TAG;
+ } else {
+ YLMSG_E("Unknown default mode %s\n", optarg);
+ cmd_data_help();
+ goto cleanup;
+ }
+ break;
+ case 'f': /* --format */
+ if (!strcasecmp(optarg, "xml")) {
+ format = LYD_XML;
+ } else if (!strcasecmp(optarg, "json")) {
+ format = LYD_JSON;
+ } else if (!strcasecmp(optarg, "lyb")) {
+ format = LYD_LYB;
+ } else {
+ YLMSG_E("Unknown output format %s\n", optarg);
+ cmd_data_help();
+ goto cleanup;
+ }
+ break;
+ case 'o': /* --output */
+ if (out) {
+ YLMSG_E("Only a single output can be specified.\n");
+ goto cleanup;
+ } else {
+ if (ly_out_new_filepath(optarg, &out)) {
+ YLMSG_E("Unable open output file %s (%s)\n", optarg, strerror(errno));
+ goto cleanup;
+ }
+ }
+ break;
+ case 'O': { /* --operational */
+ struct ly_in *in;
+ LYD_FORMAT f;
+
+ if (operational) {
+ YLMSG_E("The operational datastore (-O) cannot be set multiple times.\n");
+ goto cleanup;
+ }
+ if (get_input(optarg, NULL, &f, &in)) {
+ goto cleanup;
+ }
+ operational = fill_cmdline_file(NULL, in, optarg, f);
+ break;
+ } /* case 'O' */
+ case 'r': /* --request */
+ if (ly_set_add(&request_paths, optarg, 0, NULL)) {
+ YLMSG_E("Storing request path \"%s\" failed.\n", optarg);
+ goto cleanup;
+ }
+ break;
+
+ case 'e': /* --present */
+ options_validate |= LYD_VALIDATE_PRESENT;
+ break;
+ case 'm': /* --merge */
+ data_merge = 1;
+ break;
+ case 's': /* --strict */
+ options_parse |= LYD_PARSE_STRICT;
+ break;
+ case 't': /* --type */
+ if (data_type_set) {
+ YLMSG_E("The data type (-t) cannot be set multiple times.\n");
+ goto cleanup;
+ }
+
+ if (!strcasecmp(optarg, "config")) {
+ options_parse |= LYD_PARSE_NO_STATE;
+ } else if (!strcasecmp(optarg, "get")) {
+ options_parse |= LYD_PARSE_ONLY;
+ } else if (!strcasecmp(optarg, "getconfig") || !strcasecmp(optarg, "get-config")) {
+ options_parse |= LYD_PARSE_ONLY | LYD_PARSE_NO_STATE;
+ } else if (!strcasecmp(optarg, "edit")) {
+ options_parse |= LYD_PARSE_ONLY;
+ } else if (!strcasecmp(optarg, "rpc") || !strcasecmp(optarg, "action")) {
+ data_type = LYD_VALIDATE_OP_RPC;
+ } else if (!strcasecmp(optarg, "reply") || !strcasecmp(optarg, "rpcreply")) {
+ data_type = LYD_VALIDATE_OP_REPLY;
+ } else if (!strcasecmp(optarg, "notif") || !strcasecmp(optarg, "notification")) {
+ data_type = LYD_VALIDATE_OP_NOTIF;
+ } else if (!strcasecmp(optarg, "data")) {
+ /* default option */
+ } else {
+ YLMSG_E("Unknown data tree type %s.\n", optarg);
+ cmd_data_help();
+ goto cleanup;
+ }
+
+ data_type_set = 1;
+ break;
+
+ case 'x': /* --xpath */
+ if (ly_set_add(&xpaths, optarg, 0, NULL)) {
+ YLMSG_E("Storing XPath \"%s\" failed.\n", optarg);
+ goto cleanup;
+ }
+ break;
+
+ case 'h': /* --help */
+ cmd_data_help();
+ goto cleanup;
+ default:
+ YLMSG_E("Unknown option.\n");
+ goto cleanup;
+ }
+ }
+
+ if (optind == argc) {
+ YLMSG_E("Missing the data file to process.\n");
+ goto cleanup;
+ }
+
+ if (data_merge) {
+ if (data_type || (options_parse & LYD_PARSE_ONLY)) {
+ /* switch off the option, incompatible input data type */
+ data_merge = 0;
+ } else {
+ /* postpone validation after the merge of all the input data */
+ options_parse |= LYD_PARSE_ONLY;
+ }
+ } else if (xpaths.count) {
+ data_merge = 1;
+ }
+
+ if (xpaths.count && format) {
+ YLMSG_E("The --format option cannot be combined with --xpath option.\n");
+ cmd_data_help();
+ goto cleanup;
+ }
+
+ if (operational && !data_type) {
+ YLMSG_W("Operational datastore takes effect only with RPCs/Actions/Replies/Notifications input data types.\n");
+ free_cmdline_file(operational);
+ operational = NULL;
+ }
+
+ /* process input data files provided as standalone command line arguments */
+ if (prepare_inputs(argc, argv, ((data_type == LYD_VALIDATE_OP_REPLY) && !request_paths.count) ? &requests : NULL,
+ &inputs)) {
+ goto cleanup;
+ }
+
+ if (data_type == LYD_VALIDATE_OP_REPLY) {
+ if (check_request_paths(*ctx, &request_paths, &inputs)) {
+ goto cleanup;
+ }
+ }
+
+ /* default output stream */
+ if (!out) {
+ if (ly_out_new_file(stdout, &out)) {
+ YLMSG_E("Unable to set stdout as output.\n");
+ goto cleanup;
+ }
+ }
+
+ /* parse, validate and print data */
+ if (process_data(*ctx, data_type, data_merge, format, out,
+ options_parse, options_validate, options_print,
+ operational, &inputs, &request_paths, &requests, &xpaths)) {
+ goto cleanup;
+ }
+
+cleanup:
+ ly_out_free(out, NULL, 0);
+ ly_set_erase(&inputs, free_cmdline_file);
+ ly_set_erase(&requests, free_cmdline_file);
+ ly_set_erase(&request_paths, NULL);
+ ly_set_erase(&xpaths, NULL);
+ free_cmdline_file(operational);
+ free_cmdline(argv);
+
+}
diff --git a/tools/lint/cmd_list.c b/tools/lint/cmd_list.c
new file mode 100644
index 0000000..39a8d69
--- /dev/null
+++ b/tools/lint/cmd_list.c
@@ -0,0 +1,86 @@
+/**
+ * @file cmd_list.c
+ * @author Michal Vasko <mvasko@cesnet.cz>
+ * @author Radek Krejci <rkrejci@cesnet.cz>
+ * @brief 'list' command of the libyang's yanglint tool.
+ *
+ * Copyright (c) 2015-2020 CESNET, z.s.p.o.
+ *
+ * This source code is licensed under BSD 3-Clause License (the "License").
+ * You may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://opensource.org/licenses/BSD-3-Clause
+ */
+
+#define _GNU_SOURCE
+
+#include "cmd.h"
+
+#include <getopt.h>
+#include <stdio.h>
+#include <strings.h>
+
+#include "libyang.h"
+
+#include "common.h"
+
+void
+cmd_list_help(void)
+{
+ printf("Usage: list [-f (xml | json)]\n"
+ " Print the list of modules in the current context\n\n"
+ " -f FORMAT, --format=FORMAT\n"
+ " Print the list as ietf-yang-library data in the specified\n"
+ " data FORMAT. If format not specified, a simple list is\n"
+ " printed with an indication of imported (i) / implemented (I)\n"
+ " modules.\n");
+}
+
+void
+cmd_list(struct ly_ctx **ctx, const char *cmdline)
+{
+ int argc = 0;
+ char **argv = NULL;
+ int opt, opt_index;
+ struct option options[] = {
+ {"format", required_argument, NULL, 'f'},
+ {"help", no_argument, NULL, 'h'},
+ {NULL, 0, NULL, 0}
+ };
+ LYD_FORMAT format = LYD_UNKNOWN;
+ struct ly_out *out = NULL;
+
+ if (parse_cmdline(cmdline, &argc, &argv)) {
+ goto cleanup;
+ }
+
+ while ((opt = getopt_long(argc, argv, "f:h", options, &opt_index)) != -1) {
+ switch (opt) {
+ case 'f': /* --format */
+ if (!strcasecmp(optarg, "xml")) {
+ format = LYD_XML;
+ } else if (!strcasecmp(optarg, "json")) {
+ format = LYD_JSON;
+ } else {
+ YLMSG_E("Unknown output format %s\n", optarg);
+ cmd_list_help();
+ goto cleanup;
+ }
+ break;
+ case 'h':
+ cmd_list_help();
+ goto cleanup;
+ default:
+ YLMSG_E("Unknown option.\n");
+ goto cleanup;
+ }
+ }
+
+ ly_out_new_file(stdout, &out);
+ print_list(out, *ctx, format);
+ ly_out_free(out, NULL, 0);
+
+cleanup:
+ free_cmdline(argv);
+}
diff --git a/tools/lint/cmd_load.c b/tools/lint/cmd_load.c
new file mode 100644
index 0000000..1ae2c1e
--- /dev/null
+++ b/tools/lint/cmd_load.c
@@ -0,0 +1,129 @@
+/**
+ * @file cmd_load.c
+ * @author Michal Vasko <mvasko@cesnet.cz>
+ * @author Radek Krejci <rkrejci@cesnet.cz>
+ * @brief 'load' command of the libyang's yanglint tool.
+ *
+ * Copyright (c) 2015-2020 CESNET, z.s.p.o.
+ *
+ * This source code is licensed under BSD 3-Clause License (the "License").
+ * You may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://opensource.org/licenses/BSD-3-Clause
+ */
+
+#define _GNU_SOURCE
+
+#include "cmd.h"
+
+#include <getopt.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <string.h>
+
+#include "libyang.h"
+
+#include "common.h"
+
+void
+cmd_load_help(void)
+{
+ printf("Usage: load [-i] <module-name1>[@<revision>] [<module-name2>[@revision] ...]\n"
+ " Add a new module of the specified name, yanglint will find\n"
+ " them in searchpaths. if the <revision> of the module not\n"
+ " specified, the latest revision available is loaded.\n\n"
+ " -F FEATURES, --features=FEATURES\n"
+ " Features to support, default all.\n"
+ " <modname>:[<feature>,]*\n"
+ " -i, --makeimplemented\n"
+ " Make the imported modules \"referenced\" from any loaded\n"
+ " <schema> module also implemented. If specified a second time,\n"
+ " all the modules are set implemented.\n");
+}
+
+void
+cmd_load(struct ly_ctx **ctx, const char *cmdline)
+{
+ int argc = 0;
+ char **argv = NULL;
+ int opt, opt_index;
+ struct option options[] = {
+ {"features", required_argument, NULL, 'F'},
+ {"help", no_argument, NULL, 'h'},
+ {"makeimplemented", no_argument, NULL, 'i'},
+ {NULL, 0, NULL, 0}
+ };
+ uint16_t options_ctx = 0;
+ struct ly_set fset = {0};
+
+ if (parse_cmdline(cmdline, &argc, &argv)) {
+ goto cleanup;
+ }
+
+ while ((opt = getopt_long(argc, argv, "F:hi", options, &opt_index)) != -1) {
+ switch (opt) {
+ case 'F': /* --features */
+ if (parse_features(optarg, &fset)) {
+ goto cleanup;
+ }
+ break;
+
+ case 'h':
+ cmd_load_help();
+ goto cleanup;
+
+ case 'i': /* --makeimplemented */
+ if (options_ctx & LY_CTX_REF_IMPLEMENTED) {
+ options_ctx &= ~LY_CTX_REF_IMPLEMENTED;
+ options_ctx |= LY_CTX_ALL_IMPLEMENTED;
+ } else {
+ options_ctx |= LY_CTX_REF_IMPLEMENTED;
+ }
+ break;
+
+ default:
+ YLMSG_E("Unknown option.\n");
+ goto cleanup;
+ }
+ }
+
+ if (argc == optind) {
+ /* no argument */
+ cmd_add_help();
+ goto cleanup;
+ }
+
+ if (options_ctx) {
+ ly_ctx_set_options(*ctx, options_ctx);
+ }
+
+ for (int i = 0; i < argc - optind; i++) {
+ /* process the schema module files */
+ char *revision;
+ const char **features = NULL;
+
+ /* get revision */
+ revision = strchr(argv[optind + i], '@');
+ if (revision) {
+ revision[0] = '\0';
+ ++revision;
+ }
+
+ /* get features list for this module */
+ get_features(&fset, argv[optind + i], &features);
+
+ /* load the module */
+ if (!ly_ctx_load_module(*ctx, argv[optind + i], revision, features)) {
+ /* libyang printed the error messages */
+ goto cleanup;
+ }
+ }
+
+cleanup:
+ if (options_ctx) {
+ ly_ctx_unset_options(*ctx, options_ctx);
+ }
+ ly_set_erase(&fset, free_features);
+ free_cmdline(argv);
+}
diff --git a/tools/lint/cmd_print.c b/tools/lint/cmd_print.c
new file mode 100644
index 0000000..a1db023
--- /dev/null
+++ b/tools/lint/cmd_print.c
@@ -0,0 +1,194 @@
+/**
+ * @file cmd_print.c
+ * @author Michal Vasko <mvasko@cesnet.cz>
+ * @author Radek Krejci <rkrejci@cesnet.cz>
+ * @brief 'print' command of the libyang's yanglint tool.
+ *
+ * Copyright (c) 2015-2020 CESNET, z.s.p.o.
+ *
+ * This source code is licensed under BSD 3-Clause License (the "License").
+ * You may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://opensource.org/licenses/BSD-3-Clause
+ */
+
+#define _GNU_SOURCE
+
+#include "cmd.h"
+
+#include <errno.h>
+#include <getopt.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <string.h>
+#include <strings.h>
+
+#include "libyang.h"
+
+#include "common.h"
+
+void
+cmd_print_help(void)
+{
+ printf("Usage: print [-f (yang | yin | tree | info [-q -P PATH])] [-o OUTFILE]\n"
+ " [<module-name1>[@revision]] ...\n"
+ " Print a schema module. The <module-name> is not required\n"
+ " only in case the -P option is specified.\n\n"
+ " -f FORMAT, --format=FORMAT\n"
+ " Print the module in the specified FORMAT. If format not\n"
+ " specified, the 'tree' format is used.\n"
+ " -P PATH, --schema-node=PATH\n"
+ " Print only the specified subtree of the schema.\n"
+ " The PATH is the XPath subset mentioned in documentation as\n"
+ " the Path format. The option can be combined with --single-node\n"
+ " option to print information only about the specified node.\n"
+ " -q, --single-node\n"
+ " Supplement to the --schema-node option to print information\n"
+ " only about a single node specified as PATH argument.\n"
+ " -o OUTFILE, --output=OUTFILE\n"
+ " Write the output to OUTFILE instead of stdout.\n");
+}
+
+void
+cmd_print(struct ly_ctx **ctx, const char *cmdline)
+{
+ LY_ERR ret;
+ int argc = 0;
+ char **argv = NULL;
+ int opt, opt_index;
+ struct option options[] = {
+ {"format", required_argument, NULL, 'f'},
+ {"help", no_argument, NULL, 'h'},
+ {"output", required_argument, NULL, 'o'},
+ {"schema-node", required_argument, NULL, 'P'},
+ {"single-node", no_argument, NULL, 'q'},
+ {NULL, 0, NULL, 0}
+ };
+ uint16_t options_print = 0;
+ const char *node_path = NULL;
+ LYS_OUTFORMAT format = LYS_OUT_TREE;
+ const char *out_path = NULL;
+ struct ly_out *out = NULL;
+
+ if (parse_cmdline(cmdline, &argc, &argv)) {
+ goto cleanup;
+ }
+
+ while ((opt = getopt_long(argc, argv, "f:ho:P:q", options, &opt_index)) != -1) {
+ switch (opt) {
+ case 'o': /* --output */
+ if (out) {
+ if (ly_out_filepath(out, optarg) != NULL) {
+ YLMSG_E("Unable open output file %s (%s)\n", optarg, strerror(errno));
+ goto cleanup;
+ }
+ } else {
+ if (ly_out_new_filepath(optarg, &out)) {
+ YLMSG_E("Unable open output file %s (%s)\n", optarg, strerror(errno));
+ goto cleanup;
+ }
+ }
+ break;
+
+ case 'f': /* --format */
+ if (!strcasecmp(optarg, "yang")) {
+ format = LYS_OUT_YANG;
+ } else if (!strcasecmp(optarg, "yin")) {
+ format = LYS_OUT_YIN;
+ } else if (!strcasecmp(optarg, "info")) {
+ format = LYS_OUT_YANG_COMPILED;
+ } else if (!strcasecmp(optarg, "tree")) {
+ format = LYS_OUT_TREE;
+ } else {
+ YLMSG_E("Unknown output format %s\n", optarg);
+ cmd_print_help();
+ goto cleanup;
+ }
+ break;
+
+ case 'P': /* --schema-node */
+ node_path = optarg;
+ break;
+
+ case 'q': /* --single-node */
+ options_print |= LYS_PRINT_NO_SUBSTMT;
+ break;
+
+ case 'h':
+ cmd_print_help();
+ goto cleanup;
+ default:
+ YLMSG_E("Unknown option.\n");
+ goto cleanup;
+ }
+ }
+
+ /* file name */
+ if ((argc == optind) && !node_path) {
+ YLMSG_E("Missing the name of the module to print.\n");
+ goto cleanup;
+ }
+
+ if (out_path) {
+ ret = ly_out_new_filepath(out_path, &out);
+ } else {
+ ret = ly_out_new_file(stdout, &out);
+ }
+ if (ret) {
+ YLMSG_E("Could not open the output file (%s).\n", strerror(errno));
+ goto cleanup;
+ }
+
+ if (node_path) {
+ const struct lysc_node *node;
+ node = lys_find_path(*ctx, NULL, node_path, 0);
+ if (!node) {
+ node = lys_find_path(*ctx, NULL, node_path, 1);
+
+ if (!node) {
+ YLMSG_E("The requested schema node \"%s\" does not exists.\n", node_path);
+ goto cleanup;
+ }
+ }
+ if (lys_print_node(out, node, format, 0, options_print)) {
+ YLMSG_E("Unable to print schema node %s.\n", node_path);
+ goto cleanup;
+ }
+ } else {
+ for (int i = 0; i < argc - optind; i++) {
+ struct lys_module *module;
+ char *revision;
+
+ /* get revision */
+ revision = strchr(argv[optind + i], '@');
+ if (revision) {
+ revision[0] = '\0';
+ ++revision;
+ }
+
+ if (revision) {
+ module = ly_ctx_get_module(*ctx, argv[optind + i], revision);
+ } else {
+ module = ly_ctx_get_module_latest(*ctx, argv[optind + i]);
+ }
+ if (!module) {
+ /* TODO try to find it as a submodule */
+ if (revision) {
+ YLMSG_E("No (sub)module \"%s\" in revision %s found.\n", argv[optind + i], revision);
+ } else {
+ YLMSG_E("No (sub)module \"%s\" found.\n", argv[optind + i]);
+ }
+ goto cleanup;
+ }
+ if (lys_print_module(out, module, format, 0, options_print)) {
+ YLMSG_E("Unable to print module %s.\n", argv[optind + i]);
+ goto cleanup;
+ }
+ }
+ }
+
+cleanup:
+ free_cmdline(argv);
+ ly_out_free(out, NULL, out_path ? 1 : 0);
+}
diff --git a/tools/lint/cmd_searchpath.c b/tools/lint/cmd_searchpath.c
new file mode 100644
index 0000000..a94a343
--- /dev/null
+++ b/tools/lint/cmd_searchpath.c
@@ -0,0 +1,90 @@
+/**
+ * @file cmd_searchpath.c
+ * @author Michal Vasko <mvasko@cesnet.cz>
+ * @author Radek Krejci <rkrejci@cesnet.cz>
+ * @brief 'searchpath' command of the libyang's yanglint tool.
+ *
+ * Copyright (c) 2015-2020 CESNET, z.s.p.o.
+ *
+ * This source code is licensed under BSD 3-Clause License (the "License").
+ * You may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://opensource.org/licenses/BSD-3-Clause
+ */
+
+#define _GNU_SOURCE
+
+#include "cmd.h"
+
+#include <getopt.h>
+#include <stdint.h>
+#include <stdio.h>
+
+#include "libyang.h"
+
+#include "common.h"
+
+void
+cmd_searchpath_help(void)
+{
+ printf("Usage: searchpath [--clear] [<modules-dir-path> ...]\n"
+ " Set paths of directories where to search for imports and\n"
+ " includes of the schema modules. The current working directory\n"
+ " and the path of the module being added is used implicitly.\n"
+ " The 'load' command uses these paths to search even for the\n"
+ " schema modules to be loaded.\n");
+}
+
+void
+cmd_searchpath(struct ly_ctx **ctx, const char *cmdline)
+{
+ int argc = 0;
+ char **argv = NULL;
+ int opt, opt_index;
+ struct option options[] = {
+ {"clear", no_argument, NULL, 'c'},
+ {"help", no_argument, NULL, 'h'},
+ {NULL, 0, NULL, 0}
+ };
+ int8_t cleared = 0;
+
+ if (parse_cmdline(cmdline, &argc, &argv)) {
+ goto cleanup;
+ }
+
+ while ((opt = getopt_long(argc, argv, "ch", options, &opt_index)) != -1) {
+ switch (opt) {
+ case 'c':
+ ly_ctx_unset_searchdir(*ctx, NULL);
+ cleared = 1;
+ break;
+ case 'h':
+ cmd_searchpath_help();
+ goto cleanup;
+ default:
+ YLMSG_E("Unknown option.\n");
+ goto cleanup;
+ }
+ }
+
+ if (!cleared && (argc == optind)) {
+ /* no argument - print the paths */
+ const char * const *dirs = ly_ctx_get_searchdirs(*ctx);
+
+ printf("List of the searchpaths:\n");
+ for (uint32_t i = 0; dirs[0]; ++i) {
+ printf(" %s\n", dirs[i]);
+ }
+ goto cleanup;
+ }
+
+ for (int i = 0; i < argc - optind; i++) {
+ if (ly_ctx_set_searchdir(*ctx, argv[optind + i])) {
+ goto cleanup;
+ }
+ }
+
+cleanup:
+ free_cmdline(argv);
+}
diff --git a/tools/lint/commands.c b/tools/lint/commands.c
deleted file mode 100644
index 51dd07c..0000000
--- a/tools/lint/commands.c
+++ /dev/null
@@ -1,1545 +0,0 @@
-/**
- * @file commands.c
- * @author Michal Vasko <mvasko@cesnet.cz>
- * @brief libyang's yanglint tool commands
- *
- * Copyright (c) 2015 CESNET, z.s.p.o.
- *
- * This source code is licensed under BSD 3-Clause License (the "License").
- * You may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://opensource.org/licenses/BSD-3-Clause
- */
-
-#define _GNU_SOURCE
-
-#include "commands.h"
-
-#include <ctype.h>
-#include <errno.h>
-#include <getopt.h>
-#include <libgen.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/stat.h>
-
-#include "compat.h"
-#include "libyang.h"
-
-COMMAND commands[];
-extern int done;
-extern struct ly_ctx *ctx;
-
-void
-cmd_add_help(void)
-{
- printf("add [-i] <path-to-model> [<paths-to-other-models> ...]\n");
- printf("\t-i - make all the imported modules implemented\n");
-}
-
-void
-cmd_load_help(void)
-{
- printf("load [-i] <model-name> [<other-model-names> ...]\n");
- printf("\t-i - make all the imported modules implemented\n");
-}
-
-void
-cmd_clear_help(void)
-{
- printf("clear [<yang-library> | -e]\n");
- printf("\t Replace the current context with an empty one, searchpaths are not kept.\n");
- printf("\t If <yang-library> path specified, load the modules according to the yang library data.\n");
- printf("\t Option '-e' causes ietf-yang-library will not be loaded.\n");
-}
-
-void
-cmd_print_help(void)
-{
- printf("print [-f (yang | yin | tree [<tree-options>] | info [-P <info-path>] [-(-s)ingle-node])] [-o <output-file>]"
- " <model-name>[@<revision>]\n");
- printf("\n");
- printf("\ttree-options:\t--tree-print-groupings\t(print top-level groupings in a separate section)\n");
- printf("\t \t--tree-print-uses\t(print uses nodes instead the resolved grouping nodes)\n");
- printf("\t \t--tree-no-leafref-target\t(do not print the target nodes of leafrefs)\n");
- printf("\t \t--tree-path <data-path>\t(print only the specified subtree)\n");
- printf("\t \t--tree-line-length <line-length>\t(wrap lines if longer than line-length,\n");
- printf("\t \t\tnot a strict limit, longer lines can often appear)\n");
- printf("\n");
- printf("\tinfo-path:\t<data-path> | identity/<identity-name> | feature/<feature-name>\n");
- printf("\n");
- printf("\tschema-path:\t( /<module-name>:<node-identifier> )+\n");
-}
-
-void
-cmd_data_help(void)
-{
- printf("data [-(-s)trict] [-t TYPE] [-d DEFAULTS] [-o <output-file>] [-f (xml | json | lyb)] [-r <running-file-name>]\n");
- printf(" <data-file-name> [<RPC/action-data-file-name> | <yang-data name>]\n\n");
- printf("Accepted TYPEs:\n");
- printf("\tauto - resolve data type (one of the following) automatically (as pyang does),\n");
- printf("\t this option is applicable only in case of XML input data.\n");
- printf("\tdata - LYD_OPT_DATA (default value) - complete datastore including status data.\n");
- printf("\tconfig - LYD_OPT_CONFIG - complete configuration datastore.\n");
- printf("\tget - LYD_OPT_GET - <get> operation result.\n");
- printf("\tgetconfig - LYD_OPT_GETCONFIG - <get-config> operation result.\n");
- printf("\tedit - LYD_OPT_EDIT - <edit-config>'s data (content of its <config> element).\n");
- printf("\trpc - LYD_OPT_RPC - NETCONF RPC message.\n");
- printf("\trpcreply - LYD_OPT_RPCREPLY (last parameter mandatory in this case)\n");
- printf("\tnotif - LYD_OPT_NOTIF - NETCONF Notification message.\n");
- printf("\tyangdata - LYD_OPT_DATA_TEMPLATE - yang-data extension (last parameter mandatory in this case)\n\n");
- printf("Accepted DEFAULTS:\n");
- printf("\tall - add missing default nodes\n");
- printf("\tall-tagged - add missing default nodes and mark all the default nodes with the attribute.\n");
- printf("\ttrim - remove all nodes with a default value\n");
- printf("\timplicit-tagged - add missing nodes and mark them with the attribute\n\n");
- printf("Option -r:\n");
- printf("\tOptional parameter for 'rpc', 'rpcreply' and 'notif' TYPEs, the file contains running\n");
- printf("\tconfiguration datastore data referenced from the RPC/Notification. Note that the file is\n");
- printf("\tvalidated as 'data' TYPE. Special value '!' can be used as argument to ignore the\n");
- printf("\texternal references.\n\n");
- printf("\tIf an XPath expression (when/must) needs access to configuration data, you can provide\n");
- printf("\tthem in a file, which will be parsed as 'data' TYPE.\n\n");
-}
-
-void
-cmd_xpath_help(void)
-{
- printf("xpath [-t TYPE] [-x <additional-tree-file-name>] -e <XPath-expression>\n"
- " <XML-data-file-name> [<JSON-rpc/action-schema-nodeid>]\n");
- printf("Accepted TYPEs:\n");
- printf("\tauto - resolve data type (one of the following) automatically (as pyang does),\n");
- printf("\t this option is applicable only in case of XML input data.\n");
- printf("\tconfig - LYD_OPT_CONFIG\n");
- printf("\tget - LYD_OPT_GET\n");
- printf("\tgetconfig - LYD_OPT_GETCONFIG\n");
- printf("\tedit - LYD_OPT_EDIT\n");
- printf("\trpc - LYD_OPT_RPC\n");
- printf("\trpcreply - LYD_OPT_RPCREPLY (last parameter mandatory in this case)\n");
- printf("\tnotif - LYD_OPT_NOTIF\n\n");
- printf("Option -x:\n");
- printf("\tIf RPC/action/notification/RPC reply (for TYPEs 'rpc', 'rpcreply', and 'notif') includes\n");
- printf("\tan XPath expression (when/must) that needs access to the configuration data, you can provide\n");
- printf("\tthem in a file, which will be parsed as 'config'.\n");
-}
-
-void
-cmd_list_help(void)
-{
- printf("list [-f (xml | json)]\n\n");
- printf("\tBasic list output (no -f): i - imported module, I - implemented module\n");
-}
-
-void
-cmd_feature_help(void)
-{
- printf("feature [ -(-e)nable | -(-d)isable (* | <feature-name>[,<feature-name> ...]) ] <model-name>[@<revision>]\n");
-}
-
-void
-cmd_searchpath_help(void)
-{
- printf("searchpath [<model-dir-path> | --clear]\n\n");
- printf("\tThey are used to search for imports and includes of a model.\n");
- printf("\tThe \"load\" command uses these directories to find models directly.\n");
-}
-
-void
-cmd_verb_help(void)
-{
- printf("verb (error/0 | warning/1 | verbose/2 | debug/3)\n");
-}
-
-#ifndef NDEBUG
-
-void
-cmd_debug_help(void)
-{
- printf("debug (dict | yang | yin | xpath | diff)+\n");
-}
-
-#endif
-
-LYS_INFORMAT
-get_schema_format(const char *path)
-{
- char *ptr;
-
- if ((ptr = strrchr(path, '.')) != NULL) {
- ++ptr;
- if (!strcmp(ptr, "yang")) {
- return LYS_IN_YANG;
- } else if (!strcmp(ptr, "yin")) {
- return LYS_IN_YIN;
- } else {
- fprintf(stderr, "Input file in an unknown format \"%s\".\n", ptr);
- return LYS_IN_UNKNOWN;
- }
- } else {
- fprintf(stdout, "Input file \"%s\" without extension - unknown format.\n", path);
- return LYS_IN_UNKNOWN;
- }
-}
-
-int
-cmd_add(const char *arg)
-{
- int path_len, ret = 1;
- char *path, *dir, *s, *arg_ptr;
- const struct lys_module *model;
- LYS_INFORMAT format = LYS_IN_UNKNOWN;
-
- if (strlen(arg) < 5) {
- cmd_add_help();
- return 1;
- }
-
- arg_ptr = strdup(arg + 3 /* ignore "add" */);
-
- for (s = strstr(arg_ptr, "-i"); s ; s = strstr(s + 2, "-i")) {
- if (s[2] == '\0' || s[2] == ' ') {
- ly_ctx_set_options(ctx, LY_CTX_ALL_IMPLEMENTED);
- s[0] = s[1] = ' ';
- }
- }
- s = arg_ptr;
-
- while (arg_ptr[0] == ' ') {
- ++arg_ptr;
- }
- if (strchr(arg_ptr, ' ')) {
- path_len = strchr(arg_ptr, ' ') - arg_ptr;
- } else {
- path_len = strlen(arg_ptr);
- }
- path = strndup(arg_ptr, path_len);
-
- while (path) {
- int unset_path = 1;
- format = get_schema_format(path);
- if (format == LYS_IN_UNKNOWN) {
- free(path);
- goto cleanup;
- }
-
- /* add temporarily also the path of the module itself */
- dir = strdup(path);
- if (ly_ctx_set_searchdir(ctx, dirname(dir)) == LY_EEXIST) {
- unset_path = 0;
- }
- /* parse the file */
- lys_parse_path(ctx, path, format, &model);
- ly_ctx_unset_searchdir_last(ctx, unset_path);
- free(path);
- free(dir);
-
- if (!model) {
- /* libyang printed the error messages */
- goto cleanup;
- }
-
- /* next model */
- arg_ptr += path_len;
- while (arg_ptr[0] == ' ') {
- ++arg_ptr;
- }
- if (strchr(arg_ptr, ' ')) {
- path_len = strchr(arg_ptr, ' ') - arg_ptr;
- } else {
- path_len = strlen(arg_ptr);
- }
-
- if (path_len) {
- path = strndup(arg_ptr, path_len);
- } else {
- path = NULL;
- }
- }
- if (format == LYS_IN_UNKNOWN) {
- /* no schema on input */
- cmd_add_help();
- goto cleanup;
- }
- ret = 0;
-
-cleanup:
- free(s);
- ly_ctx_unset_options(ctx, LY_CTX_ALL_IMPLEMENTED);
-
- return ret;
-}
-
-int
-cmd_load(const char *arg)
-{
- int name_len, ret = 1;
- char *name, *s, *arg_ptr;
- const struct lys_module *model;
-
- if (strlen(arg) < 6) {
- cmd_load_help();
- return 1;
- }
-
- arg_ptr = strdup(arg + 4 /* ignore "load" */);
-
- for (s = strstr(arg_ptr, "-i"); s ; s = strstr(s + 2, "-i")) {
- if (s[2] == '\0' || s[2] == ' ') {
- ly_ctx_set_options(ctx, LY_CTX_ALL_IMPLEMENTED);
- s[0] = s[1] = ' ';
- }
- }
- s = arg_ptr;
-
- while (arg_ptr[0] == ' ') {
- ++arg_ptr;
- }
- if (strchr(arg_ptr, ' ')) {
- name_len = strchr(arg_ptr, ' ') - arg_ptr;
- } else {
- name_len = strlen(arg_ptr);
- }
- name = strndup(arg_ptr, name_len);
-
- while (name) {
- model = ly_ctx_load_module(ctx, name, NULL, NULL);
- free(name);
- if (!model) {
- /* libyang printed the error messages */
- goto cleanup;
- }
-
- /* next model */
- arg_ptr += name_len;
- while (arg_ptr[0] == ' ') {
- ++arg_ptr;
- }
- if (strchr(arg_ptr, ' ')) {
- name_len = strchr(arg_ptr, ' ') - arg_ptr;
- } else {
- name_len = strlen(arg_ptr);
- }
-
- if (name_len) {
- name = strndup(arg_ptr, name_len);
- } else {
- name = NULL;
- }
- }
- ret = 0;
-
-cleanup:
- free(s);
- ly_ctx_unset_options(ctx, LY_CTX_ALL_IMPLEMENTED);
-
- return ret;
-}
-
-int
-cmd_print(const char *arg)
-{
- int c, argc, option_index, ret = 1, tree_ll = 0, output_opts = 0;
- char **argv = NULL, *ptr, *model_name, *revision;
- const char *out_path = NULL, *target_path = NULL;
- const struct lys_module *module;
- LYS_OUTFORMAT format = LYS_OUT_TREE;
- struct ly_out *out = NULL;
- static struct option long_options[] = {
- {"help", no_argument, 0, 'h'},
- {"format", required_argument, 0, 'f'},
- {"output", required_argument, 0, 'o'},
-#if 0
- {"tree-print-groupings", no_argument, 0, 'g'},
- {"tree-print-uses", no_argument, 0, 'u'},
- {"tree-no-leafref-target", no_argument, 0, 'n'},
- {"tree-path", required_argument, 0, 'P'},
-#endif
- {"info-path", required_argument, 0, 'P'},
- {"single-node", no_argument, 0, 's'},
-#if 0
- {"tree-line-length", required_argument, 0, 'L'},
-#endif
- {NULL, 0, 0, 0}
- };
- void *rlcd;
-
- argc = 1;
- argv = malloc(2*sizeof *argv);
- *argv = strdup(arg);
- ptr = strtok(*argv, " ");
- while ((ptr = strtok(NULL, " "))) {
- rlcd = realloc(argv, (argc+2)*sizeof *argv);
- if (!rlcd) {
- fprintf(stderr, "Memory allocation failed (%s:%d, %s)", __FILE__, __LINE__, strerror(errno));
- goto cleanup;
- }
- argv = rlcd;
- argv[argc++] = ptr;
- }
- argv[argc] = NULL;
-
- optind = 0;
- while (1) {
- option_index = 0;
- c = getopt_long(argc, argv, "chf:go:guP:sL:", long_options, &option_index);
- if (c == -1) {
- break;
- }
-
- switch (c) {
- case 'h':
- cmd_print_help();
- ret = 0;
- goto cleanup;
- case 'f':
- if (!strcmp(optarg, "yang")) {
- format = LYS_OUT_YANG;
- } else if (!strcmp(optarg, "yin")) {
- format = LYS_OUT_YIN;
-#if 0
- } else if (!strcmp(optarg, "tree")) {
- format = LYS_OUT_TREE;
- } else if (!strcmp(optarg, "tree-rfc")) {
- format = LYS_OUT_TREE;
- output_opts |= LYS_OUTOPT_TREE_RFC;
-#endif
- } else if (!strcmp(optarg, "info")) {
- format = LYS_OUT_YANG_COMPILED;
- } else {
- fprintf(stderr, "Unknown output format \"%s\".\n", optarg);
- goto cleanup;
- }
- break;
- case 'o':
- if (out_path) {
- fprintf(stderr, "Output specified twice.\n");
- goto cleanup;
- }
- out_path = optarg;
- break;
-#if 0
- case 'g':
- output_opts |= LYS_OUTOPT_TREE_GROUPING;
- break;
- case 'u':
- output_opts |= LYS_OUTOPT_TREE_USES;
- break;
- case 'n':
- output_opts |= LYS_OUTOPT_TREE_NO_LEAFREF;
- break;
-#endif
- case 'P':
- target_path = optarg;
- break;
- case 's':
- output_opts |= LYS_PRINT_NO_SUBSTMT;
- break;
-#if 0
- case 'L':
- tree_ll = atoi(optarg);
- break;
-#endif
- case '?':
- fprintf(stderr, "Unknown option \"%d\".\n", (char)c);
- goto cleanup;
- }
- }
-
- /* file name */
- if (optind == argc && !target_path) {
- fprintf(stderr, "Missing the module name.\n");
- goto cleanup;
- }
-
-#if 0
- /* tree fromat with or without gropings */
- if ((output_opts || tree_ll) && format != LYS_OUT_TREE) {
- fprintf(stderr, "--tree options take effect only in case of the tree output format.\n");
- }
-#endif
-
- if (!target_path) {
- /* module, revision */
- model_name = argv[optind];
- revision = NULL;
- if (strchr(model_name, '@')) {
- revision = strchr(model_name, '@');
- revision[0] = '\0';
- ++revision;
- }
-
- if (revision) {
- module = ly_ctx_get_module(ctx, model_name, revision);
- } else {
- module = ly_ctx_get_module_latest(ctx, model_name);
- }
-#if 0
- if (!module) {
- /* not a module, try to find it as a submodule */
- module = (const struct lys_module *)ly_ctx_get_submodule(ctx, NULL, NULL, model_name, revision);
- }
-#endif
-
- if (!module) {
- if (revision) {
- fprintf(stderr, "No (sub)module \"%s\" in revision %s found.\n", model_name, revision);
- } else {
- fprintf(stderr, "No (sub)module \"%s\" found.\n", model_name);
- }
- goto cleanup;
- }
- }
-
- if (out_path) {
- ret = ly_out_new_filepath(out_path, &out);
- } else {
- ret = ly_out_new_file(stdout, &out);
- }
- if (ret) {
- fprintf(stderr, "Could not open the output file (%s).\n", strerror(errno));
- goto cleanup;
- }
-
- if (target_path) {
- const struct lysc_node *node = lys_find_path(ctx, NULL, target_path, 0);
- if (node) {
- ret = lys_print_node(out, node, format, tree_ll, output_opts);
- } else {
- fprintf(stderr, "The requested schema node \"%s\" does not exists.\n", target_path);
- }
- } else {
- ret = lys_print_module(out, module, format, tree_ll, output_opts);
- }
-
-cleanup:
- free(*argv);
- free(argv);
-
- ly_out_free(out, NULL, out_path ? 1 : 0);
-
- return ret;
-}
-
-static int
-parse_data(char *filepath, int *options, const struct lyd_node *tree, const char *rpc_act_file,
- struct lyd_node **result)
-{
- struct lyd_node *data = NULL, *rpc_act = NULL;
- int opts = *options;
- struct ly_in *in;
-
- if (ly_in_new_filepath(filepath, 0, &in)) {
- fprintf(stderr, "Unable to open input YANG data file \"%s\".", filepath);
- return EXIT_FAILURE;
- }
-
-#if 0
- if ((opts & LYD_OPT_TYPEMASK) == LYD_OPT_TYPEMASK) {
- /* automatically detect data type from the data top level */
- if (informat != LYD_XML) {
- fprintf(stderr, "Only XML data can be automatically explored.\n");
- return EXIT_FAILURE;
- }
-
- xml = lyxml_parse_path(ctx, filepath, 0);
- if (!xml) {
- fprintf(stderr, "Failed to parse XML data for automatic type detection.\n");
- return EXIT_FAILURE;
- }
-
- /* NOTE: namespace is ignored to simplify usage of this feature */
-
- if (!strcmp(xml->name, "data")) {
- fprintf(stdout, "Parsing %s as complete datastore.\n", filepath);
- opts = (opts & ~LYD_OPT_TYPEMASK) | LYD_OPT_DATA_ADD_YANGLIB;
- } else if (!strcmp(xml->name, "config")) {
- fprintf(stdout, "Parsing %s as config data.\n", filepath);
- opts = (opts & ~LYD_OPT_TYPEMASK) | LYD_OPT_CONFIG;
- } else if (!strcmp(xml->name, "get-reply")) {
- fprintf(stdout, "Parsing %s as <get> reply data.\n", filepath);
- opts = (opts & ~LYD_OPT_TYPEMASK) | LYD_OPT_GET;
- } else if (!strcmp(xml->name, "get-config-reply")) {
- fprintf(stdout, "Parsing %s as <get-config> reply data.\n", filepath);
- opts = (opts & ~LYD_OPT_TYPEMASK) | LYD_OPT_GETCONFIG;
- } else if (!strcmp(xml->name, "edit-config")) {
- fprintf(stdout, "Parsing %s as <edit-config> data.\n", filepath);
- opts = (opts & ~LYD_OPT_TYPEMASK) | LYD_OPT_EDIT;
- } else if (!strcmp(xml->name, "rpc")) {
- fprintf(stdout, "Parsing %s as <rpc> data.\n", filepath);
- opts = (opts & ~LYD_OPT_TYPEMASK) | LYD_OPT_RPC;
- } else if (!strcmp(xml->name, "rpc-reply")) {
- if (!rpc_act_file) {
- fprintf(stderr, "RPC/action reply data require additional argument (file with the RPC/action).\n");
- lyxml_free(ctx, xml);
- return EXIT_FAILURE;
- }
- fprintf(stdout, "Parsing %s as <rpc-reply> data.\n", filepath);
- opts = (opts & ~LYD_OPT_TYPEMASK) | LYD_OPT_RPCREPLY;
- rpc_act = lyd_parse_path(ctx, rpc_act_file, informat, LYD_OPT_RPC, val_tree);
- if (!rpc_act) {
- fprintf(stderr, "Failed to parse RPC/action.\n");
- lyxml_free(ctx, xml);
- return EXIT_FAILURE;
- }
- } else if (!strcmp(xml->name, "notification")) {
- fprintf(stdout, "Parsing %s as <notification> data.\n", filepath);
- opts = (opts & ~LYD_OPT_TYPEMASK) | LYD_OPT_NOTIF;
- } else if (!strcmp(xml->name, "yang-data")) {
- fprintf(stdout, "Parsing %s as <yang-data> data.\n", filepath);
- opts = (opts & ~LYD_OPT_TYPEMASK) | LYD_OPT_DATA_TEMPLATE;
- if (!rpc_act_file) {
- fprintf(stderr, "YANG-DATA require additional argument (name instance of yang-data extension).\n");
- lyxml_free(ctx, xml);
- return EXIT_FAILURE;
- }
- } else {
- fprintf(stderr, "Invalid top-level element for automatic data type recognition.\n");
- lyxml_free(ctx, xml);
- return EXIT_FAILURE;
- }
-
- if (opts & LYD_OPT_RPCREPLY) {
- data = lyd_parse_xml(ctx, &xml->child, opts, rpc_act, val_tree);
- } else if (opts & (LYD_OPT_RPC | LYD_OPT_NOTIF)) {
- data = lyd_parse_xml(ctx, &xml->child, opts, val_tree);
- } else if (opts & LYD_OPT_DATA_TEMPLATE) {
- data = lyd_parse_xml(ctx, &xml->child, opts, rpc_act_file);
- } else {
- data = lyd_parse_xml(ctx, &xml->child, opts);
- }
- lyxml_free(ctx, xml);
- } else {
- if (opts & LYD_OPT_RPCREPLY) {
- if (!rpc_act_file) {
- fprintf(stderr, "RPC/action reply data require additional argument (file with the RPC/action).\n");
- return EXIT_FAILURE;
- }
- rpc_act = lyd_parse_path(ctx, rpc_act_file, informat, LYD_OPT_RPC, trees);
- if (!rpc_act) {
- fprintf(stderr, "Failed to parse RPC/action.\n");
- return EXIT_FAILURE;
- }
- if (trees) {
- const struct lyd_node **trees_new;
- unsigned int u;
- trees_new = lyd_trees_new(1, rpc_act);
-
- LY_ARRAY_FOR(trees, u) {
- trees_new = lyd_trees_add(trees_new, trees[u]);
- }
- lyd_trees_free(trees, 0);
- trees = trees_new;
- } else {
- trees = lyd_trees_new(1, rpc_act);
- }
- data = lyd_parse_path(ctx, filepath, informat, opts, trees);
- } else if (opts & (LYD_OPT_RPC | LYD_OPT_NOTIF)) {
- data = lyd_parse_path(ctx, filepath, informat, opts, trees);
- } else if (opts & LYD_OPT_DATA_TEMPLATE) {
- if (!rpc_act_file) {
- fprintf(stderr, "YANG-DATA require additional argument (name instance of yang-data extension).\n");
- return EXIT_FAILURE;
- }
- data = lyd_parse_path(ctx, filepath, informat, opts, rpc_act_file);
- } else {
-#endif
-
- lyd_parse_data(ctx, in, 0, opts, LYD_VALIDATE_PRESENT, &data);
-#if 0
- }
- }
-#endif
- ly_in_free(in, 0);
-
- lyd_free_all(rpc_act);
-
- if (ly_err_first(ctx)) {
- fprintf(stderr, "Failed to parse data.\n");
- lyd_free_all(data);
- return EXIT_FAILURE;
- }
-
- *result = data;
- *options = opts;
- return EXIT_SUCCESS;
-}
-
-int
-cmd_data(const char *arg)
-{
- int c, argc, option_index, ret = 1;
- int options = 0, printopt = 0;
- char **argv = NULL, *ptr;
- const char *out_path = NULL;
- struct lyd_node *data = NULL;
- struct lyd_node *tree = NULL;
- LYD_FORMAT outformat = 0;
- struct ly_out *out = NULL;
- static struct option long_options[] = {
- {"defaults", required_argument, 0, 'd'},
- {"help", no_argument, 0, 'h'},
- {"format", required_argument, 0, 'f'},
- {"option", required_argument, 0, 't'},
- {"output", required_argument, 0, 'o'},
- {"running", required_argument, 0, 'r'},
- {"strict", no_argument, 0, 's'},
- {NULL, 0, 0, 0}
- };
- void *rlcd;
-
- argc = 1;
- argv = malloc(2*sizeof *argv);
- *argv = strdup(arg);
- ptr = strtok(*argv, " ");
- while ((ptr = strtok(NULL, " "))) {
- rlcd = realloc(argv, (argc + 2) * sizeof *argv);
- if (!rlcd) {
- fprintf(stderr, "Memory allocation failed (%s:%d, %s)", __FILE__, __LINE__, strerror(errno));
- goto cleanup;
- }
- argv = rlcd;
- argv[argc++] = ptr;
- }
- argv[argc] = NULL;
-
- optind = 0;
- while (1) {
- option_index = 0;
- c = getopt_long(argc, argv, "d:hf:o:st:r:", long_options, &option_index);
- if (c == -1) {
- break;
- }
-
- switch (c) {
- case 'd':
- if (!strcmp(optarg, "all")) {
- printopt = (printopt & ~LYD_PRINT_WD_MASK) | LYD_PRINT_WD_ALL;
- } else if (!strcmp(optarg, "all-tagged")) {
- printopt = (printopt & ~LYD_PRINT_WD_MASK) | LYD_PRINT_WD_ALL_TAG;
- } else if (!strcmp(optarg, "trim")) {
- printopt = (printopt & ~LYD_PRINT_WD_MASK) | LYD_PRINT_WD_TRIM;
- } else if (!strcmp(optarg, "implicit-tagged")) {
- printopt = (printopt & ~LYD_PRINT_WD_MASK) | LYD_PRINT_WD_IMPL_TAG;
- }
- break;
- case 'h':
- cmd_data_help();
- ret = 0;
- goto cleanup;
- case 'f':
- if (!strcmp(optarg, "xml")) {
- outformat = LYD_XML;
- } else if (!strcmp(optarg, "json")) {
- outformat = LYD_JSON;
- } else if (!strcmp(optarg, "lyb")) {
- outformat = LYD_LYB;
- } else {
- fprintf(stderr, "Unknown output format \"%s\".\n", optarg);
- goto cleanup;
- }
- break;
- case 'o':
- if (out_path) {
- fprintf(stderr, "Output specified twice.\n");
- goto cleanup;
- }
- out_path = optarg;
- break;
-#if 0
- case 'r':
- if (optarg[0] == '!') {
- /* ignore extenral dependencies to the running datastore */
- options |= LYD_OPT_NOEXTDEPS;
- } else {
- /* external file with the running datastore */
- val_tree = lyd_parse_path(ctx, optarg, LYD_XML, LYD_OPT_DATA_NO_YANGLIB, trees);
- if (!val_tree) {
- fprintf(stderr, "Failed to parse the additional data tree for validation.\n");
- goto cleanup;
- }
- if (!trees) {
- trees = lyd_trees_new(1, val_tree);
- } else {
- trees = lyd_trees_add(trees, val_tree);
- }
- }
- break;
-#endif
- case 's':
- options |= LYD_PARSE_STRICT;
- break;
- case 't':
- if (!strcmp(optarg, "auto")) {
- /* no flags */
- } else if (!strcmp(optarg, "data")) {
- /* no flags */
- /*} else if (!strcmp(optarg, "config")) {
- options |= LYD_OPT_CONFIG;
- } else if (!strcmp(optarg, "get")) {
- options |= LYD_OPT_GET;
- } else if (!strcmp(optarg, "getconfig")) {
- options |= LYD_OPT_GETCONFIG;
- } else if (!strcmp(optarg, "edit")) {
- options |= LYD_OPT_EDIT;*/
- } else {
- fprintf(stderr, "Invalid parser option \"%s\".\n", optarg);
- cmd_data_help();
- goto cleanup;
- }
- break;
- case '?':
- fprintf(stderr, "Unknown option \"%d\".\n", (char)c);
- goto cleanup;
- }
- }
-
- /* file name */
- if (optind == argc) {
- fprintf(stderr, "Missing the data file name.\n");
- goto cleanup;
- }
-
- if (parse_data(argv[optind], &options, tree, argv[optind + 1], &data)) {
- goto cleanup;
- }
-
- if (out_path) {
- ret = ly_out_new_filepath(out_path, &out);
- } else {
- ret = ly_out_new_file(stdout, &out);
- }
- if (ret) {
- fprintf(stderr, "Could not open the output file (%s).\n", strerror(errno));
- goto cleanup;
- }
-
- if (outformat) {
- ret = lyd_print_all(out, data, outformat, printopt);
- ret = ret < 0 ? ret * (-1) : 0;
- }
-
-cleanup:
- free(*argv);
- free(argv);
-
- ly_out_free(out, NULL, out_path ? 1 : 0);
-
- lyd_free_all(data);
-
- return ret;
-}
-#if 0
-int
-cmd_xpath(const char *arg)
-{
- int c, argc, option_index, ret = 1, long_str;
- char **argv = NULL, *ptr, *expr = NULL;
- unsigned int i, j;
- int options = 0;
- struct lyd_node *data = NULL, *node, *val_tree = NULL;
- struct lyd_node_leaf_list *key;
- struct ly_set *set;
- static struct option long_options[] = {
- {"help", no_argument, 0, 'h'},
- {"expr", required_argument, 0, 'e'},
- {NULL, 0, 0, 0}
- };
- void *rlcd;
-
- long_str = 0;
- argc = 1;
- argv = malloc(2 * sizeof *argv);
- *argv = strdup(arg);
- ptr = strtok(*argv, " ");
- while ((ptr = strtok(NULL, " "))) {
- if (long_str) {
- ptr[-1] = ' ';
- if (ptr[strlen(ptr) - 1] == long_str) {
- long_str = 0;
- ptr[strlen(ptr) - 1] = '\0';
- }
- } else {
- rlcd = realloc(argv, (argc + 2) * sizeof *argv);
- if (!rlcd) {
- fprintf(stderr, "Memory allocation failed (%s:%d, %s)", __FILE__, __LINE__, strerror(errno));
- goto cleanup;
- }
- argv = rlcd;
- argv[argc] = ptr;
- if (ptr[0] == '"') {
- long_str = '"';
- ++argv[argc];
- }
- if (ptr[0] == '\'') {
- long_str = '\'';
- ++argv[argc];
- }
- if (ptr[strlen(ptr) - 1] == long_str) {
- long_str = 0;
- ptr[strlen(ptr) - 1] = '\0';
- }
- ++argc;
- }
- }
- argv[argc] = NULL;
-
- optind = 0;
- while (1) {
- option_index = 0;
- c = getopt_long(argc, argv, "he:t:x:", long_options, &option_index);
- if (c == -1) {
- break;
- }
-
- switch (c) {
- case 'h':
- cmd_xpath_help();
- ret = 0;
- goto cleanup;
- case 'e':
- expr = optarg;
- break;
- case 't':
- if (!strcmp(optarg, "auto")) {
- options = (options & ~LYD_OPT_TYPEMASK) | LYD_OPT_TYPEMASK;
- } else if (!strcmp(optarg, "config")) {
- options = (options & ~LYD_OPT_TYPEMASK) | LYD_OPT_CONFIG;
- } else if (!strcmp(optarg, "get")) {
- options = (options & ~LYD_OPT_TYPEMASK) | LYD_OPT_GET;
- } else if (!strcmp(optarg, "getconfig")) {
- options = (options & ~LYD_OPT_TYPEMASK) | LYD_OPT_GETCONFIG;
- } else if (!strcmp(optarg, "edit")) {
- options = (options & ~LYD_OPT_TYPEMASK) | LYD_OPT_EDIT;
- } else if (!strcmp(optarg, "rpc")) {
- options = (options & ~LYD_OPT_TYPEMASK) | LYD_OPT_RPC;
- } else if (!strcmp(optarg, "rpcreply")) {
- options = (options & ~LYD_OPT_TYPEMASK) | LYD_OPT_RPCREPLY;
- } else if (!strcmp(optarg, "notif")) {
- options = (options & ~LYD_OPT_TYPEMASK) | LYD_OPT_NOTIF;
- } else if (!strcmp(optarg, "yangdata")) {
- options = (options & ~LYD_OPT_TYPEMASK) | LYD_OPT_DATA_TEMPLATE;
- } else {
- fprintf(stderr, "Invalid parser option \"%s\".\n", optarg);
- cmd_data_help();
- goto cleanup;
- }
- break;
- case 'x':
- val_tree = lyd_parse_path(ctx, optarg, LYD_XML, LYD_OPT_CONFIG);
- if (!val_tree) {
- fprintf(stderr, "Failed to parse the additional data tree for validation.\n");
- goto cleanup;
- }
- break;
- case '?':
- fprintf(stderr, "Unknown option \"%d\".\n", (char)c);
- goto cleanup;
- }
- }
-
- if (optind == argc) {
- fprintf(stderr, "Missing the file with data.\n");
- goto cleanup;
- }
-
- if (!expr) {
- fprintf(stderr, "Missing the XPath expression.\n");
- goto cleanup;
- }
-
- if (parse_data(argv[optind], &options, val_tree, argv[optind + 1], &data)) {
- goto cleanup;
- }
-
- if (!(set = lyd_find_path(data, expr))) {
- goto cleanup;
- }
-
- /* print result */
- printf("Result:\n");
- if (!set->number) {
- printf("\tEmpty\n");
- } else {
- for (i = 0; i < set->number; ++i) {
- node = set->set.d[i];
- switch (node->schema->nodetype) {
- case LYS_CONTAINER:
- printf("\tContainer ");
- break;
- case LYS_LEAF:
- printf("\tLeaf ");
- break;
- case LYS_LEAFLIST:
- printf("\tLeaflist ");
- break;
- case LYS_LIST:
- printf("\tList ");
- break;
- case LYS_ANYXML:
- printf("\tAnyxml ");
- break;
- case LYS_ANYDATA:
- printf("\tAnydata ");
- break;
- default:
- printf("\tUnknown ");
- break;
- }
- printf("\"%s\"", node->schema->name);
- if (node->schema->nodetype & (LYS_LEAF | LYS_LEAFLIST)) {
- printf(" (val: %s)", ((struct lyd_node_leaf_list *)node)->value_str);
- } else if (node->schema->nodetype == LYS_LIST) {
- key = (struct lyd_node_leaf_list *)node->child;
- printf(" (");
- for (j = 0; j < ((struct lys_node_list *)node->schema)->keys_size; ++j) {
- if (j) {
- printf(" ");
- }
- printf("\"%s\": %s", key->schema->name, key->value_str);
- key = (struct lyd_node_leaf_list *)key->next;
- }
- printf(")");
- }
- printf("\n");
- }
- }
- printf("\n");
-
- ly_set_free(set);
- ret = 0;
-
-cleanup:
- free(*argv);
- free(argv);
-
- lyd_free_withsiblings(data);
-
- return ret;
-}
-#endif
-
-int
-print_list(FILE *out, struct ly_ctx *ctx, LYD_FORMAT outformat)
-{
- struct lyd_node *ylib;
- uint32_t idx = 0, has_modules = 0;
- const struct lys_module *mod;
-
- if (outformat != LYD_UNKNOWN) {
- if (ly_ctx_get_yanglib_data(ctx, &ylib)) {
- fprintf(stderr, "Getting context info (ietf-yang-library data) failed.\n");
- return 1;
- }
-
- lyd_print_file(out, ylib, outformat, LYD_PRINT_WITHSIBLINGS);
- lyd_free_all(ylib);
- return 0;
- }
-
- /* iterate schemas in context and provide just the basic info */
- fprintf(out, "List of the loaded models:\n");
- while ((mod = ly_ctx_get_module_iter(ctx, &idx))) {
- has_modules++;
-
- /* conformance print */
- if (mod->implemented) {
- fprintf(out, "\tI");
- } else {
- fprintf(out, "\ti");
- }
-
- /* module print */
- fprintf(out, " %s", mod->name);
- if (mod->revision) {
- fprintf(out, "@%s", mod->revision);
- }
-
- /* submodules print */
- if (mod->parsed && mod->parsed->includes) {
- uint64_t u = 0;
- fprintf(out, " (");
- LY_ARRAY_FOR(mod->parsed->includes, u) {
- fprintf(out, "%s%s", !u ? "" : ",", mod->parsed->includes[u].name);
- if (mod->parsed->includes[u].rev[0]) {
- fprintf(out, "@%s", mod->parsed->includes[u].rev);
- }
- }
- fprintf(out, ")");
- }
-
- /* finish the line */
- fprintf(out, "\n");
- }
-
- if (!has_modules) {
- fprintf(out, "\t(none)\n");
- }
-
- return 0;
-}
-
-int
-cmd_list(const char *arg)
-{
- char **argv = NULL, *ptr;
- int c, argc, option_index;
- LYD_FORMAT outformat = LYD_UNKNOWN;
- static struct option long_options[] = {
- {"help", no_argument, 0, 'h'},
- {"format", required_argument, 0, 'f'},
- {NULL, 0, 0, 0}
- };
- void *rlcd;
-
- argc = 1;
- argv = malloc(2*sizeof *argv);
- *argv = strdup(arg);
- ptr = strtok(*argv, " ");
- while ((ptr = strtok(NULL, " "))) {
- rlcd = realloc(argv, (argc+2)*sizeof *argv);
- if (!rlcd) {
- fprintf(stderr, "Memory allocation failed (%s:%d, %s)", __FILE__, __LINE__, strerror(errno));
- goto error;
- }
- argv = rlcd;
- argv[argc++] = ptr;
- }
- argv[argc] = NULL;
-
- optind = 0;
- while (1) {
- option_index = 0;
- c = getopt_long(argc, argv, "hf:", long_options, &option_index);
- if (c == -1) {
- break;
- }
-
- switch (c) {
- case 'h':
- cmd_data_help();
- free(*argv);
- free(argv);
- return 0;
- case 'f':
- if (!strcmp(optarg, "xml")) {
- outformat = LYD_XML;
- } else if (!strcmp(optarg, "json")) {
- outformat = LYD_JSON;
- } else {
- fprintf(stderr, "Unknown output format \"%s\".\n", optarg);
- goto error;
- }
- break;
- case '?':
- /* getopt_long() prints message */
- goto error;
- }
- }
- if (optind != argc) {
- fprintf(stderr, "Unknown parameter \"%s\"\n", argv[optind]);
-error:
- free(*argv);
- free(argv);
- return 1;
- }
- free(*argv);
- free(argv);
-
- return print_list(stdout, ctx, outformat);
-}
-
-int
-cmd_feature(const char *arg)
-{
- int c, argc, option_index, ret = 1, task = 0;
- char **argv = NULL, *ptr, *model_name, *revision, *feat_names = NULL;
- const struct lys_module *module;
- static struct option long_options[] = {
- {"help", no_argument, 0, 'h'},
- {"enable", required_argument, 0, 'e'},
- {"disable", required_argument, 0, 'd'},
- {NULL, 0, 0, 0}
- };
- void *rlcd;
-
- argc = 1;
- argv = malloc(2*sizeof *argv);
- *argv = strdup(arg);
- ptr = strtok(*argv, " ");
- while ((ptr = strtok(NULL, " "))) {
- rlcd = realloc(argv, (argc + 2) * sizeof *argv);
- if (!rlcd) {
- fprintf(stderr, "Memory allocation failed (%s:%d, %s)", __FILE__, __LINE__, strerror(errno));
- goto cleanup;
- }
- argv = rlcd;
- argv[argc++] = ptr;
- }
- argv[argc] = NULL;
-
- optind = 0;
- while (1) {
- option_index = 0;
- c = getopt_long(argc, argv, "he:d:", long_options, &option_index);
- if (c == -1) {
- break;
- }
-
- switch (c) {
- case 'h':
- cmd_feature_help();
- ret = 0;
- goto cleanup;
- case 'e':
- if (task) {
- fprintf(stderr, "Only one of enable or disable can be specified.\n");
- goto cleanup;
- }
- task = 1;
- feat_names = optarg;
- break;
- case 'd':
- if (task) {
- fprintf(stderr, "Only one of enable, or disable can be specified.\n");
- goto cleanup;
- }
- task = 2;
- feat_names = optarg;
- break;
- case '?':
- fprintf(stderr, "Unknown option \"%d\".\n", (char)c);
- goto cleanup;
- }
- }
-
- /* module name */
- if (optind == argc) {
- fprintf(stderr, "Missing the module name.\n");
- goto cleanup;
- }
-
- revision = NULL;
- model_name = argv[optind];
- if (strchr(model_name, '@')) {
- revision = strchr(model_name, '@');
- revision[0] = '\0';
- ++revision;
- }
-
- if (!revision) {
- module = ly_ctx_get_module_implemented(ctx, model_name);
- } else {
- module = ly_ctx_get_module(ctx, model_name, revision);
- if (module && !module->implemented) {
- module = NULL;
- }
- }
-#if 0
- if (!module) {
- /* not a module, try to find it as a submodule */
- module = (const struct lys_module *)ly_ctx_get_submodule(ctx, NULL, NULL, model_name, revision);
- }
-#endif
-
- if (module == NULL) {
- if (revision) {
- fprintf(stderr, "No implemented (sub)module \"%s\" in revision %s found.\n", model_name, revision);
- } else {
- fprintf(stderr, "No implemented (sub)module \"%s\" found.\n", model_name);
- }
- goto cleanup;
- }
-
- if (!task) {
- size_t len, max_len = 0;
- uint32_t idx = 0;
- const struct lysp_feature *f = NULL;
-
- printf("%s features:\n", module->name);
-
- /* get the max len */
- while ((f = lysp_feature_next(f, module->parsed, &idx))) {
- len = strlen(f->name);
- if (len > max_len) {
- max_len = len;
- }
- }
-
- idx = 0;
- f = NULL;
- while ((f = lysp_feature_next(f, module->parsed, &idx))) {
- printf("\t%-*s (%s)\n", (int)max_len, f->name, (f->flags & LYS_FENABLED) ? "on" : "off");
- }
- if (!max_len) {
- printf("\t(none)\n");
- }
- } else {
- feat_names = strtok(feat_names, ",");
- while (feat_names) {
- /*if (((task == 1) && lys_feature_enable(module, feat_names))
- || ((task == 2) && lys_feature_disable(module, feat_names))) {
- fprintf(stderr, "Feature \"%s\" not found.\n", feat_names);
- ret = 1;
- }*/
- feat_names = strtok(NULL, ",");
- }
- }
-
-cleanup:
- free(*argv);
- free(argv);
-
- return ret;
-}
-
-int
-cmd_searchpath(const char *arg)
-{
- const char *path;
- const char * const *searchpaths;
- int index;
- struct stat st;
-
- for (path = strchr(arg, ' '); path && (path[0] == ' '); ++path);
- if (!path || (path[0] == '\0')) {
- searchpaths = ly_ctx_get_searchdirs(ctx);
- if (searchpaths) {
- for (index = 0; searchpaths[index]; index++) {
- fprintf(stdout, "%s\n", searchpaths[index]);
- }
- }
- return 0;
- }
-
- if ((!strncmp(path, "-h", 2) && (path[2] == '\0' || path[2] == ' ')) ||
- (!strncmp(path, "--help", 6) && (path[6] == '\0' || path[6] == ' '))) {
- cmd_searchpath_help();
- return 0;
- } else if (!strncmp(path, "--clear", 7) && (path[7] == '\0' || path[7] == ' ')) {
- ly_ctx_unset_searchdir(ctx, NULL);
- return 0;
- }
-
- if (stat(path, &st) == -1) {
- fprintf(stderr, "Failed to stat the search path (%s).\n", strerror(errno));
- return 1;
- }
- if (!S_ISDIR(st.st_mode)) {
- fprintf(stderr, "\"%s\" is not a directory.\n", path);
- return 1;
- }
-
- ly_ctx_set_searchdir(ctx, path);
-
- return 0;
-}
-
-int
-cmd_clear(const char *arg)
-{
- struct ly_ctx *ctx_new;
- int options = 0;
-#if 0
- int i;
- char *ylpath;
- const char * const *searchpaths;
- LYD_FORMAT format;
-
- /* get optional yang library file name */
- for (i = 5; arg[i] && isspace(arg[i]); i++);
- if (arg[i]) {
- if (arg[i] == '-' && arg[i + 1] == 'e') {
- options = LY_CTX_NOYANGLIBRARY;
- goto create_empty;
- } else {
- ylpath = strdup(&arg[i]);
- format = detect_data_format(ylpath);
- if (format == LYD_UNKNOWN) {
- free(ylpath);
- fprintf(stderr, "Unable to resolve format of the yang library file, please add \".xml\" or \".json\" suffix.\n");
- goto create_empty;
- }
- searchpaths = ly_ctx_get_searchdirs(ctx);
- ctx_new = ly_ctx_new_ylpath(searchpaths ? searchpaths[0] : NULL, ylpath, format, 0);
- free(ylpath);
- }
- } else {
-create_empty:
-#else
- (void) arg; /* TODO yang-library support */
- {
-#endif
- ly_ctx_new(NULL, options, &ctx_new);
- }
-
- if (!ctx_new) {
- fprintf(stderr, "Failed to create context.\n");
- return 1;
- }
-
- /* final switch */
- ly_ctx_destroy(ctx, NULL);
- ctx = ctx_new;
-
- return 0;
-}
-
-int
-cmd_verb(const char *arg)
-{
- const char *verb;
- if (strlen(arg) < 5) {
- cmd_verb_help();
- return 1;
- }
-
- verb = arg + 5;
- if (!strcmp(verb, "error") || !strcmp(verb, "0")) {
- ly_log_level(LY_LLERR);
-#ifndef NDEBUG
- ly_log_dbg_groups(0);
-#endif
- } else if (!strcmp(verb, "warning") || !strcmp(verb, "1")) {
- ly_log_level(LY_LLWRN);
-#ifndef NDEBUG
- ly_log_dbg_groups(0);
-#endif
- } else if (!strcmp(verb, "verbose") || !strcmp(verb, "2")) {
- ly_log_level(LY_LLVRB);
-#ifndef NDEBUG
- ly_log_dbg_groups(0);
-#endif
- } else if (!strcmp(verb, "debug") || !strcmp(verb, "3")) {
- ly_log_level(LY_LLDBG);
-#ifndef NDEBUG
- ly_log_dbg_groups(LY_LDGDICT | LY_LDGYANG | LY_LDGYIN | LY_LDGXPATH | LY_LDGDIFF);
-#endif
- } else {
- fprintf(stderr, "Unknown verbosity \"%s\"\n", verb);
- return 1;
- }
-
- return 0;
-}
-
-#ifndef NDEBUG
-
-int
-cmd_debug(const char *arg)
-{
- const char *beg, *end;
- int grps = 0;
- if (strlen(arg) < 6) {
- cmd_debug_help();
- return 1;
- }
-
- end = arg + 6;
- while (end[0]) {
- for (beg = end; isspace(beg[0]); ++beg);
- if (!beg[0]) {
- break;
- }
-
- for (end = beg; (end[0] && !isspace(end[0])); ++end);
-
- if (!strncmp(beg, "dict", end - beg)) {
- grps |= LY_LDGDICT;
- } else if (!strncmp(beg, "yang", end - beg)) {
- grps |= LY_LDGYANG;
- } else if (!strncmp(beg, "yin", end - beg)) {
- grps |= LY_LDGYIN;
- } else if (!strncmp(beg, "xpath", end - beg)) {
- grps |= LY_LDGXPATH;
- } else if (!strncmp(beg, "diff", end - beg)) {
- grps |= LY_LDGDIFF;
- } else {
- fprintf(stderr, "Unknown debug group \"%.*s\"\n", (int)(end - beg), beg);
- return 1;
- }
- }
- ly_log_dbg_groups(grps);
-
- return 0;
-}
-
-#endif
-
-int
-cmd_quit(const char *UNUSED(arg))
-{
- done = 1;
- return 0;
-}
-
-int
-cmd_help(const char *arg)
-{
- int i;
- char *args = strdup(arg);
- char *cmd = NULL;
-
- strtok(args, " ");
- if ((cmd = strtok(NULL, " ")) == NULL) {
-
-generic_help:
- fprintf(stdout, "Available commands:\n");
-
- for (i = 0; commands[i].name; i++) {
- if (commands[i].helpstring != NULL) {
- fprintf(stdout, " %-15s %s\n", commands[i].name, commands[i].helpstring);
- }
- }
- } else {
- /* print specific help for the selected command */
-
- /* get the command of the specified name */
- for (i = 0; commands[i].name; i++) {
- if (strcmp(cmd, commands[i].name) == 0) {
- break;
- }
- }
-
- /* execute the command's help if any valid command specified */
- if (commands[i].name) {
- if (commands[i].help_func != NULL) {
- commands[i].help_func();
- } else {
- printf("%s\n", commands[i].helpstring);
- }
- } else {
- /* if unknown command specified, print the list of commands */
- printf("Unknown command \'%s\'\n", cmd);
- goto generic_help;
- }
- }
-
- free(args);
- return 0;
-}
-
-COMMAND commands[] = {
- {"help", cmd_help, NULL, "Display commands description"},
- {"add", cmd_add, cmd_add_help, "Add a new model from a specific file"},
- {"load", cmd_load, cmd_load_help, "Load a new model from the searchdirs"},
- {"print", cmd_print, cmd_print_help, "Print a model"},
- {"data", cmd_data, cmd_data_help, "Load, validate and optionally print instance data"},
-#if 0
- {"xpath", cmd_xpath, cmd_xpath_help, "Get data nodes satisfying an XPath expression"},
-#endif
- {"list", cmd_list, cmd_list_help, "List all the loaded models"},
- {"feature", cmd_feature, cmd_feature_help, "Print/enable/disable all/specific features of models"},
- {"searchpath", cmd_searchpath, cmd_searchpath_help, "Print/set the search path(s) for models"},
- {"clear", cmd_clear, cmd_clear_help, "Clear the context - remove all the loaded models"},
- {"verb", cmd_verb, cmd_verb_help, "Change verbosity"},
-#ifndef NDEBUG
- {"debug", cmd_debug, cmd_debug_help, "Display specific debug message groups"},
-#endif
- {"quit", cmd_quit, NULL, "Quit the program"},
- /* synonyms for previous commands */
- {"?", cmd_help, NULL, "Display commands description"},
- {"exit", cmd_quit, NULL, "Quit the program"},
- {NULL, NULL, NULL, NULL}
-};
diff --git a/tools/lint/commands.h b/tools/lint/commands.h
deleted file mode 100644
index 247d373..0000000
--- a/tools/lint/commands.h
+++ /dev/null
@@ -1,44 +0,0 @@
-/**
- * @file main.c
- * @author Michal Vasko <mvasko@cesnet.cz>
- * @brief libyang's yanglint tool commands header
- *
- * Copyright (c) 2015 CESNET, z.s.p.o.
- *
- * This source code is licensed under BSD 3-Clause License (the "License").
- * You may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://opensource.org/licenses/BSD-3-Clause
- */
-
-#ifndef COMMANDS_H_
-#define COMMANDS_H_
-
-#ifdef __GNUC__
-# define UNUSED(x) UNUSED_ ## x __attribute__((__unused__))
-#else
-# define UNUSED(x) UNUSED_ ## x
-#endif
-
-#include "libyang.h"
-
-#define PROMPT "> "
-
-struct model_hint {
- char* hint;
- struct model_hint* next;
-};
-
-typedef struct {
- char *name; /* User printable name of the function. */
- int (*func)(const char*); /* Function to call to do the command. */
- void (*help_func)(void); /* Display command help. */
- char *helpstring; /* Documentation for this function. */
-} COMMAND;
-
-LYS_INFORMAT get_schema_format(const char *path);
-
-extern COMMAND commands[];
-
-#endif /* COMMANDS_H_ */
diff --git a/tools/lint/common.c b/tools/lint/common.c
new file mode 100644
index 0000000..bc4d572
--- /dev/null
+++ b/tools/lint/common.c
@@ -0,0 +1,586 @@
+/**
+ * @file common.c
+ * @author Radek Krejci <rkrejci@cesnet.cz>
+ * @brief libyang's yanglint tool - common functions for both interactive and non-interactive mode.
+ *
+ * Copyright (c) 2020 CESNET, z.s.p.o.
+ *
+ * This source code is licensed under BSD 3-Clause License (the "License").
+ * You may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://opensource.org/licenses/BSD-3-Clause
+ */
+
+#define _GNU_SOURCE
+
+#include "common.h"
+
+#include <assert.h>
+#include <errno.h>
+#include <getopt.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+
+#include "compat.h"
+#include "libyang.h"
+
+int
+parse_schema_path(const char *path, char **dir, char **module)
+{
+ char *p;
+
+ assert(dir);
+ assert(module);
+
+ /* split the path to dirname and basename for further work */
+ *dir = strdup(path);
+ *module = strrchr(*dir, '/');
+ if (!(*module)) {
+ *module = *dir;
+ *dir = strdup("./");
+ } else {
+ *module[0] = '\0'; /* break the dir */
+ *module = strdup((*module) + 1);
+ }
+ /* get the pure module name without suffix or revision part of the filename */
+ if ((p = strchr(*module, '@'))) {
+ /* revision */
+ *p = '\0';
+ } else if ((p = strrchr(*module, '.'))) {
+ /* fileformat suffix */
+ *p = '\0';
+ }
+
+ return 0;
+}
+
+int
+get_input(const char *filepath, LYS_INFORMAT *format_schema, LYD_FORMAT *format_data, struct ly_in **in)
+{
+ struct stat st;
+
+ /* check that the filepath exists and is a regular file */
+ if (stat(filepath, &st) == -1) {
+ YLMSG_E("Unable to use input filepath (%s) - %s.\n", filepath, strerror(errno));
+ return -1;
+ }
+ if (!S_ISREG(st.st_mode)) {
+ YLMSG_E("Provided input file (%s) is not a regular file.\n", filepath);
+ return -1;
+ }
+
+ /* get the file format */
+ if (get_format(filepath, format_schema, format_data)) {
+ return -1;
+ }
+
+ if (ly_in_new_filepath(filepath, 0, in)) {
+ YLMSG_E("Unable to process input file.\n");
+ return -1;
+ }
+
+ return 0;
+}
+
+void
+free_features(void *flist)
+{
+ struct schema_features *rec = (struct schema_features *)flist;
+
+ if (rec) {
+ free(rec->module);
+ if (rec->features) {
+ for (uint32_t u = 0; rec->features[u]; ++u) {
+ free(rec->features[u]);
+ }
+ free(rec->features);
+ }
+ free(rec);
+ }
+}
+
+void
+get_features(struct ly_set *fset, const char *module, const char ***features)
+{
+ /* get features list for this module */
+ for (uint32_t u = 0; u < fset->count; ++u) {
+ struct schema_features *sf = (struct schema_features *)fset->objs[u];
+ if (!strcmp(module, sf->module)) {
+ *features = (const char **)sf->features;
+ return;
+ }
+ }
+}
+
+int
+parse_features(const char *fstring, struct ly_set *fset)
+{
+ struct schema_features *rec;
+ char *p;
+
+ rec = calloc(1, sizeof *rec);
+ if (!rec) {
+ YLMSG_E("Unable to allocate features information record (%s).\n", strerror(errno));
+ return -1;
+ }
+ if (ly_set_add(fset, rec, 1, NULL)) {
+ YLMSG_E("Unable to store features information (%s).\n", strerror(errno));
+ free(rec);
+ return -1;
+ }
+
+ /* fill the record */
+ p = strchr(fstring, ':');
+ if (!p) {
+ YLMSG_E("Invalid format of the features specification (%s)", fstring);
+ return -1;
+ }
+ rec->module = strndup(fstring, p - fstring);
+
+ /* start count on 2 to include terminating NULL byte */
+ for (int count = 2; p; ++count) {
+ size_t len = 0;
+ char *token = p + 1;
+ p = strchr(token, ',');
+ if (!p) {
+ /* the last item, if any */
+ len = strlen(token);
+ } else {
+ len = p - token;
+ }
+ if (len) {
+ char **fp = realloc(rec->features, count * sizeof *rec->features);
+ if (!fp) {
+ YLMSG_E("Unable to store features list information (%s).\n", strerror(errno));
+ return -1;
+ }
+ rec->features = fp;
+ rec->features[count - 1] = NULL; /* terminating NULL-byte */
+ fp = &rec->features[count - 2]; /* array item to set */
+ (*fp) = strndup(token, len);
+ }
+ }
+
+ return 0;
+}
+
+struct cmdline_file *
+fill_cmdline_file(struct ly_set *set, struct ly_in *in, const char *path, LYD_FORMAT format)
+{
+ struct cmdline_file *rec;
+
+ rec = malloc(sizeof *rec);
+ if (!rec) {
+ YLMSG_E("Allocating memory for data file information failed.\n");
+ return NULL;
+ }
+ if (set && ly_set_add(set, rec, 1, NULL)) {
+ free(rec);
+ YLMSG_E("Storing data file information failes.\n");
+ return NULL;
+ }
+ rec->in = in;
+ rec->path = path;
+ rec->format = format;
+
+ return rec;
+}
+
+void
+free_cmdline_file(void *cmdline_file)
+{
+ struct cmdline_file *rec = (struct cmdline_file *)cmdline_file;
+
+ if (rec) {
+ ly_in_free(rec->in, 1);
+ free(rec);
+ }
+}
+
+void
+free_cmdline(char *argv[])
+{
+ if (argv) {
+ free(argv[0]);
+ free(argv);
+ }
+}
+
+int
+parse_cmdline(const char *cmdline, int *argc_p, char **argv_p[])
+{
+ int count;
+ char **vector;
+ char *ptr;
+ char qmark = 0;
+
+ assert(cmdline);
+ assert(argc_p);
+ assert(argv_p);
+
+ /* init */
+ optind = 0; /* reinitialize getopt() */
+ count = 1;
+ vector = malloc((count + 1) * sizeof *vector);
+ vector[0] = strdup(cmdline);
+
+ /* command name */
+ strtok(vector[0], " ");
+
+ /* arguments */
+ while ((ptr = strtok(NULL, " "))) {
+ size_t len;
+ void *r;
+
+ len = strlen(ptr);
+
+ if (qmark) {
+ /* still in quotated text */
+ /* remove NULL termination of the previous token since it is not a token,
+ * but a part of the quotation string */
+ ptr[-1] = ' ';
+
+ if ((ptr[len - 1] == qmark) && (ptr[len - 2] != '\\')) {
+ /* end of quotation */
+ qmark = 0;
+ /* shorten the argument by the terminating quotation mark */
+ ptr[len - 1] = '\0';
+ }
+ continue;
+ }
+
+ /* another token in cmdline */
+ ++count;
+ r = realloc(vector, (count + 1) * sizeof *vector);
+ if (!r) {
+ YLMSG_E("Memory allocation failed (%s:%d, %s),", __FILE__, __LINE__, strerror(errno));
+ free(vector);
+ return -1;
+ }
+ vector = r;
+ vector[count - 1] = ptr;
+
+ if ((ptr[0] == '"') || (ptr[0] == '\'')) {
+ /* remember the quotation mark to identify end of quotation */
+ qmark = ptr[0];
+
+ /* move the remembered argument after the quotation mark */
+ ++vector[count - 1];
+
+ /* check if the quotation is terminated within this token */
+ if ((ptr[len - 1] == qmark) && (ptr[len - 2] != '\\')) {
+ /* end of quotation */
+ qmark = 0;
+ /* shorten the argument by the terminating quotation mark */
+ ptr[len - 1] = '\0';
+ }
+ }
+ }
+ vector[count] = NULL;
+
+ *argc_p = count;
+ *argv_p = vector;
+
+ return 0;
+}
+
+int
+get_format(const char *filename, LYS_INFORMAT *schema, LYD_FORMAT *data)
+{
+ char *ptr;
+ LYS_INFORMAT informat_s;
+ LYD_FORMAT informat_d;
+
+ /* get the file format */
+ if ((ptr = strrchr(filename, '.')) != NULL) {
+ ++ptr;
+ if (!strcmp(ptr, "yang")) {
+ informat_s = LYS_IN_YANG;
+ informat_d = 0;
+ } else if (!strcmp(ptr, "yin")) {
+ informat_s = LYS_IN_YIN;
+ informat_d = 0;
+ } else if (!strcmp(ptr, "xml")) {
+ informat_s = 0;
+ informat_d = LYD_XML;
+ } else if (!strcmp(ptr, "json")) {
+ informat_s = 0;
+ informat_d = LYD_JSON;
+ } else {
+ YLMSG_E("Input file \"%s\" in an unknown format \"%s\".\n", filename, ptr);
+ return 0;
+ }
+ } else {
+ YLMSG_E("Input file \"%s\" without file extension - unknown format.\n", filename);
+ return 1;
+ }
+
+ if (informat_d) {
+ if (!data) {
+ YLMSG_E("Input file \"%s\" not expected to contain data instances (unexpected format).\n", filename);
+ return 2;
+ }
+ (*data) = informat_d;
+ } else if (informat_s) {
+ if (!schema) {
+ YLMSG_E("Input file \"%s\" not expected to contain schema definition (unexpected format).\n", filename);
+ return 3;
+ }
+ (*schema) = informat_s;
+ }
+
+ return 0;
+}
+
+int
+print_list(struct ly_out *out, struct ly_ctx *ctx, LYD_FORMAT outformat)
+{
+ struct lyd_node *ylib;
+ uint32_t idx = 0, has_modules = 0;
+ const struct lys_module *mod;
+
+ if (outformat != LYD_UNKNOWN) {
+ if (ly_ctx_get_yanglib_data(ctx, &ylib)) {
+ YLMSG_E("Getting context info (ietf-yang-library data) failed.\n");
+ return 1;
+ }
+
+ lyd_print_all(out, ylib, outformat, 0);
+ lyd_free_all(ylib);
+ return 0;
+ }
+
+ /* iterate schemas in context and provide just the basic info */
+ ly_print(out, "List of the loaded models:\n");
+ while ((mod = ly_ctx_get_module_iter(ctx, &idx))) {
+ has_modules++;
+
+ /* conformance print */
+ if (mod->implemented) {
+ ly_print(out, " I");
+ } else {
+ ly_print(out, " i");
+ }
+
+ /* module print */
+ ly_print(out, " %s", mod->name);
+ if (mod->revision) {
+ ly_print(out, "@%s", mod->revision);
+ }
+
+ /* submodules print */
+ if (mod->parsed && mod->parsed->includes) {
+ uint64_t u = 0;
+ ly_print(out, " (");
+ LY_ARRAY_FOR(mod->parsed->includes, u) {
+ ly_print(out, "%s%s", !u ? "" : ",", mod->parsed->includes[u].name);
+ if (mod->parsed->includes[u].rev[0]) {
+ ly_print(out, "@%s", mod->parsed->includes[u].rev);
+ }
+ }
+ ly_print(out, ")");
+ }
+
+ /* finish the line */
+ ly_print(out, "\n");
+ }
+
+ if (!has_modules) {
+ ly_print(out, "\t(none)\n");
+ }
+
+ ly_print_flush(out);
+ return 0;
+}
+
+int
+check_request_paths(struct ly_ctx *ctx, struct ly_set *request_paths, struct ly_set *data_inputs)
+{
+ if ((request_paths->count > 1) && (request_paths->count != data_inputs->count)) {
+ YLMSG_E("Number of request paths does not match the number of reply data files (%u:%u).\n",
+ request_paths->count, data_inputs->count);
+ return -1;
+ }
+
+ for (uint32_t u = 0; u < request_paths->count; ++u) {
+ const char *path = (const char *)request_paths->objs[u];
+ const struct lysc_node *action = NULL;
+
+ action = lys_find_path(ctx, NULL, path, 0);
+ if (!action) {
+ YLMSG_E("The request path \"%s\" is not valid.\n", path);
+ return -1;
+ } else if (!(action->nodetype & (LYS_RPC | LYS_ACTION))) {
+ YLMSG_E("The request path \"%s\" does not represent RPC/Action.\n", path);
+ return -1;
+ }
+ }
+
+ return 0;
+}
+
+int
+evaluate_xpath(const struct lyd_node *tree, const char *xpath)
+{
+ struct ly_set *set;
+
+ if (lyd_find_xpath(tree, xpath, &set)) {
+ return -1;
+ }
+
+ /* print result */
+ printf("XPath \"%s\" evaluation result:\n", xpath);
+ if (!set->count) {
+ printf("\tEmpty\n");
+ } else {
+ for (uint32_t u = 0; u < set->count; ++u) {
+ struct lyd_node *node = (struct lyd_node *)set->objs[u];
+ printf(" %s \"%s\"", lys_nodetype2str(node->schema->nodetype), node->schema->name);
+ if (node->schema->nodetype & (LYS_LEAF | LYS_LEAFLIST)) {
+ printf(" (value: \"%s\")\n", ((struct lyd_node_term *)node)->value.canonical);
+ } else if (node->schema->nodetype == LYS_LIST) {
+ printf(" (");
+ for (struct lyd_node *key = ((struct lyd_node_inner *)node)->child; key && lysc_is_key(key->schema); key = key->next) {
+ printf("%s\"%s\": \"%s\";", (key != ((struct lyd_node_inner *)node)->child) ? " " : "",
+ key->schema->name, ((struct lyd_node_term *)key)->value.canonical);
+ }
+ printf(")\n");
+ }
+ }
+ }
+
+ ly_set_free(set, NULL);
+ return 0;
+}
+
+LY_ERR
+process_data(struct ly_ctx *ctx, uint8_t data_type, uint8_t merge, LYD_FORMAT format, struct ly_out *out,
+ uint32_t options_parse, uint32_t options_validate, uint32_t options_print,
+ struct cmdline_file *operational_f, struct ly_set *inputs, struct ly_set *request_paths, struct ly_set *requests,
+ struct ly_set *xpaths)
+{
+ LY_ERR ret;
+ struct lyd_node *tree = NULL, *merged_tree = NULL;
+ struct lyd_node *operational;
+
+ /* additional operational datastore */
+ if (operational_f && operational_f->in) {
+ ret = lyd_parse_data(ctx, operational_f->in, operational_f->format, LYD_PARSE_ONLY, 0, &operational);
+ if (ret) {
+ YLMSG_E("Failed to parse operational datastore file \"%s\".\n", operational_f->path);
+ goto cleanup;
+ }
+ }
+
+ for (uint32_t u = 0; u < inputs->count; ++u) {
+ struct cmdline_file *input_f = (struct cmdline_file *)inputs->objs[u];
+ struct cmdline_file *request_f;
+ switch (data_type) {
+ case 0:
+ ret = lyd_parse_data(ctx, input_f->in, input_f->format, options_parse, options_validate, &tree);
+ break;
+ case LYD_VALIDATE_OP_RPC:
+ ret = lyd_parse_rpc(ctx, input_f->in, input_f->format, &tree, NULL);
+ break;
+ case LYD_VALIDATE_OP_REPLY: {
+ struct lyd_node *request = NULL;
+
+ /* get the request data */
+ if (request_paths->count) {
+ const char *path;
+ if (request_paths->count > 1) {
+ /* one to one */
+ path = (const char *)request_paths->objs[u];
+ } else {
+ /* one to all */
+ path = (const char *)request_paths->objs[0];
+ }
+ ret = lyd_new_path(NULL, ctx, path, NULL, 0, &request);
+ if (ret) {
+ YLMSG_E("Failed to create request data from path \"%s\".\n", path);
+ goto cleanup;
+ }
+ } else {
+ assert(requests->count > u);
+ request_f = (struct cmdline_file *)requests->objs[u];
+
+ ret = lyd_parse_rpc(ctx, request_f->in, request_f->format, &request, NULL);
+ if (ret) {
+ YLMSG_E("Failed to parse input data file \"%s\".\n", input_f->path);
+ goto cleanup;
+ }
+ }
+
+ /* get the reply data */
+ ret = lyd_parse_reply(request, input_f->in, input_f->format, &tree, NULL);
+ lyd_free_all(request);
+
+ break;
+ } /* case PARSE_REPLY */
+ case LYD_VALIDATE_OP_NOTIF:
+ ret = lyd_parse_notif(ctx, input_f->in, input_f->format, &tree, NULL);
+ break;
+ }
+
+ if (ret) {
+ YLMSG_E("Failed to parse input data file \"%s\".\n", input_f->path);
+ goto cleanup;
+ }
+
+ if (merge) {
+ /* merge the data so far parsed for later validation and print */
+ if (!merged_tree) {
+ merged_tree = tree;
+ } else {
+ ret = lyd_merge_siblings(&merged_tree, tree, LYD_MERGE_DESTRUCT);
+ if (ret) {
+ YLMSG_E("Merging %s with previous data failed.\n", input_f->path);
+ goto cleanup;
+ }
+ }
+ tree = NULL;
+ } else if (format) {
+ lyd_print_all(out, tree, format, options_print);
+ } else if (operational) {
+ /* additional validation of the RPC/Action/reply/Notification with the operational datastore */
+ ret = lyd_validate_op(tree, operational, data_type, NULL);
+ if (ret) {
+ YLMSG_E("Failed to validate input data file \"%s\" with operational datastore \"%s\".\n",
+ input_f->path, operational_f->path);
+ goto cleanup;
+ }
+ }
+ lyd_free_all(tree);
+ tree = NULL;
+ }
+
+ if (merge) {
+ /* validate the merged result */
+ ret = lyd_validate_all(&merged_tree, ctx, LYD_VALIDATE_PRESENT, NULL);
+ if (ret) {
+ YLMSG_E("Merged data are not valid.\n");
+ goto cleanup;
+ }
+
+ if (format) {
+ /* and print it */
+ lyd_print_all(out, merged_tree, format, options_print);
+ }
+
+ for (uint32_t u = 0; u < xpaths->count; ++u) {
+ if (evaluate_xpath(merged_tree, (const char *)xpaths->objs[u])) {
+ goto cleanup;
+ }
+ }
+ }
+
+cleanup:
+ /* cleanup */
+ lyd_free_all(merged_tree);
+ lyd_free_all(tree);
+
+ return ret;
+}
diff --git a/tools/lint/common.h b/tools/lint/common.h
new file mode 100644
index 0000000..5352082
--- /dev/null
+++ b/tools/lint/common.h
@@ -0,0 +1,207 @@
+/**
+ * @file common.h
+ * @author Radek Krejci <rkrejci@cesnet.cz>
+ * @brief libyang's yanglint tool - common functions and definitions for both interactive and non-interactive mode.
+ *
+ * Copyright (c) 2020 CESNET, z.s.p.o.
+ *
+ * This source code is licensed under BSD 3-Clause License (the "License").
+ * You may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://opensource.org/licenses/BSD-3-Clause
+ */
+
+#ifndef COMMON_H_
+#define COMMON_H_
+
+#include <stdint.h>
+#include <stdio.h>
+
+#include "libyang.h"
+
+#define PROMPT "> "
+
+/**
+ * @brief log error message
+ */
+#define YLMSG_E(MSG, ...) \
+ fprintf(stderr, "YANGLINT[E]" MSG, ##__VA_ARGS__)
+
+/**
+ * @brief log warning message
+ */
+#define YLMSG_W(MSG, ...) \
+ fprintf(stderr, "YANGLINT[W]: " MSG, ##__VA_ARGS__)
+
+/**
+ * @brief Storage for the list of the features (their names) in a specific YANG module.
+ */
+struct schema_features {
+ char *module;
+ char **features;
+};
+
+/**
+ * @brief Data connected with a file provided on a command line as a file path.
+ */
+struct cmdline_file {
+ struct ly_in *in;
+ const char *path;
+ LYD_FORMAT format;
+};
+
+/**
+ * @brief Free the schema features list (struct schema_features *)
+ * @param[in,out] flist The (struct schema_features *) to free.
+ */
+void free_features(void *flist);
+
+/**
+ * @brief Get the list of features connected with the specific YANG module.
+ *
+ * @param[in] fset The set of features information (struct schema_features *).
+ * @param[in] module Name of the YANG module which features should be found.
+ * @param[out] features Pointer to the list of features being returned.
+ */
+void get_features(struct ly_set *fset, const char *module, const char ***features);
+
+/**
+ * @brief Parse features being specified for the specific YANG module.
+ *
+ * Format of the input @p fstring is as follows: <module_name>:[<feature>,]*
+ *
+ * @param[in] fstring Input string to be parsed.
+ * @param[in, out] fset Features information set (of struct schema_features *). The set is being filled.
+ */
+int parse_features(const char *fstring, struct ly_set *fset);
+
+/**
+ * @brief Parse path of a schema module file into the directory and module name.
+ *
+ * @param[in] path Schema module file path to be parsed.
+ * @param[out] dir Pointer to the directory path where the file resides. Caller is expected to free the returned string.
+ * @param[out] module Pointer to the name of the module (without file suffixes or revision information) specified by the
+ * @path. Caller is expected to free the returned string.
+ * @return 0 on success
+ * @return -1 on error
+ */
+int parse_schema_path(const char *path, char **dir, char **module);
+
+/**
+ * @brief Get input handler for the specified path.
+ *
+ * Using the @p format_schema and @p format_data the type of the file can be limited (by providing NULL) or it can be
+ * got known if both types are possible.
+ *
+ * @param[in] filepath Path of the file to open.
+ * @param[out] format_schema Format of the schema detected from the file name. If NULL specified, the schema formats are
+ * prohibited and such files are refused.
+ * @param[out] format_data Format of the data detected from the file name. If NULL specified, the data formats are
+ * prohibited and such files are refused.
+ * @param[out] in Created input handler referring the file behind the @p filepath.
+ * @return 0 on success.
+ * @return -1 on failure.
+ */
+int get_input(const char *filepath, LYS_INFORMAT *format_schema, LYD_FORMAT *format_data, struct ly_in **in);
+
+/**
+ * @brief Free the command line file data (struct cmdline_file *)
+ * @param[in,out] cmdline_file The (struct cmdline_file *) to free.
+ */
+void free_cmdline_file(void *cmdline_file);
+
+/**
+ * @brief Create and fill the command line file data (struct cmdline_file *).
+ * @param[in] set Optional parameter in case the record is supposed to be added into a set.
+ * @param[in] in Input file handler.
+ * @param[in] path Filepath of the file.
+ * @param[in] format Format of the data file.
+ * @return The created command line file structure.
+ * @return NULL on failure
+ */
+struct cmdline_file *fill_cmdline_file(struct ly_set *set, struct ly_in *in, const char *path, LYD_FORMAT format);
+
+/**
+ * @brief Helper function to prepare argc, argv pair from a command line string.
+ *
+ * @param[in] cmdline Complete command line string.
+ * @param[out] argc_p Pointer to store argc value.
+ * @param[out] argv_p Pointer to store argv vector.
+ * @return 0 on success, non-zero on failure.
+ */
+int parse_cmdline(const char *cmdline, int *argc_p, char **argv_p[]);
+
+/**
+ * @brief Destructor for the argument vector prepared by ::parse_cmdline().
+ *
+ * @param[in,out] argv Argument vector to destroy.
+ */
+void free_cmdline(char *argv[]);
+
+/**
+ * @brief Get expected format of the @p filename's content according to the @p filename's suffix.
+ * @param[in] filename Name of the file to examine.
+ * @param[out] schema Pointer to a variable to store the expected input schema format. Do not provide the pointer in case a
+ * schema format is not expected.
+ * @param[out] data Pointer to a variable to store the expected input data format. Do not provide the pointer in case a data
+ * format is not expected.
+ * @return zero in case a format was successfully detected.
+ * @return nonzero in case it is not possible to get valid format from the @p filename.
+ */
+int get_format(const char *filename, LYS_INFORMAT *schema, LYD_FORMAT *data);
+
+/**
+ * @brief Print list of schemas in the context.
+ *
+ * @param[in] out Output handler where to print.
+ * @param[in] ctx Context to print.
+ * @param[in] outformat Optional output format. If not specified (:LYD_UNKNOWN), a simple list with single module per line
+ * is printed. Otherwise, the ietf-yang-library data are printed in the specified format.
+ * @return zero in case the data successfully printed.
+ * @return nonzero in case of error.
+ */
+int print_list(struct ly_out *out, struct ly_ctx *ctx, LYD_FORMAT outformat);
+
+/**
+ * @brief Check correctness of the specified Request XPaths for the input data files representing RPCs/Actions.
+ *
+ * If the requests specified as XPath(s) of the RPC/Action, there must be only a single path applying to all the replies
+ * or their number must correspond to the number of replies in input data files.
+ *
+ * @param[in] ctx libyang context with the schema modules to check the correctness of the paths.
+ * @param[in] request_paths The set of Requests' XPaths to check.
+ * @param[in] data_inputs The set of data file inputs with the replies to be parsed.
+ * @return 0 on success
+ * @return -1 on error
+ */
+int check_request_paths(struct ly_ctx *ctx, struct ly_set *request_paths, struct ly_set *data_inputs);
+
+/**
+ * @brief Process the input data files - parse, validate and print according to provided options.
+ *
+ * @param[in] ctx libyang context with schema.
+ * @param[in] data_type The type of data in the input files, can be 0 for standard data tree and ::LYD_VALIDATE_OP values for
+ * the operations.
+ * @param[in] merge Flag if the data should be merged before validation.
+ * @param[in] format Data format for printing.
+ * @param[in] out The output handler for printing.
+ * @param[in] options_parse Parser options.
+ * @param[in] options_validate Validation options.
+ * @param[in] options_print Printer options.
+ * @param[in] operational_f Optional operational datastore file information for the case of an extended validation of
+ * operation(s).
+ * @param[in] inputs Set of file informations of input data files.
+ * @param[in] request_paths Set of xpaths refering to the request RPCs/Actions for the replies being processed.
+ * @param[in] requests The set of input data files containing request RPCs/Actions for the replies being processed.
+ * Alternative to @p request_paths.
+ * @param[in] xpath The set of XPaths to be evaluated on the processed data tree, basic information about the resulting set
+ * is printed. Alternative to data printing.
+ * return LY_ERR value.
+ */
+LY_ERR process_data(struct ly_ctx *ctx, uint8_t data_type, uint8_t merge, LYD_FORMAT format, struct ly_out *out,
+ uint32_t options_parse, uint32_t options_validate, uint32_t options_print,
+ struct cmdline_file *operational_f, struct ly_set *inputs, struct ly_set *request_paths, struct ly_set *requests,
+ struct ly_set *xpaths);
+
+#endif /* COMMON_H_ */
diff --git a/tools/lint/completion.c b/tools/lint/completion.c
index 2d66926..4db17a0 100644
--- a/tools/lint/completion.c
+++ b/tools/lint/completion.c
@@ -22,9 +22,11 @@
#include "libyang.h"
-#include "commands.h"
+#include "cmd.h"
+#include "common.h"
#include "linenoise/linenoise.h"
+/* from the main.c */
extern struct ly_ctx *ctx;
static void
@@ -41,11 +43,11 @@
++(*match_count);
p = realloc(*matches, *match_count * sizeof **matches);
if (!p) {
- fprintf(stderr, "Memory allocation failed (%s:%d, %s)", __FILE__, __LINE__, strerror(errno));
+ YLMSG_E("Memory allocation failed (%s:%d, %s)", __FILE__, __LINE__, strerror(errno));
return;
}
*matches = p;
- (*matches)[*match_count-1] = strdup(commands[i].name);
+ (*matches)[*match_count - 1] = strdup(commands[i].name);
}
}
}
@@ -92,11 +94,11 @@
++(*match_count);
p = realloc(*matches, *match_count * sizeof **matches);
if (!p) {
- fprintf(stderr, "Memory allocation failed (%s:%d, %s)", __FILE__, __LINE__, strerror(errno));
+ YLMSG_E("Memory allocation failed (%s:%d, %s)", __FILE__, __LINE__, strerror(errno));
return;
}
*matches = p;
- (*matches)[*match_count-1] = strdup(module->name);
+ (*matches)[*match_count - 1] = strdup(module->name);
}
LY_ARRAY_FOR(module->parsed->includes, u) {
@@ -104,11 +106,11 @@
++(*match_count);
p = realloc(*matches, *match_count * sizeof **matches);
if (!p) {
- fprintf(stderr, "Memory allocation failed (%s:%d, %s)", __FILE__, __LINE__, strerror(errno));
+ YLMSG_E("Memory allocation failed (%s:%d, %s)", __FILE__, __LINE__, strerror(errno));
return;
}
*matches = p;
- (*matches)[*match_count-1] = strdup(module->parsed->includes[u].submodule->name);
+ (*matches)[*match_count - 1] = strdup(module->parsed->includes[u].submodule->name);
}
}
}
@@ -122,9 +124,9 @@
if (!strncmp(buf, "add ", 4)) {
linenoisePathCompletion(buf, hint, lc);
- } else if ((!strncmp(buf, "searchpath ", 11) || !strncmp(buf, "data ", 5)
- || !strncmp(buf, "config ", 7) || !strncmp(buf, "filter ", 7)
- || !strncmp(buf, "xpath ", 6) || !strncmp(buf, "clear ", 6)) && !last_is_opt(hint)) {
+ } else if ((!strncmp(buf, "searchpath ", 11) || !strncmp(buf, "data ", 5) ||
+ !strncmp(buf, "config ", 7) || !strncmp(buf, "filter ", 7) ||
+ !strncmp(buf, "xpath ", 6) || !strncmp(buf, "clear ", 6)) && !last_is_opt(hint)) {
linenoisePathCompletion(buf, hint, lc);
} else if ((!strncmp(buf, "print ", 6) || !strncmp(buf, "feature ", 8)) && !last_is_opt(hint)) {
get_model_completion(hint, &matches, &match_count);
diff --git a/tools/lint/configuration.c b/tools/lint/configuration.c
index 5bda4ed..6e684a8 100644
--- a/tools/lint/configuration.c
+++ b/tools/lint/configuration.c
@@ -24,6 +24,8 @@
#include "linenoise/linenoise.h"
+#include "common.h"
+
/* Yanglint home (appended to ~/) */
#define YL_DIR ".yanglint"
@@ -35,14 +37,14 @@
char *user_home, *yl_dir;
if (!(pw = getpwuid(getuid()))) {
- fprintf(stderr, "Determining home directory failed (%s).\n", strerror(errno));
+ YLMSG_E("Determining home directory failed (%s).\n", strerror(errno));
return NULL;
}
user_home = pw->pw_dir;
yl_dir = malloc(strlen(user_home) + 1 + strlen(YL_DIR) + 1);
if (!yl_dir) {
- fprintf(stderr, "Memory allocation failed (%s).\n", strerror(errno));
+ YLMSG_E("Memory allocation failed (%s).\n", strerror(errno));
return NULL;
}
sprintf(yl_dir, "%s/%s", user_home, YL_DIR);
@@ -51,14 +53,14 @@
if (ret == -1) {
if (errno == ENOENT) {
/* directory does not exist */
- fprintf(stdout, "Configuration directory \"%s\" does not exist, creating it.\n", yl_dir);
+ YLMSG_E("Configuration directory \"%s\" does not exist, creating it.\n", yl_dir);
if (mkdir(yl_dir, 00700)) {
- fprintf(stderr, "Configuration directory \"%s\" cannot be created (%s).\n", yl_dir, strerror(errno));
+ YLMSG_E("Configuration directory \"%s\" cannot be created (%s).\n", yl_dir, strerror(errno));
free(yl_dir);
return NULL;
}
} else {
- fprintf(stderr, "Configuration directory \"%s\" exists but cannot be accessed (%s).\n", yl_dir, strerror(errno));
+ YLMSG_E("Configuration directory \"%s\" exists but cannot be accessed (%s).\n", yl_dir, strerror(errno));
free(yl_dir);
return NULL;
}
@@ -71,22 +73,23 @@
load_config(void)
{
char *yl_dir, *history_file;
+
if ((yl_dir = get_yanglint_dir()) == NULL) {
return;
}
history_file = malloc(strlen(yl_dir) + 9);
if (!history_file) {
- fprintf(stderr, "Memory allocation failed (%s).\n", strerror(errno));
+ YLMSG_E("Memory allocation failed (%s).\n", strerror(errno));
free(yl_dir);
return;
}
sprintf(history_file, "%s/history", yl_dir);
if (access(history_file, F_OK) && (errno == ENOENT)) {
- fprintf(stdout, "No saved history.\n");
+ YLMSG_E("No saved history.\n");
} else if (linenoiseHistoryLoad(history_file)) {
- fprintf(stderr, "Failed to load history.\n");
+ YLMSG_E("Failed to load history.\n");
}
free(history_file);
@@ -104,14 +107,14 @@
history_file = malloc(strlen(yl_dir) + 9);
if (!history_file) {
- fprintf(stderr, "Memory allocation failed (%s).\n", strerror(errno));
+ YLMSG_E("Memory allocation failed (%s).\n", strerror(errno));
free(yl_dir);
return;
}
sprintf(history_file, "%s/history", yl_dir);
if (linenoiseHistorySave(history_file)) {
- fprintf(stderr, "Failed to save history.\n");
+ YLMSG_E("Failed to save history.\n");
}
free(history_file);
diff --git a/tools/lint/configuration.h b/tools/lint/configuration.h
index a299407..d677876 100644
--- a/tools/lint/configuration.h
+++ b/tools/lint/configuration.h
@@ -15,7 +15,6 @@
#ifndef CONFIGURATION_H_
#define CONFIGURATION_H_
-
/**
* @brief Finds the current user's yanglint dir
* @return NULL on failure, dynamically allocated yanglint dir path
diff --git a/tools/lint/main.c b/tools/lint/main.c
index 310b822..ebbd7f8 100644
--- a/tools/lint/main.c
+++ b/tools/lint/main.c
@@ -3,7 +3,7 @@
* @author Radek Krejci <rkrejci@cesnet.cz>
* @brief libyang's yanglint tool
*
- * Copyright (c) 2015-2017 CESNET, z.s.p.o.
+ * Copyright (c) 2015-2020 CESNET, z.s.p.o.
*
* This source code is licensed under BSD 3-Clause License (the "License").
* You may not use this file except in compliance with the License.
@@ -14,21 +14,19 @@
#define _GNU_SOURCE
+#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "libyang.h"
-#include "compat.h"
-#include "tools/config.h"
-
-#include "commands.h"
+#include "cmd.h"
+#include "common.h"
#include "completion.h"
#include "configuration.h"
#include "linenoise/linenoise.h"
-
int done;
struct ly_ctx *ctx = NULL;
@@ -36,10 +34,10 @@
int main_ni(int argc, char *argv[]);
int
-main(int argc, char* argv[])
+main(int argc, char *argv[])
{
- char *cmd, *cmdline, *cmdstart;
- int i, j;
+ char *cmdline;
+ int cmdlen;
if (argc > 1) {
/* run in non-interactive mode */
@@ -51,11 +49,13 @@
load_config();
if (ly_ctx_new(NULL, 0, &ctx)) {
- fprintf(stderr, "Failed to create context.\n");
+ YLMSG_E("Failed to create context.\n");
return 1;
}
while (!done) {
+ uint8_t executed = 0;
+
/* get the command from user */
cmdline = linenoise(PROMPT);
@@ -72,38 +72,25 @@
}
/* isolate the command word. */
- for (i = 0; cmdline[i] && (cmdline[i] == ' '); i++);
- cmdstart = cmdline + i;
- for (j = 0; cmdline[i] && (cmdline[i] != ' '); i++, j++);
- cmd = strndup(cmdstart, j);
-
- /* parse the command line */
- for (i = 0; commands[i].name; i++) {
- if (strcmp(cmd, commands[i].name) == 0) {
- break;
- }
- }
+ for (cmdlen = 0; cmdline[cmdlen] && (cmdline[cmdlen] != ' '); cmdlen++) {}
/* execute the command if any valid specified */
- if (commands[i].name) {
- /* display help */
- if ((strchr(cmdstart, ' ') != NULL) && ((strncmp(strchr(cmdstart, ' ')+1, "-h", 2) == 0)
- || (strncmp(strchr(cmdstart, ' ')+1, "--help", 6) == 0))) {
- if (commands[i].help_func != NULL) {
- commands[i].help_func();
- } else {
- printf("%s\n", commands[i].helpstring);
- }
- } else {
- commands[i].func((const char *)cmdstart);
+ for (uint16_t i = 0; commands[i].name; i++) {
+ if (strncmp(cmdline, commands[i].name, (size_t)cmdlen) || (commands[i].name[cmdlen] != '\0')) {
+ continue;
}
- } else {
- /* if unknown command specified, tell it to user */
- fprintf(stderr, "%s: no such command, type 'help' for more information.\n", cmd);
- }
- linenoiseHistoryAdd(cmdline);
- free(cmd);
+ commands[i].func(&ctx, cmdline);
+ executed = 1;
+ break;
+ }
+
+ if (!executed) {
+ /* if unknown command specified, tell it to user */
+ YLMSG_E("Unknown command \"%.*s\", type 'help' for more information.\n", cmdlen, cmdline);
+ }
+
+ linenoiseHistoryAdd(cmdline);
free(cmdline);
}
diff --git a/tools/lint/main_ni.c b/tools/lint/main_ni.c
index dda395d..2187540 100644
--- a/tools/lint/main_ni.c
+++ b/tools/lint/main_ni.c
@@ -3,7 +3,7 @@
* @author Radek Krejci <rkrejci@cesnet.cz>
* @brief libyang's yanglint tool - noninteractive code
*
- * Copyright (c) 2015-2018 CESNET, z.s.p.o.
+ * Copyright (c) 2020 CESNET, z.s.p.o.
*
* This source code is licensed under BSD 3-Clause License (the "License").
* You may not use this file except in compliance with the License.
@@ -14,174 +14,266 @@
#define _GNU_SOURCE
+#include <errno.h>
+#include <getopt.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
-#include <getopt.h>
-#include <errno.h>
-#include <libgen.h>
-#include <sys/stat.h>
#include <string.h>
#include <strings.h>
+#include <sys/stat.h>
#include "libyang.h"
+#include "common.h"
#include "tools/config.h"
-#include "commands.h"
+/**
+ * @brief Context structure to hold and pass variables in a structured form.
+ */
+struct context {
+ /* libyang context for the run */
+ struct ly_ctx *ctx;
+ /* prepared output (--output option or stdout by default) */
+ struct ly_out *out;
-volatile uint8_t verbose = 0;
+ struct ly_set searchpaths;
-#if 0
-/* from commands.c */
-int print_list(FILE *out, struct ly_ctx *ctx, LYD_FORMAT outformat);
-#endif
+ /* options flags */
+ uint8_t list; /* -l option to print list of schemas */
-void
+ /*
+ * schema
+ */
+ /* set schema modules' features via --feature option (struct schema_features *) */
+ struct ly_set schema_features;
+
+ /* set of loaded schema modules (struct lys_module *) */
+ struct ly_set schema_modules;
+
+ /* options to parse and print schema modules */
+ uint32_t schema_parse_options;
+ uint32_t schema_print_options;
+
+ /* specification of printing schema node subtree, option --schema-node */
+ const char *schema_node_path;
+ const struct lysc_node *schema_node;
+
+ /* value of --format in case of schema format */
+ LYS_OUTFORMAT schema_out_format;
+
+ /*
+ * data
+ */
+ /* various options based on --type option */
+ uint8_t data_type; /* values taken from LYD_VALIDATE_OP and extended by 0 for standard data tree */
+ uint32_t data_parse_options;
+ uint32_t data_validate_options;
+ uint32_t data_print_options;
+
+ /* flag for --merge option */
+ uint8_t data_merge;
+
+ /* value of --format in case of data format */
+ LYD_FORMAT data_out_format;
+
+ /* input data files (struct cmdline_file *) */
+ struct ly_set data_inputs;
+
+ /* the request files for reply data (struct cmdline_file *)
+ * In case the data_type is PARSE_REPLY, the parsing function requires information about the request for this reply.
+ * One way to provide the request is a data file containing the full RPC/Action request which will be parsed.
+ * Alternatively, it can be set as the Path of the requested RPC/Action and in that case it is stored in
+ * data_request_paths.
+ */
+ struct ly_set data_requests;
+ /* An alternative way of providing requests for parsing data replies, instead of providing full
+ * request in a data file, only the Path of the requested RPC/Action is provided and stored as
+ * const char *. Note that the number of items in the set must be 1 (1 applies to all) or equal to
+ * data_inputs_count (1 to 1 mapping).
+ */
+ struct ly_set data_request_paths;
+
+ /* storage for --operational */
+ struct cmdline_file data_operational;
+};
+
+static void
+erase_context(struct context *c)
+{
+ /* data */
+ ly_set_erase(&c->data_inputs, free_cmdline_file);
+ ly_set_erase(&c->data_requests, free_cmdline_file);
+ ly_set_erase(&c->data_request_paths, NULL);
+ ly_in_free(c->data_operational.in, 1);
+
+ /* schema */
+ ly_set_erase(&c->schema_features, free_features);
+ ly_set_erase(&c->schema_modules, NULL);
+
+ /* context */
+ ly_set_erase(&c->searchpaths, NULL);
+
+ ly_out_free(c->out, NULL, 0);
+ ly_ctx_destroy(c->ctx, NULL);
+}
+
+static void
+version(void)
+{
+ printf("yanglint %s\n", PROJECT_VERSION);
+}
+
+static void
help(int shortout)
{
- fprintf(stdout, "Usage:\n");
- fprintf(stdout, " yanglint [options] [-f { yang | yin | tree | tree-rfc | info}] <file>...\n");
- fprintf(stdout, " Validates the YANG module in <file>, and all its dependencies.\n\n");
- fprintf(stdout, " yanglint [options] [-f { xml | json }] <schema>... <file>...\n");
- fprintf(stdout, " Validates the YANG modeled data in <file> according to the <schema>.\n\n");
- fprintf(stdout, " yanglint\n");
- fprintf(stdout, " Starts interactive mode with more features.\n\n");
+
+ printf("Usage:\n"
+ " yanglint [Options] [-f { yang | yin | info}] <schema>...\n"
+ " Validates the YANG module in <schema>, and all its dependencies.\n\n"
+ " yanglint [Options] [-f { xml | json }] <schema>... <file> [<request>]...\n"
+ " Validates the YANG modeled data in <file> according to the <schema>.\n\n"
+ " yanglint\n"
+ " Starts interactive mode with more features.\n\n");
if (shortout) {
return;
}
- fprintf(stdout, "Options:\n"
- " -h, --help Show this help message and exit.\n"
- " -v, --version Show version number and exit.\n"
- " -V, --verbose Show verbose messages, can be used multiple times to\n"
- " increase verbosity.\n"
+ printf("Options:\n"
+ " -h, --help Show this help message and exit.\n"
+ " -v, --version Show version number and exit.\n"
+ " -V, --verbose Show verbose messages, can be used multiple times to\n"
+ " increase verbosity.\n"
#ifndef NDEBUG
- " -G GROUPS, --debug=GROUPS\n"
- " Enable printing of specific debugging message group\n"
- " (nothing will be printed unless verbosity is set to debug):\n"
- " <group>[,<group>]* (dict, yang, yin, xpath, diff)\n\n"
+ " -G GROUPS, --debug=GROUPS\n"
+ " Enable printing of specific debugging message group\n"
+ " (nothing will be printed unless verbosity is set to debug):\n"
+ " <group>[,<group>]* (dict, yang, yin, xpath, diff)\n\n"
#endif
- " -p PATH, --path=PATH Search path for schema (YANG/YIN) modules. The option can be used multiple times.\n"
- " Current working directory and path of the module being added is used implicitly.\n\n"
- " -D, --disable-searchdir\n"
- " Do not implicitly search in CWD for schema modules. If specified a second time,\n"
- " do not even search the module directory (all modules must be explicitly specified).\n\n"
- " -s, --strict Strict data parsing (do not skip unknown data),\n"
- " has no effect for schemas.\n\n"
- " -m, --merge Merge input data files into a single tree and validate at once,\n"
- " has no effect for the auto, rpc, rpcreply and notif TYPEs.\n\n"
- " -f FORMAT, --format=FORMAT\n"
- " Convert to FORMAT. Supported formats: \n"
- " yang, yin, tree and info for schemas,\n"
- " xml, json for data.\n"
- " -a, --auto Modify the xml output by adding envelopes for autodetection.\n\n"
- " -i, --allimplemented Make all the imported modules implemented.\n\n"
- " -l, --list Print info about the loaded schemas in ietf-yang-library format,\n"
- " the -f option applies here to specify data encoding.\n"
- " (i - imported module, I - implemented module)\n\n"
- " -o OUTFILE, --output=OUTFILE\n"
- " Write the output to OUTFILE instead of stdout.\n\n"
- " -F FEATURES, --features=FEATURES\n"
- " Features to support, default all.\n"
- " <modname>:[<feature>,]*\n\n"
- " -d MODE, --default=MODE\n"
- " Print data with default values, according to the MODE\n"
- " (to print attributes, ietf-netconf-with-defaults model\n"
- " must be loaded):\n"
- " all - Add missing default nodes.\n"
- " all-tagged - Add missing default nodes and mark all the default\n"
- " nodes with the attribute.\n"
- " trim - Remove all nodes with a default value.\n"
- " implicit-tagged - Add missing nodes and mark them with the attribute.\n\n"
- " -t TYPE, --type=TYPE\n"
- " Specify data tree type in the input data file:\n"
- " auto - Resolve data type (one of the following) automatically\n"
- " (as pyang does) - applicable only on XML input data.\n"
- " data - Complete datastore with status data (default type).\n"
- " config - Configuration datastore (without status data).\n"
- " get - Result of the NETCONF <get> operation.\n"
- " getconfig - Result of the NETCONF <get-config> operation.\n"
- " edit - Content of the NETCONF <edit-config> operation.\n"
- " rpc - Content of the NETCONF <rpc> message, defined as YANG's rpc input statement.\n"
- " rpcreply - Reply to the RPC. The input data <file>s are expected in pairs - each RPC reply\n"
- " input data <file> must be followed by the origin RPC input data <file> for the reply.\n"
- " The same rule of pairing applies also in case of 'auto' TYPE and input data file\n"
- " containing RPC reply.\n"
- " notif - Notification instance (content of the <notification> element without <eventTime>.\n\n"
- " -O FILE, --operational=FILE\n"
- " - Optional parameter for 'rpc', 'rpcreply' and 'notif' TYPEs, the FILE contains running\n"
- " configuration datastore and state data (operational datastore) referenced from\n"
- " the RPC/Notification. The same data apply to all input data <file>s. Note that\n"
- " the file is validated as 'data' TYPE. Special value '!' can be used as FILE argument\n"
- " to ignore the external references.\n\n"
- " -y YANGLIB_PATH - Path to a yang-library data describing the initial context.\n\n"
- "Tree output specific options:\n"
- " --tree-help - Print help on tree symbols and exit.\n"
- " --tree-print-groupings\n"
- " Print top-level groupings in a separate section.\n"
- " --tree-print-uses - Print uses nodes instead the resolved grouping nodes.\n"
- " --tree-no-leafref-target\n"
- " Do not print target nodes of leafrefs.\n"
- " --tree-path=SCHEMA_PATH\n"
- " Print only the specified subtree.\n"
- " --tree-line-length=LINE_LENGTH\n"
- " Wrap lines if longer than the specified length (it is not a strict limit, longer lines\n"
- " can often appear).\n\n"
- "Info output specific options:\n"
- " -P INFOPATH, --info-path=INFOPATH\n"
- " - Schema path with full module names used as node's prefixes, the path identify the root\n"
- " node of the subtree to print information about.\n"
- " --single-node - Print information about a single node instead of a subtree."
- "\n");
+
+ " -d MODE, --default=MODE\n"
+ " Print data with default values, according to the MODE\n"
+ " (to print attributes, ietf-netconf-with-defaults model\n"
+ " must be loaded):\n"
+ " all - Add missing default nodes.\n"
+ " all-tagged - Add missing default nodes and mark all the default\n"
+ " nodes with the attribute.\n"
+ " trim - Remove all nodes with a default value.\n"
+ " implicit-tagged - Add missing nodes and mark them with the attribute.\n\n"
+
+ " -D, --disable-searchdir\n"
+ " Do not implicitly search in current working directory for\n"
+ " schema modules. If specified a second time, do not even\n"
+ " search in the module directory (all modules must be \n"
+ " explicitly specified).\n\n"
+
+ " -p PATH, --path=PATH\n"
+ " Search path for schema (YANG/YIN) modules. The option can be\n"
+ " used multiple times. The current working directory and the\n"
+ " path of the module being added is used implicitly.\n\n"
+
+ " -F FEATURES, --features=FEATURES\n"
+ " Features to support, default all.\n"
+ " <modname>:[<feature>,]*\n\n"
+
+ " -i, --makeimplemented\n"
+ " Make the imported modules \"referenced\" from any loaded\n"
+ " module also implemented. If specified a second time, all the\n"
+ " modules are set implemented.\n\n"
+
+ " -l, --list Print info about the loaded schemas.\n"
+ " (i - imported module, I - implemented module)\n"
+ " In case the -f option with data encoding is specified,\n"
+ " the list is printed as ietf-yang-library data.\n\n"
+
+ " -o OUTFILE, --output=OUTFILE\n"
+ " Write the output to OUTFILE instead of stdout.\n\n"
+
+ " -f FORMAT, --format=FORMAT\n"
+ " Convert input into FORMAT. Supported formats: \n"
+ " yang, yin, tree and info for schemas,\n"
+ " xml, json for data.\n\n"
+
+ " -P PATH, --schema-node=PATH\n"
+ " Print only the specified subtree of the schema.\n"
+ " The PATH is the XPath subset mentioned in documentation as\n"
+ " the Path format. The option can be combined with --single-node\n"
+ " option to print information only about the specified node.\n"
+ " -q, --single-node\n"
+ " Supplement to the --schema-node option to print information\n"
+ " only about a single node specified as PATH argument.\n\n"
+
+ " -s, --strict Strict data parsing (do not skip unknown data), has no effect\n"
+ " for schemas.\n\n"
+
+ " -e, --present Validate only with the schema modules whose data actually\n"
+ " exist in the provided input data files. Takes effect only\n"
+ " with the 'data' or 'config' TYPEs. Used to avoid requiring\n"
+ " mandatory nodes from modules which data are not present in the\n"
+ " provided input data files.\n\n"
+
+ " -t TYPE, --type=TYPE\n"
+ " Specify data tree type in the input data file(s):\n"
+ " data - Complete datastore with status data (default type).\n"
+ " config - Configuration datastore (without status data).\n"
+ " get - Result of the NETCONF <get> operation.\n"
+ " getconfig - Result of the NETCONF <get-config> operation.\n"
+ " edit - Content of the NETCONF <edit-config> operation.\n"
+ " rpc - Content of the NETCONF <rpc> message, defined as YANG's\n"
+ " RPC/Action input statement.\n"
+ " reply - Reply to the RPC/Action. Besides the reply itself,\n"
+ " yanglint(1) requires information about the request for\n"
+ " the reply. The request (RPC/Action) can be provided as\n"
+ " the --request option or as another input data <file>\n"
+ " provided right after the reply data <file> and\n"
+ " containing complete RPC/Action for the reply.\n"
+ " notif - Notification instance (content of the <notification>\n"
+ " element without <eventTime>).\n"
+ " -r PATH, --request=PATH\n"
+ " The alternative way of providing request information for the\n"
+ " '--type=reply'. The PATH is the XPath subset described in\n"
+ " documentation as Path format. It is required to point to the\n"
+ " RPC or Action in the schema which is supposed to be a request\n"
+ " for the reply(ies) being parsed from the input data files.\n"
+ " In case of multiple input data files, the 'request' option can\n"
+ " be set once for all the replies or multiple times each for the\n"
+ " respective input data file.\n\n"
+
+ " -O FILE, --operational=FILE\n"
+ " Provide optional data to extend validation of the 'rpc',\n"
+ " 'reply' or 'notif' TYPEs. The FILE is supposed to contain\n"
+ " the :running configuration datastore and state data\n"
+ " (operational datastore) referenced from the RPC/Notification.\n\n"
+
+ " -m, --merge Merge input data files into a single tree and validate at\n"
+ " once.The option has effect only for 'data' and 'config' TYPEs.\n\n"
+
+#if 0
+ " -y YANGLIB_PATH - Path to a yang-library data describing the initial context.\n\n"
+ "Tree output specific options:\n"
+ " --tree-help - Print help on tree symbols and exit.\n"
+ " --tree-print-groupings\n"
+ " Print top-level groupings in a separate section.\n"
+ " --tree-print-uses - Print uses nodes instead the resolved grouping nodes.\n"
+ " --tree-no-leafref-target\n"
+ " Do not print target nodes of leafrefs.\n"
+ " --tree-path=SCHEMA_PATH\n"
+ " Print only the specified subtree.\n"
+ " --tree-line-length=LINE_LENGTH\n"
+ " Wrap lines if longer than the specified length (it is not a strict limit, longer lines\n"
+ " can often appear).\n\n"
+#endif
+ "\n");
}
-void
-tree_help(void)
-{
- fprintf(stdout, "Each node is printed as:\n\n");
- fprintf(stdout, "<status> <flags> <name> <opts> <type> <if-features>\n\n"
- " <status> is one of:\n"
- " + for current\n"
- " x for deprecated\n"
- " o for obsolete\n\n"
- " <flags> is one of:\n"
- " rw for configuration data\n"
- " ro for status data\n"
- " -x for RPCs\n"
- " -n for Notification\n\n"
- " <name> is the name of the node\n"
- " (<name>) means that the node is a choice node\n"
- " :(<name>) means that the node is a case node\n\n"
- " if the node is augmented into the tree from another module,\n"
- " it is printed with the module name as <module-name>:<name>.\n\n"
- " <opts> is one of:\n"
- " ? for an optional leaf or choice\n"
- " ! for a presence container\n"
- " * for a leaf-list or list\n"
- " [<keys>] for a list's keys\n\n"
- " <type> is the name of the type for leafs and leaf-lists\n"
- " If there is a default value defined, it is printed within\n"
- " angle brackets <default-value>.\n"
- " If the type is a leafref, the type is printed as -> TARGET`\n\n"
- " <if-features> is the list of features this node depends on,\n"
- " printed within curly brackets and a question mark {...}?\n\n");
-}
-
-void
-version(void)
-{
- fprintf(stdout, "yanglint %s\n", PROJECT_VERSION);
-}
-
-void
+static void
libyang_verbclb(LY_LOG_LEVEL level, const char *msg, const char *path)
{
char *levstr;
- if (level <= verbose) {
- switch(level) {
+ if (level <= ly_log_level(LY_LLCUR)) {
+ switch (level) {
case LY_LLERR:
levstr = "err :";
break;
@@ -196,933 +288,519 @@
break;
}
if (path) {
- fprintf(stderr, "%s %s (%s)\n", levstr, msg, path);
+ fprintf(stderr, "libyang %s %s (%s)\n", levstr, msg, path);
} else {
- fprintf(stderr, "%s %s\n", levstr, msg);
+ fprintf(stderr, "libyang %s %s\n", levstr, msg);
}
}
}
-/*
- * return:
- * 0 - error
- * 1 - schema format
- * 2 - data format
+static int
+fill_context_inputs(int argc, char *argv[], struct context *c)
+{
+ struct ly_in *in;
+ uint8_t request_expected = 0;
+
+ /* process the operational content if any */
+ if (c->data_operational.path) {
+ if (get_input(c->data_operational.path, NULL, &c->data_operational.format, &c->data_operational.in)) {
+ return -1;
+ }
+ }
+
+ for (int i = 0; i < argc - optind; i++) {
+ LYS_INFORMAT format_schema = LYS_IN_UNKNOWN;
+ LYD_FORMAT format_data = LYD_UNKNOWN;
+ in = NULL;
+
+ if (get_input(argv[optind + i], &format_schema, &format_data, &in)) {
+ return -1;
+ }
+
+ if (format_schema) {
+ LY_ERR ret;
+ uint8_t path_unset = 1; /* flag to unset the path from the searchpaths list (if not already present) */
+ char *dir, *module;
+ const char *fall = "*";
+ const char **features = &fall;
+ const struct lys_module *mod;
+
+ if (parse_schema_path(argv[optind + i], &dir, &module)) {
+ return -1;
+ }
+
+ /* add temporarily also the path of the module itself */
+ if (ly_ctx_set_searchdir(c->ctx, dir) == LY_EEXIST) {
+ path_unset = 0;
+ }
+
+ /* get features list for this module */
+ get_features(&c->schema_features, module, &features);
+
+ /* temporary cleanup */
+ free(dir);
+ free(module);
+
+ ret = lys_parse(c->ctx, in, format_schema, features, &mod);
+ ly_ctx_unset_searchdir_last(c->ctx, path_unset);
+ ly_in_free(in, 1);
+ if (ret) {
+ YLMSG_E("Processing schema module from %s failed.\n", argv[optind + i]);
+ return -1;
+ }
+
+ if (c->schema_out_format) {
+ /* modules will be printed */
+ if (ly_set_add(&c->schema_modules, (void *)mod, 1, NULL)) {
+ YLMSG_E("Storing parsed schema module (%s) for print failed.\n", argv[optind + i]);
+ return -1;
+ }
+ }
+ } else if (request_expected) {
+ if (fill_cmdline_file(&c->data_requests, in, argv[optind + i], format_data)) {
+ ly_in_free(in, 1);
+ return -1;
+ }
+
+ request_expected = 0;
+ } else if (format_data) {
+ struct cmdline_file *rec;
+
+ rec = fill_cmdline_file(&c->data_inputs, in, argv[optind + i], format_data);
+ if (!rec) {
+ ly_in_free(in, 1);
+ return -1;
+ }
+
+ if ((c->data_type == LYD_VALIDATE_OP_REPLY) && !c->data_request_paths.count) {
+ /* requests for the replies are expected in another input file */
+ if (++i == argc - optind) {
+ /* there is no such file */
+ YLMSG_E("Missing request input file for the reply input file %s.\n", rec->path);
+ return -1;
+ }
+
+ request_expected = 1;
+ }
+ }
+ }
+
+ if (request_expected) {
+
+ YLMSG_E("Missing request input file for the reply input file %s.\n",
+ ((struct cmdline_file *)c->data_inputs.objs[c->data_inputs.count - 1])->path);
+ return -1;
+ }
+
+ return 0;
+}
+
+/**
+ * @brief Process command line options and store the settings into the context.
+ *
+ * return -1 in case of error;
+ * return 0 in case of success and ready to process
+ * return 1 in case of success, but expect to exit.
*/
static int
-get_fileformat(const char *filename, LYS_INFORMAT *schema, LYD_FORMAT *data)
+fill_context(int argc, char *argv[], struct context *c)
{
- char *ptr;
- LYS_INFORMAT informat_s;
- LYD_FORMAT informat_d;
+ int ret;
- /* get the file format */
- if ((ptr = strrchr(filename, '.')) != NULL) {
- ++ptr;
- if (!strcmp(ptr, "yang")) {
- informat_s = LYS_IN_YANG;
- informat_d = 0;
- } else if (!strcmp(ptr, "yin")) {
- informat_s = LYS_IN_YIN;
- informat_d = 0;
- } else if (!strcmp(ptr, "xml")) {
- informat_s = 0;
- informat_d = LYD_XML;
- } else if (!strcmp(ptr, "json")) {
- informat_s = 0;
- informat_d = LYD_JSON;
- } else {
- fprintf(stderr, "yanglint error: input file in an unknown format \"%s\".\n", ptr);
- return 0;
- }
- } else {
- fprintf(stderr, "yanglint error: input file \"%s\" without file extension - unknown format.\n", filename);
- return 0;
- }
-
- if (data) {
- (*data) = informat_d;
- }
-
- if (schema) {
- (*schema) = informat_s;
- }
-
- if (informat_s) {
- return 1;
- } else {
- return 2;
- }
-}
-
-int
-main_ni(int argc, char* argv[])
-{
- int ret = EXIT_FAILURE;
- int opt, opt_index = 0, i, featsize = 0;
+ int opt, opt_index;
struct option options[] = {
-#if 0
- {"auto", no_argument, NULL, 'a'},
-#endif
{"default", required_argument, NULL, 'd'},
+ {"disable-searchdir", no_argument, NULL, 'D'},
+ {"present", no_argument, NULL, 'e'},
{"format", required_argument, NULL, 'f'},
{"features", required_argument, NULL, 'F'},
-#if 0
- {"tree-print-groupings", no_argument, NULL, 'g'},
- {"tree-print-uses", no_argument, NULL, 'u'},
- {"tree-no-leafref-target", no_argument, NULL, 'n'},
- {"tree-path", required_argument, NULL, 'P'},
- {"tree-line-length", required_argument, NULL, 'L'},
+#ifndef NDEBUG
+ {"debug", required_argument, NULL, 'G'},
#endif
{"help", no_argument, NULL, 'h'},
-#if 0
- {"tree-help", no_argument, NULL, 'H'},
-#endif
- {"allimplemented", no_argument, NULL, 'i'},
- {"disable-cwd-search", no_argument, NULL, 'D'},
+ {"makeimplemented", no_argument, NULL, 'i'},
{"list", no_argument, NULL, 'l'},
-#if 0
{"merge", no_argument, NULL, 'm'},
-#endif
{"output", required_argument, NULL, 'o'},
- {"path", required_argument, NULL, 'p'},
- {"info-path", required_argument, NULL, 'P'},
-#if 0
- {"running", required_argument, NULL, 'r'},
{"operational", required_argument, NULL, 'O'},
-#endif
+ {"path", required_argument, NULL, 'p'},
+ {"schema-node", required_argument, NULL, 'P'},
{"single-node", no_argument, NULL, 'q'},
+ {"request", required_argument, NULL, 'r'},
{"strict", no_argument, NULL, 's'},
{"type", required_argument, NULL, 't'},
{"version", no_argument, NULL, 'v'},
{"verbose", no_argument, NULL, 'V'},
-#ifndef NDEBUG
- {"debug", required_argument, NULL, 'G'},
-#endif
- {NULL, required_argument, NULL, 'y'},
{NULL, 0, NULL, 0}
};
- struct ly_out *out = NULL;
- struct ly_ctx *ctx = NULL;
- const struct lys_module *mod;
- LYS_OUTFORMAT outformat_s = 0;
- LYS_INFORMAT informat_s;
- LYD_FORMAT informat_d, outformat_d = 0;
-#if 0
- LYD_FORMAT ylformat = 0;
-#endif
- struct ly_set *searchpaths = NULL;
- const char *outtarget_s = NULL;
- char **feat = NULL, *ptr, *featlist, *dir;
- struct stat st;
- uint32_t u;
- int options_ctx = LY_CTX_NO_YANGLIBRARY, list = 0, outoptions_s = 0, outline_length_s = 0;
- int autodetection = 0, options_parser = 0, merge = 0;
- const char *oper_file = NULL;
- int options_dflt = 0;
-#if 0
- ly_bool envelope = 0;
- const char *envelope_s = NULL;
- char *ylpath = NULL;
- struct lyxml_elem *iter, *elem;
- struct *subroot, *next, *node;
-#endif
- struct lyd_node *tree = NULL;
- struct dataitem {
- const char *filename;
- struct lyd_node *tree;
- struct dataitem *next;
- LYD_FORMAT format;
- int flags;
- } *data = NULL, *data_item, *data_prev = NULL;
- struct ly_set *mods = NULL;
- void *p;
- opterr = 0;
+ uint16_t options_ctx = 0;
+ uint8_t data_type_set = 0;
+
#ifndef NDEBUG
- while ((opt = getopt_long(argc, argv, "acd:f:F:gunP:L:hHiDlmo:p:O:st:vVG:y:", options, &opt_index)) != -1)
+ while ((opt = getopt_long(argc, argv, "d:Df:F:hilmo:P:qr:st:vV", options, &opt_index)) != -1) {
#else
- while ((opt = getopt_long(argc, argv, "acd:f:F:gunP:L:hHiDlmo:p:O:st:vVy:", options, &opt_index)) != -1)
+ while ((opt = getopt_long(argc, argv, "d:Df:F:G:hilmo:P:qr:st:vV", options, &opt_index)) != -1) {
#endif
- {
switch (opt) {
-#if 0
- }
- case 'a':
- envelope = 1;
- break;
-#endif
- case 'd':
- if (!strcmp(optarg, "all")) {
- options_dflt = (options_dflt & ~LYD_PRINT_WD_MASK) | LYD_PRINT_WD_ALL;
- } else if (!strcmp(optarg, "all-tagged")) {
- options_dflt = (options_dflt & ~LYD_PRINT_WD_MASK) | LYD_PRINT_WD_ALL_TAG;
- } else if (!strcmp(optarg, "trim")) {
- options_dflt = (options_dflt & ~LYD_PRINT_WD_MASK) | LYD_PRINT_WD_TRIM;
- } else if (!strcmp(optarg, "implicit-tagged")) {
- options_dflt = (options_dflt & ~LYD_PRINT_WD_MASK) | LYD_PRINT_WD_IMPL_TAG;
+ case 'd': /* --default */
+ if (!strcasecmp(optarg, "all")) {
+ c->data_print_options = (c->data_print_options & ~LYD_PRINT_WD_MASK) | LYD_PRINT_WD_ALL;
+ } else if (!strcasecmp(optarg, "all-tagged")) {
+ c->data_print_options = (c->data_print_options & ~LYD_PRINT_WD_MASK) | LYD_PRINT_WD_ALL_TAG;
+ } else if (!strcasecmp(optarg, "trim")) {
+ c->data_print_options = (c->data_print_options & ~LYD_PRINT_WD_MASK) | LYD_PRINT_WD_TRIM;
+ } else if (!strcasecmp(optarg, "implicit-tagged")) {
+ c->data_print_options = (c->data_print_options & ~LYD_PRINT_WD_MASK) | LYD_PRINT_WD_IMPL_TAG;
} else {
- fprintf(stderr, "yanglint error: unknown default mode %s\n", optarg);
+ YLMSG_E("Unknown default mode %s\n", optarg);
help(1);
- goto cleanup;
+ return -1;
}
break;
- case 'f':
- if (!strcasecmp(optarg, "yang")) {
- outformat_s = LYS_OUT_YANG;
- outformat_d = 0;
-#if 0
- } else if (!strcasecmp(optarg, "tree")) {
- outformat_s = LYS_OUT_TREE;
- outformat_d = 0;
- } else if (!strcasecmp(optarg, "tree-rfc")) {
- outformat_s = LYS_OUT_TREE;
- outoptions_s |= LYS_OUTOPT_TREE_RFC;
- outformat_d = 0;
-#endif
- } else if (!strcasecmp(optarg, "yin")) {
- outformat_s = LYS_OUT_YIN;
- outformat_d = 0;
- } else if (!strcasecmp(optarg, "info")) {
- outformat_s = LYS_OUT_YANG_COMPILED;
- outformat_d = 0;
- } else if (!strcasecmp(optarg, "xml")) {
- outformat_s = 0;
- outformat_d = LYD_XML;
- } else if (!strcasecmp(optarg, "json")) {
- outformat_s = 0;
- outformat_d = LYD_JSON;
- } else {
- fprintf(stderr, "yanglint error: unknown output format %s\n", optarg);
- help(1);
- goto cleanup;
- }
- break;
- case 'F':
- featsize++;
- if (!feat) {
- p = malloc(sizeof *feat);
- } else {
- p = realloc(feat, featsize * sizeof *feat);
- }
- if (!p) {
- fprintf(stderr, "yanglint error: Memory allocation failed (%s:%d, %s)", __FILE__, __LINE__, strerror(errno));
- goto cleanup;
- }
- feat = p;
- feat[featsize - 1] = strdup(optarg);
- ptr = strchr(feat[featsize - 1], ':');
- if (!ptr) {
- fprintf(stderr, "yanglint error: Invalid format of the features specification (%s)", optarg);
- goto cleanup;
- }
- *ptr = '\0';
- break;
-#if 0
- case 'g':
- outoptions_s |= LYS_OUTOPT_TREE_GROUPING;
- break;
- case 'u':
- outoptions_s |= LYS_OUTOPT_TREE_USES;
- break;
- case 'n':
- outoptions_s |= LYS_OUTOPT_TREE_NO_LEAFREF;
- break;
-#endif
- case 'P':
- outtarget_s = optarg;
- break;
-#if 0
- case 'L':
- outline_length_s = atoi(optarg);
- break;
-#endif
- case 'h':
- help(0);
- ret = EXIT_SUCCESS;
- goto cleanup;
-#if 0
- case 'H':
- tree_help();
- ret = EXIT_SUCCESS;
- goto cleanup;
-#endif
- case 'i':
- options_ctx |= LY_CTX_ALL_IMPLEMENTED;
- break;
- case 'D':
+ case 'D': /* --disable-search */
if (options_ctx & LY_CTX_DISABLE_SEARCHDIRS) {
- fprintf(stderr, "yanglint error: -D specified too many times.\n");
- goto cleanup;
- } else if (options_ctx & LY_CTX_DISABLE_SEARCHDIR_CWD) {
+ YLMSG_W("The -D option specified too many times.\n");
+ }
+ if (options_ctx & LY_CTX_DISABLE_SEARCHDIR_CWD) {
options_ctx &= ~LY_CTX_DISABLE_SEARCHDIR_CWD;
options_ctx |= LY_CTX_DISABLE_SEARCHDIRS;
} else {
options_ctx |= LY_CTX_DISABLE_SEARCHDIR_CWD;
}
break;
- case 'l':
- list = 1;
- break;
-#if 0
- case 'm':
- merge = 1;
- break;
-#endif
- case 'o':
- if (out) {
- if (ly_out_filepath(out, optarg) != NULL) {
- fprintf(stderr, "yanglint error: unable open output file %s (%s)\n", optarg, strerror(errno));
- goto cleanup;
- }
- } else {
- if (ly_out_new_filepath(optarg, &out)) {
- fprintf(stderr, "yanglint error: unable open output file %s (%s)\n", optarg, strerror(errno));
- goto cleanup;
- }
- }
- break;
- case 'p':
+
+ case 'p': { /* --path */
+ struct stat st;
+
if (stat(optarg, &st) == -1) {
- fprintf(stderr, "yanglint error: Unable to use search path (%s) - %s.\n", optarg, strerror(errno));
- goto cleanup;
+ YLMSG_E("Unable to use search path (%s) - %s.\n", optarg, strerror(errno));
+ return -1;
}
if (!S_ISDIR(st.st_mode)) {
- fprintf(stderr, "yanglint error: Provided search path is not a directory.\n");
- goto cleanup;
+ YLMSG_E("Provided search path is not a directory.\n");
+ return -1;
}
- if (!searchpaths) {
- if (ly_set_new(&searchpaths)) {
- fprintf(stderr, "yanglint error: Preparing storage for searchpaths failed.\n");
- goto cleanup;
+
+ if (ly_set_add(&c->searchpaths, optarg, 0, NULL)) {
+ YLMSG_E("Storing searchpath failed.\n");
+ return -1;
+ }
+
+ break;
+ } /* case 'p' */
+
+ case 'i': /* --makeimplemented */
+ if (options_ctx & LY_CTX_REF_IMPLEMENTED) {
+ options_ctx &= ~LY_CTX_REF_IMPLEMENTED;
+ options_ctx |= LY_CTX_ALL_IMPLEMENTED;
+ } else {
+ options_ctx |= LY_CTX_REF_IMPLEMENTED;
+ }
+ break;
+
+ case 'F': /* --features */
+ if (parse_features(optarg, &c->schema_features)) {
+ return -1;
+ }
+ break;
+
+ case 'l': /* --list */
+ c->list = 1;
+ break;
+
+ case 'o': /* --output */
+ if (c->out) {
+ YLMSG_E("Only a single output can be specified.\n");
+ return -1;
+ } else {
+ if (ly_out_new_filepath(optarg, &c->out)) {
+ YLMSG_E("Unable open output file %s (%s)\n", optarg, strerror(errno));
+ return -1;
}
}
- if (ly_set_add(searchpaths, optarg, 0, NULL)) {
- fprintf(stderr, "yanglint error: Storing searchpath failed.\n");
- goto cleanup;
- }
break;
-#if 0
- case 'O':
- if (oper_file || (options_parser & LYD_OPT_NOEXTDEPS)) {
- fprintf(stderr, "yanglint error: The operational datastore (-O) cannot be set multiple times.\n");
- goto cleanup;
- }
- if (optarg[0] == '!') {
- /* ignore extenral dependencies to the operational datastore */
- options_parser |= LYD_OPT_NOEXTDEPS;
+
+ case 'f': /* --format */
+ if (!strcasecmp(optarg, "yang")) {
+ c->schema_out_format = LYS_OUT_YANG;
+ c->data_out_format = 0;
+ } else if (!strcasecmp(optarg, "yin")) {
+ c->schema_out_format = LYS_OUT_YIN;
+ c->data_out_format = 0;
+ } else if (!strcasecmp(optarg, "info")) {
+ c->schema_out_format = LYS_OUT_YANG_COMPILED;
+ c->data_out_format = 0;
+ } else if (!strcasecmp(optarg, "tree")) {
+ c->schema_out_format = LYS_OUT_TREE;
+ c->data_out_format = 0;
+ } else if (!strcasecmp(optarg, "xml")) {
+ c->schema_out_format = 0;
+ c->data_out_format = LYD_XML;
+ } else if (!strcasecmp(optarg, "json")) {
+ c->schema_out_format = 0;
+ c->data_out_format = LYD_JSON;
} else {
- /* external file with the operational datastore */
- oper_file = optarg;
- }
- break;
-#endif
- case 's':
- options_parser |= LYD_PARSE_STRICT;
- break;
- case 't':
- if (!strcmp(optarg, "auto")) {
- autodetection = 1;
- /*} else if (!strcmp(optarg, "config")) {
- options_parser |= LYD_OPT_CONFIG;
- } else if (!strcmp(optarg, "get")) {
- options_parser |= LYD_OPT_GET;
- } else if (!strcmp(optarg, "getconfig")) {
- options_parser |= LYD_OPT_GETCONFIG;
- } else if (!strcmp(optarg, "edit")) {
- options_parser |= LYD_OPT_EDIT;*/
- } else if (!strcmp(optarg, "data")) {
- /* no options */
- } else {
- fprintf(stderr, "yanglint error: unknown data tree type %s\n", optarg);
+ YLMSG_E("Unknown output format %s\n", optarg);
help(1);
- goto cleanup;
+ return -1;
}
break;
- case 'v':
- version();
- ret = EXIT_SUCCESS;
- goto cleanup;
- case 'V':
- verbose++;
+
+ case 'P': /* --schema-node */
+ c->schema_node_path = optarg;
break;
+
+ case 'q': /* --single-node */
+ c->schema_print_options |= LYS_PRINT_NO_SUBSTMT;
+ break;
+
+ case 's': /* --strict */
+ c->data_parse_options |= LYD_PARSE_STRICT;
+ break;
+
+ case 'e': /* --present */
+ c->data_validate_options |= LYD_VALIDATE_PRESENT;
+ break;
+
+ case 't': /* --type */
+ if (data_type_set) {
+ YLMSG_E("The data type (-t) cannot be set multiple times.\n");
+ return -1;
+ }
+
+ if (!strcasecmp(optarg, "config")) {
+ c->data_parse_options |= LYD_PARSE_NO_STATE;
+ } else if (!strcasecmp(optarg, "get")) {
+ c->data_parse_options |= LYD_PARSE_ONLY;
+ } else if (!strcasecmp(optarg, "getconfig") || !strcasecmp(optarg, "get-config")) {
+ c->data_parse_options |= LYD_PARSE_ONLY | LYD_PARSE_NO_STATE;
+ } else if (!strcasecmp(optarg, "edit")) {
+ c->data_parse_options |= LYD_PARSE_ONLY;
+ } else if (!strcasecmp(optarg, "rpc") || !strcasecmp(optarg, "action")) {
+ c->data_type = LYD_VALIDATE_OP_RPC;
+ } else if (!strcasecmp(optarg, "reply") || !strcasecmp(optarg, "rpcreply")) {
+ c->data_type = LYD_VALIDATE_OP_REPLY;
+ } else if (!strcasecmp(optarg, "notif") || !strcasecmp(optarg, "notification")) {
+ c->data_type = LYD_VALIDATE_OP_NOTIF;
+ } else if (!strcasecmp(optarg, "data")) {
+ /* default option */
+ } else {
+ YLMSG_E("Unknown data tree type %s\n", optarg);
+ help(1);
+ return -1;
+ }
+
+ data_type_set = 1;
+ break;
+
+ case 'O': /* --operational */
+ if (c->data_operational.path) {
+ YLMSG_E("The operational datastore (-O) cannot be set multiple times.\n");
+ return -1;
+ }
+ c->data_operational.path = optarg;
+ break;
+
+ case 'r': /* --request */
+ if (ly_set_add(&c->data_request_paths, optarg, 0, NULL)) {
+ YLMSG_E("Storing request path failed.\n");
+ return -1;
+ }
+ break;
+
+ case 'm': /* --merge */
+ c->data_merge = 1;
+ break;
+
+ case 'h': /* --help */
+ help(0);
+ return 1;
+
+ case 'v': /* --version */
+ version();
+ return 1;
+
+ case 'V': { /* --verbose */
+ LY_LOG_LEVEL verbosity = ly_log_level(LY_LLCUR);
+
+ if (verbosity < LY_LLDBG) {
+ ly_log_level(verbosity + 1);
+ }
+ break;
+ } /* case 'V' */
+
#ifndef NDEBUG
- case 'G':
- u = 0;
- ptr = optarg;
+ case 'G': { /* --debug */
+ uint32_t dbg_groups = 0;
+ const char *ptr = optarg;
+
while (ptr[0]) {
- if (!strncmp(ptr, "dict", 4)) {
- u |= LY_LDGDICT;
+ if (!strncasecmp(ptr, "dict", 4)) {
+ dbg_groups |= LY_LDGDICT;
ptr += 4;
- } else if (!strncmp(ptr, "yang", 4)) {
- u |= LY_LDGYANG;
+ } else if (!strncasecmp(ptr, "yang", 4)) {
+ dbg_groups |= LY_LDGYANG;
ptr += 4;
- } else if (!strncmp(ptr, "yin", 3)) {
- u |= LY_LDGYIN;
+ } else if (!strncasecmp(ptr, "yin", 3)) {
+ dbg_groups |= LY_LDGYIN;
ptr += 3;
- } else if (!strncmp(ptr, "xpath", 5)) {
- u |= LY_LDGXPATH;
+ } else if (!strncasecmp(ptr, "xpath", 5)) {
+ dbg_groups |= LY_LDGXPATH;
ptr += 5;
- } else if (!strncmp(ptr, "diff", 4)) {
- u |= LY_LDGDIFF;
+ } else if (!strncasecmp(ptr, "diff", 4)) {
+ dbg_groups |= LY_LDGDIFF;
ptr += 4;
}
if (ptr[0]) {
if (ptr[0] != ',') {
- fprintf(stderr, "yanglint error: unknown debug group string \"%s\"\n", optarg);
- goto cleanup;
+ YLMSG_E("Unknown debug group string \"%s\"\n", optarg);
+ return -1;
}
++ptr;
}
}
- ly_log_dbg_groups(u);
+ ly_log_dbg_groups(dbg_groups);
break;
+ } /* case 'G' */
#endif
-#if 0
- case 'y':
- ptr = strrchr(optarg, '.');
- if (ptr) {
- ptr++;
- if (!strcmp(ptr, "xml")) {
- ylformat = LYD_XML;
- } else if (!strcmp(ptr, "json")) {
- ylformat = LYD_JSON;
- } else {
- fprintf(stderr, "yanglint error: yang-library file in an unknown format \"%s\".\n", ptr);
- goto cleanup;
- }
- } else {
- fprintf(stderr, "yanglint error: yang-library file in an unknown format.\n");
- goto cleanup;
- }
- ylpath = optarg;
- break;
-#endif
- default:
- help(1);
- if (optopt) {
- fprintf(stderr, "yanglint error: invalid option: -%c\n", optopt);
- } else {
- fprintf(stderr, "yanglint error: invalid option: %s\n", argv[optind - 1]);
- }
- goto cleanup;
+ } /* switch */
+ }
+
+ /* libyang context */
+ if (ly_ctx_new(NULL, options_ctx, &c->ctx)) {
+ YLMSG_E("Unable to create libyang context.\n");
+ return -1;
+ }
+ for (uint32_t u = 0; u < c->searchpaths.count; ++u) {
+ ly_ctx_set_searchdir(c->ctx, c->searchpaths.objs[u]);
+ }
+
+ /* additional checks for the options combinations */
+ if (!c->list && (optind >= argc)) {
+ help(1);
+ YLMSG_E("Missing <schema> to process.\n");
+ return 1;
+ }
+
+ if (c->data_merge) {
+ if (c->data_type || (c->data_parse_options & LYD_PARSE_ONLY)) {
+ /* switch off the option, incompatible input data type */
+ c->data_merge = 0;
+ } else {
+ /* postpone validation after the merge of all the input data */
+ c->data_parse_options |= LYD_PARSE_ONLY;
}
}
- /* check options compatibility */
- if (!list && optind >= argc) {
- help(1);
- fprintf(stderr, "yanglint error: missing <file> to process\n");
- goto cleanup;
+ if (c->data_operational.path && !c->data_type) {
+ YLMSG_E("Operational datastore takes effect only with RPCs/Actions/Replies/Notifications input data types.\n");
+ c->data_operational.path = NULL;
}
- if (outformat_s && outformat_s != LYS_OUT_TREE && (optind + 1) < argc) {
- /* we have multiple schemas to be printed as YIN or YANG */
- fprintf(stderr, "yanglint error: too many schemas to convert and store.\n");
- goto cleanup;
- }
- if (outoptions_s || outtarget_s || outline_length_s) {
-#if 0
- if (outformat_d || (outformat_s && outformat_s != LYS_OUT_TREE)) {
- /* we have --tree-print-grouping with other output format than tree */
- fprintf(stderr,
- "yanglint warning: --tree options take effect only in case of the tree output format.\n");
+
+ /* default output stream */
+ if (!c->out) {
+ if (ly_out_new_file(stdout, &c->out)) {
+ YLMSG_E("Unable to set stdout as output.\n");
+ return -1;
}
}
- if (merge) {
- if (autodetection || (options_parser & (LYD_OPT_RPC | LYD_OPT_RPCREPLY | LYD_OPT_NOTIF))) {
- fprintf(stderr, "yanglint warning: merging not allowed, ignoring option -m.\n");
- merge = 0;
- } else {
- /* first, files will be parsed as trusted to allow missing data, then the data trees will be merged
- * and the result will be validated */
- options_parser |= LYD_OPT_TRUSTED;
+
+ /* process input files provided as standalone command line arguments,
+ * schema modules are parsed and inserted into the context,
+ * data files are just checked and prepared into internal structures for further processing */
+ ret = fill_context_inputs(argc, argv, c);
+ if (ret) {
+ return ret;
+ }
+
+ /* the second batch of checks */
+ if (c->schema_print_options && !c->schema_out_format) {
+ YLMSG_W("Schema printer options specified, but the schema output format is missing.\n");
+ }
+ if (c->schema_parse_options && !c->schema_modules.count) {
+ YLMSG_W("Schema parser options specified, but no schema input file provided.\n");
+ }
+ if (c->data_print_options && !c->data_out_format) {
+ YLMSG_W("data printer options specified, but the data output format is missing.\n");
+ }
+ if ((c->data_parse_options || c->data_type) && !c->data_inputs.count) {
+ YLMSG_W("Data parser options specified, but no data input file provided.\n");
+ }
+
+ if (c->schema_node_path) {
+ c->schema_node = lys_find_path(c->ctx, NULL, c->schema_node_path, 0);
+ if (!c->schema_node) {
+ c->schema_node = lys_find_path(c->ctx, NULL, c->schema_node_path, 1);
+
+ if (!c->schema_node) {
+ YLMSG_E("Invalid schema path.\n");
+ return -1;
+ }
}
-#endif
}
- if (!outformat_d && options_dflt) {
- /* we have options for printing default nodes, but data output not specified */
- fprintf(stderr, "yanglint warning: default mode is ignored when not printing data.\n");
+
+ if (c->data_type == LYD_VALIDATE_OP_REPLY) {
+ if (check_request_paths(c->ctx, &c->data_request_paths, &c->data_inputs)) {
+ return -1;
+ }
}
-#if 0
- if (outformat_s && (options_parser || autodetection)) {
- /* we have options for printing data tree, but output is schema */
- fprintf(stderr, "yanglint warning: data parser options are ignored when printing schema.\n");
- }
- if (oper_file && (!autodetection && !(options_parser & (LYD_OPT_RPC | LYD_OPT_RPCREPLY | LYD_OPT_NOTIF)))) {
- fprintf(stderr, "yanglint warning: operational datastore applies only to RPCs or Notifications.\n");
- /* ignore operational datastore file */
- oper_file = NULL;
- }
- if ((options_parser & LYD_OPT_TYPEMASK) == LYD_OPT_DATA) {
- /* add option to ignore ietf-yang-library data for implicit data type */
- options_parser |= LYD_OPT_DATA_NO_YANGLIB;
- }
-#endif
+
+ return 0;
+}
+
+int
+main_ni(int argc, char *argv[])
+{
+ int ret = EXIT_SUCCESS, r;
+ struct context c = {0};
/* set callback for printing libyang messages */
ly_set_log_clb(libyang_verbclb, 1);
-#if 0
- /* create libyang context */
- if (ylpath) {
- ctx = ly_ctx_new_ylpath(searchpaths ? (const char*)searchpaths->set.g[0] : NULL, ylpath, ylformat, options_ctx);
- } else {
-#else
- {
-#endif
- ly_ctx_new(NULL, options_ctx, &ctx);
+
+ r = fill_context(argc, argv, &c);
+ if (r < 0) {
+ ret = EXIT_FAILURE;
}
- if (!ctx) {
+ if (r) {
goto cleanup;
}
- /* set searchpaths */
- if (searchpaths) {
- for (u = 0; u < searchpaths->count; u++) {
- ly_ctx_set_searchdir(ctx, (const char*)searchpaths->objs[u]);
+ /* do the required job - parse, validate, print */
+
+ if (c.list) {
+ /* print the list of schemas */
+ print_list(c.out, c.ctx, c.data_out_format);
+ } else if (c.schema_out_format) {
+ if (c.schema_node) {
+ ret = lys_print_node(c.out, c.schema_node, c.schema_out_format, 0, c.schema_print_options);
+ if (ret) {
+ YLMSG_E("Unable to print schema node %s.\n", c.schema_node_path);
+ goto cleanup;
+ }
+ } else {
+ for (uint32_t u = 0; u < c.schema_modules.count; ++u) {
+ ret = lys_print_module(c.out, (struct lys_module *)c.schema_modules.objs[u], c.schema_out_format, 0,
+ c.schema_print_options);
+ if (ret) {
+ YLMSG_E("Unable to print module %s.\n", ((struct lys_module *)c.schema_modules.objs[u])->name);
+ goto cleanup;
+ }
+ }
}
- }
-
- /* derefered setting of verbosity in libyang after context initiation */
- ly_log_level(verbose);
-
- if (ly_set_new(&mods)) {
- fprintf(stderr, "yanglint error: Preparing storage for the parsed modules failed.\n");
- goto cleanup;
- }
-
-
- /* divide input files */
- for (i = 0; i < argc - optind; i++) {
- /* get the file format */
- if (!get_fileformat(argv[optind + i], &informat_s, &informat_d)) {
+ } else if (c.data_out_format) {
+ if (process_data(c.ctx, c.data_type, c.data_merge, c.data_out_format, c.out,
+ c.data_parse_options, c.data_validate_options, c.data_print_options,
+ &c.data_operational, &c.data_inputs, &c.data_request_paths, &c.data_requests, NULL)) {
goto cleanup;
}
-
- if (informat_s) {
- /* load/validate schema */
- int unset_path = 1;
-
- if (verbose >= 2) {
- fprintf(stdout, "Validating %s schema file.\n", argv[optind + i]);
- }
-
- /* add temporarily also the path of the module itself */
- dir = strdup(argv[optind + i]);
- if (ly_ctx_set_searchdir(ctx, ptr = dirname(dir)) == LY_EEXIST) {
- unset_path = 0;
- }
- lys_parse_path(ctx, argv[optind + i], informat_s, &mod);
- ly_ctx_unset_searchdir_last(ctx, unset_path);
- free(dir);
- if (!mod) {
- goto cleanup;
- }
- if (ly_set_add(mods, (void *)mod, 0, NULL)) {
- fprintf(stderr, "yanglint error: Storing parsed module for further processing failed.\n");
- goto cleanup;
- }
- } else {
- if (autodetection && informat_d != LYD_XML) {
- /* data file content autodetection is possible only for XML input */
- fprintf(stderr, "yanglint error: data type autodetection is applicable only to XML files.\n");
- goto cleanup;
- }
-
- /* remember data filename and its format */
- if (!data) {
- data = data_item = malloc(sizeof *data);
- } else {
- for (data_item = data; data_item->next; data_item = data_item->next);
- data_item->next = malloc(sizeof *data_item);
- data_item = data_item->next;
- }
- data_item->filename = argv[optind + i];
- data_item->format = informat_d;
- data_item->flags = options_parser;
- data_item->tree = NULL;
- data_item->next = NULL;
- }
}
- if (outformat_d && !data && !list) {
- fprintf(stderr, "yanglint error: no input data file for the specified data output format.\n");
- goto cleanup;
- }
-
- /* enable specified features, if not specified, all the module's features are enabled */
- u = 4; /* skip internal libyang modules */
- while ((mod = ly_ctx_get_module_iter(ctx, &u))) {
- if (!mod->implemented) {
- continue;
- }
-
- for (i = 0; i < featsize; i++) {
- if (!strcmp(feat[i], mod->name)) {
- /* parse features spec */
- featlist = strdup(feat[i] + strlen(feat[i]) + 1);
- ptr = NULL;
- while((ptr = strtok(ptr ? NULL : featlist, ","))) {
- if (verbose >= 2) {
- fprintf(stdout, "Enabling feature %s in module %s.\n", ptr, mod->name);
- }
- /*if (lys_feature_enable(mod, ptr)) {
- fprintf(stderr, "Feature %s not defined in module %s.\n", ptr, mod->name);
- }*/
- }
- free(featlist);
- break;
- }
- }
- if (i == featsize) {
- if (verbose >= 2) {
- fprintf(stdout, "Enabling all features in module %s.\n", mod->name);
- }
- //lys_feature_enable(mod, "*");
- }
- }
- if (!out && (outformat_s || data)) {
- ly_out_new_file(stdout, &out);
- }
- /* convert (print) to FORMAT */
- if (outformat_s) {
- if (outtarget_s) {
- const struct lysc_node *node = lys_find_path(ctx, NULL, outtarget_s, 0);
- if (node) {
- lys_print_node(out, node, outformat_s, outline_length_s, outoptions_s);
- } else {
- fprintf(stderr, "yanglint error: The requested schema node \"%s\" does not exists.\n", outtarget_s);
- }
- } else {
- for (u = 0; u < mods->count; u++) {
- if (u) {
- ly_print(out, "\n");
- }
- lys_print_module(out, (struct lys_module *)mods->objs[u], outformat_s, outline_length_s, outoptions_s);
- }
- }
- } else if (data) {
-
- /* prepare operational datastore when specified for RPC/Notification */
- if (oper_file) {
- struct ly_in *in;
- tree = NULL;
-
- if (ly_in_new_filepath(oper_file, 0, &in)) {
- fprintf(stderr, "yanglint error: Unable to open an operational data file \"%s\".\n", oper_file);
- goto cleanup;
- }
- if (lyd_parse_data(ctx, in, 0, LYD_PARSE_ONLY, 0, &tree) || !tree) {
- fprintf(stderr, "yanglint error: Failed to parse the operational datastore file for RPC/Notification validation.\n");
- ly_in_free(in, 0);
- goto cleanup;
- }
- ly_in_free(in, 0);
- }
-
- for (data_item = data, data_prev = NULL; data_item; data_prev = data_item, data_item = data_item->next) {
- /* parse data file - via LYD_OPT_TRUSTED postpone validation when all data are loaded and merged */
-#if 0
- if (autodetection) {
- /* erase option not covered by LYD_OPT_TYPEMASK, but used according to the type */
- options_parser &= ~LYD_OPT_DATA_NO_YANGLIB;
- /* automatically detect data type from the data top level */
- data_item->xml = lyxml_parse_path(ctx, data_item->filename, 0);
- if (!data_item->xml) {
- fprintf(stderr, "yanglint error: parsing XML data for data type autodetection failed.\n");
- goto cleanup;
- }
-
- /* NOTE: namespace is ignored to simplify usage of this feature */
- if (!strcmp(data_item->xml->name, "data")) {
- if (verbose >= 2) {
- fprintf(stdout, "Parsing %s as complete datastore.\n", data_item->filename);
- }
- options_parser = (options_parser & ~LYD_OPT_TYPEMASK) | LYD_OPT_DATA_NO_YANGLIB;
- data_item->type = LYD_OPT_DATA;
- } else if (!strcmp(data_item->xml->name, "config")) {
- if (verbose >= 2) {
- fprintf(stdout, "Parsing %s as config data.\n", data_item->filename);
- }
- options_parser = (options_parser & ~LYD_OPT_TYPEMASK) | LYD_OPT_CONFIG;
- data_item->type = LYD_OPT_CONFIG;
- } else if (!strcmp(data_item->xml->name, "get-reply")) {
- if (verbose >= 2) {
- fprintf(stdout, "Parsing %s as <get> reply data.\n", data_item->filename);
- }
- options_parser = (options_parser & ~LYD_OPT_TYPEMASK) | LYD_OPT_GET;
- data_item->type = LYD_OPT_GET;
- } else if (!strcmp(data_item->xml->name, "get-config-reply")) {
- if (verbose >= 2) {
- fprintf(stdout, "Parsing %s as <get-config> reply data.\n", data_item->filename);
- }
- options_parser = (options_parser & ~LYD_OPT_TYPEMASK) | LYD_OPT_GETCONFIG;
- data_item->type = LYD_OPT_GETCONFIG;
- } else if (!strcmp(data_item->xml->name, "edit-config")) {
- if (verbose >= 2) {
- fprintf(stdout, "Parsing %s as <edit-config> data.\n", data_item->filename);
- }
- options_parser = (options_parser & ~LYD_OPT_TYPEMASK) | LYD_OPT_EDIT;
- data_item->type = LYD_OPT_EDIT;
- } else if (!strcmp(data_item->xml->name, "rpc")) {
- if (verbose >= 2) {
- fprintf(stdout, "Parsing %s as <rpc> data.\n", data_item->filename);
- }
- options_parser = (options_parser & ~LYD_OPT_TYPEMASK) | LYD_OPT_RPC;
- data_item->type = LYD_OPT_RPC;
- } else if (!strcmp(data_item->xml->name, "rpc-reply")) {
- if (verbose >= 2) {
- fprintf(stdout, "Parsing %s as <rpc-reply> data.\n", data_item->filename);
- }
-
- data_item->type = LYD_OPT_RPCREPLY;
- if (!data_item->next || (data_prev && !data_prev->tree)) {
- fprintf(stderr, "RPC reply (%s) must be paired with the original RPC, see help.\n", data_item->filename);
- goto cleanup;
- }
-
- continue;
- } else if (!strcmp(data_item->xml->name, "notification")) {
- if (verbose >= 2) {
- fprintf(stdout, "Parsing %s as <notification> data.\n", data_item->filename);
- }
- options_parser = (options_parser & ~LYD_OPT_TYPEMASK) | LYD_OPT_NOTIF;
- data_item->type = LYD_OPT_NOTIF;
-
- /* ignore eventTime element if present */
- while (data_item->xml->child && !strcmp(data_item->xml->child->name, "eventTime")) {
- lyxml_free(ctx, data_item->xml->child);
- }
- } else {
- fprintf(stderr, "yanglint error: invalid top-level element \"%s\" for data type autodetection.\n",
- data_item->xml->name);
- goto cleanup;
- }
-
- data_item->tree = lyd_parse_xml(ctx, &data_item->xml->child, options_parser, oper);
- if (data_prev && data_prev->type == LYD_OPT_RPCREPLY) {
-parse_reply:
- /* check result of the RPC parsing, we are going to do another parsing in this step */
- if (ly_errno) {
- goto cleanup;
- }
-
- /* check that we really have RPC for the reply */
- if (data_item->type != LYD_OPT_RPC) {
- fprintf(stderr, "yanglint error: RPC reply (%s) must be paired with the original RPC, see help.\n", data_prev->filename);
- goto cleanup;
- }
-
- if (data_prev->format == LYD_XML) {
- /* ignore <ok> and <rpc-error> elements if present */
- u = 0;
- LY_TREE_FOR_SAFE(data_prev->xml->child, iter, elem) {
- if (!strcmp(data_prev->xml->child->name, "ok")) {
- if (u) {
- /* rpc-error or ok already present */
- u = 0x8; /* error flag */
- } else {
- u = 0x1 | 0x4; /* <ok> flag with lyxml_free() flag */
- }
- } else if (!strcmp(data_prev->xml->child->name, "rpc-error")) {
- if (u && (u & 0x1)) {
- /* ok already present, rpc-error can be present multiple times */
- u = 0x8; /* error flag */
- } else {
- u = 0x2 | 0x4; /* <rpc-error> flag with lyxml_free() flag */
- }
- }
-
- if (u == 0x8) {
- fprintf(stderr, "yanglint error: Invalid RPC reply (%s) content.\n", data_prev->filename);
- goto cleanup;
- } else if (u & 0x4) {
- lyxml_free(ctx, data_prev->xml->child);
- u &= ~0x4; /* unset lyxml_free() flag */
- }
- }
-
- /* finally, parse RPC reply from the previous step */
- data_prev->tree = lyd_parse_xml(ctx, &data_prev->xml->child,
- (options_parser & ~LYD_OPT_TYPEMASK) | LYD_OPT_RPCREPLY, data_item->tree, oper);
- } else { /* LYD_JSON */
- data_prev->tree = lyd_parse_path(ctx, data_prev->filename, data_item->format,
- (options_parser & ~LYD_OPT_TYPEMASK) | LYD_OPT_RPCREPLY, data_item->tree, oper);
- }
- }
- } else if ((options_parser & LYD_OPT_TYPEMASK) == LYD_OPT_RPCREPLY) {
- if (data_prev && !data_prev->tree) {
- /* now we should have RPC for the preceding RPC reply */
- data_item->tree = lyd_parse_path(ctx, data_item->filename, data_item->format,
- (options_parser & ~LYD_OPT_TYPEMASK) | LYD_OPT_RPC, oper);
- data_item->type = LYD_OPT_RPC;
- goto parse_reply;
- } else {
- /* now we have RPC reply which will be parsed in next step together with its RPC */
- if (!data_item->next) {
- fprintf(stderr, "yanglint error: RPC reply (%s) must be paired with the original RPC, see help.\n", data_item->filename);
- goto cleanup;
- }
- if (data_item->format == LYD_XML) {
- /* create rpc-reply container to unify handling with autodetection */
- data_item->xml = calloc(1, sizeof *data_item->xml);
- if (!data_item->xml) {
- fprintf(stderr, "yanglint error: Memory allocation failed failed.\n");
- goto cleanup;
- }
- data_item->xml->name = lydict_insert(ctx, "rpc-reply", 9);
- data_item->xml->prev = data_item->xml;
- data_item->xml->child = lyxml_parse_path(ctx, data_item->filename, LYXML_PARSE_MULTIROOT | LYXML_PARSE_NOMIXEDCONTENT);
- if (data_item->xml->child) {
- data_item->xml->child->parent = data_item->xml;
- }
- }
- continue;
- }
- } else {
-#else
- {
-#endif
- /* TODO optimize use of ly_in in the loop */
- struct ly_in *in;
- if (ly_in_new_filepath(data_item->filename, 0, &in)) {
- fprintf(stderr, "yanglint error: input data file \"%s\".\n", data_item->filename);
- goto cleanup;
- }
- if (lyd_parse_data(ctx, in, 0, options_parser, LYD_VALIDATE_PRESENT, &data_item->tree)) {
- fprintf(stderr, "yanglint error: Failed to parse input data file \"%s\".\n", data_item->filename);
- ly_in_free(in, 0);
- goto cleanup;
- }
- ly_in_free(in, 0);
- }
-#if 0
- if (merge && data != data_item) {
- if (!data->tree) {
- data->tree = data_item->tree;
- } else if (data_item->tree) {
- /* merge results */
- if (lyd_merge(data->tree, data_item->tree, LYD_OPT_DESTRUCT | LYD_OPT_EXPLICIT)) {
- fprintf(stderr, "yanglint error: merging multiple data trees failed.\n");
- goto cleanup;
- }
- }
- data_item->tree = NULL;
- }
-#endif
- }
-#if 0
- if (merge) {
- /* validate the merged data tree, do not trust the input, invalidate all the data first */
- LY_TREE_FOR(data->tree, subroot) {
- LY_TREE_DFS_BEGIN(subroot, next, node) {
- node->validity = LYD_VAL_OK;
- switch (node->schema->nodetype) {
- case LYS_LEAFLIST:
- case LYS_LEAF:
- if (((struct lys_node_leaf *)node->schema)->type.base == LY_TYPE_LEAFREF) {
- node->validity |= LYD_VAL_LEAFREF;
- }
- break;
- case LYS_LIST:
- node->validity |= LYD_VAL_UNIQUE;
- /* falls through */
- case LYS_CONTAINER:
- case LYS_NOTIF:
- case LYS_RPC:
- case LYS_ACTION:
- node->validity |= LYD_VAL_MAND;
- break;
- default:
- break;
- }
- LY_TREE_DFS_END(subroot, next, node)
- }
- }
- if (lyd_validate(&data->tree, options_parser & ~LYD_OPT_TRUSTED, ctx)) {
- goto cleanup;
- }
- }
-#endif
- /* print only if data output format specified */
- if (outformat_d) {
- for (data_item = data; data_item; data_item = data_item->next) {
- if (!merge && verbose >= 2) {
- fprintf(stdout, "File %s:\n", data_item->filename);
- }
-#if 0
- if (outformat_d == LYD_XML && envelope) {
- switch (data_item->type) {
- case LYD_OPT_DATA:
- envelope_s = "data";
- break;
- case LYD_OPT_CONFIG:
- envelope_s = "config";
- break;
- case LYD_OPT_GET:
- envelope_s = "get-reply";
- break;
- case LYD_OPT_GETCONFIG:
- envelope_s = "get-config-reply";
- break;
- case LYD_OPT_EDIT:
- envelope_s = "edit-config";
- break;
- case LYD_OPT_RPC:
- envelope_s = "rpc";
- break;
- case LYD_OPT_RPCREPLY:
- envelope_s = "rpc-reply";
- break;
- case LYD_OPT_NOTIF:
- envelope_s = "notification";
- break;
- }
- fprintf(out, "<%s>\n", envelope_s);
- if (data_item->type == LYD_OPT_RPC && data_item->tree->schema->nodetype != LYS_RPC) {
- /* action */
- fprintf(out, "<action xmlns=\"urn:ietf:params:xml:ns:yang:1\">\n");
- }
- }
-#endif
- lyd_print_all(out, data_item->tree, outformat_d, options_dflt);
-#if 0
- if (envelope_s) {
- if (data_item->type == LYD_OPT_RPC && data_item->tree->schema->nodetype != LYS_RPC) {
- fprintf(out, "</action>\n");
- }
- fprintf(out, "</%s>\n", envelope_s);
- }
- if (merge) {
- /* stop after first item */
- break;
- }
-#endif
- }
- }
- }
-#if 0
- if (list) {
- print_list(out, ctx, outformat_d);
- }
-#endif
-
- ret = EXIT_SUCCESS;
cleanup:
- ly_set_free(mods, NULL);
- ly_set_free(searchpaths, NULL);
- for (i = 0; i < featsize; i++) {
- free(feat[i]);
- }
- free(feat);
- for (; data; data = data_item) {
- data_item = data->next;
- lyd_free_all(data->tree);
- free(data);
- }
- ly_ctx_destroy(ctx, NULL);
+ /* cleanup */
+ erase_context(&c);
- ly_out_free(out, NULL, 1);
return ret;
}