env-sync 0.1.1

Easily update your local env file with a git-trackable file
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
//! Environment file parsing with comment preservation.
//!
//! This module provides zero-copy parsing of `.env` files that preserves comments
//! and associates them with environment variables. Comments can appear before
//! variables (preceding comments) or on the same line (inline comments).
//!
//! # Examples
//!
//! ```rust,no_run
//! use env_sync::parse::EnvFile;
//! use std::convert::TryFrom;
//!
//! let content = r#"
//! # Database configuration
//! DB_HOST=localhost
//! DB_PORT=5432 # Default PostgreSQL port
//! "#;
//!
//! let env_file = EnvFile::try_from(content).unwrap();
//! println!("{}", env_file);
//! ```

use std::{borrow::Cow, convert::TryFrom, fmt};

#[cfg(feature = "tracing")]
use tracing::{debug, trace};

const COMMENT_PREFIX: &str = "#";
const ASSIGNMENT_OPERATOR: &str = "=";

/// Represents a parsed environment file with preserved comments.
///
/// The `EnvFile` contains a sequence of entries that can be variables,
/// comments, or empty lines, maintaining the original file structure.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct EnvFile<'a> {
  pub entries: Vec<EnvEntry<'a>>,
}

impl<'a> fmt::Display for EnvFile<'a> {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    for entry in &self.entries {
      write!(f, "{}", entry)?;
    }
    Ok(())
  }
}

impl<'a> TryFrom<&'a str> for EnvFile<'a> {
  type Error = ParseError;

  fn try_from(s: &'a str) -> Result<Self, Self::Error> {
    #[cfg(feature = "tracing")]
    debug!("Parsing env file with {} lines", s.lines().count());

    let mut entries = Vec::new();
    let mut pending_comments = Vec::new();

    for line in s.lines() {
      #[cfg(feature = "tracing")]
      trace!("Parsing line: {:?}", line);

      let mut entry: EnvEntry = line.try_into()?;

      if let EnvEntry::Variable(ref mut var) = entry {
        #[cfg(feature = "tracing")]
        trace!(
          "Found variable: {} with {} pending comments",
          var.key,
          pending_comments.len()
        );

        var.preceding_comments = std::mem::take(&mut pending_comments);
      } else if let EnvEntry::OrphanComment(comment) = entry {
        #[cfg(feature = "tracing")]
        trace!("Found comment, adding to pending");

        pending_comments.push(comment);
        continue;
      } else if matches!(entry, EnvEntry::EmptyLine) && !pending_comments.is_empty() {
        #[cfg(feature = "tracing")]
        trace!(
          "Empty line with {} pending comments, flushing",
          pending_comments.len()
        );

        for comment in pending_comments.drain(..) {
          entries.push(EnvEntry::OrphanComment(comment));
        }
      }

      entries.push(entry);
    }

    for comment in pending_comments {
      entries.push(EnvEntry::OrphanComment(comment));
    }

    #[cfg(feature = "tracing")]
    debug!("Parsed {} entries", entries.len());

    Ok(Self { entries })
  }
}

impl<'a> EnvFile<'a> {
  /// Finds an environment variable by its key.
  ///
  /// Returns the first variable with the matching key, or `None` if not found.
  pub fn get(&self, key: &str) -> Option<&EnvVariable<'a>> {
    self.entries.iter().find_map(|entry| {
      if let EnvEntry::Variable(var) = entry {
        if var.key == key { Some(var) } else { None }
      } else {
        None
      }
    })
  }
}

/// Represents a single entry in an environment file.
#[derive(Debug, Clone, PartialEq)]
pub enum EnvEntry<'a> {
  /// A variable assignment with optional comments
  Variable(EnvVariable<'a>),
  /// A comment not associated with a variable
  OrphanComment(EnvComment<'a>),
  /// An empty line
  EmptyLine,
}

impl<'a> fmt::Display for EnvEntry<'a> {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    match self {
      EnvEntry::Variable(var) => {
        write!(f, "{}", var)?;
        writeln!(f)
      }
      EnvEntry::OrphanComment(comment) => {
        writeln!(f, "{}", comment)
      }
      EnvEntry::EmptyLine => {
        writeln!(f)
      }
    }
  }
}

impl<'a> TryFrom<&'a str> for EnvEntry<'a> {
  type Error = ParseError;

  fn try_from(s: &'a str) -> Result<Self, Self::Error> {
    let trimmed = s.trim();

    if trimmed.is_empty() {
      Ok(EnvEntry::EmptyLine)
    } else if trimmed.starts_with(COMMENT_PREFIX) {
      Ok(EnvEntry::OrphanComment(trimmed.try_into()?))
    } else {
      Ok(EnvEntry::Variable(trimmed.try_into()?))
    }
  }
}

/// Represents an environment variable with its value and associated comments.
#[derive(Debug, Clone, PartialEq)]
pub struct EnvVariable<'a> {
  /// The variable name
  pub key: Cow<'a, str>,
  /// The variable value
  pub value: Cow<'a, str>,
  /// Comments that appear before this variable
  pub preceding_comments: Vec<EnvComment<'a>>,
  /// Comment that appears on the same line as the variable
  pub inline_comment: Option<EnvComment<'a>>,
}

impl<'a> fmt::Display for EnvVariable<'a> {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    for comment in &self.preceding_comments {
      writeln!(f, "{}", comment)?;
    }
    write!(f, "{}{}{}", self.key, ASSIGNMENT_OPERATOR, self.value)?;
    if let Some(comment) = &self.inline_comment {
      write!(f, " {}", comment)?;
    }
    Ok(())
  }
}

impl<'a> TryFrom<&'a str> for EnvVariable<'a> {
  type Error = ParseError;

  fn try_from(s: &'a str) -> Result<Self, Self::Error> {
    #[cfg(feature = "tracing")]
    trace!("Parsing variable from: {:?}", s);

    if let Some((key, value_part)) = s.split_once(ASSIGNMENT_OPERATOR) {
      let key = key.trim();

      let (value, inline_comment) =
        if let Some((value, comment)) = value_part.split_once(COMMENT_PREFIX) {
          (value.trim(), Some(EnvComment(Cow::Borrowed(comment))))
        } else {
          (value_part.trim(), None)
        };

      #[cfg(feature = "tracing")]
      trace!(
        "Parsed variable: key={}, value={}, has_inline_comment={}",
        key,
        value,
        inline_comment.is_some()
      );

      Ok(EnvVariable {
        key: Cow::Borrowed(key),
        value: Cow::Borrowed(value),
        preceding_comments: Vec::new(),
        inline_comment,
      })
    } else {
      Err(ParseError::InvalidLine(s.to_string()))
    }
  }
}

/// Represents a comment in an environment file.
///
/// The comment content excludes the leading `#` character.
#[derive(Debug, Clone, PartialEq)]
pub struct EnvComment<'a>(Cow<'a, str>);

impl<'a> fmt::Display for EnvComment<'a> {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    write!(f, "{}{}", COMMENT_PREFIX, self.0)
  }
}

impl<'a> TryFrom<&'a str> for EnvComment<'a> {
  type Error = ParseError;

  fn try_from(s: &'a str) -> Result<Self, Self::Error> {
    #[cfg(feature = "tracing")]
    trace!("Parsing comment from: {:?}", s);

    let trimmed = s.trim();
    if let Some(content) = trimmed.strip_prefix(COMMENT_PREFIX) {
      #[cfg(feature = "tracing")]
      trace!("Parsed comment content: {:?}", content);

      Ok(EnvComment(Cow::Borrowed(content)))
    } else {
      Err(ParseError::InvalidLine(s.to_string()))
    }
  }
}

/// Errors that can occur during parsing.
#[derive(Debug, thiserror::Error)]
pub enum ParseError {
  /// A line that cannot be parsed as a variable, comment, or empty line
  #[error("Invalid line: {0}")]
  InvalidLine(String),
}

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

  #[test]
  fn test_parse_simple() {
    let input = "KEY=value\nANOTHER=test";
    let env: EnvFile = input.try_into().unwrap();

    assert_eq!(env.entries.len(), 2);
    match &env.entries[0] {
      EnvEntry::Variable(var) => {
        assert_eq!(var.key, "KEY");
        assert_eq!(var.value, "value");
      }
      _ => panic!("Expected variable"),
    }
    match &env.entries[1] {
      EnvEntry::Variable(var) => {
        assert_eq!(var.key, "ANOTHER");
        assert_eq!(var.value, "test");
      }
      _ => panic!("Expected variable"),
    }
  }

  #[test]
  fn test_parse_with_comments() {
    let input = "# This is a comment\nKEY=value\n# Another comment\n# Multi line\nTEST=123";
    let env: EnvFile = input.try_into().unwrap();

    let mut iter = env.entries.iter();

    // First entry should be KEY variable with one preceding comment
    match iter.next().unwrap() {
      EnvEntry::Variable(var) => {
        assert_eq!(var.key, "KEY");
        assert_eq!(var.value, "value");
        assert_eq!(var.preceding_comments.len(), 1);
        assert_eq!(var.preceding_comments[0].to_string(), "# This is a comment");
      }
      _ => panic!("Expected variable"),
    }

    // Second entry should be TEST variable with two preceding comments
    match iter.next().unwrap() {
      EnvEntry::Variable(var) => {
        assert_eq!(var.key, "TEST");
        assert_eq!(var.value, "123");
        assert_eq!(var.preceding_comments.len(), 2);
        assert_eq!(var.preceding_comments[0].to_string(), "# Another comment");
        assert_eq!(var.preceding_comments[1].to_string(), "# Multi line");
      }
      _ => panic!("Expected variable"),
    }

    assert!(iter.next().is_none());
  }

  #[test]
  fn test_parse_inline_comments() {
    let input = "KEY=value # This is inline\nTEST=123";
    let env: EnvFile = input.try_into().unwrap();

    match &env.entries[0] {
      EnvEntry::Variable(var) => {
        assert_eq!(var.key, "KEY");
        assert_eq!(var.value, "value");
        assert_eq!(
          var.inline_comment,
          Some(EnvComment(Cow::Owned(" This is inline".to_string())))
        );
      }
      _ => panic!("Expected variable"),
    }
  }

  #[test]
  fn test_roundtrip() {
    let input = "# Comment\nKEY=value\n\n# Orphan\nTEST=123 # inline";
    let env: EnvFile = input.try_into().unwrap();
    let output = env.to_string();

    // Parse the output again and compare
    let env2: EnvFile = output.as_str().try_into().unwrap();
    assert_eq!(env, env2);
  }

  #[test]
  fn test_env_entry_from_str() {
    // Test empty line
    let entry: EnvEntry = "".try_into().unwrap();
    assert_eq!(entry, EnvEntry::EmptyLine);

    // Test comment
    let entry: EnvEntry = "# This is a comment".try_into().unwrap();
    match entry {
      EnvEntry::OrphanComment(comment) => assert_eq!(
        comment,
        EnvComment(Cow::Owned(" This is a comment".to_string()))
      ),
      _ => panic!("Expected OrphanComment"),
    }

    // Test variable
    let entry: EnvEntry = "KEY=value".try_into().unwrap();
    match entry {
      EnvEntry::Variable(var) => {
        assert_eq!(var.key, "KEY");
        assert_eq!(var.value, "value");
        assert!(var.preceding_comments.is_empty());
        assert!(var.inline_comment.is_none());
      }
      _ => panic!("Expected Variable"),
    }

    // Test variable with inline comment
    let entry: EnvEntry = "KEY=value # comment".try_into().unwrap();
    match entry {
      EnvEntry::Variable(var) => {
        assert_eq!(var.key, "KEY");
        assert_eq!(var.value, "value");
        assert_eq!(
          var.inline_comment,
          Some(EnvComment(Cow::Owned(" comment".to_string())))
        );
      }
      _ => panic!("Expected Variable"),
    }

    // Test invalid line
    assert!(EnvEntry::try_from("invalid line without equals").is_err());
  }

  #[test]
  fn test_key_without_value() {
    // Test key with equals but no value
    let entry: EnvEntry = "KEY=".try_into().unwrap();
    match entry {
      EnvEntry::Variable(var) => {
        assert_eq!(var.key, "KEY");
        assert_eq!(var.value, "");
        assert!(var.inline_comment.is_none());
      }
      _ => panic!("Expected Variable"),
    }

    // Test key with equals and whitespace
    let entry: EnvEntry = "KEY=   ".try_into().unwrap();
    match entry {
      EnvEntry::Variable(var) => {
        assert_eq!(var.key, "KEY");
        assert_eq!(var.value, "");
        assert!(var.inline_comment.is_none());
      }
      _ => panic!("Expected Variable"),
    }
  }
}