main.c (2199B)
1 #include <limits.h> 2 #include <stdio.h> 3 #include <stdlib.h> 4 #include <string.h> 5 #include <unistd.h> 6 7 #include "command/command.h" 8 9 static int cmd_init(int argc, const char **argv) { 10 const char *target_dir = "."; 11 if (argc >= 2) { 12 target_dir = argv[1]; 13 } 14 15 // Check if target directory exists and is accessible 16 if (access(target_dir, F_OK | X_OK) != 0) { 17 fprintf(stderr, "Error: directory '%s' does not exist or is not accessible\n", target_dir); 18 return 1; 19 } 20 21 // Build path to .dep file 22 char dep_path[PATH_MAX]; 23 int ret = snprintf(dep_path, sizeof(dep_path), "%s/.dep", target_dir); 24 if (ret < 0 || ret >= sizeof(dep_path)) { 25 fprintf(stderr, "Error: path too long\n"); 26 return 1; 27 } 28 29 // Check if .dep already exists 30 if (access(dep_path, F_OK) == 0) { 31 printf("Target directory already initialized\n"); 32 return 0; 33 } 34 35 // Create empty .dep file 36 FILE *f = fopen(dep_path, "w"); 37 if (!f) { 38 fprintf(stderr, "Error: could not create .dep file in '%s'\n", target_dir); 39 return 1; 40 } 41 fclose(f); 42 43 printf("Initialized successfully\n"); 44 return 0; 45 } 46 47 void __attribute__((constructor)) cmd_init_setup(void) { 48 struct cmd_struct *cmd = calloc(1, sizeof(struct cmd_struct)); 49 if (!cmd) { 50 fprintf(stderr, "Failed to allocate memory for init command\n"); 51 return; 52 } 53 cmd->next = commands; 54 cmd->fn = cmd_init; 55 static const char *init_names[] = {"init", NULL}; 56 cmd->name = init_names; 57 cmd->display = "init"; 58 cmd->description = "Initialize a new project with a .dep file"; 59 cmd->help_text = 60 "dep init - Initialize a new project with a .dep file\n" 61 "\n" 62 "Usage:\n" 63 " dep init\n" 64 " dep init <directory>\n" 65 "\n" 66 "Description:\n" 67 " Create an empty .dep file in the current directory or a specified directory.\n" 68 " The .dep file is used to list dependencies for the project.\n" 69 "\n" 70 "Examples:\n" 71 " dep init # Create .dep in current directory\n" 72 " dep init /path/to/project # Create .dep in specified directory\n"; 73 commands = cmd; 74 }