intelli-shell 3.4.5

Like IntelliSense, but for shells
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
use std::borrow::Cow;

use semver::Version;
use tokio_util::sync::CancellationToken;

use crate::{
    cli::UpdateProcess,
    config::{Config, Theme},
    errors::AppError,
    format_error,
    model::IntelliShellRelease,
    process::{Process, ProcessOutput},
    service::IntelliShellService,
    utils::{InstallationMethod, VersionExt, detect_installation_method, render_markdown_to_ansi},
};

impl Process for UpdateProcess {
    async fn execute(
        self,
        config: Config,
        service: IntelliShellService,
        cancellation_token: CancellationToken,
    ) -> color_eyre::Result<ProcessOutput> {
        let current_version_str = env!("CARGO_PKG_VERSION");
        let current_version_tag = format!("v{current_version_str}");
        let current_version = crate::service::CURRENT_VERSION.clone();

        // Force fetch to ensure we have latest data
        let mut releases = match service.get_or_fetch_releases(true, cancellation_token).await {
            Ok(r) => r,
            Err(AppError::UserFacing(err)) => {
                return Ok(ProcessOutput::fail().stderr(format_error!(config.theme, "{err}")));
            }
            Err(AppError::Unexpected(report)) => return Err(report),
        };

        let latest_release = releases.first().map(|r| r.version.clone());

        let target_version = if let Some(target) = &self.to {
            // Find the release matching the target version
            if !releases.iter().any(|r| &r.version == target) {
                return Ok(ProcessOutput::fail().stderr(format_error!(
                    config.theme,
                    "Requested version {} was not found in the list of releases.",
                    config.theme.accent.apply(target)
                )));
            }
            target.clone()
        } else {
            // Check if latest is newer than current
            match releases.first() {
                Some(r) if r.version > current_version => r.version.clone(),
                _ => {
                    return Ok(ProcessOutput::success().stdout(format!(
                        "You're all set! You are running the latest version of intelli-shell ({}).",
                        config.theme.accent.apply(current_version_tag)
                    )));
                }
            }
        };

        // Common header for all update-needed messages
        let header = if let Some(target) = &self.to {
            if target > &current_version {
                format!(
                    "🚀 Updating to version {} (from {})",
                    config.theme.accent.apply(target),
                    config.theme.secondary.apply(&current_version_tag)
                )
            } else if target < &current_version {
                format!(
                    "⏬ Downgrading to version {} (from {})",
                    config.theme.accent.apply(target),
                    config.theme.secondary.apply(&current_version_tag)
                )
            } else {
                format!("🔄 Reinstalling version {}", config.theme.accent.apply(target))
            }
        } else {
            format!(
                "🚀 A new version is available! ({} -> {})",
                config.theme.secondary.apply(&current_version_tag),
                config.theme.accent.apply(target_version.to_tag()),
            )
        };

        // Detect the installation method to provide tailored instructions
        match detect_installation_method(&config.data_dir) {
            // Handle automatic update via the installer
            InstallationMethod::Installer => {
                println!("{header}\n\nDownloading ...");

                let target_version_tag = target_version.to_tag();
                let status = tokio::task::spawn_blocking(move || {
                    self_update::backends::github::Update::configure()
                        .repo_owner("lasantosr")
                        .repo_name("intelli-shell")
                        .bin_name("intelli-shell")
                        .show_output(false)
                        .show_download_progress(true)
                        .no_confirm(true)
                        .current_version(current_version_str)
                        .target_version_tag(&target_version_tag)
                        .build()?
                        .update()
                })
                .await?;

                println!("\n");

                // Provide update feedback
                match status {
                    Ok(self_update::Status::UpToDate(_)) => unreachable!(),
                    Ok(self_update::Status::Updated(_)) => {
                        // If the current version is not present, there has been a gap
                        let gap =
                            target_version > current_version && !releases.iter().any(|r| r.version == current_version);
                        // We don't need considerations for the current version or older, or versions beyond
                        // target_version
                        releases.retain(|r| r.version > current_version && r.version <= target_version);
                        // Build aggregated considerations message
                        let considerations = build_considerations_message(&releases, &target_version);

                        // Build the final message
                        let mut msg = format!(
                            "✅ You're all set! You are now on intelli-shell {}.\n\n",
                            config.theme.accent.apply(target_version.to_tag())
                        );
                        if !considerations.is_empty() {
                            if gap {
                                msg.push_str(
                                    "⚠️ You have skipped many versions. The following migration steps are required, \
                                     but please check GitHub Releases as this list may be incomplete:\n\n",
                                );
                            } else {
                                msg.push_str("💡 Some updates require additional steps to complete:\n\n");
                            }
                        } else if gap {
                            msg.push_str(
                                "⚠️ You have skipped many versions, please check GitHub Releases to ensure no manual \
                                 migration steps were missed.\n\n",
                            );
                        }
                        if !considerations.is_empty() {
                            msg.push_str(&render_markdown_to_ansi(&considerations, &config.theme));
                            msg.push_str("\n\n");
                        }
                        let is_latest = latest_release.as_ref() == Some(&target_version);
                        let changelog_cmd = if target_version > current_version {
                            if is_latest {
                                format!("intelli-shell changelog --from {}", current_version_str)
                            } else {
                                format!(
                                    "intelli-shell changelog --from {} --to {}",
                                    current_version_str, target_version
                                )
                            }
                        } else if target_version < current_version {
                            format!(
                                "intelli-shell changelog --from {} --to {}",
                                target_version, current_version_str
                            )
                        } else {
                            format!(
                                "intelli-shell changelog --from {} --to {}",
                                target_version, target_version
                            )
                        };

                        msg.push_str(&format!(
                            "📄 To view the full changelog, run: {}",
                            config.theme.accent.apply(changelog_cmd)
                        ));
                        Ok(ProcessOutput::success().stdout(msg))
                    }
                    Err(err) => Ok(ProcessOutput::fail().stderr(format!(
                        "❌ Update failed:\n{err}\n\nPlease check your network connection or file permissions.",
                    ))),
                }
            }
            // Provide clear, copyable instructions for other installation methods
            installation_method => {
                let instructions = get_manual_update_instructions(installation_method, &config.theme);
                let full_message = format!("{header}\n\n{instructions}");
                Ok(ProcessOutput::success().stdout(full_message))
            }
        }
    }
}

/// Generates user-friendly update instructions based on the installation method
fn get_manual_update_instructions(method: InstallationMethod, theme: &Theme) -> String {
    match method {
        InstallationMethod::Cargo => format!(
            "It looks like you installed with {}. To update, please run:\n\n{}\n",
            theme.secondary.apply("cargo"),
            theme
                .accent
                .apply("  LIBSQLITE3_FLAGS=\"-DSQLITE_ENABLE_MATH_FUNCTIONS\" cargo install intelli-shell --locked")
        ),
        InstallationMethod::Nix => format!(
            "It looks like you installed with {}. Consider updating it via your Nix configuration.",
            theme.secondary.apply("Nix")
        ),
        InstallationMethod::Homebrew => format!(
            "It looks like you installed with {}. To update, please run:\n\n{}\n",
            theme.secondary.apply("Homebrew"),
            theme.accent.apply("  brew upgrade intelli-shell")
        ),
        InstallationMethod::Source => format!(
            "It looks like you installed from {}. You might need to run:\n\n{}\n",
            theme.secondary.apply("source"),
            theme.accent.apply("  git pull && cargo build --release")
        ),
        InstallationMethod::Unknown(Some(path)) => format!(
            "Could not determine the installation method. Your executable is located at:\n\n  {}\n\nPlease update \
             manually or consider reinstalling with the recommended script.",
            theme.accent.apply(path)
        ),
        InstallationMethod::Unknown(None) => {
            "Could not determine the installation method. Please update manually.".to_string()
        }
        InstallationMethod::Installer => unreachable!(),
    }
}

/// Builds the aggregated considerations message from a list of releases.
///
/// `releases` is expected to be ordered Newest -> Oldest (as returned by `get_or_fetch_releases`).
fn build_considerations_message(releases: &[IntelliShellRelease], latest_version: &Version) -> String {
    // Collect only releases that have considerations
    let mut active_updates: Vec<(&IntelliShellRelease, String)> = releases
        .iter()
        .filter_map(|r| {
            r.body
                .as_deref()
                .and_then(extract_update_considerations)
                .map(|c| (r, c))
        })
        .collect();

    // Check if there's a single version with consideration, being the latest
    let is_single_latest =
        active_updates.len() == 1 && active_updates.first().map(|(r, _)| &r.version) == Some(latest_version);

    // Reorder to Chronological (Oldest -> Newest) for display
    active_updates.reverse();

    // Aggregate considerations
    let mut considerations = String::new();
    for (release, cons) in active_updates {
        // Add Version Header if needed
        if !is_single_latest {
            considerations.push_str(&format!("- **{}**\n", release.tag));
        }
        // Process body lines
        for line in cons.lines() {
            let trimmed = line.trim();
            if trimmed.is_empty() {
                continue;
            }

            // Check if the line already acts as a list item
            let has_bullet = trimmed.starts_with('-') || trimmed.starts_with('*') || trimmed.starts_with('+');

            // Normalize: Ensure the line is a list item
            // If it has a bullet, we keep the raw 'line' to preserve existing nesting/indentation.
            // If it doesn't, we force it to be a bullet item.
            let normalized_line = if has_bullet {
                Cow::Borrowed(line)
            } else {
                Cow::Owned(format!("- {}", trimmed))
            };

            // Indent: Shift everything right if we are nesting under a version header
            if !is_single_latest {
                considerations.push_str("  ");
            }

            considerations.push_str(&normalized_line);
            considerations.push('\n');
        }
    }
    considerations
}

/// Extracts the "Update Considerations" section from the release body, if present.
fn extract_update_considerations(body: &str) -> Option<String> {
    let lines = body.lines();
    let mut capturing = false;
    let mut content = String::new();

    for line in lines {
        let trimmed = line.trim();
        if trimmed.starts_with('#') {
            if trimmed.to_lowercase().contains("update consideration")
                || trimmed.to_lowercase().contains("update instructions")
                || trimmed.to_lowercase().contains("update guide")
                || trimmed.to_lowercase().contains("upgrade consideration")
                || trimmed.to_lowercase().contains("upgrade instructions")
                || trimmed.to_lowercase().contains("upgrade guide")
                || trimmed.to_lowercase().contains("migration")
            {
                capturing = true;
                continue;
            } else if capturing {
                break;
            }
        }

        if capturing {
            if !content.is_empty() {
                content.push('\n');
            }
            content.push_str(line);
        }
    }

    let trimmed_content = content.trim();
    if trimmed_content.is_empty() {
        None
    } else {
        Some(trimmed_content.to_string())
    }
}

#[cfg(test)]
mod tests {
    use chrono::Utc;

    use super::*;
    use crate::model::IntelliShellRelease;

    #[test]
    fn test_extract_update_considerations() {
        let body = r#"
# Release Notes

Some intro text.

## Update Considerations

This is a critical update.
Please restart your shell.

## Changelog

- Fix bug A
- Add feature B
"#;
        let expected = "This is a critical update.\nPlease restart your shell.";
        assert_eq!(extract_update_considerations(body), Some(expected.to_string()));

        let body_no_considerations = r#"
# Release Notes

## Changelog
- Fix bug A
"#;
        assert_eq!(extract_update_considerations(body_no_considerations), None);

        let body_empty_considerations = r#"
## Update Considerations

## Changelog
"#;
        assert_eq!(extract_update_considerations(body_empty_considerations), None);

        let body_last_section = r#"
## Update Considerations
Last section.
"#;
        assert_eq!(
            extract_update_considerations(body_last_section),
            Some("Last section.".to_string())
        );
    }

    #[test]
    fn test_build_considerations_message() {
        fn make_release(version: &str, body: Option<&str>) -> IntelliShellRelease {
            IntelliShellRelease {
                tag: format!("v{}", version),
                version: Version::parse(version).unwrap(),
                title: "Release".into(),
                body: body.map(|s| s.into()),
                published_at: Utc::now(),
                fetched_at: Utc::now(),
            }
        }

        // Case 1: Multiple updates with considerations
        let releases_multi = vec![
            make_release("1.2.0", Some("## Update Considerations\nCritical 1.2")),
            make_release("1.1.0", Some("No considerations")),
            make_release(
                "1.0.0",
                Some("## Update Considerations\n- Explicit list item\nImplicit item"),
            ),
        ];
        let latest_multi = Version::parse("1.2.0").unwrap();

        let msg_multi = build_considerations_message(&releases_multi, &latest_multi);

        // Expected order: 1.0.0, then 1.2.0
        assert!(msg_multi.contains("- **v1.0.0**"));
        assert!(msg_multi.contains("  - Explicit list item"));
        assert!(msg_multi.contains("  - Implicit item"));
        assert!(msg_multi.contains("- **v1.2.0**"));
        assert!(msg_multi.contains("  - Critical 1.2"));

        // Case 2: Single latest update with considerations
        let releases_single = vec![make_release("1.3.0", Some("## Update Considerations\nJust me"))];
        let latest_single = Version::parse("1.3.0").unwrap();

        let msg_single = build_considerations_message(&releases_single, &latest_single);

        // Should NOT have version header
        assert!(!msg_single.contains("**v1.3.0**"));
        // Should NOT have indentation
        assert!(msg_single.contains("- Just me"));
        assert!(!msg_single.contains("  - Just me"));

        // Case 3: Single OLD update with considerations (e.g. skipped 1.4, installing 1.5 which has none, but 1.4 has)
        // If active_updates has 1 element which is NOT latest, it should have header.
        let releases_gap = vec![
            make_release("1.5.0", None),
            make_release("1.4.0", Some("## Update Considerations\nGap update")),
        ];
        let latest_gap = Version::parse("1.5.0").unwrap();

        let msg_gap = build_considerations_message(&releases_gap, &latest_gap);

        assert!(msg_gap.contains("- **v1.4.0**"));
        assert!(msg_gap.contains("  - Gap update"));
    }
}