forked from 3dem/relion
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfilename.cpp
597 lines (530 loc) · 16.1 KB
/
filename.cpp
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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
/***************************************************************************
*
* Author: "Sjors H.W. Scheres"
* MRC Laboratory of Molecular Biology
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program 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 General Public License for more details.
*
* This complete copyright notice must be included in any revised version of the
* source code. Additional authorship citations may be added, but existing
* author citations must be preserved.
***************************************************************************/
/***************************************************************************
* Authors: Carlos Oscar S. Sorzano ([email protected])
*
*
* Unidad de Bioinformatica of Centro Nacional de Biotecnologia , CSIC
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
* 02111-1307 USA
*
* All comments concerning this program package may be sent to the
* e-mail address '[email protected]'
***************************************************************************/
#include "src/filename.h"
#include "src/funcs.h"
#include <unistd.h>
// Constructor with root, number and extension .............................
void FileName::compose(const std::string &str, long int no, const std::string &ext, int numberlength)
{
*this = (FileName) str;
if (no != -1)
{
char aux_str[numberlength+1];
std::string tmp_fileformat;
tmp_fileformat = (std::string) "%0" +
integerToString(numberlength)+
(std::string)"d";
sprintf(aux_str, tmp_fileformat.c_str(), no);
*this += aux_str;
}
if (ext != "")
*this += (std::string)"." + ext;
}
// Constructor: prefix number and filename, mainly for selfiles..
void FileName::compose(long int no , const std::string &str, int numberlength)
{
*this = (FileName) str;
if (no != -1)
{
char aux_str[numberlength+1];
std::string tmp_fileformat;
tmp_fileformat = (std::string) "%0" +
integerToString(numberlength)+
(std::string)"d@";
sprintf(aux_str, tmp_fileformat.c_str(), no);
*this = aux_str + str;
}
else
*this = str;
}
// Is in stack ............................................................
bool FileName::isInStack() const
{
return find("@") != std::string::npos;
}
// Decompose ..............................................................
void FileName::decompose(long int &no, std::string &str) const
{
size_t idx = find('@');
if(idx != std::string::npos)
{
no = textToInteger(substr(0,idx));
str = substr(idx+1,length()-idx);
}
else{
no=-1;
str = *this;
}
}
// Convert to lower case characters .........................................
FileName FileName::toLowercase() const
{
FileName result = *this;
for(unsigned int i=0;i<result.length();i++)
result[i] = tolower(result[i]);
return result;
}
// Convert to upper case characters .........................................
FileName FileName::toUppercase() const
{
FileName result = *this;
for(unsigned int i=0;i<result.length();i++)
result[i] = toupper(result[i]);
return result;
}
// Is substring present?
bool FileName::contains(const std::string& str) const
{
int point = rfind(str);
if (point > -1)
return true;
else
return false;
}
// Get substring before first instance of str
FileName FileName::beforeFirstOf(const std::string& str) const
{
int point = find(str);
if (point > -1)
return substr(0, point);
else
return *this;
}
// Get substring before last instance of str
FileName FileName::beforeLastOf(const std::string& str) const
{
int point = rfind(str);
if (point > -1)
return substr(0, point);
else
return *this;
}
// Get substring after first instance of str
FileName FileName::afterFirstOf(const std::string& str) const
{
int point = find(str);
if (point > -1)
return substr(point + 1);
else
return *this;
}
// Get substring after last instance of str
FileName FileName::afterLastOf(const std::string& str) const
{
int point = rfind(str);
if (point > -1)
return substr(point + 1);
else
return *this;
}
// Get the base name of a filename .........................................
std::string FileName::getBaseName() const
{
std::string basename = "";
std::string myname = *this;
int myindex = 0;
for (int p = myname.size() - 1; p >= 0; p--)
{
if (myname[p] == '/')
{
myindex = p + 1;
break;
}
}
for (int p = myindex; p < myname.size(); p++)
{
if (myname[p] != '.')
basename += myname[p];
else
break;
}
return basename;
}
// Get the extension of a filename .........................................
std::string FileName::getExtension() const
{
int last_point = find_last_of(".");
if (last_point == -1)
return "";
else
return substr(last_point + 1);
}
// Init random .............................................................
void FileName::initRandom(int length)
{
randomize_random_generator();
*this = "";
for (int i = 0; i < length; i++)
*this += 'a' + FLOOR(rnd_unif(0, 26));
}
// Add at beginning ........................................................
FileName FileName::addPrefix(const std::string &prefix) const
{
FileName retval = *this;
int skip_directories = find_last_of("/") + 1;
return retval.insert(skip_directories, prefix);
}
// Add at the end ..........................................................
FileName FileName::addExtension(const std::string &ext) const
{
if (ext == "")
return *this;
else
{
FileName retval = *this;
retval = retval.append((std::string)"." + ext);
return retval;
}
}
// Remove last extension ...................................................
FileName FileName::withoutExtension() const
{
FileName retval = *this;
return retval.substr(0, rfind("."));
}
// Insert before extension .................................................
FileName FileName::insertBeforeExtension(const std::string &str) const
{
return withoutExtension() + str + "." + getExtension();
}
// Remove an extension wherever it is ......................................
FileName FileName::removeExtension(const std::string &ext) const
{
int first = find((std::string)"." + ext);
if (first == -1)
return *this;
else
{
FileName retval = *this;
return retval.erase(first, 1 + ext.length());
}
}
// Remove all extensions....................................................
FileName FileName::removeAllExtensions() const
{
int first = rfind("/");
first = find(".", first + 1);
if (first == -1)
return *this;
else
return substr(0, first);
}
// Replace all substrings
void FileName::replaceAllSubstrings(std::string from, std::string to)
{
FileName result;
size_t start_pos = 0;
while((start_pos = (*this).find(from, start_pos)) != std::string::npos)
{
(*this).replace(start_pos, from.length(), to);
start_pos += to.length(); // Handles case where 'to' is a substring of 'from'
}
}
FileName FileName::getFileFormat() const
{
int first;
FileName result;
if (find("#") != std::string::npos)
return "raw";
else if ( (first = rfind(":"))!=std::string::npos)
result = substr(first + 1) ;
else if ( (first = rfind("."))!=std::string::npos)
result = substr(first + 1);
else
result="";
return result.toLowercase();
}
FileName FileName::removeFileFormat() const
{
if ( find("#", 0) > -1 )
REPORT_ERROR("Not implemented for raw data");
size_t found=rfind(":");
if (found!=std::string::npos)
return substr(0, found);
return *this;
}
bool FileName::isStarFile() const
{
//file names containing @, : or % are not metadatas
size_t found=this->find('@');
if (found!=std::string::npos)
return false;
// Allow :star to indicate that file really is a STAR file!
//found=this->find(':');
//if (found!=std::string::npos)
// return false;
found=this->find('#');
if (found!=std::string::npos)
return false;
FileName ext = getFileFormat();
if (ext=="star")
{
return true;
}
else
{
return false;
}
}
// Substitute one extension by other .......................................
FileName FileName::substituteExtension(const std::string &ext1,
const std::string &ext2) const
{
int first = find((std::string)"." + ext1);
if (first == -1)
return *this;
else
{
FileName retval = *this;
return retval.replace(first, 1 + ext1.length(), (std::string)"." + ext2);
}
}
// Remove a substring ......................................................
FileName FileName::without(const std::string &str) const
{
if (str.length() == 0)
return *this;
int pos = find(str);
if (pos == -1)
return *this;
else
{
FileName retval = *this;
return retval.erase(pos, str.length());
}
}
// Remove until prefix .....................................................
FileName FileName::removeUntilPrefix(const std::string &str) const
{
if (str.length() == 0)
return *this;
int pos = find(str);
if (pos == -1)
return *this;
else
{
FileName retval = *this;
return retval.erase(0, pos + str.length());
}
}
// Remove directories ......................................................
FileName FileName::removeDirectories(int keep) const
{
int last_slash = rfind("/");
int tokeep = keep;
while (tokeep > 0)
{
last_slash = rfind("/", last_slash - 1);
tokeep--;
}
if (last_slash == -1)
return *this;
else
return substr(last_slash + 1, length() - last_slash);
}
size_t FileName::getFileSize() const
{
struct stat filestatus;
stat( this->c_str(), &filestatus );
return filestatus.st_size;
}
int FileName::globFiles(std::vector<FileName> &files, bool do_clear) const
{
if (do_clear)
files.clear();
glob_t glob_result;
glob((*this).c_str(), GLOB_TILDE, NULL, &glob_result);
for(unsigned long int i = 0; i < glob_result.gl_pathc; ++i)
{
files.push_back(std::string(glob_result.gl_pathv[i]));
}
globfree(&glob_result);
return files.size();
}
bool FileName::getTheOtherHalf(FileName &fn_out) const
{
FileName ret = this->afterLastOf("/");
if (ret.contains("half1"))
ret.replaceAllSubstrings("half1", "half2");
else if (ret.contains("half2"))
ret.replaceAllSubstrings("half2", "half1");
else
return false;
if (this->contains("/"))
ret = this->beforeLastOf("/") + "/" + ret;
fn_out = ret;
return true;
}
bool exists(const FileName &fn)
{
struct stat buffer;
return (stat (fn.c_str(), &buffer) == 0);
}
void touch(const FileName &fn)
{
std::ofstream fh;
fh.open(fn.c_str(), std::ios::out);
if (!fh)
REPORT_ERROR( (std::string)"Filename::touch ERROR: Cannot open file: " + fn);
fh.close();
}
void copy(const FileName &fn_src, const FileName &fn_dest)
{
std::ifstream srce( fn_src.c_str(), std::ios::binary ) ;
std::ofstream dest( fn_dest.c_str(), std::ios::binary ) ;
dest << srce.rdbuf() ;
}
int mktree(const FileName &fn_dir, mode_t mode)
{
std::string s = fn_dir;
size_t pre=0,pos;
std::string dir;
int mdret;
// force trailing / so we can handle everything in loop
if(s[s.size()-1]!='/')
s+='/';
while((pos=s.find_first_of('/',pre))!=std::string::npos)
{
dir=s.substr(0,pos++);
pre=pos;
// if leading / first time is 0 length
if (dir.size() == 0)
continue;
if ((mdret = mkdir(dir.c_str(), mode)) && errno != EEXIST)
{
return mdret;
}
}
return mdret;
}
bool decomposePipelineFileName(FileName fn_in, FileName &fn_pre, FileName &fn_jobnr, FileName &fn_post)
{
size_t slashpos = 0;
int i = 0;
while (slashpos < fn_in.length())
{
i++;
slashpos = fn_in.find("/", slashpos+1);
if (fn_in[slashpos+1]=='j' && fn_in[slashpos+2]=='o' && fn_in[slashpos+3]=='b' &&
std::isdigit(fn_in[slashpos+4]) && std::isdigit(fn_in[slashpos+5]) && std::isdigit(fn_in[slashpos+6]))
{
// find the second slash
size_t slashpos2 = fn_in.find("/", slashpos+6);
if (slashpos2 == std::string::npos)
slashpos2 = fn_in.length() - 1;
fn_pre = fn_in.substr(0, slashpos+1); // this has the first slash
fn_jobnr = fn_in.substr(slashpos+1, slashpos2-slashpos); // this has the second slash
fn_post = fn_in.substr(slashpos2+1); // this has the rest
return true;
}
if (i>20)
REPORT_ERROR("decomposePipelineFileName: BUG or found more than 20 directories deep structure for pipeline filename: " + fn_in);
}
// This was not a pipeline filename
fn_pre="";
fn_jobnr="";
fn_post=fn_in;
return false;
}
bool decomposePipelineSymlinkName(FileName fn_in, FileName &fn_pre, FileName &fn_jobnr, FileName &fn_post)
{
bool dont_expand = false;
// Symlinks are always in the second directory. (e.g. Refine3D/JOB_ALIAS_AS_LINK/...)
size_t slashpos = 0;
int i = 0;
while (slashpos < fn_in.length())
{
i++;
slashpos = fn_in.find("/", slashpos+1);
if (i==2)
break;
}
// We ignore links in the first directory (link/XXX)
if (i != 2)
dont_expand = true;
FileName second_dir = fn_in.substr(0, slashpos);
// std::cout << second_dir << std::endl;
// We also ignore jobXXX even if it is a symbolic link.
// e.g. MotionCorr/job003 ==> /path/to/online_processing/MotionCorr/job003
// This is safe because we don't allow an alias name to start from 'job'.
if (second_dir.afterLastOf("/").substr(0, 3) == "job")
dont_expand = true;
// Check whether this is a symbol link
char linkname[4096];
ssize_t len_max = sizeof(linkname) - 1;
ssize_t len = ::readlink(second_dir.c_str(), linkname, len_max);
if (len == len_max)
REPORT_ERROR("Too long path in decomposePipelineSymlinkName.");
if (!dont_expand && len != -1)
{
// This is a symbolic link!
if (linkname[len - 1] == '/')
linkname[len - 1] = '\0'; // remove trailing '/'
linkname[len] = '\0';
FileName fn_link = std::string(linkname);
// TODO: FIXME: This condition is still not perfect. For example,
// Micrograph/mic001.mrc -> ../../../storage/mic001.mrc breaks the code.
// Meanwhile one can circumvent this case by using an absolute path in the symlink.
if (fn_link.substr(0, 3) == "../")
{
fn_link = fn_link.substr(3) + fn_in.substr(slashpos);
// std::cout << "fn_link=" << fn_link << std::endl;
return decomposePipelineFileName(fn_link, fn_pre, fn_jobnr, fn_post);
}
else
{
fn_pre = fn_jobnr = "";
fn_post = fn_in;
return false;
}
}
// If it is not a symlink, just decompose the filename
return decomposePipelineFileName(fn_in, fn_pre, fn_jobnr, fn_post);
}
FileName getOutputFileWithNewUniqueDate(FileName fn_input, FileName fn_new_outputdir)
{
FileName fn_pre, fn_jobnr, fn_post;
decomposePipelineFileName(fn_input, fn_pre, fn_jobnr, fn_post);
return fn_new_outputdir + fn_post;
}