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>
29 #include <stdint.h> /* intmax_t */
38 #include <termios.h> /* tcflush */
42 #include <alpm_list.h>
50 int trans_init(alpm_transflag_t flags
, int check_valid
)
54 check_syncdbs(0, check_valid
);
56 ret
= alpm_trans_init(config
->handle
, flags
);
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"),
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"),
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
)));
97 return !config
->print
;
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
));
107 int check_syncdbs(size_t need_repos
, int check_valid
)
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"));
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
)));
132 /* discard unhandled input on the terminal's input buffer */
133 static int flush_term_input(void) {
135 if(isatty(fileno(stdin
))) {
136 return tcflush(fileno(stdin
), TCIFLUSH
);
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
;
157 if(ioctl(1, TIOCGSIZE
, &win
) == 0) {
158 termwidth
= win
.ts_cols
;
160 #elif defined(TIOCGWINSZ)
162 if(ioctl(1, TIOCGWINSZ
, &win
) == 0) {
163 termwidth
= win
.ws_col
;
166 return termwidth
== 0 ? default_tty
: termwidth
;
169 /* does the same thing as 'rm -rf' */
170 int rmrf(const char *path
)
179 if(errno
== ENOENT
) {
181 } else if(errno
== EPERM
) {
183 } else if(errno
== EISDIR
) {
185 } else if(errno
== ENOTDIR
) {
188 /* not a directory */
192 dirp
= opendir(path
);
196 for(dp
= readdir(dirp
); dp
!= NULL
; dp
= readdir(dirp
)) {
198 if(strcmp(dp
->d_name
, "..") != 0 && strcmp(dp
->d_name
, ".") != 0) {
200 snprintf(name
, PATH_MAX
, "%s/%s", path
, dp
->d_name
);
201 errflag
+= rmrf(name
);
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
, '/');
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
)
237 /* null or empty path */
238 if(path
== NULL
|| path
== '\0') {
243 last
= strrchr(ret
, '/');
246 /* we found a '/', so terminate our string */
255 /* output a string, but wrap words properly with a specified indentation
257 void indentprint(const char *str
, size_t indent
)
262 const unsigned short cols
= getcols();
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
) {
275 len
= strlen(str
) + 1;
276 wcstr
= calloc(len
, sizeof(wchar_t));
277 len
= mbstowcs(wcstr
, str
, len
);
287 const wchar_t *q
, *next
;
289 if(p
== NULL
|| *p
== L
' ') continue;
290 next
= wcschr(p
, L
' ');
292 next
= p
+ wcslen(p
);
294 /* len captures # cols */
298 len
+= wcwidth(*q
++);
300 if(len
> (cols
- cidx
- 1)) {
301 /* wrap to a newline and reindent */
302 printf("\n%-*s", (int)indent
, "");
310 printf("%lc", (wint_t)*p
);
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. */
328 while(isspace((unsigned char)*pch
)) {
332 size_t len
= strlen(pch
);
334 memmove(str
, pch
, len
+ 1);
340 /* check if there wasn't anything but whitespace in the string. */
345 end
= (str
+ strlen(str
) - 1);
346 while(isspace((unsigned char)*end
)) {
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
);
369 q
= strstr(p
, needle
);
371 list
= alpm_list_add(list
, (char *)q
);
373 q
= strstr(p
, needle
);
376 /* no occurences of needle found */
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));
391 for(i
= list
; i
; i
= alpm_list_next(i
)) {
394 /* add chars between this occurence and last occurence, if any */
395 memcpy(newp
, p
, (size_t)(q
- p
));
398 memcpy(newp
, replace
, replacesz
);
402 alpm_list_free(list
);
405 /* add the rest of 'p' */
412 /** Splits a string into a list of strings using the chosen character as
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
;
426 while((str
= strchr(str
, splitchar
))) {
427 dup
= strndup(prev
, (size_t)(str
- prev
));
431 list
= alpm_list_add(list
, dup
);
441 list
= alpm_list_add(list
, dup
);
446 static size_t string_length(const char *s
)
451 if(!s
|| s
[0] == '\0') {
454 /* len goes from # bytes -> # chars -> # cols */
456 wcstr
= calloc(len
, sizeof(wchar_t));
457 len
= mbstowcs(wcstr
, s
, len
);
458 len
= wcswidth(wcstr
, len
);
464 void string_display(const char *title
, const char *string
)
467 printf("%s ", title
);
469 if(string
== NULL
|| string
[0] == '\0') {
472 /* compute the length of title + a space */
473 size_t len
= string_length(title
) + 1;
474 indentprint(string
, len
);
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]) {
493 for(i
= 0, curcell
= line
; curcell
&& i
< colcount
;
494 i
++, curcell
= alpm_list_next(curcell
)) {
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) {
509 printf("%*s", col_padding
, "");
511 /* left-align all but the last column */
513 printf("%s%*s", value
, cell_padding
, "");
515 printf("%*s%s", cell_padding
, "", value
);
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;
550 colwidths
= malloc(totalcols
* sizeof(size_t));
551 coldata
= calloc(totalcols
, sizeof(int));
552 if(!colwidths
|| !coldata
) {
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
;
578 for(i
= header
, curcol
= 0; i
; i
= alpm_list_next(i
), curcol
++) {
579 /* only include columns that have data */
580 if(coldata
[curcol
]) {
582 totalwidth
+= colwidths
[curcol
];
586 /* add padding between columns */
588 totalwidth
+= padding
* (usefulcols
- 1);
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
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
) {
618 totalcols
= alpm_list_count(header
);
619 totalwidth
= table_calc_widths(header
, rows
, padding
, totalcols
,
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"));
627 if(!totalwidth
|| !widths
|| !has_data
) {
632 printf("%s\n\n", title
);
635 table_print_line(header
, padding
, totalcols
, widths
, has_data
);
638 for(i
= rows
; i
; i
= alpm_list_next(i
)) {
639 table_print_line(i
->data
, padding
, totalcols
, widths
, has_data
);
647 void list_display(const char *title
, const alpm_list_t
*list
)
649 const alpm_list_t
*i
;
653 len
= string_length(title
) + 1;
654 printf("%s ", title
);
658 printf("%s\n", _("None"));
660 const unsigned short maxcols
= getcols();
662 const char *str
= list
->data
;
664 cols
+= string_length(str
);
665 for(i
= alpm_list_next(list
); i
; i
= alpm_list_next(i
)) {
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
) {
673 for(j
= 1; j
<= len
; j
++) {
676 } else if(cols
!= len
) {
677 /* 2 spaces are added if this is not the first element on a line. */
688 void list_display_linebreak(const char *title
, const alpm_list_t
*list
)
693 len
= string_length(title
) + 1;
694 printf("%s ", title
);
698 printf("%s\n", _("None"));
700 const alpm_list_t
*i
;
701 /* Print the first element */
702 indentprint((const char *)list
->data
, len
);
705 for(i
= alpm_list_next(list
); i
; i
= alpm_list_next(i
)) {
707 for(j
= 1; j
<= len
; j
++) {
710 indentprint((const char *)i
->data
, len
);
716 void signature_display(const char *title
, alpm_siglist_t
*siglist
)
721 len
= string_length(title
) + 1;
722 printf("%s ", title
);
724 if(siglist
->count
== 0) {
728 for(i
= 0; i
< siglist
->count
; i
++) {
730 const char *status
, *validity
, *name
;
732 alpm_sigresult_t
*result
= siglist
->results
+ i
;
733 /* Don't re-indent the first result */
736 for(j
= 1; j
<= len
; j
++) {
740 switch(result
->status
) {
741 case ALPM_SIGSTATUS_VALID
:
744 case ALPM_SIGSTATUS_KEY_EXPIRED
:
745 status
= _("Key expired");
747 case ALPM_SIGSTATUS_SIG_EXPIRED
:
748 status
= _("Expired");
750 case ALPM_SIGSTATUS_INVALID
:
751 status
= _("Invalid");
753 case ALPM_SIGSTATUS_KEY_UNKNOWN
:
754 status
= _("Key unknown");
756 case ALPM_SIGSTATUS_KEY_DISABLED
:
757 status
= _("Key disabled");
760 status
= _("Signature error");
763 switch(result
->validity
) {
764 case ALPM_SIGVALIDITY_FULL
:
765 validity
= _("full trust");
767 case ALPM_SIGVALIDITY_MARGINAL
:
768 validity
= _("marginal trust");
770 case ALPM_SIGVALIDITY_NEVER
:
771 validity
= _("never trust");
773 case ALPM_SIGVALIDITY_UNKNOWN
:
775 validity
= _("unknown trust");
778 name
= result
->key
.uid
? result
->key
.uid
: result
->key
.fingerprint
;
779 ret
= pm_asprintf(&sigline
, _("%s, %s from \"%s\""),
780 status
, validity
, name
);
782 pm_printf(ALPM_LOG_ERROR
, _("failed to allocate string\n"));
785 indentprint(sigline
, len
);
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
;
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
);
807 str
= _("Download Size");
808 res
= alpm_list_add(res
, str
);
814 /* returns package info as list of strings */
815 static alpm_list_t
*create_verbose_row(pm_target_t
*target
, int dl_size
)
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
);
827 pm_asprintf(&str
, "%s/%s", alpm_db_get_name(db
), alpm_pkg_get_name(target
->install
));
829 pm_asprintf(&str
, "%s", alpm_pkg_get_name(target
->install
));
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
);
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
);
853 size
= target
->install
? alpm_pkg_download_size(target
->install
) : 0;
854 human_size
= humanize_size(size
, 'M', 2, &label
);
856 pm_asprintf(&str
, "%.2f %s", human_size
, label
);
860 ret
= alpm_list_add(ret
, str
);
866 /* prepare a list of pkgs to display */
867 static void _display_targets(alpm_list_t
*targets
, int verbose
)
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
;
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
);
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
));
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
));
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
);
924 list_display(str
, names
);
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
;
933 alpm_list_free(rows
);
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
) {
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
));
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
));
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
);
1013 static off_t
pkg_get_size(alpm_pkg_t
*pkg
)
1015 switch(config
->op
) {
1017 return alpm_pkg_download_size(pkg
);
1019 return alpm_pkg_get_size(pkg
);
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
) {
1031 servers
= alpm_db_get_servers(alpm_pkg_get_db(pkg
));
1033 pm_asprintf(&string
, "%s/%s", servers
->data
,
1034 alpm_pkg_get_filename(pkg
));
1038 return strdup(alpm_pkg_get_filename(pkg
));
1040 pm_asprintf(&string
, "%s-%s", alpm_pkg_get_name(pkg
), alpm_pkg_get_version(pkg
));
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
--) {
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
,
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
;
1078 for(index
= 0; index
< unitcount
- 1; index
++) {
1079 if(target_unit
!= '\0' && labels
[index
][0] == target_unit
) {
1081 } else if(target_unit
== '\0' && val
<= 2048.0 && val
>= -2048.0) {
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
))) {
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
;
1111 if(strstr(temp
, "%n")) {
1112 string
= strreplace(temp
, "%n", alpm_pkg_get_name(pkg
));
1117 if(strstr(temp
, "%v")) {
1118 string
= strreplace(temp
, "%v", alpm_pkg_get_version(pkg
));
1123 if(strstr(temp
, "%l")) {
1124 char *pkgloc
= pkg_get_location(pkg
);
1125 string
= strreplace(temp
, "%l", pkgloc
);
1131 if(strstr(temp
, "%r")) {
1132 const char *repo
= "local";
1133 alpm_db_t
*db
= alpm_pkg_get_db(pkg
);
1135 repo
= alpm_db_get_name(db
);
1137 string
= strreplace(temp
, "%r", repo
);
1142 if(strstr(temp
, "%s")) {
1144 pm_asprintf(&size
, "%jd", (intmax_t)pkg_get_size(pkg
));
1145 string
= strreplace(temp
, "%s", size
);
1149 printf("%s\n",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
;
1168 ret
= strcmp(dep1
->name
, dep2
->name
);
1170 ret
= dep1
->mod
- dep2
->mod
;
1173 if(dep1
->version
&& dep2
->version
) {
1174 ret
= strcmp(dep1
->version
, dep2
->version
);
1175 } else if(!dep1
->version
&& dep2
->version
) {
1177 } else if(dep1
->version
&& !dep2
->version
) {
1182 if(dep1
->desc
&& dep2
->desc
) {
1183 ret
= strcmp(dep1
->desc
, dep2
->desc
);
1184 } else if(!dep1
->desc
&& dep2
->desc
) {
1186 } else if(dep1
->desc
&& !dep2
->desc
) {
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
));
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
));
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
= " ";
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
;
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
);
1259 dbname
= alpm_db_get_name(db
);
1260 if(strcmp(alpm_db_get_name(db
), dbname
) != 0) {
1261 display_repo_list(dbname
, list
);
1263 dbname
= alpm_db_get_name(db
);
1266 pm_asprintf(&string
, "%d) %s", nth
, alpm_pkg_get_name(pkg
));
1267 list
= alpm_list_add(list
, string
);
1270 display_repo_list(dbname
, 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"),
1288 pm_printf(ALPM_LOG_ERROR
, _("invalid number: %s\n"), s
);
1293 static int multiselect_parse(char *array
, int count
, char *response
)
1295 char *str
, *saveptr
;
1297 for(str
= response
; ; str
= NULL
) {
1302 char *starts
= strtok_r(str
, " ", &saveptr
);
1304 if(starts
== NULL
) {
1307 len
= strtrim(starts
);
1311 if(*starts
== '^') {
1316 /* if first token is including, we unselect all targets */
1317 memset(array
, 0, count
);
1321 /* check for range */
1323 if((p
= strchr(starts
+ 1, '-'))) {
1329 if(parseindex(starts
, &start
, 1, count
) != 0)
1333 array
[start
-1] = include
;
1336 if(parseindex(ends
, &end
, start
, count
) != 0) {
1339 for(d
= start
; d
<= end
; d
++) {
1340 array
[d
-1] = include
;
1348 int multiselect_question(char *array
, int count
)
1350 char *response
, *lastchar
;
1352 size_t response_len
= 64;
1354 if(config
->noconfirm
) {
1357 /* Use stderr so questions are always displayed when redirecting output */
1361 response
= malloc(response_len
);
1365 lastchar
= response
+ response_len
- 1;
1366 /* sentinel byte to later see if we filled up the entire string */
1370 memset(array
, 1, count
);
1372 fprintf(stream
, "\n");
1373 fprintf(stream
, _("Enter a selection (default=all)"));
1374 fprintf(stream
, ": ");
1377 if(config
->noconfirm
) {
1378 fprintf(stream
, "\n");
1384 if(fgets(response
, response_len
, stdin
)) {
1385 const size_t response_incr
= 64;
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
);
1394 lastchar
= response
+ response_len
- 1;
1397 if(fgets(response
+ response_len
- response_incr
- 1,
1398 response_incr
+ 1, stdin
) == 0) {
1404 len
= strtrim(response
);
1406 if(multiselect_parse(array
, count
, response
) == -1) {
1407 /* only loop if user gave an invalid answer */
1422 int select_question(int count
)
1428 if(config
->noconfirm
) {
1431 /* Use stderr so questions are always displayed when redirecting output */
1436 fprintf(stream
, "\n");
1437 fprintf(stream
, _("Enter a number (default=%d)"), preset
);
1438 fprintf(stream
, ": ");
1440 if(config
->noconfirm
) {
1441 fprintf(stream
, "\n");
1447 if(fgets(response
, sizeof(response
), stdin
)) {
1448 size_t len
= strtrim(response
);
1451 if(parseindex(response
, &n
, 1, count
) != 0)
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
)
1469 if(config
->noconfirm
) {
1472 /* Use stderr so questions are always displayed when redirecting output */
1476 /* ensure all text makes it to the screen before we prompt the user */
1480 vfprintf(stream
, fmt
, args
);
1483 fprintf(stream
, " %s ", _("[Y/n]"));
1485 fprintf(stream
, " %s ", _("[y/N]"));
1488 if(config
->noconfirm
) {
1489 fprintf(stream
, "\n");
1496 if(fgets(response
, sizeof(response
), stdin
)) {
1497 size_t len
= strtrim(response
);
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) {
1510 } else if(strcasecmp(response
, _("N")) == 0 || strcasecmp(response
, _("NO")) == 0) {
1517 int yesno(char *fmt
, ...)
1522 va_start(args
, fmt
);
1523 ret
= question(1, fmt
, args
);
1529 int noyes(char *fmt
, ...)
1534 va_start(args
, fmt
);
1535 ret
= question(0, fmt
, args
);
1541 int pm_printf(alpm_loglevel_t level
, const char *format
, ...)
1546 /* print the message using va_arg list */
1547 va_start(args
, format
);
1548 ret
= pm_vfprintf(stderr
, level
, format
, args
);
1554 int pm_asprintf(char **string
, const char *format
, ...)
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"));
1570 int pm_vasprintf(char **string
, alpm_loglevel_t level
, const char *format
, va_list args
)
1575 /* if current logmask does not overlap with level, do not print msg */
1576 if(!(config
->logmask
& level
)) {
1580 /* print the message using va_arg list */
1581 ret
= vasprintf(&msg
, format
, args
);
1583 /* print a prefix to the message */
1585 case ALPM_LOG_ERROR
:
1586 pm_asprintf(string
, _("error: %s"), msg
);
1588 case ALPM_LOG_WARNING
:
1589 pm_asprintf(string
, _("warning: %s"), msg
);
1591 case ALPM_LOG_DEBUG
:
1592 pm_asprintf(string
, "debug: %s", msg
);
1594 case ALPM_LOG_FUNCTION
:
1595 pm_asprintf(string
, "function: %s", msg
);
1598 pm_asprintf(string
, "%s", msg
);
1606 int pm_vfprintf(FILE *stream
, alpm_loglevel_t level
, const char *format
, va_list args
)
1610 /* if current logmask does not overlap with level, do not print msg */
1611 if(!(config
->logmask
& level
)) {
1615 #if defined(PACMAN_DEBUG)
1616 /* If debug is on, we'll timestamp the output */
1617 if(config
->logmask
& ALPM_LOG_DEBUG
) {
1620 char timestr
[10] = {0};
1623 tmp
= localtime(&t
);
1624 strftime(timestr
, 9, "%H:%M:%S", tmp
);
1627 fprintf(stream
, "[%s] ", timestr
);
1631 /* print a prefix to the message */
1633 case ALPM_LOG_ERROR
:
1634 fprintf(stream
, _("error: "));
1636 case ALPM_LOG_WARNING
:
1637 fprintf(stream
, _("warning: "));
1639 case ALPM_LOG_DEBUG
:
1640 fprintf(stream
, "debug: ");
1642 case ALPM_LOG_FUNCTION
:
1643 fprintf(stream
, "function: ");
1649 /* print the message using va_arg list */
1650 ret
= vfprintf(stream
, format
, args
);
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
);
1663 char *strndup(const char *s
, size_t n
)
1665 size_t len
= strnlen(s
, n
);
1666 char *new = (char *) malloc(len
+ 1);
1672 return (char *)memcpy(new, s
, len
);
1676 /* vim: set ts=2 sw=2 noet: */