/nobber/trunk

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/nobber/trunk
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
#pragma once

/*******
 * utils.h
 * These utility functions and macros can requiers nob.h
 *
 * You may use them as you see fit.
 *
 * This header file uses the standard STB-style inclue stuff:
 * define NOBBER_UTILS_IMPREMENTATION 
 * to in one file, so they get built.
 ******/

#include <stdlib.h>
#include <stdio.h>

#include <alloca.h>
#include <errno.h>
#include <linux/limits.h>
#include <stdlib.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <stdint.h>
#include <inttypes.h>
#include <unistd.h>
#include <assert.h>
#if defined(__unix__) || defined(__linux__)
    #include <unistd.h>
#endif
#ifdef __darwin__
    #include <mach-o/dyld.h>
#endif

#include "nob.h"

#define IN /*Does nothing, just a mark.*/
#define OUT /*Does nothing, just a mark.*/
#define INOUT /*Does nothing, just a mark.*/

typedef struct da_strings_t DaStrings;

typedef enum NobberError {
    NOBBER_RETURN_NORMAL,
    NOBBER_RETURN_UNUSED0,
    NOBBER_RETURN_UNUSED1,
    NOBBER_RETURN_UNUSED2,
    NOBBER_RETURN_UNUSED3,
    NOBBER_RETURN_UNKNOWN_COMMAND,
    NOBBER_RETURN_EXEC,
    NOBBER_RETURN_COUNT
} NobberError;

void * malloc0 (size_t size);
char * strip_extention (IN char * file_name);
char * c_to_o_ext (IN char * str);
DaStrings * compile_files (IN char * source_files[], size_t source_files_len, IN char * build_flags[], size_t build_flags_len, INOUT Nob_Cmd * cmd, INOUT Nob_Procs * procs);
void link_files (IN DaStrings * object_files, IN char * exec_name, IN char * link_flags[], size_t link_flags_len, INOUT Nob_Cmd * cmd);
void clean_files (IN char * source_files[], size_t len, char * exec_name, INOUT Nob_Cmd * cmd);
char * construct_string (IN char * str, ...);
NobberError run_excutable (INOUT Nob_Cmd * cmd, IN char * executable);
char * get_path_of_current_executalbe ();
char ** split_string (IN char * str, char delimeter, OUT size_t * out_size);


//#define free0(ptr) \
//    free (ptr); \
//    ptr = NULL;
#define free0(ptr) \
    memset ((void *)ptr, 0, sizeof ((void *) ptr)); \
    free (ptr);

struct da_strings_t {
    char ** items;
    size_t count;
    size_t capacity;
};


/** 
 * free the items in a list propperly!
 * TODO: Need a version that takes a FreeFunc.
 **/
#define da_free_items(Type, da) { \
    for (Type *it = (da)->items; it < (da)->items + (da)->capacity; it++) { \
        if (*it == NULL) break;\
        free (*it);\
    }\
    free ((da)->items);\
}

#ifdef NOBBER_UTILS_IMPLEMENTAITON

/* ----------------- */

void * malloc0 (size_t size) {
    void * out_val = malloc (size);
    memset (out_val, 0, size);
    return out_val;
}


// https://stackoverflow.com/questions/43163677/how-do-i-strip-a-file-extension-from-a-string-in-c
char * strip_extention (IN char * file_name) {
    char * out_str = malloc(strlen(file_name) + 1);
    strcpy (out_str, file_name);
    char *end = out_str + strlen(out_str);

    while (end > out_str && *end != '.' && *end != '\\' && *end != '/') {
        --end;
    }

    if ((end > out_str && *end == '.') &&
            (*(end - 1) != '\\' && *(end - 1) != '/')) {
        *end = '\0';
    }

    return out_str;
}

char * c_to_o_ext (IN char * str) {
    char * out_str = malloc (strlen(str) + 1);
    char * tmp_str = strip_extention (str);
    sprintf (out_str, "%s.o", tmp_str); 
    free (tmp_str);
    return out_str;
}

DaStrings * compile_files (IN char * source_files[], size_t source_files_len,
                           IN char * build_flags[], size_t build_flags_len, 
                           INOUT Nob_Cmd * cmd, INOUT Nob_Procs * procs) {
    DaStrings * object_files = malloc0 (sizeof (DaStrings));
    for (size_t i = 0; i < source_files_len; i++) {
        cmd->count = 0;
        if (source_files[i] == NULL) break;
        nob_cmd_append (cmd, "cc");
        nob_cmd_append (cmd, source_files[i]);
        nob_da_append_many (cmd, build_flags, build_flags_len);
        nob_cmd_append (cmd, "-c");
        char * tmp_str = c_to_o_ext (source_files[i]);
        nob_cmd_append (cmd, "-o", tmp_str);

        char * s = malloc0 (strlen (tmp_str) + 1);
        strcpy (s, tmp_str);
        nob_da_append (object_files, s);

        nob_cmd_run (cmd, .async = procs);
        free0 (tmp_str);
    }
    return object_files;
}

void link_files (IN DaStrings * object_files, IN char * exec_name,
        IN char * link_flags[], size_t link_flags_len,
        INOUT Nob_Cmd * cmd) {
    nob_cmd_append (cmd, "cc");
    nob_cmd_append (cmd, "-o", exec_name);
    nob_da_append_many (cmd, (char**) object_files->items, object_files->count);
    nob_da_append_many (cmd, (char**) link_flags, link_flags_len);
    nob_cmd_run (cmd);
}

void clean_files (IN char * source_files[],  size_t len, char * exec_name, INOUT Nob_Cmd * cmd) {
    cmd->count = 0;
    DaStrings tmp_strings = {0};
    for (size_t i = 0; i < len; i++) {
        if (source_files[i] == NULL) break;
        char * tmp_file = strip_extention ((char *)source_files[i]);
        char * tmp_obj_file = c_to_o_ext (tmp_file);
        nob_da_append (&tmp_strings, tmp_obj_file);
        tmp_file = c_to_o_ext (tmp_file);
        free0 (tmp_file);
    }
    nob_cmd_append (cmd, "rm");
    nob_da_append_many (cmd, tmp_strings.items, tmp_strings.count);
    for (size_t i = 0; i < tmp_strings.count; i++) {
        char * s = tmp_strings.items[i];
        if (s == NULL) break;
    }
    nob_cmd_append (cmd, exec_name);
    nob_cmd_run (cmd);
    da_free_items (char *, &tmp_strings);
}

char * construct_string (IN char * str, ...) {
    char * retval = NULL;
    va_list list = {0};
    Nob_String_Builder sb = {0};
    nob_sb_append_cstr (&sb, str);
    va_start (list, str);
    while (*str++) {
        nob_sb_append_cstr (&sb, str);
    }
    va_end (list);
    Nob_String_View sv = nob_sv_from_parts (sb.items, sb.count);
    retval = malloc0 (strlen (sv.data) + 1);
    strcpy (retval, sv.data);
    return retval;
}

NobberError run_excutable (INOUT Nob_Cmd * cmd, IN char * executable) {
    // We assume we are only running from the current directory.
    char * cwd;
    NobberError ret_val = NOBBER_RETURN_NORMAL;
    strcat (cwd, "/");
    strcat (cwd, executable);
    return ret_val;
}

char * get_path_of_current_executalbe () {
    char buf[PATH_MAX];
#if  defined(__DragonFly__) || defined(__NetBSD__) || defined(__linux__)
    #if defined(__linux__)
    #define PROC_EXE_PATH "/proc/self/exe"
    #elif defined(__NetBSD__)
    #define PROC_EXE_PATH "/proc/curproc/exe"
    #elif defined(__DragonFly__)
    #endif
    if (readlink (PROC_EXE_PATH, buf, PATH_MAX) < 0) {
        fprintf (stderr, "[ERROR] Could not readlink /proc/self/exe: %s", strerror (errno));
        return NULL;
    }
#elif defined(__FreeBSD__)
    int mib[4];
    mib[0] = CTL_KERN;
    mib[1] = KERN_PROC;
    mib[2] = KERN_PROC_PATHNAME;
    mib[3] = -1;
    sysctl(mib, 4, buf, PATH_MAX, NULL, 0);
#elif defined(__darwin__)
    if (_NSGetExecutablePath(buf, PATH_MAX) < 0) {
        fprintf (stderr, "[ERROR] Could not get executable path.");
    }
#elif defined(WIN32)
    if (!GetModuleFileNameA (NULL, buf, MAX_PATH)) {
        fprintf (stderr, "[ERROR] Could not readlink /proc/self/exe: %s", strerror (errno));
        return NULL;
    }
#else
    static_assert (false, "get_path_of_current_executalbe () is not implemented for this platform.");
#endif
    char * ret = malloc (strlen (buf));
    strcpy(ret, buf);
    return ret;
}

char ** split_string (IN char * str, char deliminator, OUT size_t * out_size) {
    char * str_cpy = strndup (str, strlen (str));
    char * ptr = str_cpy;
    char delim[2] = {deliminator, 0};
    size_t no_of_tokens = 0;

    // Count the nuber of tokens
    while (*ptr) {
        if (*ptr == deliminator) {
            no_of_tokens++;
        }
        ptr++;
    }
    if (*(--ptr) != deliminator) {
        no_of_tokens++;
    }
    no_of_tokens++; // add empty space.
    
    char ** result = malloc0 (sizeof (char *) * no_of_tokens);
    if (result) {
        size_t idx = 0;
        char * tok_ptr = str_cpy;
  
        char * token = strtok (tok_ptr, delim);
        while (token) {
            result[idx] = strndup (token, strlen (token));
            token = strtok (NULL, delim);
            idx++;
        }
        result[idx] = 0;
    }
    *out_size = no_of_tokens - 1;
    free (str_cpy);
    return result;
}


#endif // NOBBER_UTILS_IMPLEMENTATION