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
mod nc;

#[cfg(feature = "redis-connect")]
use redis::{ConnectionAddr, ConnectionInfo};
#[cfg(feature = "redis-connect")]
use std::iter::once;
use std::path::PathBuf;
use thiserror::Error;

pub use nc::{parse, parse_glob};
use std::fmt::{Display, Formatter};

#[derive(Debug)]
pub struct Config {
    pub database: Database,
    pub database_prefix: String,
    #[cfg(feature = "redis-connect")]
    pub redis: RedisConfig,
    pub nextcloud_url: String,
}

#[cfg(feature = "redis-connect")]
#[derive(Debug)]
pub enum RedisConfig {
    Single(ConnectionInfo),
    Cluster(Vec<ConnectionInfo>),
}

#[cfg(feature = "redis-connect")]
impl RedisConfig {
    pub fn addr(&self) -> impl Iterator<Item = &ConnectionAddr> {
        let boxed: Box<dyn Iterator<Item = &ConnectionAddr>> = match self {
            RedisConfig::Single(conn) => Box::new(once(&conn.addr)),
            RedisConfig::Cluster(conns) => Box::new(conns.iter().map(|conn| &conn.addr)),
        };
        boxed
    }

    pub fn db(&self) -> i64 {
        match self {
            RedisConfig::Single(conn) => conn.redis.db,
            RedisConfig::Cluster(conns) => {
                conns.first().map(|conn| conn.redis.db).unwrap_or_default()
            }
        }
    }

    pub fn username(&self) -> Option<&str> {
        match self {
            RedisConfig::Single(conn) => conn.redis.username.as_deref(),
            RedisConfig::Cluster(conns) => conns
                .first()
                .map(|conn| conn.redis.username.as_deref())
                .unwrap_or_default(),
        }
    }

    pub fn passwd(&self) -> Option<&str> {
        match self {
            RedisConfig::Single(conn) => conn.redis.password.as_deref(),
            RedisConfig::Cluster(conns) => conns
                .first()
                .map(|conn| conn.redis.password.as_deref())
                .unwrap_or_default(),
        }
    }

    pub fn into_vec(self) -> Vec<ConnectionInfo> {
        match self {
            RedisConfig::Single(conn) => vec![conn],
            RedisConfig::Cluster(vec) => vec,
        }
    }
}

type Result<T, E = Error> = std::result::Result<T, E>;

#[derive(Debug, Error)]
pub enum Error {
    #[error("Error while parsing php literal: {0:#}")]
    Php(PhpParseError),
    #[error("Provided config file doesn't seem to be a nextcloud config file: {0:#}")]
    NotAConfig(#[from] NotAConfigError),
    #[error("Failed to read config file")]
    ReadFailed(std::io::Error, PathBuf),
    #[error("invalid database configuration: {0}")]
    InvalidDb(#[from] DbError),
    #[error("no database configuration")]
    NoDb,
    #[error("Invalid redis configuration")]
    Redis,
    #[error("`overwrite.cli.url` not set`")]
    NoUrl,
}

#[derive(Debug)]
pub struct PhpParseError {
    err: php_literal_parser::ParseError,
    source: String,
    path: PathBuf,
}

impl Display for PhpParseError {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let err = self.err.clone().with_source(&self.source);
        write!(f, "{}", err)
    }
}

#[derive(Debug, Error)]
pub enum DbError {
    #[error("unsupported database type {0}")]
    Unsupported(String),
    #[error("no username set")]
    NoUsername,
    #[error("no password set")]
    NoPassword,
    #[error("no database name")]
    NoName,
}

#[derive(Debug, Error)]
pub enum NotAConfigError {
    #[error("$CONFIG not found in file")]
    NoConfig(PathBuf),
    #[error("$CONFIG is not an array")]
    NotAnArray(PathBuf),
}

#[derive(Debug)]
pub enum Database {
    Sqlite {
        database: PathBuf,
    },
    MySql {
        database: String,
        username: String,
        password: String,
        connect: DbConnect,
        disable_ssl: bool,
    },
    Postgres {
        database: String,
        username: String,
        password: String,
        connect: DbConnect,
        disable_ssl: bool,
    },
}

#[derive(Debug)]
pub enum DbConnect {
    Tcp { host: String, port: u16 },
    Socket(PathBuf),
}

#[cfg(feature = "db-sqlx")]
impl From<Database> for sqlx::any::AnyConnectOptions {
    fn from(cfg: Database) -> Self {
        use sqlx::{
            mysql::{MySqlConnectOptions, MySqlSslMode},
            postgres::{PgConnectOptions, PgSslMode},
            sqlite::SqliteConnectOptions,
        };

        match cfg {
            Database::Sqlite { database } => {
                SqliteConnectOptions::default().filename(database).into()
            }
            Database::MySql {
                database,
                username,
                password,
                connect,
                disable_ssl,
            } => {
                let mut options = MySqlConnectOptions::default()
                    .database(&database)
                    .username(&username)
                    .password(&password);
                if disable_ssl {
                    options = options.ssl_mode(MySqlSslMode::Disabled);
                }
                match connect {
                    DbConnect::Socket(socket) => {
                        options = options.socket(socket);
                    }
                    DbConnect::Tcp { host, port } => {
                        options = options.host(&host).port(port);
                    }
                }
                options.into()
            }
            Database::Postgres {
                database,
                username,
                password,
                connect,
                disable_ssl,
            } => {
                let mut options = PgConnectOptions::default()
                    .database(&database)
                    .username(&username)
                    .password(&password);
                if disable_ssl {
                    options = options.ssl_mode(PgSslMode::Disable);
                }
                match connect {
                    DbConnect::Socket(socket) => {
                        options = options.socket(socket);
                    }
                    DbConnect::Tcp { host, port } => {
                        options = options.host(&host).port(port);
                    }
                }
                options.into()
            }
        }
    }
}