summaryrefslogtreecommitdiffstats
path: root/lib/core/libimagstore/src/file_abstraction/stdio/out.rs
blob: c8540b33689fb84e240c766c30d07bf0e3f6789f (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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
//
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; version
// 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
//

//! A StdIoFileAbstraction which does not read from stdin.

use std::rc::Rc;
use std::cell::RefCell;
use std::collections::HashMap;
use std::fmt::Debug;
use std::fmt::Error as FmtError;
use std::fmt::Formatter;
use std::io::Write;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::Mutex;
use std::ops::Deref;

use libimagerror::trace::*;

use error::StoreErrorKind as SEK;
use error::StoreError as SE;
use super::FileAbstraction;
use super::FileAbstractionInstance;
use super::Drain;
use super::InMemoryFileAbstraction;
use store::Entry;
use file_abstraction::iter::PathIterator;

use super::mapper::Mapper;

// Because this is not exported in super::inmemory;
type Backend = Arc<Mutex<RefCell<HashMap<PathBuf, Entry>>>>;

pub struct StdoutFileAbstraction<W: Write, M: Mapper> {
    mapper: M,
    mem: InMemoryFileAbstraction,
    out: Rc<RefCell<W>>,
}

impl<W, M> StdoutFileAbstraction<W, M>
    where M: Mapper,
          W: Write
{

    pub fn new(out_stream: Rc<RefCell<W>>, mapper: M) -> Result<StdoutFileAbstraction<W, M>, SE> {
        Ok(StdoutFileAbstraction {
            mapper: mapper,
            mem:    InMemoryFileAbstraction::new(),
            out:    out_stream,
        })
    }

    pub fn backend(&self) -> &Backend {
        self.mem.backend()
    }

    fn backend_cloned(&self) -> Result<HashMap<PathBuf, Entry>, SE> {
        self.mem
            .backend()
            .lock()
            .map_err(|_| SE::from_kind(SEK::LockError))
            .map(|mtx| mtx.deref().borrow().clone())
    }

    pub fn mapper(&self) -> &M {
        &self.mapper
    }

}

impl<W, M> Debug for StdoutFileAbstraction<W, M>
    where M: Mapper,
          W: Write
{
    fn fmt(&self, f: &mut Formatter) -> Result<(), FmtError> {
        write!(f, "StdoutFileAbstraction({:?}", self.mem)
    }
}

impl<W, M> Drop for StdoutFileAbstraction<W, M>
    where M: Mapper,
          W: Write
{
    fn drop(&mut self) {
        use std::ops::DerefMut;

        let fill_res = match self.mem.backend().lock() {
            Err(_) => Err(SE::from_kind(SEK::LockError)),
            Ok(mut mtx) => {
                self.mapper.fs_to_write(mtx.get_mut(), self.out.borrow_mut().deref_mut())
            },
        };

        // We can do nothing but end this here with a trace.
        // As this drop gets called when imag almost exits, there is no point in exit()ing here
        // again.
        let _ = fill_res.map_err_trace();
    }
}

impl<W: Write, M: Mapper> FileAbstraction for StdoutFileAbstraction<W, M> {

    fn remove_file(&self, path: &PathBuf) -> Result<(), SE> {
        self.mem.remove_file(path)
    }

    fn copy(&self, from: &PathBuf, to: &PathBuf) -> Result<(), SE> {
        self.mem.copy(from, to)
    }

    fn rename(&self, from: &PathBuf, to: &PathBuf) -> Result<(), SE> {
        self.mem.rename(from, to)
    }

    fn create_dir_all(&self, pb: &PathBuf) -> Result<(), SE> {
        self.mem.create_dir_all(pb)
    }

    fn new_instance(&self, p: PathBuf) -> Box<FileAbstractionInstance> {
        self.mem.new_instance(p)
    }

    fn exists(&self, p: &PathBuf) -> Result<bool, SE> {
        self.mem.exists(p)
    }

    fn is_file(&self, p: &PathBuf) -> Result<bool, SE> {
        self.mem.is_file(p)
    }

    fn drain(&self) -> Result<Drain, SE> {
        self.backend_cloned().map(Drain::new)
    }

    fn fill(&mut self, mut d: Drain) -> Result<(), SE> {
        debug!("Draining into : {:?}", self);
        let mut mtx = try!(self.backend().lock().map_err(|_| SE::from_kind(SEK::IoError)));
        let backend = mtx.get_mut();

        for (path, element) in d.iter() {
            debug!("Drain into {:?}: {:?}", self, path);
            backend.insert(path, element);
        }
        Ok(())
    }

    fn pathes_recursively(&self, basepath: PathBuf) -> Result<PathIterator, SE> {
        self.mem.pathes_recursively(basepath)
    }

}