unofficial mirror of notmuch@notmuchmail.org
 help / color / mirror / code / Atom feed
blob a0cf0e3697eb0b4dd3042097a7419b11cbece775 14508 bytes (raw)
name: git-remote-notmuch.c 	 # note: path name is non-authoritative(*)

  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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
 
/* notmuch - Not much of an email program, (just index and search)
 *
 * Copyright © 2023 Felipe Contreras
 * Copyright © 2024 David Bremner
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see https://www.gnu.org/licenses/ .
 *
 * Authors: Felipe Contreras
 *	    David Bremner <david@tethera.net>
 */

#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <notmuch.h>
#include "notmuch-client.h"
#include "path-util.h"
#include "hex-escape.h"
#include "string-util.h"
#include "tag-util.h"

#define ASSERT(x) assert ((x))

/* File scope globals */
const char *debug_flags = NULL;
FILE *log_file = NULL;

/* For use with getline. */
char *buffer = NULL;
size_t buffer_len = 0;

static inline bool
equal_lastmod (const char *uuid1, unsigned long counter1,
	       const char *uuid2, unsigned long counter2)
{
    return (strcmp_null (uuid1, uuid2) == 0) && (counter1 == counter2);
}

/* Error handling */
static void
ensure (bool condition, const char *format, ...)
{
    va_list va_args;

    if (! condition) {
	va_start (va_args, format);
	vfprintf (stderr, format, va_args);
	va_end (va_args);
	fprintf (stderr, "\n");
	exit (EXIT_FAILURE);
    }
}

/* It is a (protocol) error to call this at/after EOF */
static void
buffer_line (FILE *stream)
{
    ssize_t nread;

    nread = getline (&buffer, &buffer_len, stream);
    ensure (nread >= 0, "getline %s", strerror (errno));
    chomp_newline (buffer);
}

static GStrv
tokenize_buffer ()
{
    char *tok = buffer;
    size_t tok_len = 0;

    g_autoptr (GStrvBuilder) builder = g_strv_builder_new ();

    while ((tok = strtok_len (tok + tok_len, " \t\n", &tok_len))) {
	g_strv_builder_take (builder, g_strndup (tok, tok_len));
    }

    return g_strv_builder_end (builder);
}

static void
flog (const char *format, ...)
{
    va_list va_args;

    if (log_file) {
	va_start (va_args, format);
	vfprintf (log_file, format, va_args);
	fflush (log_file);
	va_end (va_args);
    }
}

static const char *
gmessage (GError *err)
{
    if (err)
	return err->message;
    else
	return NULL;
}

static void
str2ul (const char *str, unsigned long int *num_p)
{
    gboolean ret;

    g_autoptr (GError) gerror = NULL;

    ret = g_ascii_string_to_unsigned (str, 10, 0, G_MAXUINT64, num_p, &gerror);
    ensure (ret, "converting %s to unsigned long: %s", str, gmessage (gerror));
}

static void
read_lastmod (const char *dir, char **uuid_out, unsigned long *counter_out)
{
    g_autoptr (GString) filename = g_string_new (dir);
    unsigned long num = 0;
    FILE *in;

    assert (uuid_out);
    assert (counter_out);

    g_string_append (filename, "/lastmod");

    in = fopen (filename->str, "r");
    if (! in) {
	ensure (errno == ENOENT, "error opening lastmod file");
	*uuid_out = NULL;
	*counter_out = 0;
    } else {
	g_auto (GStrv) tokens = NULL;
	buffer_line (in);

	tokens = tokenize_buffer ();

	*uuid_out = tokens[0];
	str2ul (tokens[1], &num);

	flog ("loaded uuid = %s\tlastmod = %zu\n", tokens[0], num);
    }

    *counter_out = num;

}

static void
store_lastmod (notmuch_database_t *notmuch, const char *dir)
{
    char *filename = NULL;
    FILE *out;
    unsigned long lastmod;
    const char *uuid;

    ASSERT (filename = talloc_asprintf (notmuch, "%s/lastmod", dir));

    out = fopen (filename, "w");
    ensure (out, "error opening %s for writing: %s", filename, strerror (errno));

    lastmod = notmuch_database_get_revision (notmuch, &uuid);
    ASSERT (fprintf (out, "%s\t%zu\n", uuid, lastmod) > 0);
}

static void
write_data (const char *data)
{
    printf ("data %zu\n", strlen (data));
    fputs (data, stdout);
}

static void
cmd_capabilities ()
{
    fputs ("import\nexport\nrefspec refs/heads/*:refs/notmuch/*\n\n", stdout);
    fflush (stdout);
}

static void
cmd_list (notmuch_database_t *db, const char *uuid, unsigned long lastmod)
{
    unsigned long db_lastmod;
    const char *db_uuid;

    db_lastmod = notmuch_database_get_revision (db, &db_uuid);

    printf ("? refs/heads/master%s\n\n",
	    equal_lastmod (uuid, lastmod, db_uuid, db_lastmod) ? " unchanged" : "");
}

static void
cmd_import (notmuch_database_t *notmuch,
	    const char *nm_dir,
	    const char *uuid,
	    unsigned long lastmod)
{
    const char *ident = NULL;
    const char *lastmod_str = NULL;
    notmuch_messages_t *messages;
    notmuch_status_t status;
    notmuch_query_t *query;
    char *mid_buf = NULL;
    size_t mid_buf_len = 0;

    ident = talloc_asprintf (notmuch, "%s <%s> %zu +0000",
			     notmuch_config_get (notmuch, NOTMUCH_CONFIG_USER_NAME),
			     notmuch_config_get (notmuch, NOTMUCH_CONFIG_PRIMARY_EMAIL),
			     time (NULL));


    printf ("feature done\ncommit refs/notmuch/master\nmark :1\ncommitter %s\n", ident);

    ASSERT (lastmod_str = talloc_asprintf (notmuch, "lastmod: %zu\n", lastmod));
    write_data (lastmod_str);
    if (uuid)
	puts ("from refs/notmuch/master^0");
    puts ("deleteall");

    status = notmuch_query_create_with_syntax (notmuch,
					       "",
					       NOTMUCH_QUERY_SYNTAX_XAPIAN,
					       &query);

    if (print_status_database ("git-remote-nm", notmuch, status))
	exit (EXIT_FAILURE);

    if (debug_flags && strchr (debug_flags, 's'))
	notmuch_query_set_sort (query, NOTMUCH_SORT_NEWEST_FIRST);
    else
	notmuch_query_set_sort (query, NOTMUCH_SORT_UNSORTED);

    status = notmuch_query_search_messages (query, &messages);
    if (print_status_query ("git-remote-nm", query, status))
	exit (EXIT_FAILURE);

    for (;
	 notmuch_messages_valid (messages);
	 notmuch_messages_move_to_next (messages)) {
	const char *tag_buf = "";
	const char *mid;
	const char *hash;
	int ret;

	notmuch_message_t *message = notmuch_messages_get (messages);
	mid = notmuch_message_get_message_id (message);

	ret = hex_encode (notmuch, mid, &mid_buf, &mid_buf_len);
	ensure (ret == HEX_SUCCESS, "failed to hex-encode message-id %s\n", mid);

	/* we can't use _notmuch_sha1_from_string because we don't want
	 * to include the null terminator */
	g_autoptr (GChecksum) sha1 = NULL;
	sha1 = g_checksum_new (G_CHECKSUM_SHA1);
	g_checksum_update (sha1, (const guchar *) mid, strlen (mid));
	hash = g_checksum_get_string (sha1);
	printf ("M 644 inline %2.2s/%2.2s/%s/tags\n", hash, hash + 2, mid_buf);

	for (notmuch_tags_t *tags = notmuch_message_get_tags (message);
	     notmuch_tags_valid (tags);
	     notmuch_tags_move_to_next (tags)) {
	    const char *tag_str = notmuch_tags_get (tags);
	    ASSERT (tag_buf = talloc_asprintf (message, "%s%s\n", tag_buf, tag_str));
	}
	write_data (tag_buf);
	notmuch_message_destroy (message);
    }
    puts ("");
    puts ("done");
    fflush (stdout);
    store_lastmod (notmuch, nm_dir);
}

static GString *
read_data ()
{
    ssize_t nread;
    size_t bytes;
    size_t data_size;

    g_auto (GStrv) tokens = NULL;

    ASSERT ((nread = getline (&buffer, &buffer_len, stdin) != -1));

    tokens = tokenize_buffer ();

    str2ul (tokens[1], &data_size);

    buffer = realloc (buffer, data_size + 1);
    bytes = fread (buffer, 1, data_size, stdin);
    ASSERT (bytes == data_size);

    buffer_len = data_size;

    return g_string_new_len (buffer, buffer_len);
}

static void
free_string (GString *str)
{
    g_string_free (str, true);
}

static void
cmd_export (notmuch_database_t *notmuch, const char *nm_dir)
{
    ssize_t nread;

    g_autoptr (GHashTable) blobs = NULL;

    ASSERT (blobs = g_hash_table_new_full ((GHashFunc) g_str_hash,
					   (GEqualFunc) g_str_equal,
					   g_free, (GDestroyNotify) free_string)
	    );

    while ((nread = getline (&buffer, &buffer_len, stdin)) != -1) {
	flog ("\texport %s\n", buffer);
	if (STRNCMP_LITERAL (buffer, "done") == 0) {
	    break;
	} else if (STRNCMP_LITERAL (buffer, "blob") == 0) {
	    GString *data;
	    g_auto (GStrv) tokens = NULL;


	    flog ("export blob\n");
	    buffer_line (stdin);

	    tokens = tokenize_buffer ();

	    data = read_data ();

	    flog ("\tmark%s\n", tokens[1]);
	    g_hash_table_insert (blobs, g_strdup (tokens[1]), data);
	    buffer_line (stdin);
	} else if (STRNCMP_LITERAL (buffer, "commit") == 0) {
	    char *mid = NULL;
	    size_t mid_len = 0;

	    flog ("export commit\n");

	    /* mark for commit (ignored) */
	    buffer_line (stdin);
	    /* author (ignored) */
	    buffer_line (stdin);
	    /* committer (ignored) */
	    buffer_line (stdin);

	    /* commit message (ignored) */
	    (void) read_data ();

	    while (strlen (buffer) > 0) {
		g_autoptr (GString) mark = NULL;
		g_autoptr (GString) path = NULL;
		const GString *blob;
		g_autofree char *basename = NULL;
		notmuch_message_t *message;
		const char *tok;
		size_t tok_len;
		size_t max_tok_len;
		tag_op_list_t *tag_ops;
		g_auto (GStrv) tokens = NULL;

		buffer_line (stdin);
		if (strlen (buffer) == 0)
		    break;

		tokens = tokenize_buffer ();
		flog ("looking for blob |%s|\n", tokens[2]);
		ASSERT (blob = g_hash_table_lookup (blobs, tokens[2]));

		basename = g_path_get_dirname (tokens[3] + 6);
		ASSERT (HEX_SUCCESS ==
			hex_decode (notmuch, basename, &mid, &mid_len));
		ASSERT (NOTMUCH_STATUS_SUCCESS ==
			notmuch_database_find_message (notmuch, mid, &message));
		ASSERT (message);

		ASSERT (NOTMUCH_STATUS_SUCCESS ==
			notmuch_message_freeze (message));

		tag_ops = tag_op_list_create (message);
		tok = blob->str;
		max_tok_len = blob->len;
		tok_len = 0;
		while ((tok_len < max_tok_len) &&
		       (tok = strsplit_len (tok + tok_len, '\n', &tok_len)) != NULL) {
		    const char *tag = talloc_strndup (message, tok, tok_len);
		    ASSERT (0 == tag_op_list_append (tag_ops, tag, false));
		}

		ASSERT (NOTMUCH_STATUS_SUCCESS ==
			tag_op_list_apply (message, tag_ops, TAG_FLAG_REMOVE_ALL));

		ASSERT (NOTMUCH_STATUS_SUCCESS ==
			notmuch_message_thaw (message));

		notmuch_message_destroy (message);
	    }
	    puts ("ok refs/heads/master");
	}

    }
    store_lastmod (notmuch, nm_dir);
    puts ("");
}


/* stubs since we cannot link with notmuch.o */
const notmuch_opt_desc_t notmuch_shared_options[] = {
    { }
};

const char *notmuch_requested_db_uuid = NULL;

void
notmuch_process_shared_options (unused (notmuch_database_t *notmuch),
				unused (const char *dummy))
{
}

int
notmuch_minimal_options (unused (const char *subcommand),
			 unused (int argc),
			 unused (char **argv))
{
    return 0;
}

static notmuch_database_t *
open_database (const char *arg)
{
    notmuch_status_t status;
    notmuch_database_t *notmuch;
    const char *path = NULL;
    const char *config = NULL;
    const char *profile = NULL;
    const char *scheme = NULL;
    const char *uriquery = NULL;
    g_autofree char *status_string = NULL;

    g_autoptr (GUri) uri = NULL;
    g_autoptr (GHashTable) params = NULL;
    g_autoptr (GError) gerror = NULL;
    g_autoptr (GString) address = NULL;

    address = g_string_new (arg);

    scheme = g_uri_peek_scheme (address->str);
    if (! scheme || (strcmp (scheme, "notmuch") != 0)) {
	ASSERT (g_string_prepend (address, "notmuch://"));
    }

    uri = g_uri_parse (address->str, G_URI_FLAGS_ENCODED_QUERY, &gerror);
    ensure (uri, "unable to parse URL/address %s: %s\n", address->str, gmessage (gerror));

    uriquery = g_uri_get_query (uri);
    if (uriquery) {
	flog ("uriquery = %s\n", uriquery);
	params = g_uri_parse_params (uriquery, -1, "&", G_URI_PARAMS_NONE, &gerror);
	ensure (params,  "unable to parse parameters %s: %s\n", uriquery, gmessage (gerror));
    }

    if (strlen (g_uri_get_path (uri)) > 0) {
	path = g_uri_get_path (uri);
	config = "";
    }

    if (params) {
	if (! path)
	    path = g_hash_table_lookup (params, "path");
	config = g_hash_table_lookup (params, "config");
	profile = g_hash_table_lookup (params, "profile");
    }

    flog ("url = %s\npath = %s\nconfig = %s\nprofile = %s\n",
	  address->str, path, config, profile);

    status = notmuch_database_open_with_config (path,
						NOTMUCH_DATABASE_MODE_READ_WRITE,
						config,
						profile,
						&notmuch,
						&status_string);

    ensure (status == 0, "open database: %s", status_string);

    return notmuch;
}

int
main (int argc, char *argv[])
{
    notmuch_status_t status;
    notmuch_database_t *db;
    unsigned long lastmod = 0;
    char *uuid = NULL;
    const char *nm_dir = NULL;
    g_autofree char *status_string = NULL;
    const char *git_dir;
    ssize_t nread;
    const char *log_file_name;

    debug_flags = getenv ("GIT_REMOTE_NM_DEBUG");
    log_file_name = getenv ("GIT_REMOTE_NM_LOG");

    if (log_file_name)
	log_file = fopen (log_file_name, "w");

    ensure (argc >= 3, "usage: %s ALIAS URL\n", argv[0]);

    db = open_database (argv[2]);

    git_dir = getenv ("GIT_DIR");
    ensure (git_dir, "GIT_DIR not set");
    flog ("GIT_DIR=%s\n", git_dir);

    ASSERT (nm_dir = talloc_asprintf (db, "%s/%s", git_dir, "notmuch"));

    status = mkdir_recursive (db, nm_dir, 0700, &status_string);
    ensure (status == 0, "mkdir: %s", status_string);

    read_lastmod (nm_dir, &uuid, &lastmod);

    while ((nread = getline (&buffer, &buffer_len, stdin)) != -1) {
	char *s = buffer;
	flog ("command = %s\n", buffer);

	/* skip leading space */
	while (*s && isspace (*s)) s++;

	if (! *s)
	    break;

	if (STRNCMP_LITERAL (s, "capabilities") == 0)
	    cmd_capabilities ();
	else if (STRNCMP_LITERAL (s, "export") == 0)
	    cmd_export (db, nm_dir);
	else if (STRNCMP_LITERAL (s, "import") == 0)
	    cmd_import (db, nm_dir, uuid, lastmod);
	else if (STRNCMP_LITERAL (s, "list") == 0)
	    cmd_list (db, uuid, lastmod);

	fflush (stdout);
	flog ("finished command = %s\n", s);
    }
    flog ("finished loop\n");

    notmuch_database_destroy (db);
}

debug log:

solving de689474 ...
found de689474 in https://yhetil.org/notmuch/20240908113937.286108-5-david@tethera.net/
found 39ba6bf3 in https://yhetil.org/notmuch/20240908113937.286108-4-david@tethera.net/
found 4afd198c in https://yhetil.org/notmuch/20240908113937.286108-3-david@tethera.net/

applying [1/3] https://yhetil.org/notmuch/20240908113937.286108-3-david@tethera.net/
diff --git a/git-remote-notmuch.c b/git-remote-notmuch.c\r
new file mode 100644\r
index 00000000..4afd198c\r


applying [2/3] https://yhetil.org/notmuch/20240908113937.286108-4-david@tethera.net/
diff --git a/git-remote-notmuch.c b/git-remote-notmuch.c
index 4afd198c..39ba6bf3 100644


applying [3/3] https://yhetil.org/notmuch/20240908113937.286108-5-david@tethera.net/
diff --git a/git-remote-notmuch.c b/git-remote-notmuch.c
index 39ba6bf3..de689474 100644

3:7: trailing whitespace.
/* notmuch - Not much of an email program, (just index and search)\r
3:8: trailing whitespace.
 *\r
3:9: trailing whitespace.
 * Copyright © 2023 Felipe Contreras\r
3:10: trailing whitespace.
 * Copyright © 2024 David Bremner\r
3:11: trailing whitespace.
 *\r
Checking patch git-remote-notmuch.c...
Applied patch git-remote-notmuch.c cleanly.
Checking patch git-remote-notmuch.c...
Applied patch git-remote-notmuch.c cleanly.
Checking patch git-remote-notmuch.c...
Applied patch git-remote-notmuch.c cleanly.
warning: squelched 309 whitespace errors
warning: 314 lines add whitespace errors.

index at:
100644 a0cf0e3697eb0b4dd3042097a7419b11cbece775	git-remote-notmuch.c

(*) Git path names are given by the tree(s) the blob belongs to.
    Blobs themselves have no identifier aside from the hash of its contents.^

Code repositories for project(s) associated with this public inbox

	https://yhetil.org/notmuch.git/

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).