blob: d1121a07c247bd5d5450a6716b665f36ee33a0bc [file] [log] [blame]
Radek Krejcied5acc52019-04-25 15:57:04 +02001/**
2 * @file main.c
3 * @author Radek Krejci <rkrejci@cesnet.cz>
4 * @brief libyang's yanglint tool
5 *
6 * Copyright (c) 2015-2017 CESNET, z.s.p.o.
7 *
8 * This source code is licensed under BSD 3-Clause License (the "License").
9 * You may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
11 *
12 * https://opensource.org/licenses/BSD-3-Clause
13 */
14
Radek Krejci535ea9f2020-05-29 16:01:05 +020015#define _GNU_SOURCE
Radek Krejcied5acc52019-04-25 15:57:04 +020016
17#include <stdio.h>
18#include <stdlib.h>
19#include <sys/stat.h>
20#include <string.h>
21#include <unistd.h>
22
Radek Krejcied5acc52019-04-25 15:57:04 +020023#include "libyang.h"
24
Radek Krejci535ea9f2020-05-29 16:01:05 +020025#include "tools/config.h"
26
27#include "commands.h"
28#include "completion.h"
29#include "configuration.h"
30#include "linenoise/linenoise.h"
31
32
Radek Krejcied5acc52019-04-25 15:57:04 +020033int done;
34struct ly_ctx *ctx = NULL;
35
36/* main_ni.c */
37int main_ni(int argc, char *argv[]);
38
39int
40main(int argc, char* argv[])
41{
42 char *cmd, *cmdline, *cmdstart;
43 int i, j;
44
45 if (argc > 1) {
46 /* run in non-interactive mode */
47 return main_ni(argc, argv);
48 }
49
50 /* continue in interactive mode */
51 linenoiseSetCompletionCallback(complete_cmd);
52 load_config();
53
54 if (ly_ctx_new(NULL, 0, &ctx)) {
55 fprintf(stderr, "Failed to create context.\n");
56 return 1;
57 }
58
59 while (!done) {
60 /* get the command from user */
61 cmdline = linenoise(PROMPT);
62
63 /* EOF -> exit */
64 if (cmdline == NULL) {
65 done = 1;
66 cmdline = strdup("quit");
67 }
68
69 /* empty line -> wait for another command */
70 if (*cmdline == '\0') {
71 free(cmdline);
72 continue;
73 }
74
75 /* isolate the command word. */
76 for (i = 0; cmdline[i] && (cmdline[i] == ' '); i++);
77 cmdstart = cmdline + i;
78 for (j = 0; cmdline[i] && (cmdline[i] != ' '); i++, j++);
79 cmd = strndup(cmdstart, j);
80
81 /* parse the command line */
82 for (i = 0; commands[i].name; i++) {
83 if (strcmp(cmd, commands[i].name) == 0) {
84 break;
85 }
86 }
87
88 /* execute the command if any valid specified */
89 if (commands[i].name) {
90 /* display help */
91 if ((strchr(cmdstart, ' ') != NULL) && ((strncmp(strchr(cmdstart, ' ')+1, "-h", 2) == 0)
92 || (strncmp(strchr(cmdstart, ' ')+1, "--help", 6) == 0))) {
93 if (commands[i].help_func != NULL) {
94 commands[i].help_func();
95 } else {
96 printf("%s\n", commands[i].helpstring);
97 }
98 } else {
99 commands[i].func((const char *)cmdstart);
100 }
101 } else {
102 /* if unknown command specified, tell it to user */
103 fprintf(stderr, "%s: no such command, type 'help' for more information.\n", cmd);
104 }
105 linenoiseHistoryAdd(cmdline);
106
107 free(cmd);
108 free(cmdline);
109 }
110
111 store_config();
112 ly_ctx_destroy(ctx, NULL);
113
114 return 0;
115}