any2nix 0.1.3

Serialization-powered Nix Converter.
Documentation
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
// SPDX-FileCopyrightText: 2026 Gabriel Santos de Souza <gabriel.santosdesouza@dcomp.ufs.br>
//
// SPDX-License-Identifier: GPL-3.0-or-later

#![doc(html_favicon_url = "https://zipline.gs-101.dev/u/DF6up7.ico")]
#![doc(html_logo_url = "https://zipline.gs-101.dev/u/DZWGB0.svg")]
//! This crate provides simple functions for translating different formats
//! to [Nix](https://nixos.org).
//!
//! They serve as higher-level options to
//! [serialization functions][serde].
//!
//! Due to being based on serialization, the translation process has
//! a chance to fail, primarily on invalid formatting.
//!
//! # Usage
//!
//! This crate is on [crates.io](https://crates.io/crates/any2nix) and can
//! be added as a dependency of your project:
//!
//! ```bash
//! cargo add any2nix
//! ```
//!
//! # Supported Formats
//!
//! See [Format] for an enumeration of supported formats.
//!
//! Each format is gated behind its own [feature](https://doc.rust-lang.org/cargo/reference/features.html).
//!
//! The default feature enables all formats.
//!
//! # Crate Features
//! Besides the features for each format, this crate also exposes the following
//! features:
//!
//! - `clap`: Enables command-line argument parsing through [clap].
//! - `utoipa`: Enables OpenAPI schema generation through [utoipa].
//!
//! # Examples: TOML
//!
//! ```rust
//! # #[cfg(feature = "toml")]
//! # {
//! let some_toml = r#"
//! [package]
//! name = "any2nix"
//! "#;
//! // Functions follow a clear "{format}_to_nix" naming convention.
//! let nix = match any2nix::toml_to_nix(some_toml) {
//!     Ok(v) => v,
//!     Err(e) => panic!("invalid TOML") // Returns a "Result<String, any2nix::Error>".
//! };
//!
//! println!("{}", nix);
//! // Output:
//! //
//! // {
//! //   package = {
//! //     name = "any2nix";
//! //   };
//! // }
//! # assert_eq!(nix, "{\n  package = {\n    name = \"any2nix\";\n  };\n}")
//! # }
//! ```

use std::fmt::Display;

#[cfg(feature = "clap")]
use clap::ValueEnum;
use serde::{Deserialize, Serialize};
use strum::VariantArray;
#[cfg(feature = "utoipa")]
use utoipa::ToSchema;

/// Aggregator of all errors from all used serializers (translators)
/// for simpler error handling.
#[derive(thiserror::Error, Debug)]
pub enum Error {
    #[cfg(feature = "ini")]
    #[error("{}", match .0 {
        serde_ini::de::Error::Custom(msg) => msg.strip_prefix("INI syntax error: ").unwrap_or(msg),
        serde_ini::de::Error::UnexpectedEof => "unexpected end of file",
        serde_ini::de::Error::InvalidState => "invalid state",
    })]
    Ini(#[from] serde_ini::de::Error),
    #[cfg(feature = "json")]
    #[error("{0}")]
    Json(#[from] serde_json::Error),
    #[cfg(feature = "toml")]
    #[error("{}", .0.message())]
    Toml(#[from] toml::de::Error),
    #[cfg(feature = "yaml")]
    #[error("{0}")]
    Yaml(#[from] yaml_serde::Error),
}

/// Enumeration of the currently supported formats for conversion.
///
/// # Crate Features
///
/// With `clap` enabled, it can be used to limit possible values for a flag.
///
/// With `utoipa` enabled,generates an [OpenAPI](https://www.openapis.org/)-compatible
/// schema to describe a value.
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize, VariantArray)]
#[serde(rename_all = "lowercase")]
#[cfg_attr(feature = "clap", derive(ValueEnum))]
#[cfg_attr(feature = "utoipa", derive(ToSchema))]
pub enum Format {
    #[cfg(feature = "ini")]
    Ini,
    #[cfg(feature = "json")]
    Json,
    #[cfg(feature = "toml")]
    Toml,
    #[cfg(feature = "yaml")]
    Yaml,
}

impl Display for Format {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            #[cfg(feature = "ini")]
            Self::Ini => write!(f, "INI"),
            #[cfg(feature = "json")]
            Self::Json => write!(f, "JSON"),
            #[cfg(feature = "toml")]
            Self::Toml => write!(f, "TOML"),
            #[cfg(feature = "yaml")]
            Self::Yaml => write!(f, "YAML"),
        }
    }
}

impl Format {
    pub const VARIANTS: &'static [Self] = <Self as VariantArray>::VARIANTS;

    pub fn to_nix(&self, input: &str) -> Result<String, Error> {
        match self {
            #[cfg(feature = "ini")]
            Self::Ini => ini_to_nix(input),
            #[cfg(feature = "json")]
            Self::Json => json_to_nix(input),
            #[cfg(feature = "toml")]
            Self::Toml => toml_to_nix(input),
            #[cfg(feature = "yaml")]
            Self::Yaml => yaml_to_nix(input),
        }
    }
}

/// Wrapper around deserializer functions to have them serialize the formats to Nix.
fn format_to_nix<T, E>(
    from_str: impl FnOnce(&str) -> Result<T, E>,
    input: &str,
) -> Result<String, Error>
where
    T: Serialize,
    Error: From<E>,
{
    let format = from_str(input)?;
    let nix = ser_nix::to_string(&format).expect("AST to Nix is infallible");

    Ok(nix)
}

/// Translates text in [INI](https://en.wikipedia.org/wiki/INI_file) to [Nix](https://nixos.org).
///
/// # Errors
///
/// Returns [Error::Ini] in case the input cannot be parsed as valid INI.
///
/// # Examples
///
/// ```rust
/// let some_ini = "[Actor]
/// bUseNavMeshForMovement=1
/// fNotVisibleNavmeshMoveDist=2048.0000";
/// let nix = any2nix::ini_to_nix(&some_ini)?;
///
/// println!("{}", nix);
/// // Output:
/// //
/// // {
/// //   Actor = {
/// //     bUseNavMeshForMovement = "1";
/// //     fNotVisibleNavmeshMoveDist = "2048.0000";
/// //   };
/// // }
/// # assert_eq!(nix, "{\n  Actor = {\n    bUseNavMeshForMovement = \"1\";\n    fNotVisibleNavmeshMoveDist = \"2048.0000\";\n  };\n}");
/// # Ok::<(), any2nix::Error>(())
/// ```
#[cfg(feature = "ini")]
pub fn ini_to_nix(input: &str) -> Result<String, Error> {
    format_to_nix(serde_ini::from_str::<serde_json::Value>, input)
}

/// Translates text in [JSON](https://www.json.org) to [Nix](https://nixos.org).
///
/// # Errors
///
/// Returns [Error::Json] in case the input cannot be parsed as valid JSON.
///
/// # Examples
///
/// ```rust
/// let some_json = r#"
/// {
///     "name": "any2nix",
///     "version": "0.1.0"
/// }"#;
/// let nix = any2nix::json_to_nix(&some_json)?;
///
///
/// println!("{}", nix);
/// // Output:
/// //
/// // {
/// //   name = "any2nix";
/// //   version = "0.1.0";
/// // }
/// # assert_eq!(nix, "{\n  name = \"any2nix\";\n  version = \"0.1.0\";\n}");
/// # Ok::<(), any2nix::Error>(())
/// ```
#[cfg(feature = "json")]
pub fn json_to_nix(input: &str) -> Result<String, Error> {
    format_to_nix(|s| serde_json::from_str::<serde_json::Value>(s), input)
}

/// Translates text in [TOML](https://toml.io) to [Nix](https://nixos.org).
///
/// # Errors
///
/// Returns [Error::Toml] in case the input cannot be parsed as valid TOML.
///
/// # Examples
///
/// ```rust
/// let some_toml = r#"
/// [package]
/// name = "any2nix"
/// "#;
/// let nix = any2nix::toml_to_nix(&some_toml)?;
///
/// println!("{}", nix);
/// // Output:
/// //
/// // {
/// //   package = {
/// //     name = "any2nix";
/// //   };
/// // }
/// # assert_eq!(nix, "{\n  package = {\n    name = \"any2nix\";\n  };\n}");
/// # Ok::<(), any2nix::Error>(())
/// ```
#[cfg(feature = "toml")]
pub fn toml_to_nix(input: &str) -> Result<String, Error> {
    format_to_nix(|s| toml::from_str::<toml::Value>(s), input)
}

/// Translates text in [YAML](https://yaml.org) to [Nix](https://nixos.org).
///
/// # Errors
///
/// Returns [Error::Yaml] in case the input cannot be parsed as valid YAML.
///
/// # Examples
///
/// ```rust
/// let some_yaml = r#"
/// services:
///   db:
///     image: postgres:16-alpine
///     ports:
///       - "5432:5432"
///     restart: always
/// "#;
/// let nix = any2nix::yaml_to_nix(&some_yaml)?;
///
/// println!("{}", nix);
/// // Output:
/// //
/// // {
/// //   services = {
/// //     db = {
/// //       image = "postgres:16-alpine";
/// //       ports = [
/// //         "5432:5432"
/// //       ];
/// //       restart = "always";
/// //     };
/// //   };
/// // }
/// # assert_eq!(nix, "{\n  services = {\n    db = {\n      image = \"postgres:16-alpine\";\n      ports = [\n        \"5432:5432\"\n      ];\n      restart = \"always\";\n    };\n  };\n}");
/// # Ok::<(), any2nix::Error>(())
/// ```
#[cfg(feature = "yaml")]
pub fn yaml_to_nix(input: &str) -> Result<String, Error> {
    format_to_nix(|s| yaml_serde::from_str::<yaml_serde::Value>(s), input)
}

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

    #[cfg(feature = "ini")]
    #[test]
    fn converts_valid_ini() {
        let format = Format::Ini;
        let ini = "
enable-mouse = no
[dmenu]
mode = index
";
        let nix = format.to_nix(ini);
        let expected = r#"{
  dmenu = {
    mode = "index";
  };
  enable-mouse = "no";
}"#;

        assert_eq!(nix.unwrap(), expected)
    }

    #[cfg(feature = "ini")]
    #[test]
    fn errors_on_invalid_ini() {
        let format = Format::Ini;
        let ini = r#"[broken
nonsense = "
"#;
        let nix = format.to_nix(ini);

        assert!(matches!(nix, Err(Error::Ini(_))))
    }

    #[cfg(feature = "ini")]
    #[test]
    fn fmts_ini() {
        let format_str = Format::Ini.to_string();

        assert_eq!(format_str, "INI")
    }

    #[cfg(feature = "json")]
    #[test]
    fn converts_valid_json() {
        let format = Format::Json;
        let json = r#"{
    "name": "forgejo"
}"#;
        let nix = format.to_nix(json);
        let expected = r#"{
  name = "forgejo";
}"#;

        assert_eq!(nix.unwrap(), expected)
    }

    #[cfg(feature = "json")]
    #[test]
    fn errors_on_invalid_json() {
        let format = Format::Json;
        let json = r#"{
    "unclosed": "
}"#;
        let nix = format.to_nix(json);

        assert!(matches!(nix, Err(Error::Json(_))))
    }

    #[cfg(feature = "json")]
    #[test]
    fn fmts_json() {
        let format_str = Format::Json.to_string();

        assert_eq!(format_str, "JSON")
    }

    #[cfg(feature = "toml")]
    #[test]
    fn converts_valid_toml() {
        let format = Format::Toml;
        let toml = r#"
[package]
name = "any2nix"
"#;
        let nix = format.to_nix(toml);
        let expected = r#"{
  package = {
    name = "any2nix";
  };
}"#;

        assert_eq!(nix.unwrap(), expected)
    }

    #[cfg(feature = "toml")]
    #[test]
    fn errors_on_invalid_toml() {
        let format = Format::Toml;
        let toml = "[broken
doesnt_work = foo";
        let nix = format.to_nix(toml);

        assert!(matches!(nix, Err(Error::Toml(_))))
    }

    #[cfg(feature = "toml")]
    #[test]
    fn fmts_toml() {
        let format_str = Format::Toml.to_string();

        assert_eq!(format_str, "TOML")
    }

    #[cfg(feature = "yaml")]
    #[test]
    fn converts_valid_yaml() {
        let format = Format::Yaml;
        let yaml = "countries:
  - BR
  - NO";
        let nix = format.to_nix(yaml);
        let expected = r#"{
  countries = [
    "BR"
    "NO"
  ];
}"#;

        assert_eq!(nix.unwrap(), expected)
    }

    #[cfg(feature = "yaml")]
    #[test]
    fn errors_on_invalid_yaml() {
        let format = Format::Yaml;
        let yaml = "[unclosed, sequence";
        let nix = format.to_nix(yaml);

        assert!(matches!(nix, Err(Error::Yaml(_))))
    }

    #[cfg(feature = "yaml")]
    #[test]
    fn fmts_yaml() {
        let format_str = Format::Yaml.to_string();

        assert_eq!(format_str, "YAML")
    }
}