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