summaryrefslogtreecommitdiff
path: root/rola-bucket/src/bucket/init.rs
blob: 68340099a1598d1500c97528a238b35e4cfedb54 (plain) (blame)
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
use std::{
    fs,
    path::{Path, PathBuf},
};

use shared_constants::{
    bucket::{
        DIR_BUCKET_COMPRESSED_OBJ, DIR_BUCKET_DELTA, DIR_BUCKET_ID_REVS, DIR_BUCKET_ID_TAGS,
        DIR_BUCKET_IDMAP, DIR_BUCKET_OBJ,
    },
    common::FILE_BUCKET_ROOT_CONFIG,
};
use space_system::SpaceError;

pub(crate) fn init_bucket_at(path: PathBuf) -> Result<(), SpaceError> {
    let bucket_config_file = path.join(FILE_BUCKET_ROOT_CONFIG);

    // Check if directory is empty
    let mut dir_entries = std::fs::read_dir(&path).map_err(SpaceError::Io)?;
    if dir_entries.next().is_some() {
        return Err(SpaceError::RequireEmptyDirectory);
    }

    write_config(&bucket_config_file)?;
    create_dirs(&path)?;

    Ok(())
}

fn write_config(bucket_config_file: &Path) -> Result<(), SpaceError> {
    fs::write(bucket_config_file, include_str!("../../res/bucket.toml")).map_err(SpaceError::Io)
}

fn create_dirs(bucket_dir: &Path) -> Result<(), SpaceError> {
    let dirs = [
        DIR_BUCKET_OBJ,
        DIR_BUCKET_COMPRESSED_OBJ,
        DIR_BUCKET_DELTA,
        DIR_BUCKET_ID_REVS,
        DIR_BUCKET_ID_TAGS,
        DIR_BUCKET_IDMAP,
    ];

    for dir in dirs {
        let full_path = bucket_dir.join(dir);
        fs::create_dir_all(&full_path).map_err(SpaceError::Io)?;
    }

    Ok(())
}