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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
use glob::glob;
use crate::backend::Backend;
use crate::helpers::TaskStatus;
use crate::models::{Corpus, NewCorpus, NewTask};
use std::env;
use std::error::Error;
use std::fs;
use std::path::Path;
use std::path::PathBuf;
use Archive::*;
const BUFFER_SIZE: usize = 10_240;
pub struct Importer {
pub corpus: Corpus,
pub backend: Backend,
pub cwd: PathBuf,
}
impl Default for Importer {
fn default() -> Importer {
let default_backend = Backend::default();
let name = "default";
default_backend
.add(&NewCorpus {
path: ".".to_string(),
name: name.to_string(),
complex: false,
description: String::new(),
})
.expect("Failed to create new corpus.");
let registered_corpus = Corpus::find_by_name(name, &default_backend.connection).unwrap();
Importer {
corpus: registered_corpus,
backend: default_backend,
cwd: Importer::cwd(),
}
}
}
impl Importer {
pub fn cwd() -> PathBuf { env::current_dir().unwrap() }
fn unpack(&self) -> Result<(), Box<dyn Error>> {
self.unpack_arxiv_top()?;
self.unpack_arxiv_months()?;
Ok(())
}
fn unpack_extend(&self) -> Result<(), Box<dyn Error>> {
self.unpack_extend_arxiv_top()?;
self.unpack_arxiv_months()?;
Ok(())
}
fn unpack_arxiv_top(&self) -> Result<(), Box<dyn Error>> {
println!("-- Starting top-level unpack process");
let path_str = self.corpus.path.clone();
let tars_path = path_str.to_string() + "/*.tar";
for entry in glob(&tars_path).unwrap() {
match entry {
Ok(path) => {
let archive_reader = Reader::new()
.unwrap()
.support_filter_all()
.support_format_all()
.open_filename(path.to_str().unwrap(), BUFFER_SIZE)
.unwrap();
while let Ok(e) = archive_reader.next_header() {
if e.pathname().ends_with(".pdf") {
continue;
}
let full_extract_path = path_str.to_string() + &e.pathname();
match fs::metadata(full_extract_path.clone()) {
Ok(_) => println!("File {:?} exists, won't unpack.", e.pathname()),
Err(_) => {
println!("To unpack: {:?}", full_extract_path);
match e.extract_to(&full_extract_path, Vec::new()) {
Ok(_) => {},
_ => {
println!("Failed to extract {:?}", full_extract_path);
},
}
},
}
}
},
Err(e) => println!("Failed tar glob: {:?}", e),
}
}
Ok(())
}
fn unpack_extend_arxiv_top(&self) -> Result<(), Box<dyn Error>> {
println!("-- Starting top-level unpack-extend process");
let path_str = self.corpus.path.clone();
let tars_path = path_str.to_string() + "/*.tar";
for entry in glob(&tars_path).unwrap() {
match entry {
Ok(path) => {
let archive_reader = Reader::new()
.unwrap()
.support_filter_all()
.support_format_all()
.open_filename(path.to_str().unwrap(), BUFFER_SIZE)
.unwrap();
while let Ok(e) = archive_reader.next_header() {
if e.pathname().ends_with(".pdf") {
continue;
}
let full_extract_path = path_str.to_string() + &e.pathname();
match fs::metadata(full_extract_path.clone()) {
Ok(_) => {},
Err(_) => {
let dir_extract_path = &full_extract_path[0..full_extract_path.len() - 3];
match fs::metadata(dir_extract_path) {
Ok(_) => {},
Err(_) => {
match e.extract_to(&full_extract_path, Vec::new()) {
Ok(_) => {},
_ => {
println!("Failed to extract {:?}", full_extract_path);
},
}
},
}
},
}
}
},
Err(e) => println!("Failed tar glob: {:?}", e),
}
}
Ok(())
}
fn unpack_arxiv_months(&self) -> Result<(), Box<dyn Error>> {
println!("-- Starting to unpack monthly .gz archives");
let path_str = self.corpus.path.clone();
let gzs_path = path_str + "/*/*.gz";
for entry in glob(&gzs_path).unwrap() {
match entry {
Ok(path) => {
let entry_path = path.to_str().unwrap();
let entry_dir = path.parent().unwrap().to_str().unwrap();
let base_name = path.file_stem().unwrap().to_str().unwrap();
let default_tex_target = base_name.to_string() + ".tex";
let entry_cp_dir = entry_dir.to_string() + "/" + base_name;
fs::create_dir_all(entry_cp_dir.clone()).unwrap_or_else(|reason| {
println!(
"Failed to mkdir -p {:?} because: {:?}",
entry_cp_dir.clone(),
reason.kind()
);
});
let full_extract_path = entry_cp_dir.to_string() + "/" + base_name + ".zip";
let mut archive_writer_new = Writer::new()
.unwrap()
.set_format(ArchiveFormat::Zip);
archive_writer_new
.open_filename(&full_extract_path.clone())
.unwrap();
let mut raw_read_needed = false;
match Reader::new()
.unwrap()
.support_filter_all()
.support_format_all()
.open_filename(entry_path, BUFFER_SIZE)
{
Err(_) => raw_read_needed = true,
Ok(archive_reader) => {
let mut file_count = 0;
while let Ok(e) = archive_reader.next_header() {
file_count += 1;
match archive_writer_new.write_header(e) {
Ok(_) => {},
Err(e2) => println!("Header write failed: {:?}", e2),
};
while let Ok(chunk) = archive_reader.read_data(BUFFER_SIZE) {
archive_writer_new.write_data(chunk).unwrap();
}
}
if file_count == 0 {
raw_read_needed = true;
}
},
}
if raw_read_needed {
let raw_reader_new = Reader::new()
.unwrap()
.support_filter_all()
.support_format_raw()
.open_filename(entry_path, BUFFER_SIZE);
match raw_reader_new {
Ok(raw_reader) => match raw_reader.next_header() {
Ok(_) => {
single_file_transfer(&default_tex_target, &raw_reader, &mut archive_writer_new);
},
Err(_) => println!("No content in archive: {:?}", entry_path),
},
Err(_) => println!("Unrecognizeable archive: {:?}", entry_path),
}
}
match fs::remove_file(path.clone()) {
Ok(_) => {},
Err(e) => println!("Can't remove source .gz: {:?}", e),
};
},
Err(e) => println!("Failed gz glob: {:?}", e),
}
}
Ok(())
}
pub fn walk_import(&self) -> Result<usize, Box<dyn Error>> {
println!("-- Starting import walk");
let import_extension = if self.corpus.complex { "zip" } else { "tex" };
let mut walk_q: Vec<PathBuf> = vec![Path::new(&self.corpus.path).to_owned()];
let mut import_q: Vec<NewTask> = Vec::new();
let mut import_counter = 0;
while !walk_q.is_empty() {
let current_path = walk_q.pop().unwrap();
let current_metadata = fs::metadata(current_path.clone())?;
if current_metadata.is_dir() {
println!("-- current path {:?}", current_path);
let current_local_dir = current_path.file_name().unwrap();
let current_entry =
current_local_dir.to_str().unwrap().to_string() + "." + import_extension;
let current_entry_path = current_path.to_str().unwrap().to_string() + "/" + ¤t_entry;
match fs::metadata(¤t_entry_path) {
Ok(_) => {
println!("Found entry: {:?}", current_entry_path);
import_counter += 1;
import_q.push(self.new_task(¤t_entry_path));
if import_q.len() >= 1000 {
println!("Checkpoint backend writer: job {:?}", import_counter);
self.backend.mark_imported(&import_q).unwrap();
import_q.clear();
}
},
Err(_) => {
for subentry in fs::read_dir(current_path.clone())? {
let subentry = subentry?;
walk_q.push(subentry.path());
}
},
}
}
}
if !import_q.is_empty() {
println!("Checkpoint backend writer: job {:?}", import_q.len());
self.backend.mark_imported(&import_q).unwrap();
}
println!("--- Imported {:?} entries.", import_counter);
Ok(import_counter)
}
pub fn new_task(&self, entry: &str) -> NewTask {
let abs_entry: String = if Path::new(&entry).is_relative() {
let mut new_abs = self.cwd.clone();
new_abs.push(entry);
new_abs.to_str().unwrap().to_string()
} else {
entry.to_string()
};
NewTask {
entry: abs_entry,
status: TaskStatus::NoProblem.raw(),
corpus_id: self.corpus.id,
service_id: 2,
}
}
pub fn process(&self) -> Result<(), Box<dyn Error>> {
if self.corpus.complex {
self.unpack()?;
}
self.walk_import()?;
Ok(())
}
pub fn extend_corpus(&self) -> Result<(), Box<dyn Error>> {
if self.corpus.complex {
self.unpack_extend()?;
}
for service in self
.corpus
.select_services(&self.backend.connection)
.unwrap_or_default()
.iter()
{
self.backend.mark_new_run(
&self.corpus,
service,
"cli-admin".to_string(),
"extending corpus with more entries".to_string(),
)?;
}
self.walk_import()?;
Ok(())
}
}
pub fn single_file_transfer(tex_target: &str, reader: &Reader, writer: &mut Writer) {
let mut raw_data = Vec::new();
while let Ok(chunk) = reader.read_data(BUFFER_SIZE) {
raw_data.extend(chunk.into_iter());
}
let mut ok_header = false;
match writer.write_header_new(&tex_target, raw_data.len() as i64) {
Ok(_) => {
ok_header = true;
},
Err(e) => {
println!("Couldn't write header: {:?}", e);
},
}
if ok_header {
match writer.write_data(raw_data) {
Ok(_) => {},
Err(e) => println!("Failed to write data to {:?} because {:?}", tex_target, e),
};
}
}