forked from tat/mimetic
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuildidx.cxx
122 lines (109 loc) · 2.88 KB
/
buildidx.cxx
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
/***************************************************************************
copyright : (C) 2002-2008 by Stefano Barbato
email : [email protected]
$Id: buildidx.cxx,v 1.3 2008-10-07 11:06:25 tat Exp $
***************************************************************************/
/** \example buildidx.cc
* extract a Part based on command line parameters
* more info on:
* buildidx -h
*/
#include <iostream>
#include <sstream>
#include <iterator>
#include <fstream>
#include <cassert>
#include <sys/types.h>
#include <dirent.h>
#include <mimetic/mimetic.h>
using namespace std;
using namespace mimetic;
unsigned int g_indexed = 0;
void usage()
{
cout << "buildidx [file|dir...]" << endl;
exit(-1);
}
void die(bool b, const string& msg)
{
if(b)
{
cerr << "Error: " << msg << endl << endl;
usage();
}
}
void indexFile(MimeEntity& head, const string& fqn)
{
File in(fqn);
if(in)
{
MimeEntity* pMe = new MimeEntity;
pMe->load(in.begin(), in.end(), ~imHeader);
pMe->header().push_back(Field("X-Filename",fqn));
head.body().parts().push_back(pMe);
cerr << "." << flush;
g_indexed++;
} else
cerr << "ERR: unable to open file " << fqn << endl;
}
void indexDirectory(MimeEntity& head, const string& dirFqn)
{
DIR* dir = opendir(dirFqn.c_str());
if(dir == 0)
{
cerr << "ERR: unable to read from " << dirFqn << endl;
return;
}
struct dirent* item;
struct stat st;
string ffqn;
while(0 != (item = readdir(dir)))
{
ffqn = dirFqn + "/" + item->d_name;
memset(&st,0,sizeof(struct stat));
if(stat(ffqn.c_str(),&st) == -1)
{
cerr << "ERR: unable to stat " << item->d_name<< endl;
return;
}
if(S_ISREG(st.st_mode) && item->d_name[0] != '.') // reg file
{
indexFile(head, ffqn);
}
}
closedir(dir);
}
void indexItem(MimeEntity& head, const string& item)
{
struct stat st;
if(stat(item.c_str(), &st) == -1)
{
cerr << "ERR: unable to stat " << item.c_str() << endl;
return;
}
if(S_ISREG(st.st_mode))
indexFile(head, item);
else if (S_ISDIR(st.st_mode))
indexDirectory(head, item);
else
cerr << "ERR: unknown file type " << item << endl;
}
int main(int argc, char** argv)
{
std::ios_base::sync_with_stdio(false);
if(argc > 1 && string(argv[1]) == "-h")
usage();
MultipartMixed head;
string fqn;
if(argc == 1) {
// read filenames from stdin
while(getline(cin, fqn))
indexItem(head, fqn);
} else {
for(int fc = 1; fc < argc; ++fc)
indexItem(head, argv[fc]);
}
cout << head << endl;
cerr << "index of " << g_indexed << " file(s) built" << endl;
return g_indexed;
}