Hook new optdepend structures up
[pacman-ng.git] / src / pacman / util.c
blob7be3dc5c4a5db1db86c03e10996ab981d35c7740
1 /*
2 * util.c
4 * Copyright (c) 2006-2012 Pacman Development Team <pacman-dev@archlinux.org>
5 * Copyright (c) 2002-2006 by Judd Vinet <jvinet@zeroflux.org>
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
21 #include <sys/types.h>
22 #include <sys/ioctl.h>
23 #include <sys/stat.h>
24 #include <time.h>
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <stdarg.h>
29 #include <stdint.h> /* intmax_t */
30 #include <string.h>
31 #include <errno.h>
32 #include <ctype.h>
33 #include <dirent.h>
34 #include <unistd.h>
35 #include <limits.h>
36 #include <wchar.h>
37 #ifdef HAVE_TERMIOS_H
38 #include <termios.h> /* tcflush */
39 #endif
41 #include <alpm.h>
42 #include <alpm_list.h>
44 /* pacman */
45 #include "util.h"
46 #include "conf.h"
47 #include "callback.h"
50 int trans_init(alpm_transflag_t flags, int check_valid)
52 int ret;
54 check_syncdbs(0, check_valid);
56 ret = alpm_trans_init(config->handle, flags);
57 if(ret == -1) {
58 trans_init_error();
59 return -1;
61 return 0;
64 void trans_init_error(void)
66 alpm_errno_t err = alpm_errno(config->handle);
67 pm_printf(ALPM_LOG_ERROR, _("failed to init transaction (%s)\n"),
68 alpm_strerror(err));
69 if(err == ALPM_ERR_HANDLE_LOCK) {
70 const char *lockfile = alpm_option_get_lockfile(config->handle);
71 pm_printf(ALPM_LOG_ERROR, _("could not lock database: %s\n"),
72 strerror(errno));
73 if(access(lockfile, F_OK) == 0) {
74 fprintf(stderr, _(" if you're sure a package manager is not already\n"
75 " running, you can remove %s\n"), lockfile);
80 int trans_release(void)
82 if(alpm_trans_release(config->handle) == -1) {
83 pm_printf(ALPM_LOG_ERROR, _("failed to release transaction (%s)\n"),
84 alpm_strerror(alpm_errno(config->handle)));
85 return -1;
87 return 0;
90 int needs_root(void)
92 switch(config->op) {
93 case PM_OP_DATABASE:
94 return 1;
95 case PM_OP_UPGRADE:
96 case PM_OP_REMOVE:
97 return !config->print;
98 case PM_OP_SYNC:
99 return (config->op_s_clean || config->op_s_sync ||
100 (!config->group && !config->op_s_info && !config->op_q_list &&
101 !config->op_s_search && !config->print));
102 default:
103 return 0;
107 int check_syncdbs(size_t need_repos, int check_valid)
109 int ret = 0;
110 alpm_list_t *i;
111 alpm_list_t *sync_dbs = alpm_get_syncdbs(config->handle);
113 if(need_repos && sync_dbs == NULL) {
114 pm_printf(ALPM_LOG_ERROR, _("no usable package repositories configured.\n"));
115 return 1;
118 if(check_valid) {
119 /* ensure all known dbs are valid */
120 for(i = sync_dbs; i; i = alpm_list_next(i)) {
121 alpm_db_t *db = i->data;
122 if(alpm_db_get_valid(db)) {
123 pm_printf(ALPM_LOG_ERROR, _("database '%s' is not valid (%s)\n"),
124 alpm_db_get_name(db), alpm_strerror(alpm_errno(config->handle)));
125 ret = 1;
129 return ret;
132 /* discard unhandled input on the terminal's input buffer */
133 static int flush_term_input(void) {
134 #ifdef HAVE_TCFLUSH
135 if(isatty(fileno(stdin))) {
136 return tcflush(fileno(stdin), TCIFLUSH);
138 #endif
140 /* fail silently */
141 return 0;
144 /* gets the current screen column width */
145 unsigned short getcols(void)
147 const unsigned short default_tty = 80;
148 const unsigned short default_notty = 0;
149 unsigned short termwidth = 0;
151 if(!isatty(fileno(stdout))) {
152 return default_notty;
155 #ifdef TIOCGSIZE
156 struct ttysize win;
157 if(ioctl(1, TIOCGSIZE, &win) == 0) {
158 termwidth = win.ts_cols;
160 #elif defined(TIOCGWINSZ)
161 struct winsize win;
162 if(ioctl(1, TIOCGWINSZ, &win) == 0) {
163 termwidth = win.ws_col;
165 #endif
166 return termwidth == 0 ? default_tty : termwidth;
169 /* does the same thing as 'rm -rf' */
170 int rmrf(const char *path)
172 int errflag = 0;
173 struct dirent *dp;
174 DIR *dirp;
176 if(!unlink(path)) {
177 return 0;
178 } else {
179 if(errno == ENOENT) {
180 return 0;
181 } else if(errno == EPERM) {
182 /* fallthrough */
183 } else if(errno == EISDIR) {
184 /* fallthrough */
185 } else if(errno == ENOTDIR) {
186 return 1;
187 } else {
188 /* not a directory */
189 return 1;
192 dirp = opendir(path);
193 if(!dirp) {
194 return 1;
196 for(dp = readdir(dirp); dp != NULL; dp = readdir(dirp)) {
197 if(dp->d_name) {
198 if(strcmp(dp->d_name, "..") != 0 && strcmp(dp->d_name, ".") != 0) {
199 char name[PATH_MAX];
200 snprintf(name, PATH_MAX, "%s/%s", path, dp->d_name);
201 errflag += rmrf(name);
205 closedir(dirp);
206 if(rmdir(path)) {
207 errflag++;
209 return errflag;
213 /** Parse the basename of a program from a path.
214 * @param path path to parse basename from
216 * @return everything following the final '/'
218 const char *mbasename(const char *path)
220 const char *last = strrchr(path, '/');
221 if(last) {
222 return last + 1;
224 return path;
227 /** Parse the dirname of a program from a path.
228 * The path returned should be freed.
229 * @param path path to parse dirname from
231 * @return everything preceding the final '/'
233 char *mdirname(const char *path)
235 char *ret, *last;
237 /* null or empty path */
238 if(path == NULL || path == '\0') {
239 return strdup(".");
242 ret = strdup(path);
243 last = strrchr(ret, '/');
245 if(last != NULL) {
246 /* we found a '/', so terminate our string */
247 *last = '\0';
248 return ret;
250 /* no slash found */
251 free(ret);
252 return strdup(".");
255 /* output a string, but wrap words properly with a specified indentation
257 void indentprint(const char *str, size_t indent)
259 wchar_t *wcstr;
260 const wchar_t *p;
261 int len, cidx;
262 const unsigned short cols = getcols();
264 if(!str) {
265 return;
268 /* if we're not a tty, or our tty is not wide enough that wrapping even makes
269 * sense, print without indenting */
270 if(cols == 0 || indent > cols) {
271 fputs(str, stdout);
272 return;
275 len = strlen(str) + 1;
276 wcstr = calloc(len, sizeof(wchar_t));
277 len = mbstowcs(wcstr, str, len);
278 p = wcstr;
279 cidx = indent;
281 if(!p || !len) {
282 return;
285 while(*p) {
286 if(*p == L' ') {
287 const wchar_t *q, *next;
288 p++;
289 if(p == NULL || *p == L' ') continue;
290 next = wcschr(p, L' ');
291 if(next == NULL) {
292 next = p + wcslen(p);
294 /* len captures # cols */
295 len = 0;
296 q = p;
297 while(q < next) {
298 len += wcwidth(*q++);
300 if(len > (cols - cidx - 1)) {
301 /* wrap to a newline and reindent */
302 printf("\n%-*s", (int)indent, "");
303 cidx = indent;
304 } else {
305 printf(" ");
306 cidx++;
308 continue;
310 printf("%lc", (wint_t)*p);
311 cidx += wcwidth(*p);
312 p++;
314 free(wcstr);
317 /* Trim whitespace and newlines from a string
319 size_t strtrim(char *str)
321 char *end, *pch = str;
323 if(str == NULL || *str == '\0') {
324 /* string is empty, so we're done. */
325 return 0;
328 while(isspace((unsigned char)*pch)) {
329 pch++;
331 if(pch != str) {
332 size_t len = strlen(pch);
333 if(len) {
334 memmove(str, pch, len + 1);
335 } else {
336 *str = '\0';
340 /* check if there wasn't anything but whitespace in the string. */
341 if(*str == '\0') {
342 return 0;
345 end = (str + strlen(str) - 1);
346 while(isspace((unsigned char)*end)) {
347 end--;
349 *++end = '\0';
351 return end - pch;
354 /* Replace all occurances of 'needle' with 'replace' in 'str', returning
355 * a new string (must be free'd) */
356 char *strreplace(const char *str, const char *needle, const char *replace)
358 const char *p = NULL, *q = NULL;
359 char *newstr = NULL, *newp = NULL;
360 alpm_list_t *i = NULL, *list = NULL;
361 size_t needlesz = strlen(needle), replacesz = strlen(replace);
362 size_t newsz;
364 if(!str) {
365 return NULL;
368 p = str;
369 q = strstr(p, needle);
370 while(q) {
371 list = alpm_list_add(list, (char *)q);
372 p = q + needlesz;
373 q = strstr(p, needle);
376 /* no occurences of needle found */
377 if(!list) {
378 return strdup(str);
380 /* size of new string = size of old string + "number of occurences of needle"
381 * x "size difference between replace and needle" */
382 newsz = strlen(str) + 1 +
383 alpm_list_count(list) * (replacesz - needlesz);
384 newstr = calloc(newsz, sizeof(char));
385 if(!newstr) {
386 return NULL;
389 p = str;
390 newp = newstr;
391 for(i = list; i; i = alpm_list_next(i)) {
392 q = i->data;
393 if(q > p) {
394 /* add chars between this occurence and last occurence, if any */
395 memcpy(newp, p, (size_t)(q - p));
396 newp += q - p;
398 memcpy(newp, replace, replacesz);
399 newp += replacesz;
400 p = q + needlesz;
402 alpm_list_free(list);
404 if(*p) {
405 /* add the rest of 'p' */
406 strcpy(newp, p);
409 return newstr;
412 /** Splits a string into a list of strings using the chosen character as
413 * a delimiter.
415 * @param str the string to split
416 * @param splitchar the character to split at
418 * @return a list containing the duplicated strings
420 alpm_list_t *strsplit(const char *str, const char splitchar)
422 alpm_list_t *list = NULL;
423 const char *prev = str;
424 char *dup = NULL;
426 while((str = strchr(str, splitchar))) {
427 dup = strndup(prev, (size_t)(str - prev));
428 if(dup == NULL) {
429 return NULL;
431 list = alpm_list_add(list, dup);
433 str++;
434 prev = str;
437 dup = strdup(prev);
438 if(dup == NULL) {
439 return NULL;
441 list = alpm_list_add(list, dup);
443 return list;
446 static size_t string_length(const char *s)
448 int len;
449 wchar_t *wcstr;
451 if(!s || s[0] == '\0') {
452 return 0;
454 /* len goes from # bytes -> # chars -> # cols */
455 len = strlen(s) + 1;
456 wcstr = calloc(len, sizeof(wchar_t));
457 len = mbstowcs(wcstr, s, len);
458 len = wcswidth(wcstr, len);
459 free(wcstr);
461 return len;
464 void string_display(const char *title, const char *string)
466 if(title) {
467 printf("%s ", title);
469 if(string == NULL || string[0] == '\0') {
470 printf(_("None"));
471 } else {
472 /* compute the length of title + a space */
473 size_t len = string_length(title) + 1;
474 indentprint(string, len);
476 printf("\n");
479 static void table_print_line(const alpm_list_t *line, short col_padding,
480 size_t colcount, size_t *widths, int *has_data)
482 size_t i, lastcol = 0;
483 int need_padding = 0;
484 const alpm_list_t *curcell;
486 for(i = colcount; i > 0; i--) {
487 if(has_data[i - 1]) {
488 lastcol = i - 1;
489 break;
493 for(i = 0, curcell = line; curcell && i < colcount;
494 i++, curcell = alpm_list_next(curcell)) {
495 const char *value;
496 int cell_padding;
498 if(!has_data[i]) {
499 continue;
502 value = curcell->data;
503 /* silly printf requires padding size to be an int */
504 cell_padding = (int)widths[i] - (int)string_length(value);
505 if(cell_padding < 0) {
506 cell_padding = 0;
508 if(need_padding) {
509 printf("%*s", col_padding, "");
511 /* left-align all but the last column */
512 if(i != lastcol) {
513 printf("%s%*s", value, cell_padding, "");
514 } else {
515 printf("%*s%s", cell_padding, "", value);
517 need_padding = 1;
520 printf("\n");
526 * Find the max string width of each column. Also determines whether values
527 * exist in the column and sets the value in has_data accordingly.
528 * @param header a list of header strings
529 * @param rows a list of lists of rows as strings
530 * @param padding the amount of padding between columns
531 * @param totalcols the total number of columns in the header and each row
532 * @param widths a pointer to store width data
533 * @param has_data a pointer to store whether column has data
535 * @return the total width of the table; 0 on failure
537 static size_t table_calc_widths(const alpm_list_t *header,
538 const alpm_list_t *rows, short padding, size_t totalcols,
539 size_t **widths, int **has_data)
541 const alpm_list_t *i;
542 size_t curcol, totalwidth = 0, usefulcols = 0;
543 size_t *colwidths;
544 int *coldata;
546 if(totalcols <= 0) {
547 return 0;
550 colwidths = malloc(totalcols * sizeof(size_t));
551 coldata = calloc(totalcols, sizeof(int));
552 if(!colwidths || !coldata) {
553 return 0;
555 /* header determines column count and initial values of longest_strs */
556 for(i = header, curcol = 0; i; i = alpm_list_next(i), curcol++) {
557 colwidths[curcol] = string_length(i->data);
558 /* note: header does not determine whether column has data */
561 /* now find the longest string in each column */
562 for(i = rows; i; i = alpm_list_next(i)) {
563 /* grab first column of each row and iterate through columns */
564 const alpm_list_t *j = i->data;
565 for(curcol = 0; j; j = alpm_list_next(j), curcol++) {
566 const char *str = j->data;
567 size_t str_len = string_length(str);
569 if(str_len > colwidths[curcol]) {
570 colwidths[curcol] = str_len;
572 if(str_len > 0) {
573 coldata[curcol] = 1;
578 for(i = header, curcol = 0; i; i = alpm_list_next(i), curcol++) {
579 /* only include columns that have data */
580 if(coldata[curcol]) {
581 usefulcols++;
582 totalwidth += colwidths[curcol];
586 /* add padding between columns */
587 if(usefulcols > 0) {
588 totalwidth += padding * (usefulcols - 1);
591 *widths = colwidths;
592 *has_data = coldata;
593 return totalwidth;
596 /** Displays the list in table format
598 * @param title the tables title
599 * @param header the column headers. column count is determined by the nr
600 * of headers
601 * @param rows the rows to display as a list of lists of strings. the outer
602 * list represents the rows, the inner list the cells (= columns)
604 * @return -1 if not enough terminal cols available, else 0
606 int table_display(const char *title, const alpm_list_t *header,
607 const alpm_list_t *rows)
609 const unsigned short padding = 2;
610 const alpm_list_t *i;
611 size_t *widths = NULL, totalcols, totalwidth;
612 int *has_data = NULL;
614 if(rows == NULL || header == NULL) {
615 return 0;
618 totalcols = alpm_list_count(header);
619 totalwidth = table_calc_widths(header, rows, padding, totalcols,
620 &widths, &has_data);
621 /* return -1 if terminal is not wide enough */
622 if(totalwidth > getcols()) {
623 pm_printf(ALPM_LOG_WARNING,
624 _("insufficient columns available for table display\n"));
625 return -1;
627 if(!totalwidth || !widths || !has_data) {
628 return -1;
631 if(title != NULL) {
632 printf("%s\n\n", title);
635 table_print_line(header, padding, totalcols, widths, has_data);
636 printf("\n");
638 for(i = rows; i; i = alpm_list_next(i)) {
639 table_print_line(i->data, padding, totalcols, widths, has_data);
642 free(widths);
643 free(has_data);
644 return 0;
647 void list_display(const char *title, const alpm_list_t *list)
649 const alpm_list_t *i;
650 size_t len = 0;
652 if(title) {
653 len = string_length(title) + 1;
654 printf("%s ", title);
657 if(!list) {
658 printf("%s\n", _("None"));
659 } else {
660 const unsigned short maxcols = getcols();
661 size_t cols = len;
662 const char *str = list->data;
663 fputs(str, stdout);
664 cols += string_length(str);
665 for(i = alpm_list_next(list); i; i = alpm_list_next(i)) {
666 str = i->data;
667 size_t s = string_length(str);
668 /* wrap only if we have enough usable column space */
669 if(maxcols > len && cols + s + 2 >= maxcols) {
670 size_t j;
671 cols = len;
672 printf("\n");
673 for(j = 1; j <= len; j++) {
674 printf(" ");
676 } else if(cols != len) {
677 /* 2 spaces are added if this is not the first element on a line. */
678 printf(" ");
679 cols += 2;
681 fputs(str, stdout);
682 cols += s;
684 putchar('\n');
688 void list_display_linebreak(const char *title, const alpm_list_t *list)
690 size_t len = 0;
692 if(title) {
693 len = string_length(title) + 1;
694 printf("%s ", title);
697 if(!list) {
698 printf("%s\n", _("None"));
699 } else {
700 const alpm_list_t *i;
701 /* Print the first element */
702 indentprint((const char *)list->data, len);
703 printf("\n");
704 /* Print the rest */
705 for(i = alpm_list_next(list); i; i = alpm_list_next(i)) {
706 size_t j;
707 for(j = 1; j <= len; j++) {
708 printf(" ");
710 indentprint((const char *)i->data, len);
711 printf("\n");
716 void signature_display(const char *title, alpm_siglist_t *siglist)
718 size_t len = 0;
720 if(title) {
721 len = string_length(title) + 1;
722 printf("%s ", title);
724 if(siglist->count == 0) {
725 printf(_("None"));
726 } else {
727 size_t i;
728 for(i = 0; i < siglist->count; i++) {
729 char *sigline;
730 const char *status, *validity, *name;
731 int ret;
732 alpm_sigresult_t *result = siglist->results + i;
733 /* Don't re-indent the first result */
734 if(i != 0) {
735 size_t j;
736 for(j = 1; j <= len; j++) {
737 printf(" ");
740 switch(result->status) {
741 case ALPM_SIGSTATUS_VALID:
742 status = _("Valid");
743 break;
744 case ALPM_SIGSTATUS_KEY_EXPIRED:
745 status = _("Key expired");
746 break;
747 case ALPM_SIGSTATUS_SIG_EXPIRED:
748 status = _("Expired");
749 break;
750 case ALPM_SIGSTATUS_INVALID:
751 status = _("Invalid");
752 break;
753 case ALPM_SIGSTATUS_KEY_UNKNOWN:
754 status = _("Key unknown");
755 break;
756 case ALPM_SIGSTATUS_KEY_DISABLED:
757 status = _("Key disabled");
758 break;
759 default:
760 status = _("Signature error");
761 break;
763 switch(result->validity) {
764 case ALPM_SIGVALIDITY_FULL:
765 validity = _("full trust");
766 break;
767 case ALPM_SIGVALIDITY_MARGINAL:
768 validity = _("marginal trust");
769 break;
770 case ALPM_SIGVALIDITY_NEVER:
771 validity = _("never trust");
772 break;
773 case ALPM_SIGVALIDITY_UNKNOWN:
774 default:
775 validity = _("unknown trust");
776 break;
778 name = result->key.uid ? result->key.uid : result->key.fingerprint;
779 ret = pm_asprintf(&sigline, _("%s, %s from \"%s\""),
780 status, validity, name);
781 if(ret == -1) {
782 pm_printf(ALPM_LOG_ERROR, _("failed to allocate string\n"));
783 continue;
785 indentprint(sigline, len);
786 printf("\n");
787 free(sigline);
792 /* creates a header row for use with table_display */
793 static alpm_list_t *create_verbose_header(int dl_size)
795 alpm_list_t *res = NULL;
796 char *str;
798 str = _("Name");
799 res = alpm_list_add(res, str);
800 str = _("Old Version");
801 res = alpm_list_add(res, str);
802 str = _("New Version");
803 res = alpm_list_add(res, str);
804 str = _("Net Change");
805 res = alpm_list_add(res, str);
806 if(dl_size) {
807 str = _("Download Size");
808 res = alpm_list_add(res, str);
811 return res;
814 /* returns package info as list of strings */
815 static alpm_list_t *create_verbose_row(pm_target_t *target, int dl_size)
817 char *str;
818 off_t size = 0;
819 double human_size;
820 const char *label;
821 alpm_list_t *ret = NULL;
823 /* a row consists of the package name, */
824 if(target->install) {
825 const alpm_db_t *db = alpm_pkg_get_db(target->install);
826 if(db) {
827 pm_asprintf(&str, "%s/%s", alpm_db_get_name(db), alpm_pkg_get_name(target->install));
828 } else {
829 pm_asprintf(&str, "%s", alpm_pkg_get_name(target->install));
831 } else {
832 pm_asprintf(&str, "%s", alpm_pkg_get_name(target->remove));
834 ret = alpm_list_add(ret, str);
836 /* old and new versions */
837 pm_asprintf(&str, "%s",
838 target->remove != NULL ? alpm_pkg_get_version(target->remove) : "");
839 ret = alpm_list_add(ret, str);
841 pm_asprintf(&str, "%s",
842 target->install != NULL ? alpm_pkg_get_version(target->install) : "");
843 ret = alpm_list_add(ret, str);
845 /* and size */
846 size -= target->remove ? alpm_pkg_get_isize(target->remove) : 0;
847 size += target->install ? alpm_pkg_get_isize(target->install) : 0;
848 human_size = humanize_size(size, 'M', 2, &label);
849 pm_asprintf(&str, "%.2f %s", human_size, label);
850 ret = alpm_list_add(ret, str);
852 if(dl_size) {
853 size = target->install ? alpm_pkg_download_size(target->install) : 0;
854 human_size = humanize_size(size, 'M', 2, &label);
855 if(size != 0) {
856 pm_asprintf(&str, "%.2f %s", human_size, label);
857 } else {
858 str = strdup("");
860 ret = alpm_list_add(ret, str);
863 return ret;
866 /* prepare a list of pkgs to display */
867 static void _display_targets(alpm_list_t *targets, int verbose)
869 char *str;
870 const char *label;
871 double size;
872 off_t isize = 0, rsize = 0, dlsize = 0;
873 alpm_list_t *i, *rows = NULL, *names = NULL;
874 int show_dl_size = config->op == PM_OP_SYNC;
876 if(!targets) {
877 return;
880 /* gather package info */
881 for(i = targets; i; i = alpm_list_next(i)) {
882 pm_target_t *target = i->data;
884 if(target->install) {
885 dlsize += alpm_pkg_download_size(target->install);
886 isize += alpm_pkg_get_isize(target->install);
888 if(target->remove) {
889 /* add up size of all removed packages */
890 rsize += alpm_pkg_get_isize(target->remove);
894 /* form data for both verbose and non-verbose display */
895 for(i = targets; i; i = alpm_list_next(i)) {
896 pm_target_t *target = i->data;
898 rows = alpm_list_add(rows, create_verbose_row(target, show_dl_size));
899 if(target->install) {
900 pm_asprintf(&str, "%s-%s", alpm_pkg_get_name(target->install),
901 alpm_pkg_get_version(target->install));
902 } else if(isize == 0) {
903 pm_asprintf(&str, "%s-%s", alpm_pkg_get_name(target->remove),
904 alpm_pkg_get_version(target->remove));
905 } else {
906 pm_asprintf(&str, "%s-%s [removal]", alpm_pkg_get_name(target->remove),
907 alpm_pkg_get_version(target->remove));
909 names = alpm_list_add(names, str);
912 /* print to screen */
913 pm_asprintf(&str, _("Targets (%d):"), alpm_list_count(targets));
915 printf("\n");
916 if(verbose) {
917 alpm_list_t *header = create_verbose_header(show_dl_size);
918 if(table_display(str, header, rows) != 0) {
919 /* fallback to list display if table wouldn't fit */
920 list_display(str, names);
922 alpm_list_free(header);
923 } else {
924 list_display(str, names);
926 printf("\n");
928 /* rows is a list of lists of strings, free inner lists here */
929 for(i = rows; i; i = alpm_list_next(i)) {
930 alpm_list_t *lp = i->data;
931 FREELIST(lp);
933 alpm_list_free(rows);
934 FREELIST(names);
935 free(str);
937 if(dlsize > 0 || config->op_s_downloadonly) {
938 size = humanize_size(dlsize, 'M', 2, &label);
939 printf(_("Total Download Size: %.2f %s\n"), size, label);
941 if(!config->op_s_downloadonly) {
942 if(isize > 0) {
943 size = humanize_size(isize, 'M', 2, &label);
944 printf(_("Total Installed Size: %.2f %s\n"), size, label);
946 if(rsize > 0 && isize == 0) {
947 size = humanize_size(rsize, 'M', 2, &label);
948 printf(_("Total Removed Size: %.2f %s\n"), size, label);
950 /* only show this net value if different from raw installed size */
951 if(isize > 0 && rsize > 0) {
952 size = humanize_size(isize - rsize, 'M', 2, &label);
953 printf(_("Net Upgrade Size: %.2f %s\n"), size, label);
958 static int target_cmp(const void *p1, const void *p2)
960 const pm_target_t *targ1 = p1;
961 const pm_target_t *targ2 = p2;
962 /* explicit are always sorted after implicit (e.g. deps, pulled targets) */
963 if(targ1->is_explicit != targ2->is_explicit) {
964 return targ1->is_explicit > targ2->is_explicit;
966 const char *name1 = targ1->install ?
967 alpm_pkg_get_name(targ1->install) : alpm_pkg_get_name(targ1->remove);
968 const char *name2 = targ2->install ?
969 alpm_pkg_get_name(targ2->install) : alpm_pkg_get_name(targ2->remove);
970 return strcmp(name1, name2);
973 static int pkg_cmp(const void *p1, const void *p2)
975 /* explicit cast due to (un)necessary removal of const */
976 alpm_pkg_t *pkg1 = (alpm_pkg_t *)p1;
977 alpm_pkg_t *pkg2 = (alpm_pkg_t *)p2;
978 return strcmp(alpm_pkg_get_name(pkg1), alpm_pkg_get_name(pkg2));
981 void display_targets(void)
983 alpm_list_t *i, *targets = NULL;
984 alpm_db_t *db_local = alpm_get_localdb(config->handle);
986 for(i = alpm_trans_get_add(config->handle); i; i = alpm_list_next(i)) {
987 alpm_pkg_t *pkg = i->data;
988 pm_target_t *targ = calloc(1, sizeof(pm_target_t));
989 if(!targ) return;
990 targ->install = pkg;
991 targ->remove = alpm_db_get_pkg(db_local, alpm_pkg_get_name(pkg));
992 if(alpm_list_find(config->explicit_adds, pkg, pkg_cmp)) {
993 targ->is_explicit = 1;
995 targets = alpm_list_add(targets, targ);
997 for(i = alpm_trans_get_remove(config->handle); i; i = alpm_list_next(i)) {
998 alpm_pkg_t *pkg = i->data;
999 pm_target_t *targ = calloc(1, sizeof(pm_target_t));
1000 if(!targ) return;
1001 targ->remove = pkg;
1002 if(alpm_list_find(config->explicit_removes, pkg, pkg_cmp)) {
1003 targ->is_explicit = 1;
1005 targets = alpm_list_add(targets, targ);
1008 targets = alpm_list_msort(targets, alpm_list_count(targets), target_cmp);
1009 _display_targets(targets, config->verbosepkglists);
1010 FREELIST(targets);
1013 static off_t pkg_get_size(alpm_pkg_t *pkg)
1015 switch(config->op) {
1016 case PM_OP_SYNC:
1017 return alpm_pkg_download_size(pkg);
1018 case PM_OP_UPGRADE:
1019 return alpm_pkg_get_size(pkg);
1020 default:
1021 return alpm_pkg_get_isize(pkg);
1025 static char *pkg_get_location(alpm_pkg_t *pkg)
1027 alpm_list_t *servers;
1028 char *string = NULL;
1029 switch(config->op) {
1030 case PM_OP_SYNC:
1031 servers = alpm_db_get_servers(alpm_pkg_get_db(pkg));
1032 if(servers) {
1033 pm_asprintf(&string, "%s/%s", servers->data,
1034 alpm_pkg_get_filename(pkg));
1035 return string;
1037 case PM_OP_UPGRADE:
1038 return strdup(alpm_pkg_get_filename(pkg));
1039 default:
1040 pm_asprintf(&string, "%s-%s", alpm_pkg_get_name(pkg), alpm_pkg_get_version(pkg));
1041 return string;
1045 /* a pow() implementation that is specialized for an integer base and small,
1046 * positive-only integer exponents. */
1047 static double simple_pow(int base, int exp)
1049 double result = 1.0;
1050 for(; exp > 0; exp--) {
1051 result *= base;
1053 return result;
1056 /** Converts sizes in bytes into human readable units.
1058 * @param bytes the size in bytes
1059 * @param target_unit '\0' or a short label. If equal to one of the short unit
1060 * labels ('B', 'K', ...) bytes is converted to target_unit; if '\0', the first
1061 * unit which will bring the value to below a threshold of 2048 will be chosen.
1062 * @param precision number of decimal places, ensures -0.00 gets rounded to
1063 * 0.00; -1 if no rounding desired
1064 * @param label will be set to the appropriate unit label
1066 * @return the size in the appropriate unit
1068 double humanize_size(off_t bytes, const char target_unit, int precision,
1069 const char **label)
1071 static const char *labels[] = {"B", "KiB", "MiB", "GiB",
1072 "TiB", "PiB", "EiB", "ZiB", "YiB"};
1073 static const int unitcount = sizeof(labels) / sizeof(labels[0]);
1075 double val = (double)bytes;
1076 int index;
1078 for(index = 0; index < unitcount - 1; index++) {
1079 if(target_unit != '\0' && labels[index][0] == target_unit) {
1080 break;
1081 } else if(target_unit == '\0' && val <= 2048.0 && val >= -2048.0) {
1082 break;
1084 val /= 1024.0;
1087 if(label) {
1088 *label = labels[index];
1091 /* fix FS#27924 so that it doesn't display negative zeroes */
1092 if(precision >= 0 && val < 0.0 &&
1093 val > (-0.5 / simple_pow(10, precision))) {
1094 val = 0.0;
1097 return val;
1100 void print_packages(const alpm_list_t *packages)
1102 const alpm_list_t *i;
1103 if(!config->print_format) {
1104 config->print_format = strdup("%l");
1106 for(i = packages; i; i = alpm_list_next(i)) {
1107 alpm_pkg_t *pkg = i->data;
1108 char *string = strdup(config->print_format);
1109 char *temp = string;
1110 /* %n : pkgname */
1111 if(strstr(temp, "%n")) {
1112 string = strreplace(temp, "%n", alpm_pkg_get_name(pkg));
1113 free(temp);
1114 temp = string;
1116 /* %v : pkgver */
1117 if(strstr(temp, "%v")) {
1118 string = strreplace(temp, "%v", alpm_pkg_get_version(pkg));
1119 free(temp);
1120 temp = string;
1122 /* %l : location */
1123 if(strstr(temp, "%l")) {
1124 char *pkgloc = pkg_get_location(pkg);
1125 string = strreplace(temp, "%l", pkgloc);
1126 free(pkgloc);
1127 free(temp);
1128 temp = string;
1130 /* %r : repo */
1131 if(strstr(temp, "%r")) {
1132 const char *repo = "local";
1133 alpm_db_t *db = alpm_pkg_get_db(pkg);
1134 if(db) {
1135 repo = alpm_db_get_name(db);
1137 string = strreplace(temp, "%r", repo);
1138 free(temp);
1139 temp = string;
1141 /* %s : size */
1142 if(strstr(temp, "%s")) {
1143 char *size;
1144 pm_asprintf(&size, "%jd", (intmax_t)pkg_get_size(pkg));
1145 string = strreplace(temp, "%s", size);
1146 free(size);
1147 free(temp);
1149 printf("%s\n",string);
1150 free(string);
1155 * Helper function for comparing depends using the alpm "compare func"
1156 * signature. The function descends through the structure in the following
1157 * comparison order: name, modifier (e.g., '>', '='), version, description.
1158 * @param d1 the first depend structure
1159 * @param d2 the second depend structure
1160 * @return -1, 0, or 1 if first is <, ==, or > second
1162 static int depend_cmp(const void *d1, const void *d2)
1164 const alpm_depend_t *dep1 = d1;
1165 const alpm_depend_t *dep2 = d2;
1166 int ret;
1168 ret = strcmp(dep1->name, dep2->name);
1169 if(ret == 0) {
1170 ret = dep1->mod - dep2->mod;
1172 if(ret == 0) {
1173 if(dep1->version && dep2->version) {
1174 ret = strcmp(dep1->version, dep2->version);
1175 } else if(!dep1->version && dep2->version) {
1176 ret = -1;
1177 } else if(dep1->version && !dep2->version) {
1178 ret = 1;
1181 if(ret == 0) {
1182 if(dep1->desc && dep2->desc) {
1183 ret = strcmp(dep1->desc, dep2->desc);
1184 } else if(!dep1->desc && dep2->desc) {
1185 ret = -1;
1186 } else if(dep1->desc && !dep2->desc) {
1187 ret = 1;
1191 return ret;
1194 void display_new_optdepends(alpm_pkg_t *oldpkg, alpm_pkg_t *newpkg)
1196 alpm_list_t *i, *old, *new, *optdeps, *optstrings = NULL;
1198 old = alpm_pkg_get_optdepends(oldpkg);
1199 new = alpm_pkg_get_optdepends(newpkg);
1200 optdeps = alpm_list_diff(new, old, depend_cmp);
1202 /* turn optdepends list into a text list */
1203 for(i = optdeps; i; i = alpm_list_next(i)) {
1204 alpm_depend_t *optdep = i->data;
1205 optstrings = alpm_list_add(optstrings, alpm_dep_compute_string(optdep));
1208 if(optstrings) {
1209 printf(_("New optional dependencies for %s\n"), alpm_pkg_get_name(newpkg));
1210 list_display_linebreak(" ", optstrings);
1213 alpm_list_free(optdeps);
1214 FREELIST(optstrings);
1217 void display_optdepends(alpm_pkg_t *pkg)
1219 alpm_list_t *i, *optdeps, *optstrings = NULL;
1221 optdeps = alpm_pkg_get_optdepends(pkg);
1223 /* turn optdepends list into a text list */
1224 for(i = optdeps; i; i = alpm_list_next(i)) {
1225 alpm_depend_t *optdep = i->data;
1226 optstrings = alpm_list_add(optstrings, alpm_dep_compute_string(optdep));
1229 if(optstrings) {
1230 printf(_("Optional dependencies for %s\n"), alpm_pkg_get_name(pkg));
1231 list_display_linebreak(" ", optstrings);
1234 FREELIST(optstrings);
1237 static void display_repo_list(const char *dbname, alpm_list_t *list)
1239 const char *prefix= " ";
1241 printf(":: ");
1242 printf(_("Repository %s\n"), dbname);
1243 list_display(prefix, list);
1246 void select_display(const alpm_list_t *pkglist)
1248 const alpm_list_t *i;
1249 int nth = 1;
1250 alpm_list_t *list = NULL;
1251 char *string = NULL;
1252 const char *dbname = NULL;
1254 for(i = pkglist; i; i = i->next) {
1255 alpm_pkg_t *pkg = i->data;
1256 alpm_db_t *db = alpm_pkg_get_db(pkg);
1258 if(!dbname)
1259 dbname = alpm_db_get_name(db);
1260 if(strcmp(alpm_db_get_name(db), dbname) != 0) {
1261 display_repo_list(dbname, list);
1262 FREELIST(list);
1263 dbname = alpm_db_get_name(db);
1265 string = NULL;
1266 pm_asprintf(&string, "%d) %s", nth, alpm_pkg_get_name(pkg));
1267 list = alpm_list_add(list, string);
1268 nth++;
1270 display_repo_list(dbname, list);
1271 FREELIST(list);
1274 static int parseindex(char *s, int *val, int min, int max)
1276 char *endptr = NULL;
1277 int n = strtol(s, &endptr, 10);
1278 if(*endptr == '\0') {
1279 if(n < min || n > max) {
1280 pm_printf(ALPM_LOG_ERROR,
1281 _("invalid value: %d is not between %d and %d\n"),
1282 n, min, max);
1283 return -1;
1285 *val = n;
1286 return 0;
1287 } else {
1288 pm_printf(ALPM_LOG_ERROR, _("invalid number: %s\n"), s);
1289 return -1;
1293 static int multiselect_parse(char *array, int count, char *response)
1295 char *str, *saveptr;
1297 for(str = response; ; str = NULL) {
1298 int include = 1;
1299 int start, end;
1300 size_t len;
1301 char *ends = NULL;
1302 char *starts = strtok_r(str, " ", &saveptr);
1304 if(starts == NULL) {
1305 break;
1307 len = strtrim(starts);
1308 if(len == 0)
1309 continue;
1311 if(*starts == '^') {
1312 starts++;
1313 len--;
1314 include = 0;
1315 } else if(str) {
1316 /* if first token is including, we unselect all targets */
1317 memset(array, 0, count);
1320 if(len > 1) {
1321 /* check for range */
1322 char *p;
1323 if((p = strchr(starts + 1, '-'))) {
1324 *p = 0;
1325 ends = p + 1;
1329 if(parseindex(starts, &start, 1, count) != 0)
1330 return -1;
1332 if(!ends) {
1333 array[start-1] = include;
1334 } else {
1335 int d;
1336 if(parseindex(ends, &end, start, count) != 0) {
1337 return -1;
1339 for(d = start; d <= end; d++) {
1340 array[d-1] = include;
1345 return 0;
1348 int multiselect_question(char *array, int count)
1350 char *response, *lastchar;
1351 FILE *stream;
1352 size_t response_len = 64;
1354 if(config->noconfirm) {
1355 stream = stdout;
1356 } else {
1357 /* Use stderr so questions are always displayed when redirecting output */
1358 stream = stderr;
1361 response = malloc(response_len);
1362 if(!response) {
1363 return -1;
1365 lastchar = response + response_len - 1;
1366 /* sentinel byte to later see if we filled up the entire string */
1367 *lastchar = 1;
1369 while(1) {
1370 memset(array, 1, count);
1372 fprintf(stream, "\n");
1373 fprintf(stream, _("Enter a selection (default=all)"));
1374 fprintf(stream, ": ");
1375 fflush(stream);
1377 if(config->noconfirm) {
1378 fprintf(stream, "\n");
1379 break;
1382 flush_term_input();
1384 if(fgets(response, response_len, stdin)) {
1385 const size_t response_incr = 64;
1386 size_t len;
1387 /* handle buffer not being large enough to read full line case */
1388 while(*lastchar == '\0' && lastchar[-1] != '\n') {
1389 response_len += response_incr;
1390 response = realloc(response, response_len);
1391 if(!response) {
1392 return -1;
1394 lastchar = response + response_len - 1;
1395 /* sentinel byte */
1396 *lastchar = 1;
1397 if(fgets(response + response_len - response_incr - 1,
1398 response_incr + 1, stdin) == 0) {
1399 free(response);
1400 return -1;
1404 len = strtrim(response);
1405 if(len > 0) {
1406 if(multiselect_parse(array, count, response) == -1) {
1407 /* only loop if user gave an invalid answer */
1408 continue;
1411 break;
1412 } else {
1413 free(response);
1414 return -1;
1418 free(response);
1419 return 0;
1422 int select_question(int count)
1424 char response[32];
1425 FILE *stream;
1426 int preset = 1;
1428 if(config->noconfirm) {
1429 stream = stdout;
1430 } else {
1431 /* Use stderr so questions are always displayed when redirecting output */
1432 stream = stderr;
1435 while(1) {
1436 fprintf(stream, "\n");
1437 fprintf(stream, _("Enter a number (default=%d)"), preset);
1438 fprintf(stream, ": ");
1440 if(config->noconfirm) {
1441 fprintf(stream, "\n");
1442 break;
1445 flush_term_input();
1447 if(fgets(response, sizeof(response), stdin)) {
1448 size_t len = strtrim(response);
1449 if(len > 0) {
1450 int n;
1451 if(parseindex(response, &n, 1, count) != 0)
1452 continue;
1453 return (n - 1);
1456 break;
1459 return (preset - 1);
1463 /* presents a prompt and gets a Y/N answer */
1464 static int question(short preset, char *fmt, va_list args)
1466 char response[32];
1467 FILE *stream;
1469 if(config->noconfirm) {
1470 stream = stdout;
1471 } else {
1472 /* Use stderr so questions are always displayed when redirecting output */
1473 stream = stderr;
1476 /* ensure all text makes it to the screen before we prompt the user */
1477 fflush(stdout);
1478 fflush(stderr);
1480 vfprintf(stream, fmt, args);
1482 if(preset) {
1483 fprintf(stream, " %s ", _("[Y/n]"));
1484 } else {
1485 fprintf(stream, " %s ", _("[y/N]"));
1488 if(config->noconfirm) {
1489 fprintf(stream, "\n");
1490 return preset;
1493 fflush(stream);
1494 flush_term_input();
1496 if(fgets(response, sizeof(response), stdin)) {
1497 size_t len = strtrim(response);
1498 if(len == 0) {
1499 return preset;
1502 /* if stdin is piped, response does not get printed out, and as a result
1503 * a \n is missing, resulting in broken output (FS#27909) */
1504 if(!isatty(fileno(stdin))) {
1505 fprintf(stream, "%s\n", response);
1508 if(strcasecmp(response, _("Y")) == 0 || strcasecmp(response, _("YES")) == 0) {
1509 return 1;
1510 } else if(strcasecmp(response, _("N")) == 0 || strcasecmp(response, _("NO")) == 0) {
1511 return 0;
1514 return 0;
1517 int yesno(char *fmt, ...)
1519 int ret;
1520 va_list args;
1522 va_start(args, fmt);
1523 ret = question(1, fmt, args);
1524 va_end(args);
1526 return ret;
1529 int noyes(char *fmt, ...)
1531 int ret;
1532 va_list args;
1534 va_start(args, fmt);
1535 ret = question(0, fmt, args);
1536 va_end(args);
1538 return ret;
1541 int pm_printf(alpm_loglevel_t level, const char *format, ...)
1543 int ret;
1544 va_list args;
1546 /* print the message using va_arg list */
1547 va_start(args, format);
1548 ret = pm_vfprintf(stderr, level, format, args);
1549 va_end(args);
1551 return ret;
1554 int pm_asprintf(char **string, const char *format, ...)
1556 int ret = 0;
1557 va_list args;
1559 /* print the message using va_arg list */
1560 va_start(args, format);
1561 if(vasprintf(string, format, args) == -1) {
1562 pm_printf(ALPM_LOG_ERROR, _("failed to allocate string\n"));
1563 ret = -1;
1565 va_end(args);
1567 return ret;
1570 int pm_vasprintf(char **string, alpm_loglevel_t level, const char *format, va_list args)
1572 int ret = 0;
1573 char *msg = NULL;
1575 /* if current logmask does not overlap with level, do not print msg */
1576 if(!(config->logmask & level)) {
1577 return ret;
1580 /* print the message using va_arg list */
1581 ret = vasprintf(&msg, format, args);
1583 /* print a prefix to the message */
1584 switch(level) {
1585 case ALPM_LOG_ERROR:
1586 pm_asprintf(string, _("error: %s"), msg);
1587 break;
1588 case ALPM_LOG_WARNING:
1589 pm_asprintf(string, _("warning: %s"), msg);
1590 break;
1591 case ALPM_LOG_DEBUG:
1592 pm_asprintf(string, "debug: %s", msg);
1593 break;
1594 case ALPM_LOG_FUNCTION:
1595 pm_asprintf(string, "function: %s", msg);
1596 break;
1597 default:
1598 pm_asprintf(string, "%s", msg);
1599 break;
1601 free(msg);
1603 return ret;
1606 int pm_vfprintf(FILE *stream, alpm_loglevel_t level, const char *format, va_list args)
1608 int ret = 0;
1610 /* if current logmask does not overlap with level, do not print msg */
1611 if(!(config->logmask & level)) {
1612 return ret;
1615 #if defined(PACMAN_DEBUG)
1616 /* If debug is on, we'll timestamp the output */
1617 if(config->logmask & ALPM_LOG_DEBUG) {
1618 time_t t;
1619 struct tm *tmp;
1620 char timestr[10] = {0};
1622 t = time(NULL);
1623 tmp = localtime(&t);
1624 strftime(timestr, 9, "%H:%M:%S", tmp);
1625 timestr[8] = '\0';
1627 fprintf(stream, "[%s] ", timestr);
1629 #endif
1631 /* print a prefix to the message */
1632 switch(level) {
1633 case ALPM_LOG_ERROR:
1634 fprintf(stream, _("error: "));
1635 break;
1636 case ALPM_LOG_WARNING:
1637 fprintf(stream, _("warning: "));
1638 break;
1639 case ALPM_LOG_DEBUG:
1640 fprintf(stream, "debug: ");
1641 break;
1642 case ALPM_LOG_FUNCTION:
1643 fprintf(stream, "function: ");
1644 break;
1645 default:
1646 break;
1649 /* print the message using va_arg list */
1650 ret = vfprintf(stream, format, args);
1651 return ret;
1654 #ifndef HAVE_STRNDUP
1655 /* A quick and dirty implementation derived from glibc */
1656 static size_t strnlen(const char *s, size_t max)
1658 register const char *p;
1659 for(p = s; *p && max--; ++p);
1660 return (p - s);
1663 char *strndup(const char *s, size_t n)
1665 size_t len = strnlen(s, n);
1666 char *new = (char *) malloc(len + 1);
1668 if(new == NULL)
1669 return NULL;
1671 new[len] = '\0';
1672 return (char *)memcpy(new, s, len);
1674 #endif
1676 /* vim: set ts=2 sw=2 noet: */