caio.co/de/caca


Extract sample configuration file 💬 by Caio a year ago (log)
Otherwise I'll have to update the README all the time

Blob caca/src/config.rs

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
use std::{
    net::{AddrParseError, SocketAddr, TcpListener},
    num::NonZeroUsize,
    path::PathBuf,
};

use crate::view::Theme;

#[derive(Debug, Clone, PartialEq)]
pub(crate) struct GlobalConfig {
    pub site: Site,
    pub max_file_size_bytes: u64,
    pub repo_object_cache_size: usize,
    pub rename_similarity_threshold: Option<f32>,
    pub metadata_config: MetadataConfig,
    pub global_mailmap: Option<PathBuf>,
    pub feed_size: Option<NonZeroUsize>,
    pub log_size: NonZeroUsize,
    pub allow_http_clone: bool,
    pub cache_size: NonZeroUsize,
    pub theme: Theme,
    pub num_threads: Option<usize>,
    pub export_all: bool,
    pub listen_mode: ListenMode,
    // blob_encoding?
}

impl Default for GlobalConfig {
    fn default() -> Self {
        Self {
            site: Site {
                listing_title: String::from("caio's code asylum"),
                listing_html_header: String::from("<h1>caca</h1>"),
                base_url: String::from("http://localhost:42080"),
                clone_base_url: None,
                reverse_proxy_base: None,
                repo_to_listing_name: None,
            },
            max_file_size_bytes: 2 * 1024 * 1024,
            rename_similarity_threshold: Some(0.7),
            repo_object_cache_size: 20 * 1024 * 1024,
            metadata_config: MetadataConfig::default(),
            global_mailmap: None,
            feed_size: NonZeroUsize::new(40),
            log_size: NonZeroUsize::new(30).unwrap(),
            allow_http_clone: true,
            cache_size: NonZeroUsize::new(15000).unwrap(),
            theme: Theme::AutoReload(String::from("caca/theme")),
            num_threads: None,
            export_all: true, // false => require git-daemon-export-ok
            listen_mode: ListenMode::addr("[::]:42080").expect("valid default socket addr"),
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
pub(crate) struct Site {
    pub listing_title: String,
    pub listing_html_header: String,

    pub base_url: String,
    // for mounting it as a subfolder when reverse proxying
    pub reverse_proxy_base: Option<String>,
    // fscking terrible name, but when set, a link to the index
    // will appear before the repo name in every repo page header
    pub repo_to_listing_name: Option<String>,

    // override the url displayed for clone
    // gets the repo name appended
    pub clone_base_url: Option<String>,
}

impl GlobalConfig {
    pub fn caiodotco() -> Self {
        let config = Self {
            site: Site {
                listing_title: "caio.co/de index".to_string(),
                listing_html_header:
                    r#"<h1><a class="nodec" href="..">caio.</a><strong>co/de</strong></h1>"#
                        .to_string(),
                base_url: "https://caio.co".to_string(),
                reverse_proxy_base: Some("/de".to_string()),
                clone_base_url: None,
                repo_to_listing_name: Some("caio.co/de".to_string()),
            },
            global_mailmap: Some("/etc/caca/mailmap".into()),
            listen_mode: ListenMode::External,
            theme: Theme::Static,
            ..Default::default()
        };
        config.check().expect("valid live config")
    }

    // XXX iffy but i'm not doing a builder for this thing
    pub fn check(self) -> crate::Result<Self> {
        if self
            .site
            .clone_base_url
            .as_ref()
            .is_some_and(|u| u.ends_with('/'))
        {
            return Err("clone url must not end with slash".into());
        }

        let parsed = url::Url::parse(&self.repo_clone_url("repository"))?;
        if !matches!(parsed.scheme(), "git" | "http" | "https") {
            return Err(format!(
                "clone url scheme must be git or http(s) got: {}",
                parsed.scheme()
            )
            .into());
        }

        if !self.allow_http_clone && parsed.scheme().starts_with("http") {
            return Err("clone url is http but http clone is disabled".into());
        }

        if self
            .site
            .reverse_proxy_base
            .as_ref()
            .is_some_and(|p| !p.starts_with('/') || p.ends_with('/'))
        {
            return Err(
                "reverse proxy base must start with / and not end with it. ex: /valid".into(),
            );
        }

        Ok(self)
    }

    pub fn repo_url(&self, name: &str) -> String {
        format!(
            "{}/{name}",
            self.site.reverse_proxy_base.as_deref().unwrap_or_default()
        )
    }

    pub fn listing_url(&self) -> String {
        format!(
            "{}/",
            self.site.reverse_proxy_base.as_deref().unwrap_or_default()
        )
    }

    pub fn repo_clone_url(&self, name: &str) -> String {
        if let Some(ref url) = self.site.clone_base_url {
            format!("{url}/{name}",)
        } else {
            format!(
                "{}{}/{name}",
                self.site.base_url,
                self.site.reverse_proxy_base.as_deref().unwrap_or_default()
            )
        }
    }

    pub fn feed_base_url(&self) -> String {
        // intentionally not using reverse_proxy_base
        self.site.base_url.clone()
    }

    pub fn from_bytes(data: &[u8]) -> crate::Result<Self> {
        let mut config = Self::default();
        let mut first_err: Option<Box<dyn std::error::Error>> = None;
        urso::config::parse(data, |section, _subsection, key, value| -> bool {
            match section {
                "site" => {
                    match key {
                        "listing-title" => {
                            config.site.listing_title = String::from_utf8_lossy(value).into_owned();
                        }
                        "listing-html-header" => {
                            config.site.listing_html_header =
                                String::from_utf8_lossy(value).into_owned();
                        }
                        "base-url" => {
                            config.site.base_url = String::from_utf8_lossy(value).into_owned();
                        }
                        "clone-base-url" => {
                            config.site.clone_base_url =
                                Some(String::from_utf8_lossy(value).into_owned());
                        }
                        "reverse-proxy-base" => {
                            config.site.reverse_proxy_base =
                                Some(String::from_utf8_lossy(value).into_owned());
                        }
                        "repo-to-listing-name" => {
                            config.site.repo_to_listing_name =
                                Some(String::from_utf8_lossy(value).into_owned());
                        }
                        _ => {
                            tracing::warn!("discarded unknown key `{key}` in section `{section}`");
                        }
                    };
                }
                "core" => {
                    match key {
                        "static-theme" => match from_utf8(value) {
                            Ok(true) => config.theme = Theme::Static,
                            Ok(false) => {} // autoreload
                            Err(err) => {
                                first_err = Some(err);
                                return false;
                            }
                        },
                        "theme" => {
                            config.theme =
                                Theme::AutoReload(String::from_utf8_lossy(value).into_owned());
                        }
                        "max-file-size-bytes" => match from_utf8(value) {
                            Ok(max) => config.max_file_size_bytes = max,
                            Err(err) => {
                                first_err = Some(err);
                                return false;
                            }
                        },
                        "rename-similarity-threshold" => match from_utf8(value) {
                            Ok(threshold) => {
                                if threshold == 0.0 {
                                    config.rename_similarity_threshold = None;
                                } else if (0.0f32..=1.0).contains(&threshold) {
                                    config.rename_similarity_threshold = Some(threshold);
                                } else {
                                    first_err = Some("threshold must be 0..=1".into());
                                    return false;
                                }
                            }
                            Err(err) => {
                                first_err = Some(err);
                                return false;
                            }
                        },
                        "repo-object-cache-size" => match from_utf8(value) {
                            Ok(size) => config.repo_object_cache_size = size,
                            Err(err) => {
                                first_err = Some(err);
                                return false;
                            }
                        },
                        "num-threads" => match from_utf8(value) {
                            Ok(val) => config.num_threads = Some(val),
                            Err(err) => {
                                first_err = Some(err);
                                return false;
                            }
                        },
                        "allow-http-clone" => match from_utf8(value) {
                            Ok(flag) => config.allow_http_clone = flag,
                            Err(err) => {
                                first_err = Some(err);
                                return false;
                            }
                        },
                        "export-all" => match from_utf8(value) {
                            Ok(flag) => config.export_all = flag,
                            Err(err) => {
                                first_err = Some(err);
                                return false;
                            }
                        },
                        "cache-size" => match from_utf8(value) {
                            Ok(0) => {
                                first_err = Some("must be non-zero".into());
                                return false;
                            }
                            Ok(size) => {
                                config.cache_size =
                                    NonZeroUsize::new(size).expect("checked for non-zero");
                            }
                            Err(err) => {
                                first_err = Some(err);
                                return false;
                            }
                        },
                        "global-mailmap" => {
                            config.global_mailmap =
                                Some(PathBuf::from(String::from_utf8_lossy(value).as_ref()));
                        }
                        "listen" => match ListenMode::from_bytes(value) {
                            Ok(mode) => config.listen_mode = mode,
                            Err(err) => {
                                first_err = Some(err);
                                return false;
                            }
                        },
                        _ => {
                            tracing::warn!("discarded unknown key `{key}` in section `{section}`");
                        }
                    };
                }
                "metadata" => match key {
                    "spec" => {
                        config.metadata_config.spec =
                            Some(String::from_utf8_lossy(value).into_owned());
                    }
                    "filename" => {
                        config.metadata_config.filename =
                            Some(String::from_utf8_lossy(value).into_owned());
                    }
                    "enabled" => match from_utf8(value) {
                        Ok(flag) => config.metadata_config.enabled = flag,
                        Err(err) => {
                            first_err = Some(err);
                            return false;
                        }
                    },
                    _ => {
                        tracing::warn!("discarded unknown key `{key}` in section `{section}`");
                    }
                },
                _ => {
                    tracing::warn!("discarded unknown key `{key}` in section `{section}`");
                }
            };
            true
        })?;

        config.check()
    }
}

#[derive(Debug, Clone, PartialEq)]
pub(crate) struct MetadataConfig {
    pub spec: Option<String>,
    pub filename: Option<String>,
    pub enabled: bool,
}

impl Default for MetadataConfig {
    fn default() -> Self {
        Self {
            spec: None,
            filename: None,
            enabled: true,
        }
    }
}

impl MetadataConfig {
    pub(crate) fn spec(&self) -> &str {
        self.spec.as_deref().unwrap_or("HEAD")
    }

    pub(crate) fn filename(&self) -> &str {
        self.filename.as_deref().unwrap_or(".config/caca.ini")
    }
}

#[derive(Debug, Clone, PartialEq)]
pub(crate) enum ListenMode {
    External,
    Bind(BindOptions),
}

impl ListenMode {
    // listen = "external"
    // listen = "addr"
    // listen = "addr,admin_addr"
    fn from_bytes(data: &[u8]) -> crate::Result<Self> {
        let text = std::str::from_utf8(data)?.trim();
        if text == "external" {
            Ok(Self::External)
        } else if let Some((addr, admin_addr)) = text.split_once(',') {
            Ok(Self::with_admin(addr.trim(), admin_addr.trim())?)
        } else {
            Ok(Self::addr(text)?)
        }
    }
}

impl ListenMode {
    pub fn addr(addr: &str) -> std::result::Result<Self, AddrParseError> {
        let addr = addr.parse()?;
        Ok(Self::Bind(BindOptions {
            addr,
            admin_addr: None,
        }))
    }

    pub fn with_admin(addr: &str, admin_addr: &str) -> std::result::Result<Self, AddrParseError> {
        let addr = addr.parse()?;
        let admin_addr = Some(admin_addr.parse()?);
        Ok(Self::Bind(BindOptions { addr, admin_addr }))
    }

    pub fn to_non_blocking_sockets(&self) -> crate::Result<(TcpListener, Option<TcpListener>)> {
        let (app, admin) = match self {
            ListenMode::External => {
                let mut env = listenfd::ListenFd::from_env();
                let app = env
                    .take_tcp_listener(0)?
                    .ok_or("socket activation: need at least one tcp fd from env")?;
                let admin = env.take_tcp_listener(1)?;
                (app, admin)
            }
            ListenMode::Bind(opts) => {
                let app = TcpListener::bind(opts.addr)?;
                let admin = opts.admin_addr.map(TcpListener::bind).transpose()?;
                (app, admin)
            }
        };

        app.set_nonblocking(true)?;
        if let Some(ref admin) = admin {
            admin.set_nonblocking(true)?;
        }

        Ok((app, admin))
    }
}

#[derive(Debug, Clone, PartialEq)]
pub(crate) struct BindOptions {
    pub(crate) addr: SocketAddr,
    pub(crate) admin_addr: Option<SocketAddr>,
}

fn from_utf8<T, E>(input: &[u8]) -> crate::Result<T>
where
    T: std::str::FromStr<Err = E>,
    E: 'static + std::error::Error,
{
    Ok(T::from_str(std::str::from_utf8(input)?)?)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn empty_is_default() {
        let from_empty = GlobalConfig::from_bytes(&[]).expect("from empty works");
        assert_eq!(GlobalConfig::default(), from_empty);
    }

    #[test]
    fn unknown_is_ignored() {
        let input = "
[unknown-section]
field=value

# known section, unknown field
[site]
garbage=data

# known secion and field, to ensure the parser doesn't bail
# before the end
[core]
theme=/path/to/theme
anotherjunk=12
        ";
        let from_junk =
            GlobalConfig::from_bytes(input.as_bytes()).expect("unknown junk doesn't yield error");
        assert_eq!(
            Theme::AutoReload("/path/to/theme".to_string()),
            from_junk.theme
        );
    }

    #[test]
    fn parse_caiodotco() {
        let live_config = include_str!("../../resources/caiodotco-live-config.ini");

        assert_eq!(
            GlobalConfig::caiodotco(),
            GlobalConfig::from_bytes(live_config.as_bytes()).expect("input is valid")
        );
    }
}