/src/barebox/commands/readf.c
Line | Count | Source |
1 | | // SPDX-License-Identifier: GPL-2.0-only |
2 | | |
3 | | #include <common.h> |
4 | | #include <command.h> |
5 | | #include <fs.h> |
6 | | #include <libfile.h> |
7 | | #include <malloc.h> |
8 | | #include <linux/stat.h> |
9 | | #include <linux/ctype.h> |
10 | | #include <environment.h> |
11 | | |
12 | | static int do_readf(int argc, char *argv[]) |
13 | 0 | { |
14 | 0 | unsigned char *buf = NULL, *val; |
15 | 0 | char *variable, *filename; |
16 | 0 | struct stat s; |
17 | 0 | size_t size; |
18 | 0 | int ret, i; |
19 | |
|
20 | 0 | if (argc != 3) |
21 | 0 | return COMMAND_ERROR_USAGE; |
22 | | |
23 | 0 | filename = argv[1]; |
24 | 0 | variable = argv[2]; |
25 | |
|
26 | 0 | ret = stat(filename, &s); |
27 | 0 | if (ret) |
28 | 0 | goto out; |
29 | | |
30 | 0 | if (s.st_size > 1024) { |
31 | 0 | ret = -EFBIG; |
32 | 0 | goto out; |
33 | 0 | } |
34 | | |
35 | 0 | buf = read_file(filename, &size); |
36 | 0 | if (!buf) |
37 | 0 | goto out; |
38 | | |
39 | 0 | for (i = 0; i < size; i++) { |
40 | 0 | if (!isprint(buf[i])) { |
41 | 0 | buf[i] = '\0'; |
42 | 0 | break; |
43 | 0 | } |
44 | 0 | } |
45 | |
|
46 | 0 | val = strim(buf); |
47 | |
|
48 | 0 | ret = setenv(variable, val); |
49 | 0 | out: |
50 | 0 | free(buf); |
51 | |
|
52 | 0 | return ret; |
53 | 0 | } |
54 | | |
55 | | BAREBOX_CMD_HELP_START(readf) |
56 | | BAREBOX_CMD_HELP_TEXT("Read a single line from FILE into a VARiable. Leading and trailing") |
57 | | BAREBOX_CMD_HELP_TEXT("whitespaces are removed, nonvisible characters are stripped. Input is") |
58 | | BAREBOX_CMD_HELP_TEXT("limited to 1024 characters.") |
59 | | BAREBOX_CMD_HELP_END |
60 | | |
61 | | BAREBOX_CMD_START(readf) |
62 | | .cmd = do_readf, |
63 | | BAREBOX_CMD_DESC("read file into variable") |
64 | | BAREBOX_CMD_OPTS("FILE VAR") |
65 | | BAREBOX_CMD_GROUP(CMD_GRP_SCRIPT) |
66 | | BAREBOX_CMD_HELP(cmd_readf_help) |
67 | | BAREBOX_CMD_END |