summaryrefslogtreecommitdiff
path: root/42sh/src/builtins/cd.c
blob: 90fd9dbb12d7bd1273db0f6d34df08e20d839a67 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "builtins.h"
#include "utils/env.h"

int cd_pointpoint(char *path, char *old)
{
    char *current = strrchr(path, '/');
    size_t len = current - path;
    if (len == 0)
    {
        fprintf(stderr, "cd: error with ..\n");
        return 2;
    }
    char *parent = malloc(len + 1);
    memcpy(parent, current, len);
    parent[len] = '\0';
    old = path;
    path = parent;
    env_set("OLDPWD", old);
    env_set("PWD", path);
    free(parent);

    return 0;
}

int cd(struct string **args)
{
    if (args[0] == NULL || args[1] != NULL)
    {
        fprintf(stderr, "cd: error too many arguments\n");
        fflush(stdout);
        return 2;
    }
    if (strcmp(env_get("PWD"), "") == 0)
    {
        fprintf(stderr, "cd: error with PWD\n");
        fflush(stdout);
        return 2;
    }
    char *old = env_get("OLDPWD");
    char *path = env_get("PWD");
    char *tmp = old;
    if (strcmp(args[0]->data, "-") == 0)
    {
        if (strcmp(old, "") == 0)
        {
            fprintf(stderr, "cd: error with OLDPWD\n");
            fflush(stdout);
            return 2;
        }
        printf("%s\n", old);
        old = path;
        path = tmp;
    }
    else if (strcmp(args[0]->data, "..") == 0)
    {
        int res = cd_pointpoint(path, old);
        fflush(stdout);
        return res;
    }
    else
    {
        old = path;
        path = args[0]->data;
    }
    env_set("OLDPWD", old);
    env_set("PWD", path);
    fflush(stdout);
    return 0;
}