summaryrefslogtreecommitdiffstats
path: root/src/util/pacsort.c
blob: d864fdb965a2986431e4e104f217585f9815f9b8 (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
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
/*
 *  pacsort.c - a sort utility implementing alpm_pkg_vercmp
 *
 *  Copyright (c) 2010-2015 Pacman Development Team <pacman-dev@archlinux.org>
 *
 *  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 2 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 <http://www.gnu.org/licenses/>.
 */

#include <errno.h>
#include <fnmatch.h>
#include <getopt.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <alpm.h>

#define DELIM ' '

#ifndef MIN
#define MIN(a, b)      \
	__extension__({           \
		__typeof__(a) _a = (a); \
		__typeof__(b) _b = (b); \
		_a < _b ? _a : _b;           \
	})
#endif

struct buffer_t {
	char *mem;
	size_t len;
	size_t maxlen;
};

struct list_t {
	void **list;
	size_t count;
	size_t maxcount;
};

struct input_t {
	char *data;
	int is_file;

	const char *pkgname;
	size_t pkgname_len;

	const char *pkgver;
	size_t pkgver_len;
};

static struct options_t {
	int order;
	int sortkey;
	int null;
	int filemode;
	int help;
	char delim;
} opts;

#ifndef HAVE_STRNDUP
/* A quick and dirty implementation derived from glibc */
static size_t strnlen(const char *s, size_t max)
{
	register const char *p;
	for(p = s; *p && max--; ++p);
	return (p - s);
}

char *strndup(const char *s, size_t n)
{
	size_t len = strnlen(s, n);
	char *new = (char *) malloc(len + 1);

	if(new == NULL)
		return NULL;

	new[len] = '\0';
	return (char *)memcpy(new, s, len);
}
#endif

static struct buffer_t *buffer_new(size_t initial_size)
{
	struct buffer_t *buf;

	buf = calloc(1, sizeof(*buf));
	if(!buf) {
		return NULL;
	}

	buf->mem = calloc(initial_size, sizeof(char));
	if(!buf->mem) {
		free(buf);
		return NULL;
	}

	buf->len = 0;
	buf->maxlen = initial_size;

	return buf;
}

static void buffer_free(struct buffer_t *buf)
{
	if(!buf) {
		return;
	}

	free(buf->mem);
	free(buf);
}

static int buffer_grow(struct buffer_t *buffer)
{
	size_t newsz = buffer->maxlen * 2.5;
	buffer->mem = realloc(buffer->mem, newsz * sizeof(char));
	if(!buffer->mem) {
		return 1;
	}
	buffer->maxlen = newsz;

	return 0;
}

static struct list_t *list_new(size_t initial_size)
{
	struct list_t *list;

	list = calloc(1, sizeof(struct list_t));
	if(!list) {
		return NULL;
	}

	list->list = calloc(initial_size, sizeof(char *));
	if(!list->list) {
		free(list);
		return NULL;
	}

	list->maxcount = initial_size;

	return list;
}

static int list_grow(struct list_t *list)
{
	size_t newsz = list->maxcount * 2.5;
	list->list = realloc(list->list, newsz * sizeof(char *));
	if(!list->list) {
		return 1;
	}

	list->maxcount = newsz;

	return 0;
}

static int list_add(struct list_t *list, void *obj)
{
	if(!list || !obj) {
		return 1;
	}

	if(list->count + 1 >= list->maxcount) {
		if(list_grow(list) != 0) {
			return 1;
		}
	}

	list->list[list->count] = obj;
	list->count++;

	return 0;
}

static void list_free(struct list_t *list, void (*freefn)(void *))
{
	size_t i;

	if(!list) {
		return;
	}

	if(list->list) {
		for(i = 0; i < list->count; i++) {
			freefn(list->list[i]);
		}
		free(list->list);
	}
	free(list);
}

static void input_free(void *p)
{
	struct input_t *in = p;

	if(in == NULL) {
		return;
	}

	free(in->data);
	free(in);
}

static struct input_t *input_new(const char *path, int pathlen)
{
	const char *pkgver_end;
	const char *slash;
	struct input_t *in;

	in = calloc(1, sizeof(struct input_t));
	if(in == NULL) {
		return NULL;
	}

	in->data = strndup(path, pathlen);
	if(in->data == NULL) {
		free(in);
		return NULL;
	}

	in->is_file = fnmatch("*-*.pkg.tar.?z", in->data, 0) == 0;
	if(!in->is_file) {
		return in;
	}

	/* for files, we parse the pkgname and pkgrel from the full filename. */

	slash = strrchr(in->data, '/');
	if(slash == NULL) {
		in->pkgname = in->data;
	} else {
		in->pkgname = slash + 1;
	}

	pkgver_end = strrchr(in->pkgname, '-');

	/* read backwards through pkgrel */
	for(in->pkgver = pkgver_end - 1;
			in->pkgver > in->pkgname && *in->pkgver != '-';
			--in->pkgver)
		;
	/* read backwards through pkgver */
	for(--in->pkgver;
			in->pkgver > in->pkgname && *in->pkgver != '-';
			--in->pkgver)
		;
	++in->pkgver;

	in->pkgname_len = in->pkgver - in->pkgname - 1;
	in->pkgver_len = pkgver_end - in->pkgver;

	return in;
}

static char *explode(struct buffer_t *buffer, struct list_t *list)
{
	char *ptr, *end;
	const char linedelim = opts.null ? '\0' : '\n';
	struct input_t *meta;

	ptr = buffer->mem;
	while((end = memchr(ptr, linedelim, &buffer->mem[buffer->len] - ptr))) {
		*end = '\0';
		meta = input_new(ptr, end - ptr);
		list_add(list, meta);
		ptr = end + 1;
	}

	return ptr;
}

static int splitfile(FILE *stream, struct buffer_t *buffer, struct list_t *list)
{
	size_t nread;
	char *ptr;

	while(!feof(stream)) {
		/* check if a read of BUFSIZ chars will overflow */
		if(buffer->len + BUFSIZ + 1 >= buffer->maxlen) {
			if(buffer_grow(buffer) != 0) {
				return 1;
			}
		}

		nread = fread(&buffer->mem[buffer->len], 1, BUFSIZ, stream);
		if(nread == 0) {
			break; /* EOF */
		}
		buffer->len += nread;

		if((ptr = explode(buffer, list)) == NULL) {
			return 1;
		}

		if(ptr != buffer->mem) {
			/* realign the data in the buffer */
			buffer->len = &buffer->mem[buffer->len] - ptr;
			memmove(&buffer->mem[0], ptr, buffer->len + 1);
		}
	}

	if(buffer->len) {
		struct input_t *meta = input_new(buffer->mem, buffer->len + 1);
		if(meta == NULL || list_add(list, meta) != 0) {
			return 1;
		}
	}

	return 0;
}

/* returns a pointer to the nth column of a string without being destructive */
static const char *nth_column(const char *string)
{
	const char *prev, *ptr;
	int col;

	ptr = prev = string;
	for(col = 1; ptr && col <= opts.sortkey; col++) {
		prev = ptr;
		ptr = strchr(ptr, opts.delim);
		if(ptr) {
			ptr++;
		}
	}

	return prev;
}

static int compare_versions(const char *v1, const char *v2)
{
	if(opts.sortkey == 0) {
		return opts.order * alpm_pkg_vercmp(v1, v2);
	} else {
		return opts.order * alpm_pkg_vercmp(nth_column(v1), nth_column(v2));
	}
}

static int compare_files(const struct input_t *meta1, const struct input_t *meta2)
{
	int cmp;
	char *verbuf;
	const char *v1, *v2;

	/* sort first by package name */
	cmp = memcmp(meta1->pkgname, meta2->pkgname,
			MIN(meta1->pkgname_len, meta2->pkgname_len));

	/* 1) package names differ, sort by package name */
	if(cmp != 0) {
		return opts.order * cmp;
	}

	/* 2) prefixes are the same but length differs, sort by length */
	if(meta1->pkgname_len != meta2->pkgname_len) {
		return opts.order * (meta1->pkgname_len - meta2->pkgname_len);
	}

	/* allocate once with enough space for both pkgver */
	verbuf = calloc(1, meta1->pkgver_len + 1 + meta2->pkgver_len + 1);
	memcpy(verbuf, meta1->pkgver, meta1->pkgver_len);
	memcpy(&verbuf[meta1->pkgver_len + 1], meta2->pkgver, meta2->pkgver_len);

	/* 3) sort by package version */
	v1 = verbuf;
	v2 = verbuf + meta1->pkgver_len + 1;
	cmp = compare_versions(v1, v2);
	free(verbuf);

	return cmp;
}

static int vercmp(const void *p1, const void *p2)
{
	const struct input_t *meta1, *meta2;

	meta1 = *(struct input_t **)p1;
	meta2 = *(struct input_t **)p2;

	if(opts.filemode && meta1->is_file && meta2->is_file) {
		return compare_files(meta1, meta2);
	} else {
		return compare_versions(meta1->data, meta2->data);
	}
}

static char escape_char(const char *string)
{
	if(!string) {
		return -1;
	}

	const size_t len = strlen(string);

	if(len > 2) {
		return -1;
	}

	if(len == 1) {
		return *string;
	}

	if(*string != '\\') {
		return -1;
	}

	switch(string[1]) {
		case 't':
			return '\t';
		case 'n':
			return '\n';
		case 'v':
			return '\v';
		case '0':
			return '\0';
		default:
			return -1;
	}
}

static void usage(void)
{
	fprintf(stderr, "pacsort (pacman) v" PACKAGE_VERSION "\n\n"
			"A sort utility implementing alpm_pkg_vercmp.\n\n"
			"Usage: pacsort [options] [files...]\n\n"
			"  -f, --files             assume inputs are file paths of packages\n"
			"  -h, --help              display this help message\n"
			"  -k, --key <index>       sort input starting on specified column\n"
			"  -r, --reverse           sort in reverse order (default: oldest to newest)\n"
			"  -t, --separator <sep>   specify field separator (default: space)\n"
			"  -z, --null              lines end with null bytes, not newlines\n\n");
}

static int parse_options(int argc, char **argv)
{
	int opt;

	static const struct option opttable[] = {
		{"files",     no_argument,          0, 'f'},
		{"help",      no_argument,          0, 'h'},
		{"key",       required_argument,    0, 'k'},
		{"reverse",   no_argument,          0, 'r'},
		{"separator", required_argument,    0, 't'},
		{"null",      no_argument,          0, 'z'},
		{0, 0, 0, 0}
	};

	while((opt = getopt_long(argc, argv, "fhk:rt:z", opttable, NULL)) != -1) {
		switch(opt) {
			case 'f':
				opts.filemode = 1;
				break;
			case 'h':
				opts.help = 1;
				return 0;
			case 'k':
				opts.sortkey = (int)strtol(optarg, NULL, 10);
				if(opts.sortkey <= 0) {
					fprintf(stderr, "error: invalid sort key -- %s\n", optarg);
					return 1;
				}
				break;
			case 'r':
				opts.order = -1;
				break;
			case 't':
				opts.delim = escape_char(optarg);
				if(opts.delim == -1) {
					fprintf(stderr, "error: invalid field separator -- `%s'\n", optarg);
					return 1;
				}
				break;
			case 'z':
				opts.null = 1;
				break;
			default:
				return 1;
		}
	}

	return 0;
}

int main(int argc, char *argv[])
{
	struct list_t *list;
	struct buffer_t *buffer;
	size_t i;

	/* option defaults */
	opts.order = 1;
	opts.delim = DELIM;
	opts.sortkey = 0;
	opts.null = 0;

	if(parse_options(argc, argv) != 0) {
		usage();
		return 2;
	}

	if(opts.help) {
		usage();
		return 0;
	}

	list = list_new(100);
	buffer = buffer_new(BUFSIZ * 3);

	if(optind == argc) {
		if(splitfile(stdin, buffer, list) != 0) {
			fprintf(stderr, "%s: memory exhausted\n", argv[0]);
			return ENOMEM;
		}
	} else {
		while(optind < argc) {
			FILE *input = fopen(argv[optind], "r");
			if(input) {
				if(splitfile(input, buffer, list) != 0) {
					fprintf(stderr, "%s: memory exhausted\n", argv[0]);
					return ENOMEM;
				}
				fclose(input);
			} else {
				fprintf(stderr, "%s: %s: %s\n", argv[0], argv[optind], strerror(errno));
			}
			optind++;
		}
	}

	if(list->count) {
		const char linedelim = opts.null ? '\0' : '\n';
		qsort(list->list, list->count, sizeof(void *), vercmp);
		for(i = 0; i < list->count; i++) {
			const struct input_t *in = list->list[i];
			printf("%s%c", in->data, linedelim);
		}
	}

	list_free(list, input_free);
	buffer_free(buffer);

	return 0;
}

/* vim: set noet: */