2 #include <msp/core/application.h>
3 #include <msp/core/getopt.h>
4 #include <msp/fs/dir.h>
5 #include <msp/fs/stat.h>
6 #include <msp/fs/utils.h>
7 #include <msp/io/file.h>
8 #include <msp/io/print.h>
9 #include <msp/strings/format.h>
14 class SyncDir: public RegisteredApplication<SyncDir>
21 SyncDir(int, char **);
25 void sync_directory(const FS::Path &, const FS::Path &);
26 void copy_file(const FS::Path &, const FS::Path &);
29 SyncDir::SyncDir(int argc, char **argv)
32 throw usage_error("Missing arguments", format("Usage: %s <source> <destination>", argv[0]));
35 destination = argv[2];
40 sync_directory(source, destination);
44 void SyncDir::sync_directory(const FS::Path &src, const FS::Path &dest)
46 IO::print("Syncing %s to %s\n", src, dest);
48 FS::Stat st = FS::stat(dest);
50 FS::mkpath(dest, 0755);
51 else if(!st.is_directory())
54 FS::mkdir(dest, 0755);
57 vector<string> src_files = FS::list_files(src);
58 for(const string &fn: src_files)
60 FS::Stat ss = FS::stat(src/fn);
62 sync_directory(src/fn, dest/fn);
65 FS::Stat ds = FS::stat(dest/fn);
66 if(!ds || ds.get_size()!=ss.get_size())
67 copy_file(src/fn, dest/fn);
71 for(const string &fn: FS::list_files(dest))
72 if(find(src_files.begin(), src_files.end(), fn)==src_files.end())
74 IO::print("Removing obsolete %s\n", dest/fn);
75 if(FS::is_dir(dest/fn))
82 void SyncDir::copy_file(const FS::Path &src, const FS::Path &dest)
84 IO::File in(src.str(), IO::M_READ);
85 IO::File out(dest.str(), IO::M_WRITE);
89 unsigned len = in.read(buf, sizeof(buf));