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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
use super::*;
use crate::changestore::ChangeStore;
use crate::Conflict;
use std::collections::hash_map::Entry;
use std::collections::{HashMap, HashSet};

pub trait Archive {
    type File: std::io::Write;
    fn create_file(&mut self, path: &str, perm: u16) -> Self::File;
    fn close_file(&mut self, f: Self::File) -> Result<(), anyhow::Error>;
}

#[cfg(feature = "tarball")]
pub struct Tarball<W: std::io::Write> {
    pub archive: tar::Builder<flate2::write::GzEncoder<W>>,
    pub prefix: Option<String>,
    pub buffer: Vec<u8>,
}

#[cfg(feature = "tarball")]
pub struct File {
    buf: Vec<u8>,
    path: String,
    permissions: u16,
}

#[cfg(feature = "tarball")]
impl std::io::Write for File {
    fn write(&mut self, buf: &[u8]) -> Result<usize, std::io::Error> {
        self.buf.write(buf)
    }
    fn flush(&mut self) -> Result<(), std::io::Error> {
        Ok(())
    }
}

#[cfg(feature = "tarball")]
impl<W: std::io::Write> Tarball<W> {
    pub fn new(w: W, prefix: Option<String>) -> Self {
        let encoder = flate2::write::GzEncoder::new(w, flate2::Compression::best());
        Tarball {
            archive: tar::Builder::new(encoder),
            buffer: Vec::new(),
            prefix,
        }
    }
}

#[cfg(feature = "tarball")]
impl<W: std::io::Write> Archive for Tarball<W> {
    type File = File;
    fn create_file(&mut self, path: &str, permissions: u16) -> Self::File {
        self.buffer.clear();
        File {
            buf: std::mem::replace(&mut self.buffer, Vec::new()),
            path: if let Some(ref prefix) = self.prefix {
                prefix.clone() + path
            } else {
                path.to_string()
            },
            permissions,
        }
    }
    fn close_file(&mut self, file: Self::File) -> Result<(), anyhow::Error> {
        let mut header = tar::Header::new_gnu();
        header.set_path(&file.path)?;
        header.set_size(file.buf.len() as u64);
        header.set_mode(file.permissions as u32);
        header.set_cksum();
        self.archive.append(&header, &file.buf[..])?;
        self.buffer = file.buf;
        Ok(())
    }
}

pub(crate) fn archive<'a, T: TxnT, P: ChangeStore, I: Iterator<Item = &'a str>, A: Archive>(
    changes: &P,
    txn: &T,
    channel: &ChannelRef<T>,
    prefix: &mut I,
    arch: &mut A,
) -> Result<Vec<Conflict>, anyhow::Error> {
    let channel = channel.borrow();
    let mut conflicts = Vec::new();
    let mut files = HashMap::new();
    let mut next_files = HashMap::new();
    let mut next_prefix_basename = prefix.next();
    collect_children(
        txn,
        changes,
        &channel,
        Position::ROOT,
        Inode::ROOT,
        "",
        next_prefix_basename,
        &mut files,
    )?;

    let mut done = HashMap::new();
    let mut done_inodes = HashSet::new();
    while !files.is_empty() {
        debug!("files {:?}", files.len());
        next_files.clear();
        next_prefix_basename = prefix.next();

        for (a, mut b) in files.drain() {
            debug!("files: {:?} {:?}", a, b);
            b.sort_by(|u, v| {
                txn.get_changeset(&channel.changes, u.0.change, None)
                    .unwrap()
                    .cmp(
                        &txn.get_changeset(&channel.changes, v.0.change, None)
                            .unwrap(),
                    )
            });
            let mut is_first_name = true;
            for (name_key, mut output_item) in b {
                match done.entry(output_item.pos) {
                    Entry::Occupied(e) => {
                        debug!("pos already visited: {:?} {:?}", a, output_item.pos);
                        if *e.get() != name_key {
                            conflicts.push(Conflict::MultipleNames {
                                pos: output_item.pos,
                            });
                        }
                        continue;
                    }
                    Entry::Vacant(e) => {
                        e.insert(name_key);
                    }
                }
                if let Some((inode, _)) = output_item.inode {
                    if !done_inodes.insert(inode) {
                        debug!("inode already visited: {:?} {:?}", a, inode);
                        continue;
                    }
                }
                let name = if !is_first_name {
                    conflicts.push(Conflict::Name {
                        path: a.to_string(),
                    });
                    break;
                } else {
                    is_first_name = false;
                    a.clone()
                };
                let file_name = path::file_name(&name).unwrap();
                path::push(&mut output_item.path, file_name);
                let path = std::mem::replace(&mut output_item.path, String::new());
                if output_item.meta.is_dir() {
                    collect_children(
                        txn,
                        changes,
                        &channel,
                        output_item.pos,
                        Inode::ROOT, // unused
                        &path,
                        next_prefix_basename,
                        &mut next_files,
                    )?
                } else {
                    let mut l = crate::alive::retrieve(txn, &channel, output_item.pos);
                    let mut f = arch.create_file(&path, output_item.meta.permissions());
                    {
                        let mut f = crate::vertex_buffer::ConflictsWriter::new(
                            &mut f,
                            &output_item.path,
                            &mut conflicts,
                        );
                        crate::alive::output_graph(
                            changes,
                            txn,
                            &channel,
                            &mut f,
                            &mut l,
                            &mut Vec::new(),
                        )?;
                    }
                    arch.close_file(f)?;
                }
                if output_item.is_zombie {
                    conflicts.push(Conflict::ZombieFile {
                        path: name.to_string(),
                    })
                }
            }
        }
        std::mem::swap(&mut files, &mut next_files);
    }
    Ok(conflicts)
}