summaryrefslogtreecommitdiffstats
path: root/save-git.c
blob: 6e0d989c0184bc34550fd8289516d89139856812 (plain) (blame)
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
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <git2.h>

#include "dive.h"
#include "device.h"
#include "membuffer.h"

#define VA_BUF(b, fmt) do { va_list args; va_start(args, fmt); put_vformat(b, fmt, args); va_end(args); } while (0)

static void cond_put_format(int cond, struct membuffer *b, const char *fmt, ...)
{
	if (cond) {
		VA_BUF(b, fmt);
	}
}

#define SAVE(str, x) cond_put_format(dive->x, b, str " %d\n", dive->x)

static void put_degrees(struct membuffer *b, degrees_t value, const char sep)
{
	int udeg = value.udeg;
	const char *sign = "";

	if (udeg < 0) {
		udeg = -udeg;
		sign = "-";
	}
	put_format(b,"%s%u.%06u%c", sign, FRACTION(udeg, 1000000), sep);
}

static void show_gps(struct membuffer *b, degrees_t latitude, degrees_t longitude)
{
	if (latitude.udeg || longitude.udeg) {
		put_string(b, "gps ");
		put_degrees(b, latitude, ' ');
		put_degrees(b, longitude, '\n');
	}
}

static void quote(struct membuffer *b, const char *text)
{
	const char *p = text;

	for (;;) {
		const char *escape;

		switch (*p++) {
		default:
			continue;
		case 0:
			escape = NULL;
			break;
		case 1 ... 8:
		case 11:
		case 12:
		case 14 ... 31:
			escape = "?";
			break;
		case '"':
			escape = "\\\"";
			break;
		case '\n':
			escape = "\n\t";
			if (*p == '\n')
				escape = "\n";
			break;
		}
		put_bytes(b, text, (p - text - 1));
		if (!escape)
			break;
		put_string(b, escape);
		text = p;
	}
}

static void show_utf8(struct membuffer *b, const char *prefix, const char *value, const char *postfix)
{
	if (value) {
		put_format(b, "%s\"", prefix);
		quote(b, value);
		put_format(b, "\"%s", postfix);
	}
}

static void save_overview(struct membuffer *b, struct dive *dive)
{
	show_gps(b, dive->latitude, dive->longitude);
	show_utf8(b, "location ", dive->location, "\n");
	show_utf8(b, "divemaster ", dive->divemaster, "\n");
	show_utf8(b, "buddy ", dive->buddy, "\n");
	show_utf8(b, "suit ", dive->suit, "\n");
	show_utf8(b, "notes ", dive->notes, "\n");
}

static void save_tags(struct membuffer *b, struct tag_entry *tags)
{
	const char *sep = " ";

	if (!tags)
		return;
	/* The first entry is a dummy, because people don't understand pointers to pointers */
	tags = tags->next;
	if (!tags)
		return;
	put_string(b, "tags");
	while (tags) {
		show_utf8(b, sep, tags->tag->source ? : tags->tag->name, "");
		sep = ", ";
		tags = tags->next;
	}
	put_string(b, "\n");
}

static void save_cylinder_info(struct membuffer *b, struct dive *dive)
{
	int i, nr;

	nr = nr_cylinders(dive);
	for (i = 0; i < nr; i++) {
		cylinder_t *cylinder = dive->cylinder + i;
		int volume = cylinder->type.size.mliter;
		const char *description = cylinder->type.description;
		int o2 = cylinder->gasmix.o2.permille;
		int he = cylinder->gasmix.he.permille;

		put_string(b, "cylinder");
		if (volume)
			put_milli(b, " vol=", volume, "l");
		put_pressure(b, cylinder->type.workingpressure, " workpressure=", "bar");
		show_utf8(b, " description=", description, "");
		strip_mb(b);
		if (o2) {
			put_format(b, " o2=%u.%u%%", FRACTION(o2, 10));
			if (he)
				put_format(b, " he=%u.%u%%", FRACTION(he, 10));
		}
		put_pressure(b, cylinder->start, " start=", "bar");
		put_pressure(b, cylinder->end, " end=", "bar");
		put_string(b, "\n");
	}
}

static void save_weightsystem_info(struct membuffer *b, struct dive *dive)
{
	int i, nr;

	nr = nr_weightsystems(dive);
	for (i = 0; i < nr; i++) {
		weightsystem_t *ws = dive->weightsystem + i;
		int grams = ws->weight.grams;
		const char *description = ws->description;

		put_string(b, "weightsystem");
		put_milli(b, " weight=", grams, "kg");
		show_utf8(b, " description=", description, "");
		put_string(b, "\n");
	}
}

static void save_dive_temperature(struct membuffer *b, struct dive *dive)
{
	if (!dive->airtemp.mkelvin && !dive->watertemp.mkelvin)
		return;
	if (dive->airtemp.mkelvin == dc_airtemp(&dive->dc) && dive->watertemp.mkelvin == dc_watertemp(&dive->dc))
		return;

	put_string(b, "divetemperature");
	if (dive->airtemp.mkelvin != dc_airtemp(&dive->dc))
		put_temperature(b, dive->airtemp, " air=", "°C");
	if (dive->watertemp.mkelvin != dc_watertemp(&dive->dc))
		put_temperature(b, dive->watertemp, " water=", "°C'");
	put_string(b, "\n");
}

static void save_depths(struct membuffer *b, struct divecomputer *dc)
{
	/* What's the point of this dive entry again? */
	if (!dc->maxdepth.mm && !dc->meandepth.mm)
		return;

	put_string(b, "  depth");
	put_depth(b, dc->maxdepth, " max=", "m");
	put_depth(b, dc->meandepth, " mean=", "m");
	put_string(b, "\n");
}

static void save_temperatures(struct membuffer *b, struct divecomputer *dc)
{
	if (!dc->airtemp.mkelvin && !dc->watertemp.mkelvin)
		return;
	put_string(b, "  temperature");
	put_temperature(b, dc->airtemp, " air=", "°C");
	put_temperature(b, dc->watertemp, " water=", "°C");
	put_string(b, "\n");
}

static void save_airpressure(struct membuffer *b, struct divecomputer *dc)
{
	if (!dc->surface_pressure.mbar)
		return;
	put_string(b, "  surface");
	put_pressure(b, dc->surface_pressure, " pressure=", "bar");
	put_string(b, "\n");
}

static void save_salinity(struct membuffer *b, struct divecomputer *dc)
{
	/* only save if we have a value that isn't the default of sea water */
	if (!dc->salinity || dc->salinity == SEAWATER_SALINITY)
		return;
	put_string(b, "  water");
	put_salinity(b, dc->salinity, " salinity=", "g/l");
	put_string(b, "\n");
}

static void show_date(struct membuffer *b, timestamp_t when)
{
	struct tm tm;

	utc_mkdate(when, &tm);

	put_format(b, " date=%04u-%02u-%02u",
		   tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday);
	put_format(b, " time=%02u:%02u:%02u",
		   tm.tm_hour, tm.tm_min, tm.tm_sec);
}

static void show_index(struct membuffer *b, int value, const char *pre, const char *post)
{
	if (value)
		put_format(b, " %s%d%s", pre, value, post);
}

/*
 * Samples are saved as densely as possible while still being readable,
 * since they are the bulk of the data.
 *
 * For parsing, look at the units to figure out what the numbers are.
 */
static void save_sample(struct membuffer *b, struct sample *sample, struct sample *old)
{
	put_format(b, "  %3u:%02umin", FRACTION(sample->time.seconds, 60));
	put_milli(b, " ", sample->depth.mm, "m");
	put_temperature(b, sample->temperature, " ", "°C");
	put_pressure(b, sample->cylinderpressure, " ", "bar");

	/*
	 * We only show sensor information for samples with pressure, and only if it
	 * changed from the previous sensor we showed.
	 */
	if (sample->cylinderpressure.mbar && sample->sensor != old->sensor) {
		put_format(b, " sensor=%d", sample->sensor);
		old->sensor = sample->sensor;
	}

	/* the deco/ndl values are stored whenever they change */
	if (sample->ndl.seconds != old->ndl.seconds) {
		put_format(b, " ndl=%u:%02umin", FRACTION(sample->ndl.seconds, 60));
		old->ndl = sample->ndl;
	}
	if (sample->in_deco != old->in_deco) {
		put_format(b, " in_deco=%d", sample->in_deco ? 1 : 0);
		old->in_deco = sample->in_deco;
	}
	if (sample->stoptime.seconds != old->stoptime.seconds) {
		put_format(b, " stoptime=%u:%02umin", FRACTION(sample->stoptime.seconds, 60));
		old->stoptime = sample->stoptime;
	}

	if (sample->stopdepth.mm != old->stopdepth.mm) {
		put_milli(b, " stopdepth=", sample->stopdepth.mm, "m");
		old->stopdepth = sample->stopdepth;
	}

	if (sample->cns != old->cns) {
		put_format(b, " cns=%u%%", sample->cns);
		old->cns = sample->cns;
	}

	if (sample->po2 != old->po2) {
		put_milli(b, " po2=", sample->po2, "bar");
		old->po2 = sample->po2;
	}
	show_index(b, sample->heartbeat, "heartbeat=", "");
	show_index(b, sample->bearing, "bearing=", "°");
	put_format(b, "\n");
}

static void save_samples(struct membuffer *b, int nr, struct sample *s)
{
	struct sample dummy = {};

	while (--nr >= 0) {
		save_sample(b, s, &dummy);
		s++;
	}
}

static void save_one_event(struct membuffer *b, struct event *ev)
{
	put_format(b, "  event %d:%02dmin", FRACTION(ev->time.seconds, 60));
	show_index(b, ev->type, "type=", "");
	show_index(b, ev->flags, "flags=", "");
	show_index(b, ev->value, "value=", "");
	show_utf8(b, ev->name, " name=", "");
	put_string(b, "\n");
}

static void save_events(struct membuffer *b, struct event *ev)
{
	while (ev) {
		save_one_event(b, ev);
		ev = ev->next;
	}
}

static void save_dc(struct membuffer *b, struct dive *dive, struct divecomputer *dc)
{
	put_format(b, "divecomputer");
	show_utf8(b, " model=", dc->model, "");
	if (dc->deviceid)
		put_format(b, " deviceid=%08x", dc->deviceid);
	if (dc->diveid)
		put_format(b, " diveid=%08x", dc->diveid);
	if (dc->when && dc->when != dive->when)
		show_date(b, dc->when);
	if (dc->duration.seconds && dc->duration.seconds != dive->dc.duration.seconds)
		put_duration(b, dc->duration, " duration=", "min");
	put_string(b, "\n");

	save_depths(b, dc);
	save_temperatures(b, dc);
	save_airpressure(b, dc);
	save_salinity(b, dc);
	put_duration(b, dc->surfacetime, "  surfacetime", "min\n");

	save_events(b, dc->events);
	save_samples(b, dc->samples, dc->sample);
}

/*
 * Note that we don't save the date and time or dive
 * number: they are encoded in the filename.
 */
static void create_dive_buffer(struct dive *dive, struct membuffer *b)
{
	struct divecomputer *dc;

	put_format(b, "duration %u:%02u min\n", FRACTION(dive->dc.duration.seconds, 60));
	SAVE("rating", rating);
	SAVE("visibility", visibility);
	cond_put_format(dive->tripflag == NO_TRIP, b, "notrip\n");
	save_tags(b, dive->tag_list);

	save_overview(b, dive);
	save_cylinder_info(b, dive);
	save_weightsystem_info(b, dive);
	save_dive_temperature(b, dive);

	/* Save the dive computer data */
	dc = &dive->dc;
	do {
		save_dc(b, dive, dc);
		dc = dc->next;
	} while (dc);
}

static int git_save_error(const char *fmt, ...)
{
	struct membuffer b = { 0 };
	VA_BUF(&b, fmt);

	/* We should do some UI element thing describing the failure */
	put_bytes(&b, "\n", 1);
	flush_buffer(&b, stderr);
	free_buffer(&b);

	return -1;
}

/*
 * libgit2 has a "git_treebuilder" concept, but it's broken, and can not
 * be used to do a flat tree (like the git "index") nor a recursive tree.
 * Stupid.
 *
 * So we have to do that "keep track of recursive treebuilder entries"
 * ourselves. We use 'git_treebuilder' for any regular files, and our own
 * data structures for recursive trees.
 *
 * When finally writing it out, we traverse the subdirectories depth-
 * first, writing them out, and then adding the written-out trees to
 * the git_treebuilder they existed in.
 */
struct dir {
	git_treebuilder *files;
	struct dir *subdirs, *sibling;
	char name[1];
};

/*
 * The name of a dive is the date plus a hash of the contents.
 */
static void generate_name(struct dive *dive, git_oid *id, struct membuffer *name)
{
	struct tm tm;

	utc_mkdate(dive->when, &tm);
	put_format(name, "%04u-%02u-%02u-%02u:%02u:%02u",
		tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
		tm.tm_hour, tm.tm_min, tm.tm_sec);
	cond_put_format(dive->number, name, "-%d", dive->number);
	put_format(name, "-%02x%02x%02x%02x%c",
		id->id[0], id->id[1], id->id[2], id->id[3], 0);
}

static int save_one_dive(git_repository *repo, struct dir *tree, struct dive *dive)
{
	struct membuffer buf = { 0 }, name = { 0 };
	git_oid blob_id;
	int ret;

	create_dive_buffer(dive, &buf);
	ret = git_blob_create_frombuffer(&blob_id, repo, buf.buffer, buf.len);
	free_buffer(&buf);
	if (ret)
		return git_save_error("git blob creation failed");

	generate_name(dive, &blob_id, &name);
	ret = git_treebuilder_insert(NULL, tree->files, name.buffer, &blob_id, 0100644);
	free_buffer(&name);
	if (ret)
		return git_save_error("git tree insert failed");

	return 0;
}

/*
 * This does *not* make sure the new subdirectory doesn't
 * alias some existing name. Currently we always create
 * unique subdirectory names ("tripXYZ"), but ..
 */
static struct dir *new_directory(struct dir *parent, const char *fmt, ...)
{
	struct membuffer name = { 0 };
	struct dir *subdir;

	VA_BUF(&name, fmt);
	subdir = malloc(sizeof(*subdir)+name.len);

	/*
	 * It starts out empty: no subdirectories of its own,
	 * and an empty treebuilder list of files.
	 */
	subdir->subdirs = NULL;
	git_treebuilder_create(&subdir->files, NULL);
	memcpy(subdir->name, name.buffer, name.len);
	subdir->name[name.len] = 0;

	/* Add it to the list of subdirs of the parent */
	subdir->sibling = parent->subdirs;
	parent->subdirs = subdir;

	return subdir;
}

static int save_one_trip(git_repository *repo, struct dir *tree, dive_trip_t *trip, int idx)
{
	int i;
	struct dive *dive;
	struct dir *subdir;

	subdir = new_directory(tree, "trip%03d", idx);
	for_each_dive(i, dive) {
		if (dive->divetrip == trip)
			save_one_dive(repo, subdir, dive);
	}

	return 0;
}

#define TRIPNAME_SIZE (10)

static int create_git_tree(git_repository *repo, struct dir *tree, bool select_only)
{
	int i, tripidx;
	struct dive *dive;
	dive_trip_t *trip;

	tripidx = 0;
	for (trip = dive_trip_list; trip != NULL; trip = trip->next)
		trip->index = 0;

	/* save the dives */
	for_each_dive(i, dive) {
		trip = dive->divetrip;

		if (select_only) {
			if (!dive->selected)
				continue;
			/* We don't save trips when doing selected dive saves */
			trip = NULL;
		}

		if (trip) {
			/* Did we already save this trip? */
			if (trip->index)
				continue;
			trip->index = ++tripidx;

			/* Pass that new subdirectory in for save-trip */
			save_one_trip(repo, tree, trip, tripidx);
			continue;
		}

		save_one_dive(repo, tree, dive);
	}
	return 0;
}

/*
 * libgit2 revision 0.19 and earlier do not have the signature and
 * message log arguments.
 */
#if !LIBGIT2_VER_MAJOR && LIBGIT2_VER_MINOR <= 19
  #define git_branch_create(out,repo,branch_name,target,force,sig,msg) \
	git_branch_create(out,repo,branch_name,target,force)
  #define git_reference_set_target(out,ref,target,signature,log_message) \
	git_reference_set_target(out,ref,target)
#endif

static int create_new_commit(git_repository *repo, const char *branch, git_oid *tree_id)
{
	int ret;
	git_reference *ref;
	git_object *parent;
	git_oid commit_id;
	git_signature *author;
	git_commit *commit;
	git_tree *tree;

	ret = git_branch_lookup(&ref, repo, branch, GIT_BRANCH_LOCAL);
	switch (ret) {
	default:
		return git_save_error("Bad branch '%s' (%s)", branch, strerror(errno));
	case GIT_EINVALIDSPEC:
		return git_save_error("Invalid branch name '%s'", branch);
	case GIT_ENOTFOUND: /* We'll happily create it */
		ref = NULL; parent = NULL;
		break;
	case 0:
		if (git_reference_peel(&parent, ref, GIT_OBJ_COMMIT))
			return git_save_error("Unable to look up parent in branch '%s'", branch);
		/* all good */
		break;
	}

	if (git_tree_lookup(&tree, repo, tree_id))
		return git_save_error("Could not look up newly created tree");

	/* git_signature_default() is too recent */
	if (git_signature_now(&author, "Subsurface", "subsurface@hohndel.org"))
		return git_save_error("No user name configuration in git repo");

	if (git_commit_create_v(&commit_id, repo, NULL, author, author, NULL, "subsurface commit", tree, parent != NULL, parent))
		return git_save_error("Git commit create failed (%s)", strerror(errno));

	if (git_commit_lookup(&commit, repo, &commit_id))
		return git_save_error("Could not look up newly created commit");

	if (!ref) {
		if (git_branch_create(&ref, repo, branch, commit, 0, author, "Create branch"))
			return git_save_error("Failed to create branch '%s'", branch);
	}
	if (git_reference_set_target(&ref, ref, &commit_id, author, "Subsurface save event"))
		return git_save_error("Failed to update branch '%s'", branch);

	return 0;
}

static int write_git_tree(git_repository *repo, struct dir *tree, git_oid *result)
{
	int ret;
	struct dir *subdir;

	/* Write out our subdirectories, add them to the treebuilder, and free them */
	while ((subdir = tree->subdirs) != NULL) {
		git_oid id;

		if (!write_git_tree(repo, subdir, &id))
			git_treebuilder_insert(NULL, tree->files, subdir->name, &id, 0040000);
		tree->subdirs = subdir->sibling;
		free(subdir);
	};

	/* .. write out the resulting treebuilder */
	ret = git_treebuilder_write(result, repo, tree->files);

	/* .. and free the now useless treebuilder */
	git_treebuilder_free(tree->files);

	return ret;
}

static int do_git_save(git_repository *repo, const char *branch, bool select_only)
{
	struct dir tree;
	git_oid id;

	/* Start with an empty tree: no subdirectories, no files */
	tree.name[0] = 0;
	tree.subdirs = NULL;
	if (git_treebuilder_create(&tree.files, NULL))
		return git_save_error("git treebuilder failed");

	/* Populate our tree data structure */
	if (create_git_tree(repo, &tree, select_only))
		return -1;

	if (write_git_tree(repo, &tree, &id))
		return git_save_error("git tree write failed");

	/* And save the tree! */
	create_new_commit(repo, branch, &id);
	return 0;
}

int git_save_dives(int fd, bool select_only)
{
	int len, ret;
	struct stat st;
	static char buffer[2048];
	git_repository *repo;
	char *loc, *branch;

	if (fstat(fd, &st) < 0)
		return 0;
	if (st.st_size >= sizeof(buffer))
		return 0;
	len = st.st_size;
	if (read(fd, buffer, len) != len)
		return 0;
	buffer[len] = 0;
	if (len < 4)
		return 0;
	if (memcmp(buffer, "git ", 4))
		return 0;

	/* Ok, it's a git pointer, we're going to follow it */
	close(fd);

	/* Trim any whitespace at the end */
	while (isspace(buffer[len-1]))
		buffer[--len] = 0;

	/* skip the "git" part and any whitespace from the beginning */
	loc = buffer+3;
	len -= 3;
	while (isspace(*loc)) {
		loc++;
		len--;
	}

	if (!len)
		return git_save_error("Invalid git pointer");

	/*
	 * The result should be a git directory and branch name, like
	 *  "/home/torvalds/scuba:linus"
	 */
	branch = strrchr(loc, ':');
	if (branch)
		*branch++ = 0;

	if (git_repository_open(&repo, loc))
		return git_save_error("Unable to open git repository at '%s' (branch '%s')", loc, branch);

	ret = do_git_save(repo, branch, select_only);
	git_repository_free(repo);
	return ret < 0 ? ret : 1;
}