forked from zproksi/bpatch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprocessing.cpp
269 lines (231 loc) · 8.17 KB
/
processing.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
#include "stdafx.h"
#include "actionscollection.h"
#include "binarylexeme.h"
#include "bpatchfolders.h"
#include "consoleparametersreader.h"
#include "fileprocessing.h"
#include "processing.h"
#include "timemeasurer.h"
#include "wildcharacters.h"
namespace bpatch
{
using namespace std;
namespace
{
struct ProcessingInfo
{
string_view file_source = "";
string_view file_target = "";
string_view file_actions = "";
bool overwrite = false;
};
struct FileProcessingInfo
{
unique_ptr<ActionsCollection>& todo;
string& src;
string& dst;
const bool overwrite;
size_t readed;
size_t written;
};
};
unique_ptr<ActionsCollection> CreateActionsFile(string_view actionsFileName)
{
vector<char> adata;
if (!ReadFullFile(adata, actionsFileName.data(), FolderActions()))
{
throw logic_error("Failed to read Actions file as one chunk.");
}
// Parsing of todo and lexemes
// Dictionary will be inside
return unique_ptr<ActionsCollection>(new ActionsCollection(move(adata)));
}
/// <summary>
/// Setup processing chain for ActionsCollection with Writer
/// Using Reader to read data and send data to Actions collection
/// </summary>
/// <param name="todo">Processing engine - actions collections</param>
/// <param name="pReader">reading of data from file</param>
/// <param name="pWriter">writing data to file</param>
void DoReadReplaceWrite(unique_ptr<ActionsCollection>& todo, Reader* const pReader, Writer* const pWriter)
{
using namespace std;
// setup chain to write the data
todo->SetNextReplacer(StreamReplacer::ReplacerLastInChain(pWriter));
// hold vector where we are reading data.
// no new allocations
vector<char> adata(static_cast<vector<char>::size_type>(SZBUFF_FC));
const span dataHolder(adata.data(), SZBUFF_FC);
do
{
auto fullSpan = pReader->ReadData(dataHolder);
ranges::for_each(fullSpan, [&todo](const char c) {todo->DoReplacements(c, false); });
} while (!pReader->FileReaded());
todo->DoReplacements('e', true); // only 'true' as sign of data end is important here
}
/// <summary>
/// Deside if the file will be processed inplace or as source + target
/// Creates Reader and Writer. And proceed futher to DoReadReplaceWrite
/// </summary>
/// <param name="jobInfo">description of the files pair and todo object</param>
/// <returns>true if actual processing happend</returns>
bool ProcessTheFile(FileProcessingInfo& jobInfo)
{
using namespace std;
/// --------------------------------------------------------
/// if source and target file are the same
/// -- processing inplace --
///
if (0 == jobInfo.src.compare(jobInfo.dst))
{
{
ReadWriteFileProcessing rwProcessing(jobInfo.src.c_str());
DoReadReplaceWrite(jobInfo.todo, &rwProcessing, &rwProcessing);
jobInfo.written = rwProcessing.Written();
jobInfo.readed = rwProcessing.Readed();
} // close file
// set file size
// because we can write less than read
filesystem::resize_file(jobInfo.src.c_str(), jobInfo.written);
return true; // inplace processing has been done
}
/// -------------------------------------------------------
/// source and target are different files
/// -- processing reading and writing in different files --
///
error_code ec;
if (!jobInfo.overwrite &&
filesystem::exists(jobInfo.dst, ec))
{ // check override possibility
cout << coloredconsole::toconsole("Warning: Target file '") << jobInfo.dst << "' exists. "
"Use /w instead of /t to overwrite.\n Processing skipped\n";
jobInfo.written = 0;
jobInfo.readed = 0;
return false;
}
ReadFileProcessing reader(jobInfo.src.c_str());
WriteFileProcessing writer(jobInfo.dst.c_str());
DoReadReplaceWrite(jobInfo.todo, &reader, &writer);
// we do not resize file here because we have opened/created file only for writing
jobInfo.written = writer.Written();
jobInfo.readed = reader.Readed();
return true;
}
/// <summary>
/// Wild charactes processing level.
/// ActionsCollection will be created here
/// By Mask - means file masked by either '?' or '*' or both in any combination
/// jobInfo provides result names
/// </summary>
/// <param name="jobInfo">parameters from command string</param>
/// <returns>true; or throws</returns>
bool ProcessFilesByMask(ProcessingInfo& jobInfo)
{
using namespace std;
cout << "Actions file: '" << jobInfo.file_actions << "'\n";
/// --------------------------------------------------------
/// load Actions and initialize processing class
/// Json parsing is inside
unique_ptr<ActionsCollection> todo = CreateActionsFile(jobInfo.file_actions);
// look up logic for files
wildcharacters::LookUp lookupMasks; // masked files from command line
lookupMasks.RegisterSourceAndDestination(jobInfo.file_source, jobInfo.file_target);
string srcFilename; // source file name
string dstFilename; // destination file name
size_t filesProcessed = 0;
FileProcessingInfo fileInfo{.todo = todo, .src = srcFilename, .dst = dstFilename, .overwrite = jobInfo.overwrite};
while (lookupMasks.NextFilenamesPair(srcFilename, dstFilename)) // request file names
{
cout << "Source file: '" << fileInfo.src << "'\n";
cout << "Target file: '" << fileInfo.dst << "'\n";
if (bpatch::ProcessTheFile(fileInfo))
{
++filesProcessed;
}
cout << "Readed (bytes): '" << fileInfo.readed << "'\n";
cout << "Written (bytes): '" << fileInfo.written << "'\n";
cout << "\n";
};
cout << "Files processed: '" << filesProcessed << "'\n";
return true;
}
namespace
{
bpatch::ConsoleParametersReader parametersReader;
};
/// <summary>
/// Entry point of library
/// All exceptions handling must be only here
/// </summary>
bool Processing(int argc, char* argv[])
{
using namespace coloredconsole;
TimeMeasurer fulltime("Processing took");
if (!parametersReader.ReadConsoleParameters(argc, argv))
{
cout << parametersReader.Manual();
return false;
}
int retValue = false;
try
{
cout << "\n";
cout << "Executable: '" << argv[0] << "'\n";
cout << "Current folder: '" << filesystem::current_path() << "'\n";
cout << "Actions folder: '" << FolderActions() << "'\n";
cout << "Binary data folder: '" << FolderBinaryPatterns() << "'\n";
ProcessingInfo jobInfo{
.file_source = parametersReader.Source(),
.file_target = parametersReader.Target(),
.file_actions = parametersReader.Actions(),
.overwrite = parametersReader.Overwrite()
};
retValue = bpatch::ProcessFilesByMask(jobInfo);
}
catch (filesystem::filesystem_error const& ex)
{
cerr << toconsole("file system ERROR: ") << ex.what() << '\n'
<< "path1: " << ex.path1() << '\n'
<< "path2: " << ex.path2() << '\n'
<< "value: " << ex.code().value() << '\n'
<< "message: " << ex.code().message() << '\n'
<< "category: " << ex.code().category().name() << '\n';
}
catch (range_error& rExc) // must be before runtime_error
{
cerr << toconsole("range ERROR: \"")
<< rExc.what()
<< "\""
<< endl;
}
catch (runtime_error& rExc)
{
cerr << toconsole("runtime ERROR: \"")
<< rExc.what()
<< "\""
<< endl;
}
catch (out_of_range& rExc) // must be before logic_error
{
cerr << toconsole("out of range ERROR: \"")
<< rExc.what()
<< "\""
<< endl;
}
catch (logic_error& rExc)
{
cerr << toconsole("logic ERROR: \"")
<< rExc.what()
<< "\""
<< endl;
}
catch (exception& rExc)
{
cerr << toconsole("ERROR: \"")
<< rExc.what()
<< "\""
<< endl;
}
return retValue;
}
}; // namespace bpatch