progress.c revision c498cb11d3e72e41af760bd882675f44db8b77e7
1/*
2 * progress.c - Numeric progress meter
3 *
4 * Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
5 * 	2003, 2004, 2005 by Theodore Ts'o.
6 *
7 * %Begin-Header%
8 * This file may be redistributed under the terms of the GNU Public
9 * License.
10 * %End-Header%
11 */
12
13#include "config.h"
14#include "ext2fs.h"
15#include "ext2fsP.h"
16
17#include <time.h>
18
19static char spaces[80], backspaces[80];
20static time_t last_update;
21
22static int int_log10(unsigned int arg)
23{
24	int	l;
25
26	for (l=0; arg ; l++)
27		arg = arg / 10;
28	return l;
29}
30
31void ext2fs_numeric_progress_init(ext2_filsys fs,
32				  struct ext2fs_numeric_progress_struct * progress,
33				  const char *label, __u64 max)
34{
35	/*
36	 * The PRINT_PROGRESS flag turns on or off ALL
37	 * progress-related messages, whereas the SKIP_PROGRESS
38	 * environment variable prints the start and end messages but
39	 * not the numeric countdown in the middle.
40	 */
41	if (!(fs->flags & EXT2_FLAG_PRINT_PROGRESS))
42		return;
43
44	memset(spaces, ' ', sizeof(spaces)-1);
45	spaces[sizeof(spaces)-1] = 0;
46	memset(backspaces, '\b', sizeof(backspaces)-1);
47	backspaces[sizeof(backspaces)-1] = 0;
48
49	memset(progress, 0, sizeof(*progress));
50	if (getenv("E2FSPROGS_SKIP_PROGRESS"))
51		progress->skip_progress++;
52
53
54	/*
55	 * Figure out how many digits we need
56	 */
57	progress->max = max;
58	progress->log_max = int_log10(max);
59
60	if (label) {
61		fputs(label, stdout);
62		fflush(stdout);
63	}
64	last_update = 0;
65}
66
67void ext2fs_numeric_progress_update(ext2_filsys fs,
68				    struct ext2fs_numeric_progress_struct * progress,
69				    __u64 val)
70{
71	time_t now;
72
73	if (!(fs->flags & EXT2_FLAG_PRINT_PROGRESS))
74		return;
75	if (progress->skip_progress)
76		return;
77	now = time(0);
78	if (now == last_update)
79		return;
80	last_update = now;
81
82	printf("%*llu/%*llu", progress->log_max, val,
83	       progress->log_max, progress->max);
84	fprintf(stdout, "%.*s", (2*progress->log_max)+1, backspaces);
85}
86
87void ext2fs_numeric_progress_close(ext2_filsys fs,
88				   struct ext2fs_numeric_progress_struct * progress,
89				   const char *message)
90{
91	if (!(fs->flags & EXT2_FLAG_PRINT_PROGRESS))
92		return;
93	fprintf(stdout, "%.*s", (2*progress->log_max)+1, spaces);
94	fprintf(stdout, "%.*s", (2*progress->log_max)+1, backspaces);
95	if (message)
96		fputs(message, stdout);
97}
98