gvsn 1.0.1

A fast, cross-platform Go version manager written in Rust
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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
//! Structured shell profile management.
//!
//! Provides safe, predictable manipulation of shell profile files by parsing
//! them into a structured representation, making modifications, and serializing
//! back. This avoids the fragility of string-search-and-replace approaches.

use anyhow::{Context, Result};
use std::path::Path;

/// A single block in a shell profile file.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProfileBlock {
    /// The marker that identifies this block (e.g., "# gvsn init")
    pub marker: String,
    /// The content lines of the block (without the marker line)
    pub lines: Vec<String>,
}

impl ProfileBlock {
    /// Creates a new block with the given marker and content lines.
    pub fn new(
        marker: impl Into<String>,
        lines: impl IntoIterator<Item = impl Into<String>>,
    ) -> Self {
        Self {
            marker: marker.into(),
            lines: lines.into_iter().map(Into::into).collect(),
        }
    }
}

impl std::fmt::Display for ProfileBlock {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        writeln!(f, "{}", self.marker)?;
        for line in &self.lines {
            writeln!(f, "{}", line)?;
        }
        Ok(())
    }
}

/// Represents a parsed shell profile file.
#[derive(Debug, Clone, Default)]
pub struct ShellProfile {
    /// Lines before the first gvsn block
    pub header: Vec<String>,
    /// Gvsn-managed blocks in order
    pub blocks: Vec<ProfileBlock>,
    /// Lines after the last gvsn block
    pub footer: Vec<String>,
}

/// Known gvsn block markers
pub const MARKERS: &[&str] = &[
    "# gvsn init",
    "# gvsn wrapper",
    "# gvsn path",
    "# gvsn: binary location",
];

impl ShellProfile {
    /// Parses a profile file content into a structured representation.
    pub fn parse(content: &str) -> Self {
        let mut profile = Self::default();
        let mut current_block: Option<ProfileBlock> = None;
        let mut in_gvsn_block = false;
        let mut header_done = false;

        for line in content.lines() {
            let trimmed = line.trim();

            // Check if this line starts a gvsn block. Markers are always
            // written as a complete line (see `ProfileBlock`'s `Display`
            // impl), so matching must be exact - `starts_with` would also
            // catch unrelated user comments that merely begin with the same
            // text (e.g. "# gvsn init fue lo primero que probe"), corrupting
            // them into a gvsn-managed block on the next `gvsn setup`/`implode`.
            if let Some(marker) = MARKERS.iter().find(|m| trimmed == **m) {
                // Finish previous block if any
                if let Some(block) = current_block.take() {
                    profile.blocks.push(block);
                }
                // Start new block
                current_block = Some(ProfileBlock::new(
                    marker.to_string(),
                    std::iter::empty::<String>(),
                ));
                in_gvsn_block = true;
                header_done = true;
                continue;
            }

            if in_gvsn_block {
                // End of block on blank line
                if trimmed.is_empty() {
                    if let Some(block) = current_block.take() {
                        profile.blocks.push(block);
                    }
                    in_gvsn_block = false;
                    // Don't add the blank line to footer - it's just a separator
                    continue;
                }
                // Add line to current block
                if let Some(ref mut block) = current_block {
                    block.lines.push(line.to_string());
                }
            } else if header_done {
                // We're in footer
                profile.footer.push(line.to_string());
            } else {
                // We're in header
                profile.header.push(line.to_string());
            }
        }

        // Don't forget the last block if file doesn't end with blank line
        if let Some(block) = current_block {
            profile.blocks.push(block);
        }

        profile
    }

    /// Gets a block by its marker.
    pub fn get_block(&self, marker: &str) -> Option<&ProfileBlock> {
        self.blocks.iter().find(|b| b.marker == marker)
    }

    /// Sets (or adds) a block. If a block with the same marker exists, replaces it.
    pub fn set_block(&mut self, block: ProfileBlock) {
        if let Some(existing) = self.blocks.iter_mut().find(|b| b.marker == block.marker) {
            *existing = block;
        } else {
            self.blocks.push(block);
        }
    }

    fn write_to_string<W: std::fmt::Write>(&self, f: &mut W) -> std::fmt::Result {
        // Header
        for line in &self.header {
            writeln!(f, "{}", line)?;
        }

        // Blocks
        let mut wrote_something = !self.header.is_empty();
        for (i, block) in self.blocks.iter().enumerate() {
            if i > 0 || !self.header.is_empty() {
                writeln!(f)?;
            }
            write!(f, "{}", block)?;
            wrote_something = true;
        }

        // Footer
        if !self.footer.is_empty() {
            // Ensure single blank line before footer if we wrote something before
            if wrote_something {
                writeln!(f)?;
            }
            for line in &self.footer {
                writeln!(f, "{}", line)?;
            }
        }

        Ok(())
    }
}

impl std::fmt::Display for ShellProfile {
    #[allow(clippy::inherent_to_string_shadow_display)]
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.write_to_string(f)
    }
}

/// Checks if the profile has a specific block with expected content.
impl ShellProfile {
    pub fn has_block_with_content(&self, marker: &str, expected_lines: &[String]) -> bool {
        self.get_block(marker)
            .map(|b| b.lines == expected_lines)
            .unwrap_or(false)
    }
}

/// Loads a profile from a file, or creates an empty one if it doesn't exist.
pub fn load_profile(path: &Path) -> Result<ShellProfile> {
    if path.exists() {
        let content = std::fs::read_to_string(path)
            .with_context(|| format!("Cannot read {}", path.display()))?;
        Ok(ShellProfile::parse(&content))
    } else {
        Ok(ShellProfile::default())
    }
}

/// Saves a profile to a file.
pub fn save_profile(path: &Path, profile: &ShellProfile) -> Result<()> {
    let content = profile.to_string();
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)
            .with_context(|| format!("Cannot create directory {}", parent.display()))?;
    }
    std::fs::write(path, content).with_context(|| format!("Cannot write {}", path.display()))?;
    Ok(())
}

/// Updates or adds the gvsn path block in the login profile.
#[cfg(not(target_os = "windows"))]
pub fn update_path_block(path: &Path) -> Result<bool> {
    const MARKER: &str = "# gvsn path";
    const EXPORT_LINE: &str = r#"export PATH="$HOME/.gvsn/current/bin:$PATH""#;

    let mut profile = load_profile(path)?;
    let expected_lines = vec![EXPORT_LINE.to_string()];

    let changed = !profile.has_block_with_content(MARKER, &expected_lines);
    if changed {
        profile.set_block(ProfileBlock::new(MARKER, expected_lines));
        save_profile(path, &profile)?;
    }
    Ok(changed)
}

/// Removes all gvsn-managed blocks from a profile.
pub fn strip_gvsn_blocks(path: &Path) -> Result<bool> {
    if !path.exists() {
        return Ok(false);
    }
    let mut profile = load_profile(path)?;
    let initial_len = profile.blocks.len();
    profile.blocks.clear();
    let changed = profile.blocks.len() != initial_len;
    if changed {
        save_profile(path, &profile)?;
    }
    Ok(changed)
}

/// Ensures a profile has the required gvsn blocks with correct content.
///
/// Returns true if the profile was modified.
pub fn ensure_profile(path: &Path, init_content: &str, wrapper_content: &str) -> Result<bool> {
    let mut profile = load_profile(path)?;

    let expected_init = init_content.lines().map(String::from).collect::<Vec<_>>();
    let expected_wrapper = wrapper_content
        .lines()
        .map(String::from)
        .collect::<Vec<_>>();

    let mut modified = false;

    // Check/update init block
    if !profile.has_block_with_content("# gvsn init", &expected_init) {
        profile.set_block(ProfileBlock::new("# gvsn init", expected_init));
        modified = true;
    }

    // Check/update wrapper block
    if !profile.has_block_with_content("# gvsn wrapper", &expected_wrapper) {
        profile.set_block(ProfileBlock::new("# gvsn wrapper", expected_wrapper));
        modified = true;
    }

    if modified {
        save_profile(path, &profile)?;
    }

    Ok(modified)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::tempdir;

    #[test]
    fn parse_empty() {
        let profile = ShellProfile::parse("");
        assert!(profile.header.is_empty());
        assert!(profile.blocks.is_empty());
        assert!(profile.footer.is_empty());
    }

    #[test]
    fn parse_header_only() {
        let content = "export FOO=bar\nalias ll='ls -la'\n";
        let profile = ShellProfile::parse(content);
        assert_eq!(profile.header.len(), 2);
        assert!(profile.blocks.is_empty());
    }

    #[test]
    fn parse_single_block() {
        let content = "# gvsn init\neval \"$(gvsn env --shell bash)\"\n";
        let profile = ShellProfile::parse(content);
        assert_eq!(profile.blocks.len(), 1);
        assert_eq!(profile.blocks[0].marker, "# gvsn init");
        assert_eq!(
            profile.blocks[0].lines,
            vec!["eval \"$(gvsn env --shell bash)\""]
        );
    }

    #[test]
    fn parse_ignores_user_comment_with_marker_prefix() {
        // A user comment that merely starts with a marker's text (but isn't
        // the marker itself) must stay in the header/footer, not be treated
        // as the start of a gvsn-managed block.
        let content = "# gvsn initially I used zsh\nexport FOO=bar\n";
        let profile = ShellProfile::parse(content);
        assert!(
            profile.blocks.is_empty(),
            "a prefix match must not be treated as a gvsn block"
        );
        assert_eq!(
            profile.header,
            vec![
                "# gvsn initially I used zsh".to_string(),
                "export FOO=bar".to_string(),
            ]
        );
    }

    #[test]
    fn parse_multiple_blocks() {
        let content = r#"# user config
# gvsn init
eval "$(gvsn env --shell bash)"

# gvsn wrapper
gvsn() { command gvsn "$@"; }

# more config
"#;
        let profile = ShellProfile::parse(content);
        assert_eq!(profile.header.len(), 1);
        assert_eq!(profile.blocks.len(), 2);
        assert_eq!(profile.blocks[0].marker, "# gvsn init");
        assert_eq!(profile.blocks[1].marker, "# gvsn wrapper");
        assert_eq!(profile.footer.len(), 1);
    }

    #[test]
    fn block_replacement() {
        let mut profile = ShellProfile::parse("# gvsn init\nold content\n");
        profile.set_block(ProfileBlock::new(
            "# gvsn init",
            vec!["new content".to_string()],
        ));
        assert_eq!(profile.blocks[0].lines, vec!["new content"]);
    }

    #[test]
    fn serialization_roundtrip() {
        let content = r#"# header
# gvsn init
eval "$(gvsn env --shell bash)"

# gvsn wrapper
gvsn() { command gvsn "$@"; }

# footer
"#;
        let profile = ShellProfile::parse(content);
        let serialized = profile.to_string();
        let reparsed = ShellProfile::parse(&serialized);
        assert_eq!(profile.blocks.len(), reparsed.blocks.len());
        // Note: header may have trailing empty string due to parsing behavior
        assert!(reparsed.header.starts_with(&["# header".to_string()]));
        assert_eq!(profile.footer, reparsed.footer);
    }

    #[test]
    fn file_operations() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("profile");

        // Write initial
        fs::write(&path, "# header\n# gvsn init\nold\n").unwrap();

        // Load and modify
        let mut profile = load_profile(&path).unwrap();
        assert_eq!(profile.blocks.len(), 1);
        profile.set_block(ProfileBlock::new("# gvsn init", vec!["new".to_string()]));
        save_profile(&path, &profile).unwrap();

        // Verify
        let content = fs::read_to_string(&path).unwrap();
        assert!(content.contains("new"));
        assert!(!content.contains("old"));
    }

    #[test]
    #[cfg(not(target_os = "windows"))]
    fn update_path_block_adds_block_to_new_file() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("profile");

        let changed = update_path_block(&path).unwrap();
        assert!(changed);

        let content = fs::read_to_string(&path).unwrap();
        assert!(content.contains("# gvsn path"));
        assert!(content.contains(r#"export PATH="$HOME/.gvsn/current/bin:$PATH""#));
    }

    #[test]
    #[cfg(not(target_os = "windows"))]
    fn update_path_block_is_idempotent() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("profile");

        assert!(update_path_block(&path).unwrap());
        // Second call sees the same expected content already present.
        let changed_again = update_path_block(&path).unwrap();
        assert!(!changed_again, "second call must report no change");

        let content = fs::read_to_string(&path).unwrap();
        assert_eq!(content.matches("# gvsn path").count(), 1);
    }

    #[test]
    #[cfg(not(target_os = "windows"))]
    fn update_path_block_preserves_existing_content() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("profile");
        fs::write(&path, "# my custom profile\nexport FOO=bar\n").unwrap();

        update_path_block(&path).unwrap();

        let content = fs::read_to_string(&path).unwrap();
        assert!(content.contains("export FOO=bar"));
        assert!(content.contains("# gvsn path"));
    }

    #[test]
    fn ensure_profile_creates_both_blocks_on_new_file() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("profile");

        let modified = ensure_profile(
            &path,
            "eval \"$(gvsn env --shell bash)\"",
            "gvsn() { command gvsn \"$@\"; }",
        )
        .unwrap();
        assert!(modified);

        let content = fs::read_to_string(&path).unwrap();
        assert!(content.contains("# gvsn init"));
        assert!(content.contains("eval \"$(gvsn env --shell bash)\""));
        assert!(content.contains("# gvsn wrapper"));
        assert!(content.contains("gvsn() { command gvsn \"$@\"; }"));
    }

    #[test]
    fn ensure_profile_is_idempotent() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("profile");
        let init = "eval \"$(gvsn env --shell bash)\"";
        let wrapper = "gvsn() { command gvsn \"$@\"; }";

        assert!(ensure_profile(&path, init, wrapper).unwrap());
        let changed_again = ensure_profile(&path, init, wrapper).unwrap();
        assert!(!changed_again, "second call must report no change");
    }

    #[test]
    fn ensure_profile_updates_stale_content() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("profile");
        let old_wrapper = "gvsn() { command gvsn \"$@\"; }";
        let new_wrapper = "gvsn() { command gvsn \"$@\"; case \"$1\" in use) gvsn env;; esac; }";

        ensure_profile(&path, "eval init", old_wrapper).unwrap();
        let modified = ensure_profile(&path, "eval init", new_wrapper).unwrap();
        assert!(modified);

        let content = fs::read_to_string(&path).unwrap();
        assert!(content.contains(new_wrapper));
        assert!(!content.contains(old_wrapper));
    }

    #[test]
    fn strip_profile_file() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("profile");

        // Include blank line before footer so parser treats it as footer, not part of wrapper block
        fs::write(
            &path,
            "# header\n# gvsn init\ncontent\n\n# gvsn wrapper\nmore\n\n# footer\n",
        )
        .unwrap();

        let changed = strip_gvsn_blocks(&path).unwrap();
        assert!(changed);

        let content = fs::read_to_string(&path).unwrap();
        assert!(!content.contains("# gvsn init"));
        assert!(!content.contains("# gvsn wrapper"));
        assert!(content.contains("# header"));
        assert!(content.contains("# footer"));
    }
}