aboutsummaryrefslogtreecommitdiff
path: root/project.c
blob: 880d92e6eaa36c581c404e253b804f9f071b337e (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
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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345

/*

  Copyright (c) 2010 Samuel Lidén Borell <samuel@slbdata.se>

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:

  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  THE SOFTWARE.

*/

#include <string.h>
#include <glib/gprintf.h>
#include <glib/gstdio.h>
#include "template.h"

#include "project.h"

struct Project_ {
    // Path to root directory
    gchar *path;
    
    // File states in GIT
    GData *fileStates;
    
    // GIT state
    gboolean hasUncommitted; // whether there are unstaged or uncommitted changes
};


Project *project_init(const gchar *path) {
    Project *project = g_malloc(sizeof(Project));
    project->path = (g_str_has_suffix(path, "/") ?
        g_strdup(path) : g_strconcat(path, "/", NULL));
    project->fileStates = NULL;
    project->hasUncommitted = FALSE;
    
    project_refresh(project);
    return project;
}


void project_free(Project *project) {
    g_free(project->path);
    g_free(project);
}


static gboolean run_git_command(Project *project, gchar **argv) {
    gint exitStatus;
    GError *error = NULL;
    
    if (!g_spawn_sync(project->path, argv, NULL,
                      G_SPAWN_SEARCH_PATH,
                      NULL, NULL,
                      NULL, NULL, // pipes
                      &exitStatus,
                      &error)) {
        // TODO better error message
        g_fprintf(stderr, "failed to spawn process!\n");
        g_error_free(error);
        return FALSE;
    }
    
    if (exitStatus) {
        // TODO print argv properly
        g_fprintf(stderr, "command %s %s failed. exit code: %d\n",
                  argv[0], argv[1], exitStatus);
        return FALSE;
    }
    
    return TRUE;

}

static FileState gitStateToFileState(gchar x, gchar y) {
    switch (y) {
        case '?': return FileState_Unknown;
        case 'A': return FileState_Added;
        case 'C': return FileState_Copied;
        case 'D': return FileState_Deleted;
        case 'M': return FileState_Modified;
        case 'R': return FileState_Renamed;
        default: return FileState_Unmodified;
    }
}

void project_refresh(Project *project) {
    // Clear the file state list
    g_datalist_clear(&project->fileStates);
    g_datalist_init(&project->fileStates);
    project->hasUncommitted = FALSE;
    
    // Read state from GIT
    
    // Spawn process: "git status --porcelain -z"
    static gchar *argv[] = { "git", "status", "--porcelain", "-z", NULL };
    GPid pid;
    gint output_fd;
    GError *error = NULL;
    
    if (!g_spawn_async_with_pipes(project->path, argv, NULL,
                       G_SPAWN_SEARCH_PATH | G_SPAWN_STDERR_TO_DEV_NULL,
                       NULL, NULL, &pid,
                       NULL, &output_fd, NULL, // pipes
                       &error)) {
        // TODO better error message
        g_fprintf(stderr, "failed to spawn process!\n");
        g_error_free(error);
        return;
    }
    
    // Create an IO channel so we can read from the output fd
    GIOChannel *chan = g_io_channel_unix_new(output_fd);
    if (!chan) {
        // TODO better error message
        g_fprintf(stderr, "failed to create IO channel!\n");
        g_spawn_close_pid(pid);
        return;
    }
    
    // Read the output
    error = NULL;
    gchar *data;
    gsize length;
    if (!g_io_channel_read_to_end(chan, &data, &length, &error)) {
        // TODO better error message
        g_fprintf(stderr, "failed to read from pipe!\n");
    }
    
    // Parse
    gchar *end = data + length;
    gchar *p = data;
    while (p && p != end && *p) {
        gsize entrylen = strlen(p);
        if (entrylen < 4) continue;
        
        // Parse status
        gchar x = p[0];
        gchar y = p[1];
        FileState state = gitStateToFileState(x, y);
        if (p[2] != ' ') continue;
        
        // Check if this file has uncommitted changes
        if (state != FileState_Unknown && state != FileState_Unmodified) {
            fprintf(stderr, "uncommitted file!\n");
            project->hasUncommitted = TRUE;
        }
        
        // Parse filename
        if (p[entrylen-1] == '/') p[entrylen-1] = '\0'; // remove trailing /
        p += 3;
        g_fprintf(stderr, "add filename >%s< = %d\n", p, state);
        g_datalist_set_data(&project->fileStates, p, (gpointer)state);
        
        p += entrylen - 3 + 1;
    }
    
    g_free(data);
    g_io_channel_unref(chan);
    
    // Clean up
    g_spawn_close_pid(pid);
}


const gchar *project_getPath(const Project *project) {
    return project->path;
}


gboolean project_isPage(Project *project, const gchar *uri) {
    return g_str_has_suffix(uri, ".html");
}


static gchar *readFile(const Project *project, const gchar *uri) {
    gchar *filename = g_strconcat(project->path, uri, NULL);
    gchar *contents = NULL;
    
    g_file_get_contents(filename, &contents, NULL, NULL);
    g_free(filename);
    return contents;
}


static gboolean saveFile(const Project *project, const gchar *uri,
                       const gchar *contents) {
    gchar *filename = g_strconcat(project->path, uri, NULL);
    gboolean ok = g_file_set_contents(filename, contents, -1, NULL);
    g_free(filename);
    return ok;
}


static const gchar *templateURI = "/template.html";
gboolean project_isTemplate(const Project *project, const gchar *uri) {
    return !strcmp(uri, templateURI);
}


gchar *project_getTemplateURI(const Project *project, const gchar *uri) {
    return g_strdup(!strcmp(uri, templateURI) ? NULL : templateURI);
}


FileState project_getFileState(Project *project, const gchar *uri) {
    // Skip leading / because it's not present in local paths,
    // for example from "git status"
    if (uri[0] == '/') uri++;
    
    g_printf("looking up >%s<\n", uri);
    return (FileState)g_datalist_get_data(&project->fileStates, uri);
}


gchar *project_getFileURL(const Project *project, const gchar *uri) {
    return g_strconcat("file://", project->path, uri, NULL);
}


static gchar *getTemplateContentsForPage(const Project *project, const gchar *pageURI) {
    gchar *templateURI = project_getTemplateURI(project, pageURI);
    if (!templateURI) return NULL;
    
    gchar *templateContents = project_loadPage(project, templateURI);
    g_free(templateURI);
    return templateContents;
}


static gchar *mergeWithTemplate(const Project *project, const gchar *uri,
                                const gchar *contents) {
    if (!contents) return NULL;
    
    // Load template
    gchar *templateContents = getTemplateContentsForPage(project, uri);
    if (!templateContents) return g_strdup(contents);
    
    // Merge
    Template *tem = template_parseFromString(templateContents);
    gchar *page = template_updatePage(tem, contents);
    template_free(tem);
    
    g_free(templateContents);
    return page;
}


gchar *project_loadPage(const Project *project, const gchar *uri) {
    // Load contents
    gchar *contents = readFile(project, uri);
    
    // Merge with template
    gchar *page = mergeWithTemplate(project, uri, contents);
    g_free(contents);
    return page;
}


gboolean project_savePage(Project *project, const gchar *uri, const gchar *html) {
    // Restore and update the template parts
    gchar *page = mergeWithTemplate(project, uri, html);
    
    // Save file
    return saveFile(project, uri, page);
}


gboolean project_addPage(Project *project, const gchar *uri, const gchar *templateURI) {
    gboolean ok = FALSE;
    
    // TODO: set template URI
    
    // Start with the template contents as the page contents
    gchar *templateContents = getTemplateContentsForPage(project, uri);
    
    ok = project_savePage(project, uri, templateContents ? templateContents : "");
    
    g_free(templateContents);
    
    // Add to GIT
    project_addFile(project, uri);
    
    return ok;
}

gboolean project_addFile(Project *project, const gchar *uri) {
    // Run "git add -Nf -- filename"
    static gchar *argv[] = { "git", "add", "-Nf", "--", NULL, NULL };
    
    if (uri[0] == '/') uri++;
    argv[4] = uri;
    gboolean ok = run_git_command(project, argv);
    
    return ok;
}

gboolean project_deletePage(Project *project, const gchar *uri) {
    gchar *filename = g_strconcat(project->path, uri, NULL);
    gboolean ok = (g_remove(filename) == 0);
    g_free(filename);
    return ok;
}

gboolean project_hasUncommitted(const Project *project) {
    return project->hasUncommitted;
}

gboolean project_commit(Project *project, const gchar *message) {
    // Run "git commit -m xxx -a"
    gchar *msg = g_strdup(message);
    static gchar *argv[] = { "git", "commit", "-m", NULL, "-a", NULL };
    
    argv[3] = msg;
    gboolean ok = run_git_command(project, argv);
    
    g_free(msg);
    return ok;
}

gboolean project_discard(Project *project) {
    // Run "git reset HEAD" and "git checkout ."
    static gchar *reset[] = { "git", "reset", "HEAD", NULL };
    gboolean okr = run_git_command(project, reset);
    
    static gchar *checkout[] = { "git", "checkout", ".", NULL };
    gboolean okc = run_git_command(project, checkout);
    
    return okr && okc;
}