~aleteoryx/muditaos

ref: e46cb3e1a7b2d7d7854bc9e31b3da125488c8d90 muditaos/module-utils/tar/include/tar/tar.hpp -rw-r--r-- 1.9 KiB
e46cb3e1 — Lefucjusz [BH-1888] Fix device freezing when changing volume intensively 1 year, 9 months ago
                                                                                
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
// Copyright (c) 2017-2022, Mudita Sp. z.o.o. All rights reserved.
// For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md

#pragma once

#include <filesystem>
#include <optional>
#include <vector>

#include <microtar.hpp>

namespace tar
{
    class entry
    {
      public:
        ~entry();

        std::size_t size() const;
        std::filesystem::path name() const;
        bool is_file() const;
        bool is_directory() const;

        void read(const std::byte *data, std::size_t size) const;

      private:
        explicit entry(const std::filesystem::path &path);
        friend class iterator;
        mutable mtar_t handle{};
        mtar_header_t tar_header;
    };

    class iterator
    {
      public:
        using iterator_category = std::input_iterator_tag;
        using difference_type   = std::ptrdiff_t;
        using value_type        = entry;
        using pointer           = entry *;
        using reference         = entry &;

        iterator() = default;

        explicit iterator(const std::filesystem::path &path);

        reference operator*() const;
        pointer operator->() const;

        iterator &operator++();
        iterator operator++(int);

        friend bool operator==(const iterator &a, const iterator &b);
        friend bool operator!=(const iterator &a, const iterator &b);

      private:
        std::shared_ptr<entry> entry_;
    };

    /** @brief Enable range-based `for` using iterator.
     *
     *  e.g. `for (const auto& entry : tar::iterator("<tar_name>")) ...`
     */
    inline iterator begin(const iterator &it) noexcept
    {
        return it;
    }

    inline iterator end(iterator) noexcept
    {
        return iterator{};
    }

    /**
     * Unpack contents of tar file
     * @param path path to a tar file
     * @param where where to store contents of a tar file
     */
    void unpack(const std::filesystem::path &path, const std::filesystem::path &where = {});
} // namespace tar