It now reads both stdin and the database
[backups/.git] / main.cc
1 #include <iostream>
2 #include <iterator>
3 #include <vector>
4 #include <algorithm>
5
6 #include <sqlite3.h>
7
8 #include "filedata.hpp"
9
10 using namespace std;
11
12 vector<string> split( const string &line, char c, int limit = -1 ) {
13   string::size_type start = 0, end = 0;
14
15   vector<string> out;
16   while( 0 != limit-- && end != line.size() ) {
17     if( 0 == limit ) {
18       end = line.size();
19     } else {
20       end = line.find( c, start );
21       if( end == string::npos ) {
22         end = line.size();
23       }
24     }
25     out.push_back( line.substr( start, end-start ) );
26     start = end + 1;
27   }
28   return out;
29 }
30
31 int populate_set( void *files_v, int, char **vals, char ** ) {
32   file_set *files = reinterpret_cast<file_set*>( files_v );
33   files->insert( new FileData( vals[0][0],
34         vals[1],
35         vals[2],
36         vals[3],
37         atoi( vals[4] ),
38         atoi( vals[5] ),
39         vals[6]) );
40   return 0;
41 }
42
43 int main() {
44   string file_string;
45
46   file_set current_files;
47
48   // Parse the list of files on stdin
49   do {
50     file_string.clear();
51     for( int c = cin.get(); 0 != c && ! cin.eof(); c = cin.get() ) {
52       file_string.push_back( c );
53     }
54     if( 0 != file_string.size() ) {
55       // Example entry
56       // type perms user group size datemodified name (7 total)
57       // f 0600 cnb cnb 424 20051015205340 ./.git/index
58       vector<string> vals = split( file_string, ' ', 7 );
59       current_files.insert( new FileData( vals[0][0],
60             vals[1],
61             vals[2],
62             vals[3],
63             atoi( vals[4].c_str() ),
64             atoi( vals[5].c_str() ),
65             vals[6]) );
66     }
67   } while( ! cin.eof() );
68
69   // Get the list of previously backed up files from the database.
70   sqlite3 *db;
71
72   const char *dbname = "test.db";
73   int rc = sqlite3_open( dbname, &db );
74   if( SQLITE_OK != rc ) {
75     cerr << "Cannot open database: " << dbname << ".  Error message is..." << endl;
76     cerr << sqlite3_errmsg(db) << endl;
77   }
78
79   char *sqliteErrMsg = 0;
80   file_set previous_files;
81   rc = sqlite3_exec( db, "select * from filedata;", populate_set, &previous_files, &sqliteErrMsg );
82   if( SQLITE_OK != rc ) {
83     cerr << "Problem with database.  Message is..." << endl;
84     cerr << sqliteErrMsg << endl;
85   }
86
87   sqlite3_close( db );
88
89   for( file_set::iterator i = previous_files.begin(); i != previous_files.end(); ++i ) {
90     cout << (*i)->getFileName() << endl;
91   }
92 }