source: mainline/uspace/app/bdsh/cmds/modules/cat/cat.c@ feeac0d

lfn serial ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since feeac0d was 0845589, checked in by Vojtech Horky <vojtechhorky@…>, 12 years ago

Add line numbering to bdsh/cat (thx Marin Ramesa)

  • Property mode set to 100644
File size: 9.8 KB
Line 
1/*
2 * Copyright (c) 2008 Tim Post
3 * Copyright (c) 2011, Martin Sucha
4 * All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 *
10 * - Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * - Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * - The name of the author may not be used to endorse or promote products
16 * derived from this software without specific prior written permission.
17 *
18 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
19 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
22 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
23 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 */
29
30#include <stdio.h>
31#include <stdlib.h>
32#include <unistd.h>
33#include <getopt.h>
34#include <str.h>
35#include <fcntl.h>
36#include <io/console.h>
37#include <io/color.h>
38#include <io/style.h>
39#include <io/keycode.h>
40#include <errno.h>
41#include <vfs/vfs.h>
42#include <assert.h>
43
44#include "config.h"
45#include "util.h"
46#include "errors.h"
47#include "entry.h"
48#include "cat.h"
49#include "cmds.h"
50
51static const char *cmdname = "cat";
52#define CAT_VERSION "0.0.1"
53#define CAT_DEFAULT_BUFLEN 1024
54#define CAT_FULL_FILE 0
55
56static const char *hexchars = "0123456789abcdef";
57
58static bool paging_enabled = false;
59static size_t chars_remaining = 0;
60static size_t lines_remaining = 0;
61static sysarg_t console_cols = 0;
62static sysarg_t console_rows = 0;
63static bool should_quit = false;
64static bool dash_represents_stdin = false;
65static unsigned int lineno = 0;
66static bool number = false;
67static bool last_char_was_newline = false;
68
69static console_ctrl_t *console = NULL;
70
71static struct option const long_options[] = {
72 { "help", no_argument, 0, 'h' },
73 { "version", no_argument, 0, 'v' },
74 { "head", required_argument, 0, 'H' },
75 { "tail", required_argument, 0, 't' },
76 { "buffer", required_argument, 0, 'b' },
77 { "more", no_argument, 0, 'm' },
78 { "hex", no_argument, 0, 'x' },
79 { "stdin", no_argument, 0, 's' },
80 { "number", no_argument, 0, 'n' },
81 { 0, 0, 0, 0 }
82};
83
84/* Dispays help for cat in various levels */
85void help_cmd_cat(unsigned int level)
86{
87 if (level == HELP_SHORT) {
88 printf("`%s' shows the contents of files\n", cmdname);
89 } else {
90 help_cmd_cat(HELP_SHORT);
91 printf(
92 "Usage: %s [options] <file1> [file2] [...]\n"
93 "Options:\n"
94 " -h, --help A short option summary\n"
95 " -v, --version Print version information and exit\n"
96 " -H, --head ## Print only the first ## bytes\n"
97 " -t, --tail ## Print only the last ## bytes\n"
98 " -b, --buffer ## Set the read buffer size to ##\n"
99 " -m, --more Pause after each screen full\n"
100 " -x, --hex Print bytes as hex values\n"
101 " -s, --stdin Treat `-' in file list as standard input\n"
102 " -n, --number Number all output lines\n"
103 "Currently, %s is under development, some options don't work.\n",
104 cmdname, cmdname);
105 }
106
107 return;
108}
109
110static void waitprompt()
111{
112 console_set_pos(console, 0, console_rows-1);
113 console_set_color(console, COLOR_WHITE, COLOR_BLUE, 0);
114
115 printf("ENTER/SPACE/PAGE DOWN - next page, "
116 "ESC/Q - quit, C - continue unpaged");
117 fflush(stdout);
118
119 console_set_style(console, STYLE_NORMAL);
120}
121
122static void waitkey()
123{
124 cons_event_t ev;
125 kbd_event_t *kev;
126
127 while (true) {
128 if (!console_get_event(console, &ev)) {
129 return;
130 }
131 if (ev.type == CEV_KEY && ev.ev.key.type == KEY_PRESS) {
132 kev = &ev.ev.key;
133
134 if (kev->key == KC_ESCAPE || kev->key == KC_Q) {
135 should_quit = true;
136 return;
137 }
138 if (kev->key == KC_C) {
139 paging_enabled = false;
140 return;
141 }
142 if (kev->key == KC_ENTER || kev->key == KC_SPACE ||
143 kev->key == KC_PAGE_DOWN) {
144 return;
145 }
146 }
147 }
148 assert(false);
149}
150
151static void newpage()
152{
153 console_clear(console);
154 chars_remaining = console_cols;
155 lines_remaining = console_rows - 1;
156}
157
158static void paged_char(wchar_t c)
159{
160 if (last_char_was_newline && number) {
161 lineno++;
162 printf("%6u ", lineno);
163 }
164 putchar(c);
165 last_char_was_newline = c == '\n';
166 if (paging_enabled) {
167 chars_remaining--;
168 if (c == '\n' || chars_remaining == 0) {
169 chars_remaining = console_cols;
170 lines_remaining--;
171 }
172 if (lines_remaining == 0) {
173 fflush(stdout);
174 waitprompt();
175 waitkey();
176 newpage();
177 }
178 }
179}
180
181static unsigned int cat_file(const char *fname, size_t blen, bool hex,
182 off64_t head, off64_t tail, bool tail_first)
183{
184 int fd, bytes = 0, count = 0, reads = 0;
185 char *buff = NULL;
186 int i;
187 size_t offset = 0, copied_bytes = 0;
188 off64_t file_size = 0, length = 0;
189
190 bool reading_stdin = dash_represents_stdin && (str_cmp(fname, "-") == 0);
191
192 if (reading_stdin) {
193 fd = fileno(stdin);
194 /* Allow storing the whole UTF-8 character. */
195 blen = STR_BOUNDS(1);
196 } else
197 fd = open(fname, O_RDONLY);
198
199 if (fd < 0) {
200 printf("Unable to open %s\n", fname);
201 return 1;
202 }
203
204 if (NULL == (buff = (char *) malloc(blen + 1))) {
205 close(fd);
206 printf("Unable to allocate enough memory to read %s\n",
207 fname);
208 return 1;
209 }
210
211 if (tail != CAT_FULL_FILE) {
212 file_size = lseek(fd, 0, SEEK_END);
213 if (head == CAT_FULL_FILE) {
214 head = file_size;
215 length = tail;
216 } else if (tail_first) {
217 length = head;
218 } else {
219 if (tail > head)
220 tail = head;
221 length = tail;
222 }
223
224 if (tail_first) {
225 lseek(fd, (tail >= file_size) ? 0 : (file_size - tail), SEEK_SET);
226 } else {
227 lseek(fd, ((head - tail) >= file_size) ? 0 : (head - tail), SEEK_SET);
228 }
229 } else
230 length = head;
231
232 do {
233 size_t bytes_to_read;
234 if (reading_stdin) {
235 bytes_to_read = 1;
236 } else {
237 if ((length != CAT_FULL_FILE) &&
238 (length - (off64_t)count <= (off64_t)(blen - copied_bytes))) {
239 bytes_to_read = (size_t) (length - count);
240 } else {
241 bytes_to_read = blen - copied_bytes;
242 }
243 }
244
245 bytes = read(fd, buff + copied_bytes, bytes_to_read);
246 bytes += copied_bytes;
247 copied_bytes = 0;
248
249 if (bytes > 0) {
250 buff[bytes] = '\0';
251 offset = 0;
252 for (i = 0; i < bytes && !should_quit; i++) {
253 if (hex) {
254 paged_char(hexchars[((uint8_t)buff[i])/16]);
255 paged_char(hexchars[((uint8_t)buff[i])%16]);
256 paged_char(((count+i+1) & 0xf) == 0 ? '\n' : ' ');
257 }
258 else {
259 wchar_t c = str_decode(buff, &offset, bytes);
260 if (c == 0) {
261 /* Reached end of string */
262 break;
263 } else if (c == U_SPECIAL && offset + 2 >= (size_t)bytes) {
264 /* If an extended character is cut off due to the size of the buffer,
265 we will copy it over to the next buffer so it can be read correctly. */
266 copied_bytes = bytes - offset + 1;
267 memcpy(buff, buff + offset - 1, copied_bytes);
268 break;
269 }
270 paged_char(c);
271 }
272
273 }
274 count += bytes;
275 reads++;
276 }
277
278 if (reading_stdin)
279 fflush(stdout);
280 } while (bytes > 0 && !should_quit && (count < length || length == CAT_FULL_FILE));
281
282 close(fd);
283 if (bytes == -1) {
284 printf("Error reading %s\n", fname);
285 free(buff);
286 return 1;
287 }
288
289 free(buff);
290
291 return 0;
292}
293
294/* Main entry point for cat, accepts an array of arguments */
295int cmd_cat(char **argv)
296{
297 unsigned int argc, i, ret = 0;
298 size_t buffer = 0;
299 int c, opt_ind;
300 aoff64_t head = CAT_FULL_FILE, tail = CAT_FULL_FILE;
301 bool hex = false;
302 bool more = false;
303 bool tailFirst = false;
304 sysarg_t rows, cols;
305 int rc;
306
307 /*
308 * reset global state
309 * TODO: move to structure?
310 */
311 paging_enabled = false;
312 chars_remaining = 0;
313 lines_remaining = 0;
314 console_cols = 0;
315 console_rows = 0;
316 should_quit = false;
317 console = console_init(stdin, stdout);
318 number = false;
319 lineno = 0;
320 /* This enables printing of the first number. */
321 last_char_was_newline = true;
322
323
324 argc = cli_count_args(argv);
325
326 for (c = 0, optind = 0, opt_ind = 0; c != -1;) {
327 c = getopt_long(argc, argv, "xhvmH:t:b:s:n", long_options, &opt_ind);
328 switch (c) {
329 case 'h':
330 help_cmd_cat(HELP_LONG);
331 return CMD_SUCCESS;
332 case 'v':
333 printf("%s\n", CAT_VERSION);
334 return CMD_SUCCESS;
335 case 'H':
336 if (!optarg || str_uint64_t(optarg, NULL, 10, false, &head) != EOK ) {
337 puts("Invalid head size\n");
338 return CMD_FAILURE;
339 }
340 break;
341 case 't':
342 if (!optarg || str_uint64_t(optarg, NULL, 10, false, &tail) != EOK ) {
343 puts("Invalid tail size\n");
344 return CMD_FAILURE;
345 }
346 if (head == CAT_FULL_FILE)
347 tailFirst = true;
348 break;
349 case 'b':
350 if (!optarg || str_size_t(optarg, NULL, 10, false, &buffer) != EOK ) {
351 puts("Invalid buffer size\n");
352 return CMD_FAILURE;
353 }
354 break;
355 case 'm':
356 more = true;
357 break;
358 case 'x':
359 hex = true;
360 break;
361 case 's':
362 dash_represents_stdin = true;
363 break;
364 case 'n':
365 number = true;
366 break;
367 }
368 }
369
370 argc -= optind;
371
372 if (argc < 1) {
373 printf("%s - incorrect number of arguments. Try `%s --help'\n",
374 cmdname, cmdname);
375 return CMD_FAILURE;
376 }
377
378 if (buffer < 4)
379 buffer = CAT_DEFAULT_BUFLEN;
380
381 if (more) {
382 rc = console_get_size(console, &cols, &rows);
383 if (rc != EOK) {
384 printf("%s - cannot get console size\n", cmdname);
385 return CMD_FAILURE;
386 }
387 console_cols = cols;
388 console_rows = rows;
389 paging_enabled = true;
390 newpage();
391 }
392
393 for (i = optind; argv[i] != NULL && !should_quit; i++)
394 ret += cat_file(argv[i], buffer, hex, head, tail, tailFirst);
395
396 if (ret)
397 return CMD_FAILURE;
398 else
399 return CMD_SUCCESS;
400}
401
Note: See TracBrowser for help on using the repository browser.