aboutsummaryrefslogtreecommitdiff
path: root/mkfs/block.c
blob: 73d43e804e8c9999ba41cb1495a11627a1e98985 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/* SPDX-License-Identifier: GPL-3.0-or-later */
#include "mkfs.h"
#include "util.h"

static int process_file(data_writer_t *data, file_info_t *fi)
{
	int ret, infd;

	infd = open(fi->input_file, O_RDONLY);
	if (infd < 0) {
		perror(fi->input_file);
		return -1;
	}

	ret = write_data_from_fd(data, fi, infd);

	close(infd);
	return ret;
}

static void print_name(tree_node_t *n)
{
	if (n->parent != NULL) {
		print_name(n->parent);
		fputc('/', stdout);
	}

	fputs(n->name, stdout);
}

static int find_and_process_files(data_writer_t *data, tree_node_t *n,
				  bool quiet)
{
	if (S_ISDIR(n->mode)) {
		for (n = n->data.dir->children; n != NULL; n = n->next) {
			if (find_and_process_files(data, n, quiet))
				return -1;
		}
		return 0;
	}

	if (S_ISREG(n->mode)) {
		if (!quiet) {
			fputs("packing ", stdout);
			print_name(n);
			fputc('\n', stdout);
		}

		return process_file(data, n->data.file);
	}

	return 0;
}

int write_data_to_image(data_writer_t *data, fstree_t *fs, options_t *opt)
{
	bool need_restore = false;
	const char *ptr;
	int ret;

	if (opt->packdir != NULL) {
		if (pushd(opt->packdir))
			return -1;
		need_restore = true;
	} else {
		ptr = strrchr(opt->infile, '/');

		if (ptr != NULL) {
			if (pushdn(opt->infile, ptr - opt->infile))
				return -1;

			need_restore = true;
		}
	}

	ret = find_and_process_files(data, fs->root, opt->quiet);

	ret = ret == 0 ? data_writer_flush_fragments(data) : ret;

	if (need_restore)
		ret = ret == 0 ? popd() : ret;

	return ret;
}