summaryrefslogtreecommitdiff
path: root/src/commands/echo.c
blob: b80f8729b730769103a931cb1cb28796a87a443e (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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
#include "../command.h"

#include <stdio.h>
#include <string.h>

static void print_with_escape_codes(const char* str) {
    
    size_t index = 0;
    while (true) {
        char c = str[index];
        index++;

        if (c == '\0') break;
        if (c != '\\') {
            putchar(c);
            continue;
        }

        char n = str[index];
        index++;

        switch (n) {
            case '\\':
                putchar('\\');
                break;
            case 'b':
                putchar('\b');
                break;
            case 'c':
                exit(EXIT_SUCCESS);
            case 'n':
                putchar('\n');
                break;
            case 'r':
                putchar('\r');
                break;
            case 't':
                putchar('\t');
                break;
            case 'v':
                putchar('\v');
                break;
            default:
                putchar(c);
                putchar(n);
        }
    }
}

COMMAND(echo) {

    if (argc < 1) {
        return EXIT_SUCCESS;
    }

    bool escape_codes = false;
    bool newline = true;

    int start = 0;

    if (prefix("-", argv[0])) {

        start = 1;

        for (size_t i = 0; i < strlen(argv[0] + 1); i++) {
            char c = argv[0][i + 1];
            switch (c) {
                case 'e':
                    escape_codes = true;
                    break;
                case 'E':
                    escape_codes = false;
                    break;
                case 'n':
                    newline = false;
                    break;
                default:
                    escape_codes = false;
                    newline = true;
                    start = 0;
                    break;
            }
        }
    }

    for (int i = start; i < argc; i++) {
         if (escape_codes) {
            print_with_escape_codes(argv[i]);
        } else {
            printf("%s", argv[i]);
        }

        if (i + 1 != argc) {
            putchar(' ');
        }
    } 

    if (newline) {
        putchar('\n');
    }

    return EXIT_SUCCESS;
}