main.c (2698B)
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 5 #include "command/command.h" 6 7 static void print_global_help(void) { 8 printf("Usage: dep [global options] <command> [command options]\n"); 9 printf("\n"); 10 printf("Global options:\n"); 11 printf(" n/a\n"); 12 printf("\n"); 13 printf("Commands:\n"); 14 15 struct cmd_struct *cmd = commands; 16 while (cmd) { 17 printf(" %-16s %s\n", cmd->display ? cmd->display : cmd->name[0], cmd->description ? cmd->description : ""); 18 cmd = cmd->next; 19 } 20 21 printf("\n"); 22 printf("Help topics:\n"); 23 printf(" global This help text\n"); 24 25 cmd = commands; 26 while (cmd) { 27 printf(" %-16s More detailed explanation on the %s command\n", cmd->name[0], cmd->name[0]); 28 cmd = cmd->next; 29 } 30 } 31 32 static int cmd_help(int argc, const char **argv) { 33 if (argc < 1) { 34 print_global_help(); 35 return 0; 36 } 37 38 if (argc == 1 && (!strcmp(argv[0], "help") || !strcmp(argv[0], "h") || !strcmp(argv[0], "global"))) { 39 print_global_help(); 40 return 0; 41 } 42 43 const char *topic = (argc > 1) ? argv[1] : argv[0]; 44 45 if (!strcmp(topic, "global")) { 46 print_global_help(); 47 return 0; 48 } 49 50 struct cmd_struct *cmd = commands; 51 while (cmd) { 52 if (!strcmp(topic, cmd->name[0])) { 53 if (cmd->help_text) { 54 printf("%s\n", cmd->help_text); 55 } else { 56 printf("dep %s - %s\n\n", cmd->name[0], cmd->description); 57 printf(" %s\n", cmd->display); 58 } 59 return 0; 60 } 61 cmd = cmd->next; 62 } 63 64 fprintf(stderr, "Error: unknown help topic '%s'\n", topic); 65 fprintf(stderr, "Run 'dep help' for available topics.\n"); 66 return 1; 67 } 68 69 void __attribute__((constructor)) cmd_help_setup(void) { 70 struct cmd_struct *cmd = calloc(1, sizeof(struct cmd_struct)); 71 if (!cmd) { 72 fprintf(stderr, "Failed to allocate memory for help command\n"); 73 return; 74 } 75 cmd->next = commands; 76 cmd->fn = cmd_help; 77 static const char *help_names[] = {"help", "h", NULL}; 78 cmd->name = help_names; 79 cmd->display = "help [topic]"; 80 cmd->description = "Show this help or the top-level info about a command"; 81 cmd->help_text = 82 "dep help - Show this help or the top-level info about a command\n" 83 "\n" 84 "Usage:\n" 85 " dep help\n" 86 " dep help <command>\n" 87 "\n" 88 "Description:\n" 89 " Show general help or detailed help for a specific command.\n" 90 "\n" 91 "Examples:\n" 92 " dep help # Show general help\n" 93 " dep help add # Show help for add command\n" 94 " dep help install # Show help for install command\n"; 95 commands = cmd; 96 }