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
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
//
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; version
// 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
//

use std::collections::HashMap;
use std::collections::BTreeMap;
use std::ops::Drop;
use std::path::PathBuf;
use std::result::Result as RResult;
use std::sync::Arc;
use std::sync::RwLock;
use std::io::Read;
use std::ops::Deref;
use std::ops::DerefMut;
use std::fmt::Formatter;
use std::fmt::Debug;
use std::fmt::Error as FMTError;

use toml::Value;
use toml::value::Table;
use glob::glob;
use walkdir::WalkDir;
use walkdir::Iter as WalkDirIter;

use error::{StoreError as SE, StoreErrorKind as SEK};
use error::ResultExt;
use storeid::{IntoStoreId, StoreId, StoreIdIterator};
use file_abstraction::FileAbstractionInstance;

// We re-export the following things so tests can use them
pub use file_abstraction::FileAbstraction;
pub use file_abstraction::FSFileAbstraction;
pub use file_abstraction::InMemoryFileAbstraction;

use libimagerror::trace::trace_error;
use libimagutil::debug_result::*;

use self::glob_store_iter::*;

/// The Result Type returned by any interaction with the store that could fail
pub type Result<T> = RResult<T, SE>;


#[derive(Debug, PartialEq)]
enum StoreEntryStatus {
    Present,
    Borrowed
}

/// A store entry, depending on the option type it is either borrowed currently
/// or not.
#[derive(Debug)]
struct StoreEntry {
    id: StoreId,
    file: Box<FileAbstractionInstance>,
    status: StoreEntryStatus,
}

pub enum StoreObject {
    Id(StoreId),
    Collection(PathBuf),
}

pub struct Walk {
    store_path: PathBuf,
    dirwalker: WalkDirIter,
}

impl Walk {

    fn new(mut store_path: PathBuf, mod_name: &str) -> Walk {
        let pb = store_path.clone();
        store_path.push(mod_name);
        Walk {
            store_path: pb,
            dirwalker: WalkDir::new(store_path).into_iter(),
        }
    }
}

impl ::std::ops::Deref for Walk {
    type Target = WalkDirIter;

    fn deref(&self) -> &Self::Target {
        &self.dirwalker
    }
}

impl Iterator for Walk {
    type Item = StoreObject;

    fn next(&mut self) -> Option<Self::Item> {

        while let Some(something) = self.dirwalker.next() {
            debug!("[Walk] Processing next item: {:?}", something);
            match something {
                Ok(next) => if next.file_type().is_dir() {
                    debug!("Found directory...");
                    return Some(StoreObject::Collection(next.path().to_path_buf()))
                } else /* if next.file_type().is_file() */ {
                    debug!("Found file...");
                    let n   = next.path().to_path_buf();
                    let sid = match StoreId::from_full_path(&self.store_path, n) {
                        Err(e) => {
                            debug!("Could not construct StoreId object from it");
                            trace_error(&e);
                            continue;
                        },
                        Ok(o) => o,
                    };
                    return Some(StoreObject::Id(sid))
                },
                Err(e) => {
                    warn!("Error in Walker");
                    debug!("{:?}", e);
                    return None;
                }
            }
        }

        return None;
    }
}

impl StoreEntry {

    fn new(id: StoreId, backend: &Box<FileAbstraction>) -> Result<StoreEntry> {
        let pb = id.clone().into_pathbuf()?;

        #[cfg(feature = "fs-lock")]
        {
            open_file(pb.clone())
                .and_then(|f| f.lock_exclusive())
                .chain_err(|| SEK::IoError)?;
        }

        Ok(StoreEntry {
            id: id,
            file: backend.new_instance(pb),
            status: StoreEntryStatus::Present,
        })
    }

    /// The entry is currently borrowed, meaning that some thread is currently
    /// mutating it
    fn is_borrowed(&self) -> bool {
        self.status == StoreEntryStatus::Borrowed
    }

    fn get_entry(&mut self) -> Result<Entry> {
        if !self.is_borrowed() {
            self.file
                .get_file_content(self.id.clone())
                .or_else(|err| if is_match!(err.kind(), &SEK::FileNotFound) {
                    Ok(Entry::new(self.id.clone()))
                } else {
                    Err(err)
                })
        } else {
            Err(SE::from_kind(SEK::EntryAlreadyBorrowed(self.id.clone())))
        }
    }

    fn write_entry(&mut self, entry: &Entry) -> Result<()> {
        if self.is_borrowed() {
            assert_eq!(self.id, entry.location);
            self.file
                .write_file_content(entry)
                .map(|_| ())
        } else {
            Ok(())
        }
    }
}

#[cfg(feature = "fs-lock")]
impl Drop for StoreEntry {

    fn drop(self) {
        self.get_entry()
            .and_then(|entry| open_file(entry.get_location().clone()))
            .and_then(|f| f.unlock())
    }

}


/// The Store itself, through this object one can interact with IMAG's entries
pub struct Store {
    location: PathBuf,

    ///
    /// Configuration object of the store
    ///
    configuration: Option<Value>,

    ///
    /// Internal Path->File cache map
    ///
    /// Caches the files, so they remain flock()ed
    ///
    /// Could be optimized for a threadsafe HashMap
    ///
    entries: Arc<RwLock<HashMap<StoreId, StoreEntry>>>,

    /// The backend to use
    ///
    /// This provides the filesystem-operation functions (or pretends to)
    backend: Box<FileAbstraction>,
}

impl Store {

    /// Create a new Store object
    ///
    /// This opens a Store in `location` using the configuration from `store_config` (if absent, it
    /// uses defaults).
    ///
    /// If the configuration is not valid, this fails.
    ///
    /// If the location does not exist, creating directories is by default denied and the operation
    /// fails, if not configured otherwise.
    /// An error is returned in this case.
    ///
    /// If the path exists and is a file, the operation is aborted as well, an error is returned.
    ///
    /// # Return values
    ///
    /// - On success: Store object
    ///
    pub fn new(location: PathBuf, store_config: Option<Value>) -> Result<Store> {
        let backend = Box::new(FSFileAbstraction::new());
        Store::new_with_backend(location, store_config, backend)
    }

    /// Create a Store object as descripbed in `Store::new()` documentation, but with an alternative
    /// backend implementation.
    ///
    /// Do not use directly, only for testing purposes.
    pub fn new_with_backend(location: PathBuf,
                            store_config: Option<Value>,
                            backend: Box<FileAbstraction>) -> Result<Store> {
        use configuration::*;

        debug!("Validating Store configuration");
        let _ = config_is_valid(&store_config).chain_err(|| SEK::ConfigurationError)?;

        debug!("Building new Store object");
        if !location.exists() {
            if !config_implicit_store_create_allowed(store_config.as_ref()) {
                return Err(SE::from_kind(SEK::CreateStoreDirDenied))
                    .chain_err(|| SEK::FileError)
                    .chain_err(|| SEK::IoError);
            }

            backend
                .create_dir_all(&location)
                .chain_err(|| SEK::StorePathCreate(location.clone()))
                .map_dbg_err_str("Failed")?;
        } else if location.is_file() {
            debug!("Store path exists as file");
            return Err(SE::from_kind(SEK::StorePathExists(location)));
        }

        let store = Store {
            location: location.clone(),
            configuration: store_config,
            entries: Arc::new(RwLock::new(HashMap::new())),
            backend: backend,
        };

        debug!("Store building succeeded");
        debug!("------------------------");
        debug!("{:?}", store);
        debug!("------------------------");

        Ok(store)
    }

    /// Reset the backend of the store during runtime
    ///
    /// # Warning
    ///
    /// This is dangerous!
    /// You should not be able to do that in application code, only the libimagrt should be used to
    /// do this via safe and careful wrapper functions!
    ///
    /// If you are able to do this without using `libimagrt`, please file an issue report.
    ///
    /// # Purpose
    ///
    /// With the I/O backend of the store, the store is able to pipe itself out via (for example)
    /// JSON. But because we need a functionality where we load contents from the filesystem and
    /// then pipe it to stdout, we need to be able to replace the backend during runtime.
    ///
    /// This also applies the other way round: If we get the store from stdin and have to persist it
    /// to stdout, we need to be able to replace the in-memory backend with the real filesystem
    /// backend.
    ///
    pub fn reset_backend(&mut self, mut backend: Box<FileAbstraction>) -> Result<()> {
        self.backend
            .drain()
            .and_then(|drain| backend.fill(drain))
            .map(|_| self.backend = backend)
    }

    /// Get the store configuration
    pub fn config(&self) -> Option<&Value> {
        self.configuration.as_ref()
    }

    /// Creates the Entry at the given location (inside the entry)
    ///
    /// # Return value
    ///
    /// On success: FileLockEntry
    ///
    /// On error:
    ///  - Errors StoreId::into_storeid() might return
    ///  - CreateCallError(LockPoisoned()) if the internal lock is poisened.
    ///  - CreateCallError(EntryAlreadyExists()) if the entry exists already.
    ///
    pub fn create<'a, S: IntoStoreId>(&'a self, id: S) -> Result<FileLockEntry<'a>> {
        let id = id.into_storeid()?.with_base(self.path().clone());

        debug!("Creating id: '{}'", id);

        {
            let mut hsmap = match self.entries.write() {
                Err(_) => return Err(SE::from_kind(SEK::LockPoisoned)).chain_err(|| SEK::CreateCallError),
                Ok(s) => s,
            };

            if hsmap.contains_key(&id) {
                debug!("Cannot create, internal cache already contains: '{}'", id);
                return Err(SE::from_kind(SEK::EntryAlreadyExists(id.clone())))
                           .chain_err(|| SEK::CreateCallError);
            }
            hsmap.insert(id.clone(), {
                debug!("Creating: '{}'", id);
                let mut se = StoreEntry::new(id.clone(), &self.backend)?;
                se.status = StoreEntryStatus::Borrowed;
                se
            });
        }

        debug!("Constructing FileLockEntry: '{}'", id);

        Ok(FileLockEntry::new(self, Entry::new(id)))
    }

    /// Borrow a given Entry. When the `FileLockEntry` is either `update`d or
    /// dropped, the new Entry is written to disk
    ///
    /// Implicitely creates a entry in the store if there is no entry with the id `id`. For a
    /// non-implicitely-create look at `Store::get`.
    ///
    /// # Return value
    ///
    /// On success: FileLockEntry
    ///
    /// On error:
    ///  - Errors StoreId::into_storeid() might return
    ///  - RetrieveCallError(LockPoisoned()) if the internal lock is poisened.
    ///
    pub fn retrieve<'a, S: IntoStoreId>(&'a self, id: S) -> Result<FileLockEntry<'a>> {
        let id = id.into_storeid()?.with_base(self.path().clone());
        debug!("Retrieving id: '{}'", id);
        let entry = self
            .entries
            .write()
            .map_err(|_| SE::from_kind(SEK::LockPoisoned))
            .and_then(|mut es| {
                let new_se = StoreEntry::new(id.clone(), &self.backend)?;
                let se = es.entry(id.clone()).or_insert(new_se);
                let entry = se.get_entry();
                se.status = StoreEntryStatus::Borrowed;
                entry
            })
            .chain_err(|| SEK::RetrieveCallError)?;

        debug!("Constructing FileLockEntry: '{}'", id);
        Ok(FileLockEntry::new(self, entry))
    }

    /// Get an entry from the store if it exists.
    ///
    /// # Return value
    ///
    /// On success: Some(FileLockEntry) or None
    ///
    /// On error:
    ///  - Errors StoreId::into_storeid() might return
    ///  - Errors Store::retrieve() might return
    ///
    pub fn get<'a, S: IntoStoreId + Clone>(&'a self, id: S) -> Result<Option<FileLockEntry<'a>>> {
        let id = id.into_storeid()?.with_base(self.path().clone());

        debug!("Getting id: '{}'", id);

        let exists = id.exists()? || self.entries
            .read()
            .map(|map| map.contains_key(&id))
            .map_err(|_| SE::from_kind(SEK::LockPoisoned))
            .chain_err(|| SEK::GetCallError)?;

        if !exists {
            debug!("Does not exist in internal cache or filesystem: {:?}", id);
            return Ok(None);
        }

        self.retrieve(id).map(Some).chain_err(|| SEK::GetCallError)
    }

    /// Iterate over all StoreIds for one module name
    ///
    /// # Returns
    ///
    /// On success: An iterator over all entries in the module
    ///
    /// On failure:
    ///  - (if the glob or one of the intermediate fail)
    ///  - RetrieveForModuleCallError(GlobError(EncodingError())) if the path string cannot be
    ///    encoded
    ///  - GRetrieveForModuleCallError(GlobError(lobError())) if the glob() failed.
    ///
    pub fn retrieve_for_module(&self, mod_name: &str) -> Result<StoreIdIterator> {
        let mut path = self.path().clone();
        path.push(mod_name);

        debug!("Retrieving for module: '{}'", mod_name);

        path.to_str()
            .ok_or(SE::from_kind(SEK::EncodingError))
            .and_then(|path| {
                let path = [ path, "/**/*" ].join("");
                debug!("glob()ing with '{}'", path);
                glob(&path[..]).map_err(From::from)
            })
            .and_then(|paths| {
                GlobStoreIdIterator::new(paths, self.path().clone())
                    .collect::<Result<Vec<_>>>()
            })
            .map(|v| StoreIdIterator::new(Box::new(v.into_iter())))
            .chain_err(|| SEK::RetrieveForModuleCallError)
    }

    /// Walk the store tree for the module
    ///
    /// The difference between a `Walk` and a `StoreIdIterator` is that with a `Walk`, one can find
    /// "collections" (folders).
    pub fn walk<'a>(&'a self, mod_name: &str) -> Walk {
        debug!("Creating Walk object for {}", mod_name);
        Walk::new(self.path().clone(), mod_name)
    }

    /// Return the `FileLockEntry` and write to disk
    ///
    /// See `Store::_update()`.
    ///
    pub fn update<'a>(&'a self, entry: &mut FileLockEntry<'a>) -> Result<()> {
        debug!("Updating FileLockEntry at '{}'", entry.get_location());
        self._update(entry, false).chain_err(|| SEK::UpdateCallError)
    }

    /// Internal method to write to the filesystem store.
    ///
    /// # Assumptions
    ///
    /// This method assumes that entry is dropped _right after_ the call, hence
    /// it is not public.
    ///
    /// # Return value
    ///
    /// On success: Entry
    ///
    /// On error:
    ///  - UpdateCallError(LockPoisoned()) if the internal write lock cannot be aquierd.
    ///  - IdNotFound() if the entry was not found in the stor
    ///  - Errors Entry::verify() might return
    ///  - Errors StoreEntry::write_entry() might return
    ///
    fn _update<'a>(&'a self, entry: &mut FileLockEntry<'a>, modify_presence: bool) -> Result<()> {
        let mut hsmap = match self.entries.write() {
            Err(_) => return Err(SE::from_kind(SEK::LockPoisoned)),
            Ok(e) => e,
        };

        let se = hsmap.get_mut(&entry.location).ok_or_else(|| {
            SE::from_kind(SEK::IdNotFound(entry.location.clone()))
        })?;

        assert!(se.is_borrowed(), "Tried to update a non borrowed entry.");

        debug!("Verifying Entry");
        entry.entry.verify()?;

        debug!("Writing Entry");
        se.write_entry(&entry.entry)?;
        if modify_presence {
            debug!("Modifying ppresence of {} -> Present", entry.get_location());
            se.status = StoreEntryStatus::Present;
        }

        Ok(())
    }

    /// Retrieve a copy of a given entry, this cannot be used to mutate
    /// the one on disk
    ///
    /// # Return value
    ///
    /// On success: Entry
    ///
    /// On error:
    ///  - RetrieveCopyCallError(LockPoisoned()) if the internal write lock cannot be aquierd.
    ///  - RetrieveCopyCallError(IdLocked()) if the Entry is borrowed currently
    ///  - Errors StoreEntry::new() might return
    ///
    pub fn retrieve_copy<S: IntoStoreId>(&self, id: S) -> Result<Entry> {
        let id = id.into_storeid()?.with_base(self.path().clone());
        debug!("Retrieving copy of '{}'", id);
        let entries = match self.entries.write() {
            Err(_) => {
                return Err(SE::from_kind(SEK::LockPoisoned))
                    .chain_err(|| SEK::RetrieveCopyCallError);
            },
            Ok(e) => e,
        };

        // if the entry is currently modified by the user, we cannot drop it
        if entries.get(&id).map(|e| e.is_borrowed()).unwrap_or(false) {
            return Err(SE::from_kind(SEK::IdLocked)).chain_err(|| SEK::RetrieveCopyCallError);
        }

        StoreEntry::new(id, &self.backend)?.get_entry()
    }

    /// Delete an entry
    ///
    /// # Return value
    ///
    /// On success: ()
    ///
    /// On error:
    ///  - DeleteCallError(LockPoisoned()) if the internal write lock cannot be aquierd.
    ///  - DeleteCallError(FileNotFound()) if the StoreId refers to a non-existing entry.
    ///  - DeleteCallError(FileError()) if the internals failed to remove the file.
    ///
    pub fn delete<S: IntoStoreId>(&self, id: S) -> Result<()> {
        let id = id.into_storeid()?.with_base(self.path().clone());

        debug!("Deleting id: '{}'", id);

        {
            let mut entries = match self.entries.write() {
                Err(_) => return Err(SE::from_kind(SEK::LockPoisoned))
                    .chain_err(|| SEK::DeleteCallError),
                Ok(e) => e,
            };

            // if the entry is currently modified by the user, we cannot drop it
            match entries.get(&id) {
                None => {
                    // The entry is not in the internal cache. But maybe on the filesystem?
                    debug!("Seems like {:?} is not in the internal cache", id);

                    // Small optimization: We need the pathbuf for deleting, but when calling
                    // StoreId::exists(), a PathBuf object gets allocated. So we simply get a
                    // PathBuf here, check whether it is there and if it is, we can re-use it to
                    // delete the filesystem file.
                    let pb = id.into_pathbuf()?;

                    if pb.exists() {
                        // looks like we're deleting a not-loaded file from the store.
                        debug!("Seems like {:?} is on the FS", pb);
                        return self.backend.remove_file(&pb)
                    } else {
                        debug!("Seems like {:?} is not even on the FS", pb);
                        return Err(SE::from_kind(SEK::FileNotFound))
                            .chain_err(|| SEK::DeleteCallError)
                    }
                },
                Some(e) => if e.is_borrowed() {
                    return Err(SE::from_kind(SEK::IdLocked)).chain_err(|| SEK::DeleteCallError)
                }
            }

            // remove the entry first, then the file
            entries.remove(&id);
            let pb = id.clone().with_base(self.path().clone()).into_pathbuf()?;
            if let Err(e) = self.backend.remove_file(&pb) {
                return Err(e)
                    .chain_err(|| SEK::FileError)
                    .chain_err(|| SEK::DeleteCallError);
            }
        }

        debug!("Deleted");
        Ok(())
    }

    /// Save a copy of the Entry in another place
    pub fn save_to(&self, entry: &FileLockEntry, new_id: StoreId) -> Result<()> {
        debug!("Saving '{}' to '{}'", entry.get_location(), new_id);
        self.save_to_other_location(entry, new_id, false)
    }

    /// Save an Entry in another place
    /// Removes the original entry
    pub fn save_as(&self, entry: FileLockEntry, new_id: StoreId) -> Result<()> {
        debug!("Saving '{}' as '{}'", entry.get_location(), new_id);
        self.save_to_other_location(&entry, new_id, true)
    }

    fn save_to_other_location(&self, entry: &FileLockEntry, new_id: StoreId, remove_old: bool)
        -> Result<()>
    {
        let new_id = new_id.with_base(self.path().clone());
        let hsmap = self
            .entries
            .write()
            .map_err(|_| SE::from_kind(SEK::LockPoisoned))
            .chain_err(|| SEK::MoveCallError)?;

        if hsmap.contains_key(&new_id) {
            return Err(SE::from_kind(SEK::EntryAlreadyExists(new_id.clone())))
                .chain_err(|| SEK::MoveCallError)
        }

        let old_id = entry.get_location().clone();

        let old_id_as_path = old_id.clone().with_base(self.path().clone()).into_pathbuf()?;
        let new_id_as_path = new_id.clone().with_base(self.path().clone()).into_pathbuf()?;
        self.backend.copy(&old_id_as_path, &new_id_as_path)
            .and_then(|_| {
                if remove_old {
                    debug!("Removing old '{:?}'", old_id_as_path);
                    self.backend.remove_file(&old_id_as_path)
                } else {
                    Ok(())
                }
            })
            .chain_err(|| SEK::FileError)
            .chain_err(|| SEK::MoveCallError)
    }

    /// Move an entry without loading
    ///
    /// This function moves an entry from one path to another.
    ///
    /// Generally, this function shouldn't be used by library authors, if they "just" want to move
    /// something around. A library for moving entries while caring about meta-data and links.
    ///
    /// # Errors
    ///
    /// This function returns an error in certain cases:
    ///
    /// * If the about-to-be-moved entry is borrowed
    /// * If the lock on the internal data structure cannot be aquired
    /// * If the new path already exists
    /// * If the about-to-be-moved entry does not exist
    /// * If the FS-operation failed
    ///
    /// # Warnings
    ///
    /// This should be used with _great_ care, as moving an entry from `a` to `b` might result in
    /// dangling links (see below).
    ///
    /// ## Moving linked entries
    ///
    /// If the entry which is moved is linked to another entry, these links get invalid (but we do
    /// not detect this here). As links are always two-way-links, so `a` is not only linked to `b`,
    /// but also the other way round, moving `b` to `c` results in the following scenario:
    ///
    /// * `a` links to `b`, which does not exist anymore.
    /// * `c` links to `a`, which does exist.
    ///
    /// So the link is _partly dangling_, so to say.
    ///
    pub fn move_by_id(&self, old_id: StoreId, new_id: StoreId) -> Result<()> {
        let new_id = new_id.with_base(self.path().clone());
        let old_id = old_id.with_base(self.path().clone());

        debug!("Moving '{}' to '{}'", old_id, new_id);

        {
            let mut hsmap = match self.entries.write() {
                Err(_) => return Err(SE::from_kind(SEK::LockPoisoned)),
                Ok(m)  => m,
            };

            if hsmap.contains_key(&new_id) {
                return Err(SE::from_kind(SEK::EntryAlreadyExists(new_id.clone())));
            }
            debug!("New id does not exist in cache");

            // if we do not have an entry here, we fail in `FileAbstraction::rename()` below.
            // if we have one, but it is borrowed, we really should not rename it, as this might
            // lead to strange errors
            if hsmap.get(&old_id).map(|e| e.is_borrowed()).unwrap_or(false) {
                return Err(SE::from_kind(SEK::EntryAlreadyBorrowed(old_id.clone())));
            }

            debug!("Old id is not yet borrowed");

            let old_id_pb = old_id.clone().with_base(self.path().clone()).into_pathbuf()?;
            let new_id_pb = new_id.clone().with_base(self.path().clone()).into_pathbuf()?;

            if self.backend.exists(&new_id_pb)? {
                return Err(SE::from_kind(SEK::EntryAlreadyExists(new_id.clone())));
            }
            debug!("New entry does not yet exist on filesystem. Good.");

            match self.backend.rename(&old_id_pb, &new_id_pb) {
                Err(e) => return Err(e).chain_err(|| SEK::EntryRenameError(old_id_pb, new_id_pb)),
                Ok(_) => {
                    debug!("Rename worked on filesystem");

                    // assert enforced through check hsmap.contains_key(&new_id) above.
                    // Should therefor never fail
                    assert!(hsmap
                            .remove(&old_id)
                            .and_then(|mut entry| {
                                entry.id = new_id.clone();
                                hsmap.insert(new_id.clone(), entry)
                            }).is_none())
                }
            }

        }

        debug!("Moved");
        Ok(())
    }

    /// Get _all_ entries in the store (by id as iterator)
    pub fn entries(&self) -> Result<StoreIdIterator> {
        self.backend
            .pathes_recursively(self.path().clone())
            .and_then(|iter| {
                let mut elems = vec![];
                for element in iter {
                    let is_file = {
                        let mut base = self.path().clone();
                        base.push(element.clone());
                        self.backend.is_file(&base)?
                    };

                    if is_file {
                        let sid = StoreId::from_full_path(self.path(), element)?;
                        elems.push(sid);
                    }
                }
                Ok(StoreIdIterator::new(Box::new(elems.into_iter())))
            })

    }

    /// Gets the path where this store is on the disk
    pub fn path(&self) -> &PathBuf {
        &self.location
    }

}

impl Debug for Store {

    /// TODO: Make pretty.
    fn fmt(&self, fmt: &mut Formatter) -> RResult<(), FMTError> {
        write!(fmt, " --- Store ---\n")?;
        write!(fmt, "\n")?;
        write!(fmt, " - location               : {:?}\n", self.location)?;
        write!(fmt, " - configuration          : {:?}\n", self.configuration)?;
        write!(fmt, "\n")?;
        write!(fmt, "Entries:\n")?;
        write!(fmt, "{:?}", self.entries)?;
        write!(fmt, "\n")?;
        Ok(())
    }

}

impl Drop for Store {

    ///
    /// Unlock all files on drop
    //
    /// TODO: Unlock them
    ///
    fn drop(&mut self) {
        debug!("Dropping store");
    }

}

/// A struct that allows you to borrow an Entry
pub struct FileLockEntry<'a> {
    store: &'a Store,
    entry: Entry,
}

impl<'a> FileLockEntry<'a, > {

    /// Create a new FileLockEntry based on a `Entry` object.
    ///
    /// Only for internal use.
    fn new(store: &'a Store, entry: Entry) -> FileLockEntry<'a> {
        FileLockEntry {
            store: store,
            entry: entry,
        }
    }
}

impl<'a> Debug for FileLockEntry<'a> {
    fn fmt(&self, fmt: &mut Formatter) -> RResult<(), FMTError> {
        write!(fmt, "FileLockEntry(Store = {})", self.store.location.to_str()
               .unwrap_or("Unknown Path"))
    }
}

impl<'a> Deref for FileLockEntry<'a> {
    type Target = Entry;

    fn deref(&self) -> &Self::Target {
        &self.entry
    }
}

impl<'a> DerefMut for FileLockEntry<'a> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.entry
    }
}

#[cfg(not(test))]
impl<'a> Drop for FileLockEntry<'a> {

    /// This will silently ignore errors, use `Store::update` if you want to catch the errors
    ///
    /// This might panic if the store was compiled with the early-panic feature (which is not
    /// intended for production use, though).
    fn drop(&mut self) {
        use libimagerror::trace::trace_error_dbg;
        trace!("Dropping: {:?} - from FileLockEntry::drop()", self.get_location());
        match self.store._update(self, true) {
            Err(e) => {
                trace_error_dbg(&e);
                if_cfg_panic!("ERROR WHILE DROPPING: {:?}", e);
            },
            Ok(_) => { },
        }
    }
}

#[cfg(test)]
impl<'a> Drop for FileLockEntry<'a> {

    /// This will not silently ignore errors but prints the result of the _update() call for testing
    fn drop(&mut self) {
        trace!("Dropping: {:?} - from FileLockEntry::drop() (test impl)", self.get_location());
        let _ = self.store._update(self, true).map_err(|e| trace_error(&e));
    }

}


/// `EntryContent` type
pub type EntryContent = String;

/// An Entry of the store
//
/// Contains location, header and content part.
#[derive(Debug, Clone)]
pub struct Entry {
    location: StoreId,
    header: Value,
    content: EntryContent,
}

impl Entry {

    /// Create a new store entry with its location at `loc`.
    ///
    /// This creates the entry with the default header from `Entry::default_header()` and an empty
    /// content.
    pub fn new(loc: StoreId) -> Entry {
        Entry {
            location: loc,
            header: Entry::default_header(),
            content: EntryContent::new()
        }
    }

    /// Get the default Header for an Entry.
    ///
    /// This function should be used to get a new Header, as the default header may change. Via
    /// this function, compatibility is ensured.
    pub fn default_header() -> Value { // BTreeMap<String, Value>
        Value::default_header()
    }

    /// See `Entry::from_str()`, as this function is used internally. This is just a wrapper for
    /// convenience.
    pub fn from_reader<S: IntoStoreId>(loc: S, file: &mut Read) -> Result<Entry> {
        let text = {
            let mut s = String::new();
            file.read_to_string(&mut s)?;
            s
        };
        Self::from_str(loc, &text[..])
    }

    /// Create a new Entry, with contents from the string passed.
    ///
    /// The passed string _must_ be a complete valid store entry, including header. So this is
    /// probably not what end-users want to call.
    ///
    /// # Return value
    ///
    /// This errors if
    ///
    /// - String cannot be matched on regex to find header and content
    /// - Header cannot be parsed into a TOML object
    ///
    pub fn from_str<S: IntoStoreId>(loc: S, s: &str) -> Result<Entry> {
        use util::entry_buffer_to_header_content;

        let (header, content) = entry_buffer_to_header_content(s)?;

        Ok(Entry {
            location: loc.into_storeid()?,
            header: header,
            content: content,
        })
    }

    /// Return the string representation of this entry
    ///
    /// This means not only the content of the entry, but the complete entry (from memory, not from
    /// disk).
    pub fn to_str(&self) -> String {
        format!("---\n{header}---\n{content}",
                header  = ::toml::ser::to_string_pretty(&self.header).unwrap(),
                content = self.content)
    }

    /// Get the location of the Entry
    pub fn get_location(&self) -> &StoreId {
        &self.location
    }

    /// Get the header of the Entry
    pub fn get_header(&self) -> &Value {
        &self.header
    }

    /// Get the header mutably of the Entry
    pub fn get_header_mut(&mut self) -> &mut Value {
        &mut self.header
    }

    /// Get the content of the Entry
    pub fn get_content(&self) -> &EntryContent {
        &self.content
    }

    /// Get the content mutably of the Entry
    pub fn get_content_mut(&mut self) -> &mut EntryContent {
        &mut self.content
    }

    /// Verify the entry.
    ///
    /// Currently, this only verifies the header. This might change in the future.
    pub fn verify(&self) -> Result<()> {
        self.header.verify()
    }

}

impl PartialEq for Entry {

    fn eq(&self, other: &Entry) -> bool {
        self.location == other.location && // As the location only compares from the store root
            self.header == other.header && // and the other Entry could be from another store (not
            self.content == other.content  // implemented by now, but we think ahead here)
    }

}

mod glob_store_iter {
    use std::fmt::{Debug, Formatter};
    use std::fmt::Error as FmtError;
    use std::path::PathBuf;
    use std::result::Result as RResult;
    use glob::Paths;
    use storeid::StoreId;
    use error::Result;

    use error::StoreErrorKind as SEK;
    use error::ResultExt;

    /// An iterator which is constructed from a `glob()` and returns valid `StoreId` objects or
    /// errors
    pub struct GlobStoreIdIterator {
        store_path: PathBuf,
        paths: Paths,
    }

    impl Debug for GlobStoreIdIterator {

        fn fmt(&self, fmt: &mut Formatter) -> RResult<(), FmtError> {
            write!(fmt, "GlobStoreIdIterator")
        }

    }

    impl GlobStoreIdIterator {

        pub fn new(paths: Paths, store_path: PathBuf) -> GlobStoreIdIterator {
            debug!("Create a GlobStoreIdIterator(store_path = {:?}, /* ... */)", store_path);

            GlobStoreIdIterator {
                store_path: store_path,
                paths: paths,
            }
        }

    }

    impl Iterator for GlobStoreIdIterator {
        type Item = Result<StoreId>;

        fn next(&mut self) -> Option<Self::Item> {
            while let Some(o) = self.paths.next() {
                debug!("GlobStoreIdIterator::next() => {:?}", o);
                match o.chain_err(|| SEK::StoreIdHandlingError) {
                    Err(e) => return Some(Err(e)),
                    Ok(path) => {
                        if path.exists() && path.is_file() {
                            return match StoreId::from_full_path(&self.store_path, path) {
                                Ok(id) => Some(Ok(id)),
                                Err(e) => Some(Err(e)),
                            }
                        /* } else { */
                            /* continue */
                        }
                    }
                }
            }

            None
        }

    }

}

/// Extension trait for top-level toml::Value::Table, will only yield correct results on the
/// top-level Value::Table, but not on intermediate tables.
pub trait Header {
    fn verify(&self) -> Result<()>;
    fn parse(s: &str) -> Result<Value>;
    fn default_header() -> Value;
}

impl Header for Value {

    fn verify(&self) -> Result<()> {
        match *self {
            Value::Table(ref t) => verify_header(&t),
            _ => Err(SE::from_kind(SEK::HeaderTypeFailure)),
        }
    }

    fn parse(s: &str) -> Result<Value> {
        use toml::de::from_str;

        from_str(s)
            .map_err(From::from)
            .and_then(verify_header_consistency)
            .map(Value::Table)
    }

    fn default_header() -> Value {
        let mut m = BTreeMap::new();

        m.insert(String::from("imag"), {
            let mut imag_map = BTreeMap::<String, Value>::new();

            imag_map.insert(String::from("version"), Value::String(String::from(version!())));

            Value::Table(imag_map)
        });

        Value::Table(m)
    }

}

fn verify_header_consistency(t: Table) -> Result<Table> {
    verify_header(&t).chain_err(|| SEK::HeaderInconsistency).map(|_| t)
}

fn verify_header(t: &Table) -> Result<()> {
    if !has_main_section(t) {
        Err(SE::from_kind(SEK::MissingMainSection))
    } else if !has_imag_version_in_main_section(t) {
        Err(SE::from_kind(SEK::MissingVersionInfo))
    } else if !has_only_tables(t) {
        debug!("Could not verify that it only has tables in its base table");
        Err(SE::from_kind(SEK::NonTableInBaseTable))
    } else {
        Ok(())
    }
}

fn has_only_tables(t: &Table) -> bool {
    debug!("Verifying that table has only tables");
    t.iter().all(|(_, x)| is_match!(*x, Value::Table(_)))
}

fn has_main_section(t: &Table) -> bool {
    t.contains_key("imag") && is_match!(t.get("imag"), Some(&Value::Table(_)))
}

fn has_imag_version_in_main_section(t: &Table) -> bool {
    use semver::Version;

    match *t.get("imag").unwrap() {
        Value::Table(ref sec) => {
            sec.get("version")
                .and_then(|v| {
                    match *v {
                        Value::String(ref s) => Some(Version::parse(&s[..]).is_ok()),
                        _                    => Some(false),
                    }
                })
            .unwrap_or(false)
        }
        _ => false,
    }
}


#[cfg(test)]
mod test {
    extern crate env_logger;

    use std::collections::BTreeMap;
    use storeid::StoreId;
    use store::has_main_section;
    use store::has_imag_version_in_main_section;
    use store::verify_header_consistency;

    use toml::Value;

    #[test]
    fn test_imag_section() {
        let mut map = BTreeMap::new();
        map.insert("imag".into(), Value::Table(BTreeMap::new()));

        assert!(has_main_section(&map));
    }

    #[test]
    fn test_imag_invalid_section_type() {
        let mut map = BTreeMap::new();
        map.insert("imag".into(), Value::Boolean(false));

        assert!(!has_main_section(&map));
    }

    #[test]
    fn test_imag_abscent_main_section() {
        let mut map = BTreeMap::new();
        map.insert("not_imag".into(), Value::Boolean(false));

        assert!(!has_main_section(&map));
    }

    #[test]
    fn test_main_section_without_version() {
        let mut map = BTreeMap::new();
        map.insert("imag".into(), Value::Table(BTreeMap::new()));

        assert!(!has_imag_version_in_main_section(&map));
    }

    #[test]
    fn test_main_section_with_version() {
        let mut map = BTreeMap::new();
        let mut sub = BTreeMap::new();
        sub.insert("version".into(), Value::String("0.0.0".into()));
        map.insert("imag".into(), Value::Table(sub));

        assert!(has_imag_version_in_main_section(&map));
    }

    #[test]
    fn test_main_section_with_version_in_wrong_type() {
        let mut map = BTreeMap::new();
        let mut sub = BTreeMap::new();
        sub.insert("version".into(), Value::Boolean(false));
        map.insert("imag".into(), Value::Table(sub));

        assert!(!has_imag_version_in_main_section(&map));
    }

    #[test]
    fn test_verification_good() {
        let mut header = BTreeMap::new();
        let sub = {
            let mut sub = BTreeMap::new();
            sub.insert("version".into(), Value::String(String::from("0.0.0")));

            Value::Table(sub)
        };

        header.insert("imag".into(), sub);

        assert!(verify_header_consistency(header).is_ok());
    }

    #[test]
    fn test_verification_invalid_versionstring() {
        let mut header = BTreeMap::new();
        let sub = {
            let mut sub = BTreeMap::new();
            sub.insert("version".into(), Value::String(String::from("000")));

            Value::Table(sub)
        };

        header.insert("imag".into(), sub);

        assert!(!verify_header_consistency(header).is_ok());
    }


    #[test]
    fn test_verification_current_version() {
        let mut header = BTreeMap::new();
        let sub = {
            let mut sub = BTreeMap::new();
            sub.insert("version".into(), Value::String(String::from(version!())));

            Value::Table(sub)
        };

        header.insert("imag".into(), sub);

        assert!(verify_header_consistency(header).is_ok());
    }

    static TEST_ENTRY : &'static str = "---
[imag]
version = '0.0.3'
---
Hai";

    #[test]
    fn test_entry_from_str() {
        use super::Entry;
        use std::path::PathBuf;
        println!("{}", TEST_ENTRY);
        let entry = Entry::from_str(StoreId::new_baseless(PathBuf::from("test/foo~1.3")).unwrap(),
                                    TEST_ENTRY).unwrap();

        assert_eq!(entry.content, "Hai");
    }

    #[test]
    fn test_entry_to_str() {
        use super::Entry;
        use std::path::PathBuf;
        println!("{}", TEST_ENTRY);
        let entry = Entry::from_str(StoreId::new_baseless(PathBuf::from("test/foo~1.3")).unwrap(),
                                    TEST_ENTRY).unwrap();
        let string = entry.to_str();

        assert_eq!(TEST_ENTRY, string);
    }

}

#[cfg(test)]
mod store_tests {
    use std::path::PathBuf;

    use super::Store;
    use file_abstraction::InMemoryFileAbstraction;

    pub fn get_store() -> Store {
        let backend = Box::new(InMemoryFileAbstraction::new());
        Store::new_with_backend(PathBuf::from("/"), None, backend).unwrap()
    }

    #[test]
    fn test_store_instantiation() {
        let store = get_store();

        assert_eq!(store.location, PathBuf::from("/"));
        assert!(store.entries.read().unwrap().is_empty());
    }

    #[test]
    fn test_store_create() {
        let store = get_store();

        for n in 1..100 {
            let s = format!("test-{}", n);
            let entry = store.create(PathBuf::from(s.clone())).unwrap();
            assert!(entry.verify().is_ok());
            let loc = entry.get_location().clone().into_pathbuf().unwrap();
            assert!(loc.starts_with("/"));
            assert!(loc.ends_with(s));
        }
    }

    #[test]
    fn test_store_create_with_io_backend() {
        use std::io::Cursor;
        use std::rc::Rc;
        use std::cell::RefCell;
        use serde_json::Value;

        //let sink = vec![];
        //let output : Cursor<&mut [u8]> = Cursor::new(&mut sink);
        //let output = Rc::new(RefCell::new(output));
        let output = Rc::new(RefCell::new(vec![]));

        {
            let store = {
                use file_abstraction::stdio::StdIoFileAbstraction;
                use file_abstraction::stdio::mapper::json::JsonMapper;

                // Lets have an empty store as input
                let mut input = Cursor::new(r#"
                { "version": "0.5.0",
                    "store": { }
                }
                "#);

                let mapper  = JsonMapper::new();
                let backend = StdIoFileAbstraction::new(&mut input, output.clone(), mapper).unwrap();
                let backend = Box::new(backend);

                Store::new_with_backend(PathBuf::from("/"), None, backend).unwrap()
            };

            for n in 1..100 {
                let s = format!("test-{}", n);
                let entry = store.create(PathBuf::from(s.clone())).unwrap();
                assert!(entry.verify().is_ok());
                let loc = entry.get_location().clone().into_pathbuf().unwrap();
                assert!(loc.starts_with("/"));
                assert!(loc.ends_with(s));
            }
        }

        let vec    = Rc::try_unwrap(output).unwrap().into_inner();

        let errstr = format!("Not UTF8: '{:?}'", vec);
        let string = String::from_utf8(vec);
        assert!(string.is_ok(), errstr);
        let string = string.unwrap();

        assert!(!string.is_empty(), format!("Expected not to be empty: '{}'", string));

        let json : ::serde_json::Value = ::serde_json::from_str(&string).unwrap();

        match json {
            Value::Object(ref map) => {
                assert!(map.get("version").is_some(), format!("No 'version' in JSON"));
                match map.get("version").unwrap() {
                    &Value::String(ref s) => assert_eq!("0.5.0", s),
                    _ => panic!("Wrong type in JSON at 'version'"),
                }

                assert!(map.get("store").is_some(), format!("No 'store' in JSON"));
                match map.get("store").unwrap() {
                    &Value::Object(ref objs) => {
                        for n in 1..100 {
                            let s = format!("/test-{}", n);
                            assert!(objs.get(&s).is_some(), format!("No entry: '{}'", s));
                            match objs.get(&s).unwrap() {
                                &Value::Object(ref entry) => {
                                    match entry.get("header").unwrap() {
                                        &Value::Object(_) => assert!(true),
                                        _ => panic!("Wrong type in JSON at 'store.'{}'.header'", s),
                                    }

                                    match entry.get("content").unwrap() {
                                        &Value::String(_) => assert!(true),
                                        _ => panic!("Wrong type in JSON at 'store.'{}'.content'", s),
                                    }
                                },
                                _ => panic!("Wrong type in JSON at 'store.'{}''", s),
                            }
                        }
                    },
                    _ => panic!("Wrong type in JSON at 'store'"),
                }
            },
            _ => panic!("Wrong type in JSON at top level"),
        }

    }

    #[test]
    fn test_store_get_create_get_delete_get() {
        let store = get_store();

        for n in 1..100 {
            let res = store.get(PathBuf::from(format!("test-{}", n)));
            assert!(match res { Ok(None) => true, _ => false, })
        }

        for n in 1..100 {
            let s = format!("test-{}", n);
            let entry = store.create(PathBuf::from(s.clone())).unwrap();

            assert!(entry.verify().is_ok());

            let loc = entry.get_location().clone().into_pathbuf().unwrap();

            assert!(loc.starts_with("/"));
            assert!(loc.ends_with(s));
        }

        for n in 1..100 {
            let res = store.get(PathBuf::from(format!("test-{}", n)));
            assert!(match res { Ok(Some(_)) => true, _ => false, })
        }

        for n in 1..100 {
            assert!(store.delete(PathBuf::from(format!("test-{}", n))).is_ok())
        }

        for n in 1..100 {
            let res = store.get(PathBuf::from(format!("test-{}", n)));
            assert!(match res { Ok(None) => true, _ => false, })
        }
    }

    #[test]
    fn test_store_create_twice() {
        use error::StoreErrorKind as SEK;

        let store = get_store();

        for n in 1..100 {
            let s = format!("test-{}", n % 50);
            store.create(PathBuf::from(s.clone()))
                .map_err(|e| assert!(is_match!(e.kind(), &SEK::CreateCallError) && n >= 50))
                .ok()
                .map(|entry| {
                    assert!(entry.verify().is_ok());
                    let loc = entry.get_location().clone().into_pathbuf().unwrap();
                    assert!(loc.starts_with("/"));
                    assert!(loc.ends_with(s));
                });
        }
    }

    #[test]
    fn test_store_create_in_hm() {
        use storeid::StoreId;

        let store = get_store();

        for n in 1..100 {
            let pb = StoreId::new_baseless(PathBuf::from(format!("test-{}", n))).unwrap();

            assert!(store.entries.read().unwrap().get(&pb).is_none());
            assert!(store.create(pb.clone()).is_ok());

            let pb = pb.with_base(store.path().clone());
            assert!(store.entries.read().unwrap().get(&pb).is_some());
        }
    }

    #[test]
    fn test_store_retrieve_in_hm() {
        use storeid::StoreId;

        let store = get_store();

        for n in 1..100 {
            let pb = StoreId::new_baseless(PathBuf::from(format!("test-{}", n))).unwrap();

            assert!(store.entries.read().unwrap().get(&pb).is_none());
            assert!(store.retrieve(pb.clone()).is_ok());

            let pb = pb.with_base(store.path().clone());
            assert!(store.entries.read().unwrap().get(&pb).is_some());
        }
    }

    #[test]
    fn test_get_none() {
        let store = get_store();

        for n in 1..100 {
            match store.get(PathBuf::from(format!("test-{}", n))) {
                Ok(None) => assert!(true),
                _        => assert!(false),
            }
        }
    }

    #[test]
    fn test_delete_none() {
        let store = get_store();

        for n in 1..100 {
            match store.delete(PathBuf::from(format!("test-{}", n))) {
                Err(_) => assert!(true),
                _      => assert!(false),
            }
        }
    }

    // Disabled because we cannot test this by now, as we rely on glob() in
    // Store::retieve_for_module(), which accesses the filesystem and tests run in-memory, so there
    // are no files on the filesystem in this test after Store::create().
    //
    // #[test]
    // fn test_retrieve_for_module() {
    //     let pathes = vec![
    //         "foo/1", "foo/2", "foo/3", "foo/4", "foo/5",
    //         "bar/1", "bar/2", "bar/3", "bar/4", "bar/5",
    //         "bla/1", "bla/2", "bla/3", "bla/4", "bla/5",
    //         "boo/1", "boo/2", "boo/3", "boo/4", "boo/5",
    //         "glu/1", "glu/2", "glu/3", "glu/4", "glu/5",
    //     ];

    //     fn test(store: &Store, modulename: &str) {
    //         use std::path::Component;
    //         use storeid::StoreId;

    //         let retrieved = store.retrieve_for_module(modulename);
    //         assert!(retrieved.is_ok());
    //         let v : Vec<StoreId> = retrieved.unwrap().collect();
    //         println!("v = {:?}", v);
    //         assert!(v.len() == 5);

    //         let retrieved = store.retrieve_for_module(modulename);
    //         assert!(retrieved.is_ok());

    //         assert!(retrieved.unwrap().all(|e| {
    //             let first = e.components().next();
    //             assert!(first.is_some());
    //             match first.unwrap() {
    //                 Component::Normal(s) => s == modulename,
    //                 _                    => false,
    //             }
    //         }))
    //     }

    //     let store = get_store();
    //     for path in pathes {
    //         assert!(store.create(PathBuf::from(path)).is_ok());
    //     }

    //     test(&store, "foo");
    //     test(&store, "bar");
    //     test(&store, "bla");
    //     test(&store, "boo");
    //     test(&store, "glu");
    // }

    #[test]
    fn test_store_move_moves_in_hm() {
        use storeid::StoreId;

        let store = get_store();

        for n in 1..100 {
            if n % 2 == 0 { // every second
                let id    = StoreId::new_baseless(PathBuf::from(format!("t-{}", n))).unwrap();
                let id_mv = StoreId::new_baseless(PathBuf::from(format!("t-{}", n - 1))).unwrap();

                {
                    assert!(store.entries.read().unwrap().get(&id).is_none());
                }

                {
                    assert!(store.create(id.clone()).is_ok());
                }

                {
                    let id_with_base = id.clone().with_base(store.path().clone());
                    assert!(store.entries.read().unwrap().get(&id_with_base).is_some());
                }

                let r = store.move_by_id(id.clone(), id_mv.clone());
                assert!(r.map_err(|e| println!("ERROR: {:?}", e)).is_ok());

                {
                    let id_mv_with_base = id_mv.clone().with_base(store.path().clone());
                    assert!(store.entries.read().unwrap().get(&id_mv_with_base).is_some());
                }

                assert!(match store.get(id.clone()) { Ok(None) => true, _ => false },
                        "Moved id ({:?}) is still there", id);
                assert!(match store.get(id_mv.clone()) { Ok(Some(_)) => true, _ => false },
                        "New id ({:?}) is not in store...", id_mv);
            }
        }
    }

    #[test]
    fn test_swap_backend_during_runtime() {
        use file_abstraction::InMemoryFileAbstraction;

        let mut store = {
            let backend = InMemoryFileAbstraction::new();
            let backend = Box::new(backend);

            Store::new_with_backend(PathBuf::from("/"), None, backend).unwrap()
        };

        for n in 1..100 {
            let s = format!("test-{}", n);
            let entry = store.create(PathBuf::from(s.clone())).unwrap();
            assert!(entry.verify().is_ok());
            let loc = entry.get_location().clone().into_pathbuf().unwrap();
            assert!(loc.starts_with("/"));
            assert!(loc.ends_with(s));
        }

        {
            let other_backend = InMemoryFileAbstraction::new();
            let other_backend = Box::new(other_backend);

            assert!(store.reset_backend(other_backend).is_ok())
        }

        for n in 1..100 {
            let s = format!("test-{}", n);
            let entry = store.get(PathBuf::from(s.clone()));

            assert!(entry.is_ok());
            let entry = entry.unwrap();

            assert!(entry.is_some());
            let entry = entry.unwrap();

            assert!(entry.verify().is_ok());

            let loc = entry.get_location().clone().into_pathbuf().unwrap();
            assert!(loc.starts_with("/"));
            assert!(loc.ends_with(s));
        }
    }

    #[test]
    fn test_swap_backend_during_runtime_with_io() {
        use std::io::Cursor;
        use std::rc::Rc;
        use std::cell::RefCell;
        use serde_json::Value;
        use file_abstraction::stdio::out::StdoutFileAbstraction;
        use file_abstraction::stdio::mapper::json::JsonMapper;

        // The output we later read from and check whether there is an entry
        let output  = Rc::new(RefCell::new(vec![]));

        {
            let mut store = {
                use file_abstraction::stdio::StdIoFileAbstraction;
                use file_abstraction::stdio::mapper::json::JsonMapper;

                // Lets have an empty store as input
                let mut input = Cursor::new(r#"
                { "version": "0.5.0",
                    "store": {
                        "example": {
                            "header": {
                                "imag": {
                                    "version": "0.5.0"
                                }
                            },
                            "content": "foobar"
                        }
                    }
                }
                "#);

                let output  = Rc::new(RefCell::new(::std::io::sink()));
                let mapper  = JsonMapper::new();
                let backend = StdIoFileAbstraction::new(&mut input, output, mapper).unwrap();
                let backend = Box::new(backend);

                Store::new_with_backend(PathBuf::from("/"), None, backend).unwrap()
            };

            // Replacing the backend

            {
                let mapper    = JsonMapper::new();
                let backend   = StdoutFileAbstraction::new(output.clone(), mapper);
                let _         = assert!(backend.is_ok(), format!("Should be ok: {:?}", backend));
                let backend   = backend.unwrap();
                let backend   = Box::new(backend);

                assert!(store.reset_backend(backend).is_ok());
            }
        }

        let vec    = Rc::try_unwrap(output).unwrap().into_inner();
        let errstr = format!("Not UTF8: '{:?}'", vec);
        let string = String::from_utf8(vec);
        assert!(string.is_ok(), errstr);
        let string = string.unwrap();

        assert!(!string.is_empty(), format!("Expected not to be empty: '{}'", string));

        let json : ::serde_json::Value = ::serde_json::from_str(&string).unwrap();

        match json {
            Value::Object(ref map) => {
                assert!(map.get("version").is_some(), format!("No 'version' in JSON"));
                match map.get("version").unwrap() {
                    &Value::String(ref s) => assert_eq!("0.5.0", s),
                    _ => panic!("Wrong type in JSON at 'version'"),
                }

                assert!(map.get("store").is_some(), format!("No 'store' in JSON"));
                match map.get("store").unwrap() {
                    &Value::Object(ref objs) => {
                        let s = String::from("example");
                        assert!(objs.get(&s).is_some(), format!("No entry: '{}' in \n{:?}", s, objs));
                        match objs.get(&s).unwrap() {
                            &Value::Object(ref entry) => {
                                match entry.get("header").unwrap() {
                                    &Value::Object(_) => assert!(true),
                                    _ => panic!("Wrong type in JSON at 'store.'{}'.header'", s),
                                }

                                match entry.get("content").unwrap() {
                                    &Value::String(_) => assert!(true),
                                    _ => panic!("Wrong type in JSON at 'store.'{}'.content'", s),
                                }
                            },
                            _ => panic!("Wrong type in JSON at 'store.'{}''", s),
                        }
                    },
                    _ => panic!("Wrong type in JSON at 'store'"),
                }
            },
            _ => panic!("Wrong type in JSON at top level"),
        }

    }
}