Line data Source code
1 : #include "custom_cd.h"
2 :
3 : static char latest_cd_path[MAX_PATH_LENGTH] = {0};
4 :
5 11 : bool cd(int argc, char **args)
6 : {
7 11 : char *home = getenv(HOME_ENV_VAR);
8 11 : if (home == NULL)
9 : {
10 2 : print_error("[ERROR] HOME environment variable not set");
11 2 : return false;
12 : }
13 :
14 : // Default path
15 9 : const char *param = home;
16 :
17 9 : if (latest_cd_path[0] == '\0') // Initialize
18 : {
19 8 : if (getcwd(latest_cd_path, sizeof(latest_cd_path)) == NULL)
20 : {
21 0 : print_error("[ERROR] getcwd");
22 0 : return false;
23 : }
24 : }
25 :
26 9 : if (argc > 2)
27 : {
28 1 : errno = EINVAL;
29 1 : print_error("[ERROR] Invalid number of arguments for cd");
30 1 : return false;
31 : }
32 :
33 : // Input path
34 8 : if (argc == 2)
35 : {
36 7 : if (strcmp(args[1], "-") == 0)
37 1 : param = latest_cd_path;
38 6 : else if (strcmp(args[1], "~") == 0)
39 1 : param = home;
40 : else
41 5 : param = args[1];
42 : }
43 :
44 : // Change latest path
45 : char cwd[MAX_PATH_LENGTH];
46 8 : if (getcwd(cwd, sizeof(cwd)) == NULL)
47 : {
48 0 : print_error("[ERROR] getcwd");
49 0 : return false;
50 : }
51 :
52 8 : if (chdir(param) == -1)
53 : {
54 2 : print_error("[ERROR] cd");
55 2 : return false;
56 : }
57 :
58 6 : if (strcmp(cwd, latest_cd_path) != 0)
59 1 : strcpy(latest_cd_path, cwd);
60 :
61 6 : return true;
62 : }
|