2020#include " version.hh"
2121
2222#include < boost/algorithm/string/replace.hpp>
23+ #include < boost/filesystem.hpp>
2324#include < boost/foreach.hpp>
2425#include < boost/program_options.hpp>
2526#include < boost/regex.hpp>
2627#include < boost/tokenizer.hpp>
2728
2829#include < cctype>
30+ #include < fstream>
2931#include < iostream>
3032
3133typedef std::vector<std::string> TStringList;
@@ -243,6 +245,30 @@ bool DockerFileTransformer::transform(std::istream &in, std::ostream &out)
243245 return !anyError;
244246}
245247
248+ bool transformInPlace (DockerFileTransformer &dft, const std::string &fileName)
249+ {
250+ using namespace boost ::filesystem;
251+
252+ // open input file and temporary output file
253+ std::fstream fin (fileName, std::ios::in);
254+ path tmpFileName = unique_path ();
255+ std::fstream fout (tmpFileName.native (), std::ios::out);
256+
257+ // transform fin -> fout and close the streams
258+ const bool ok = dft.transform (fin, fout);
259+ fin.close ();
260+ fout.close ();
261+
262+ if (ok)
263+ // rewrite input file by the temporary file
264+ rename (tmpFileName, fileName);
265+ else
266+ // something failed, drop the temporary file
267+ remove (tmpFileName);
268+
269+ return ok;
270+ }
271+
246272int main (int argc, char *argv[])
247273{
248274 // used also in diagnostic messages
@@ -251,10 +277,12 @@ int main(int argc, char *argv[])
251277 namespace po = boost::program_options;
252278 po::variables_map vm;
253279 po::options_description desc (std::string (" Usage: " ) + prog_name
254- + " [--verbose] cmd [arg1 [arg2 [...]]]" );
280+ + " [--in-place Dockerfile] [-- verbose] cmd [arg1 [arg2 [...]]]" );
255281
256282 try {
257283 desc.add_options ()
284+ (" in-place,i" , po::value<std::string>(),
285+ " modify the specified file in-place" )
258286 (" verbose" , " print transformations to standard error output" );
259287
260288 desc.add_options ()
@@ -308,6 +336,10 @@ int main(int argc, char *argv[])
308336 // pass cmd-line args to DockerFileTransformer
309337 DockerFileTransformer dft (prefixCmd, verbose);
310338
339+ if (vm.count (" in-place" ))
340+ // transform Dockerfile in-place
341+ return !transformInPlace (dft, vm[" in-place" ].as <std::string>());
342+
311343 // transform Dockerfile on stdin and write to stdout
312344 return !dft.transform (std::cin, std::cout);
313345}
0 commit comments