1
+ use lmdb_rs as lmdb;
2
+ use lmdb:: { DbFlags , DbHandle , Environment } ;
3
+ use serde:: { Deserialize , Serialize } ;
4
+ use std:: collections:: HashSet ;
5
+
6
+ #[ derive( Serialize , Deserialize , Debug , Clone , PartialEq , Eq ) ]
7
+ struct Commit {
8
+ pub id : String ,
9
+ parent_ids : HashSet < String > ,
10
+ message : String ,
11
+ }
12
+
13
+ struct Repository {
14
+ env : Environment ,
15
+ commits_db : DbHandle ,
16
+ }
17
+
18
+ impl Repository {
19
+
20
+ fn new ( path : & str , db : & str ) -> Self {
21
+ const USER_DIR : u32 = 0o777 ;
22
+ let env = Environment :: new ( )
23
+ . max_dbs ( 5 )
24
+ . open ( path, USER_DIR )
25
+ . expect ( "Failed to open the environment" ) ;
26
+
27
+ let commits_db = env
28
+ . create_db ( db, DbFlags :: empty ( ) )
29
+ . expect ( "Failed to create the commits database" ) ;
30
+
31
+ Repository { env, commits_db }
32
+ }
33
+
34
+ fn add_commit ( & mut self , commit : & Commit ) {
35
+ // let db = self.env.get_default_db(DbFlags::empty()).unwrap();
36
+ let txn = self . env . new_transaction ( ) . unwrap ( ) ;
37
+ let db = txn. bind ( & self . commits_db ) ;
38
+
39
+ let _ = db. set ( & commit. id , & serde_json:: to_string ( & commit) . unwrap ( ) ) ;
40
+ println ! ( "Get From DB: {}" , db. get:: <& str >( & commit. id) . unwrap( ) ) ;
41
+ }
42
+
43
+ // other methods
44
+ }
45
+
46
+ #[ cfg( test) ]
47
+ mod tests {
48
+
49
+ use super :: * ;
50
+
51
+ #[ test]
52
+ fn submit_to_repo ( ) {
53
+ let mut repo = Repository :: new ( "./db" , "commit" ) ;
54
+
55
+ let commit1 = Commit {
56
+ id : "commit1" . to_string ( ) ,
57
+ parent_ids : HashSet :: new ( ) ,
58
+ message : "Initial commit" . to_string ( ) ,
59
+ } ;
60
+ repo. add_commit ( & commit1) ;
61
+
62
+ let commit2 = Commit {
63
+ id : "commit2" . to_string ( ) ,
64
+ parent_ids : vec ! [ "commit1" . to_string( ) ] . into_iter ( ) . collect ( ) ,
65
+ message : "Add feature X" . to_string ( ) ,
66
+ } ;
67
+ repo. add_commit ( & commit2) ;
68
+
69
+ let commit3 = Commit {
70
+ id : "commit3" . to_string ( ) ,
71
+ parent_ids : vec ! [ "commit1" . to_string( ) ] . into_iter ( ) . collect ( ) ,
72
+ message : "Add feature Y" . to_string ( ) ,
73
+ } ;
74
+ repo. add_commit ( & commit3) ;
75
+
76
+ let commit4 = Commit {
77
+ id : "commit4" . to_string ( ) ,
78
+ parent_ids : vec ! [ "commit2" . to_string( ) , "commit3" . to_string( ) ]
79
+ . into_iter ( )
80
+ . collect ( ) ,
81
+ message : "Merge feature X and Y" . to_string ( ) ,
82
+ } ;
83
+ repo. add_commit ( & commit4) ;
84
+ }
85
+ }
0 commit comments