juliaup 1.19.10

Julia installer and version multiplexer
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
use anyhow::{anyhow, bail, Context, Result};
use console::style;
use retry::{
    delay::{jitter, Fibonacci},
    retry, OperationResult,
};
use semver::{BuildMetadata, Version};
use std::path::{Path, PathBuf};
use std::sync::OnceLock;
use url::Url;

/// Resolves the Julia binary path, accounting for .app bundles on macOS
#[cfg(target_os = "macos")]
pub fn resolve_julia_binary_path(base_path: &Path) -> Result<PathBuf> {
    // Check if this is a .app bundle installation
    if let Ok(entries) = std::fs::read_dir(base_path) {
        for entry in entries.flatten() {
            if entry
                .file_name()
                .to_str()
                .is_some_and(|name| name.ends_with(".app"))
            {
                // This is a DMG installation with .app bundle
                let julia_path = entry
                    .path()
                    .join("Contents")
                    .join("Resources")
                    .join("julia")
                    .join("bin")
                    .join(format!("julia{}", std::env::consts::EXE_SUFFIX));

                if julia_path.exists() {
                    return Ok(julia_path);
                }
            }
        }
    }

    // Fall back to standard path (tarball installation)
    Ok(base_path
        .join("bin")
        .join(format!("julia{}", std::env::consts::EXE_SUFFIX)))
}

#[cfg(not(target_os = "macos"))]
pub fn resolve_julia_binary_path(base_path: &Path) -> Result<PathBuf> {
    Ok(base_path
        .join("bin")
        .join(format!("julia{}", std::env::consts::EXE_SUFFIX)))
}

/// Cached result of whether the nightly server supports etag headers.
/// This is used to avoid repeated HTTP requests to check server capabilities.
static NIGHTLY_SERVER_SUPPORTS_ETAG: OnceLock<bool> = OnceLock::new();

/// Checks if the nightly server supports etag headers.
/// This is required for nightly and PR channel support because we use etags
/// to track versions of these builds.
///
/// The result is cached after the first check.
/// If JULIAUP_SERVER equals the default official ones, it works as usual (assumes ETAG support).
/// Otherwise, sends a HEAD check request to verify ETAG support.
#[cfg(not(windows))]
pub fn check_server_supports_nightlies() -> Result<bool> {
    Ok(*NIGHTLY_SERVER_SUPPORTS_ETAG.get_or_init(|| {
        // Check if JULIAUP_SERVER equals the default official one
        let is_default_server = {
            let julia_server = std::env::var("JULIAUP_SERVER")
                .unwrap_or_else(|_| "https://julialang-s3.julialang.org".to_string());

            // Normalize URL (remove trailing slashes for comparison)
            let julia_server_normalized = julia_server.trim_end_matches('/');

            julia_server_normalized == "https://julialang-s3.julialang.org"
        };

        // If using default official servers, assume ETAG support
        if is_default_server {
            return true;
        }

        // For custom servers, check via HEAD request
        let base_url = match get_julianightlies_base_url() {
            Ok(url) => url,
            Err(_) => return false,
        };

        let test_url = match base_url.join("bin/") {
            Ok(url) => url,
            Err(_) => return false,
        };

        let client = reqwest::blocking::Client::new();
        match client.head(test_url.as_str()).send() {
            Ok(response) => {
                let has_etag = response.headers().get("etag").is_some();
                log::debug!("Server etag support check: {}", has_etag);
                has_etag
            }
            Err(e) => {
                log::debug!("Failed to check server etag support: {}", e);
                false
            }
        }
    }))
}

/// Checks if the nightly server supports etag headers.
/// This is required for nightly and PR channel support because we use etags
/// to track versions of these builds.
///
/// The result is cached after the first check.
/// If JULIAUP_SERVER equals the default official ones, it works as usual (assumes ETAG support).
/// Otherwise, sends a HEAD check request to verify ETAG support.
#[cfg(windows)]
pub fn check_server_supports_nightlies() -> Result<bool> {
    use windows::core::HSTRING;
    use windows::Foundation::Uri;
    use windows::Web::Http::HttpClient;
    use windows::Web::Http::HttpMethod;
    use windows::Web::Http::HttpRequestMessage;

    Ok(*NIGHTLY_SERVER_SUPPORTS_ETAG.get_or_init(|| {
        // Check if JULIAUP_SERVER equals the default official one
        let is_default_server = {
            let julia_server = std::env::var("JULIAUP_SERVER")
                .unwrap_or_else(|_| "https://julialang-s3.julialang.org".to_string());

            // Parse and compare URLs properly to handle variations
            match Url::parse(&julia_server) {
                Ok(parsed) => {
                    if let Ok(default_url) = Url::parse("https://julialang-s3.julialang.org") {
                        parsed.scheme() == default_url.scheme()
                            && parsed.host_str() == default_url.host_str()
                            && parsed.path().trim_end_matches('/')
                                == default_url.path().trim_end_matches('/')
                    } else {
                        false
                    }
                }
                Err(_) => {
                    // Fall back to simple string comparison if URL parsing fails
                    let julia_server_normalized = julia_server.trim_end_matches('/');
                    julia_server_normalized == "https://julialang-s3.julialang.org"
                }
            }
        };

        // If using default official servers, assume ETAG support
        if is_default_server {
            return true;
        }

        // For custom servers, check via HEAD request
        let base_url = match get_julianightlies_base_url() {
            Ok(url) => url,
            Err(e) => {
                log::debug!("Failed to get nightly base URL: {}", e);
                return false;
            }
        };

        let test_url = match base_url.join("bin/") {
            Ok(url) => url,
            Err(e) => {
                log::debug!("Failed to join bin/ to base URL: {}", e);
                return false;
            }
        };

        let http_client = match HttpClient::new() {
            Ok(client) => client,
            Err(e) => {
                log::debug!("Failed to create HTTP client: {:?}", e);
                return false;
            }
        };

        let request_uri = match Uri::CreateUri(&HSTRING::from(test_url.as_str())) {
            Ok(uri) => uri,
            Err(e) => {
                log::debug!("Failed to create URI: {:?}", e);
                return false;
            }
        };

        let head_method = match HttpMethod::Head() {
            Ok(m) => m,
            Err(e) => {
                log::debug!("Failed to create HEAD method: {:?}", e);
                return false;
            }
        };

        let request = match HttpRequestMessage::Create(&head_method, &request_uri) {
            Ok(req) => req,
            Err(e) => {
                log::debug!("Failed to create request: {:?}", e);
                return false;
            }
        };

        let response = match http_client.SendRequestAsync(&request) {
            Ok(async_op) => match async_op.join() {
                Ok(resp) => resp,
                Err(e) => {
                    log::debug!("Failed to send HEAD request: {:?}", e);
                    return false;
                }
            },
            Err(e) => {
                log::debug!("Failed to start HEAD request: {:?}", e);
                return false;
            }
        };

        match response.Headers() {
            Ok(headers) => {
                let has_etag = headers.Lookup(&HSTRING::from("ETag")).is_ok();
                log::debug!("Server etag support check: {}", has_etag);
                has_etag
            }
            Err(e) => {
                log::debug!("Failed to get response headers: {:?}", e);
                false
            }
        }
    }))
}

pub fn get_juliaserver_base_url() -> Result<Url> {
    let base_url = if let Ok(val) = std::env::var("JULIAUP_SERVER") {
        if val.ends_with('/') {
            val
        } else {
            format!("{}/", val)
        }
    } else {
        "https://julialang-s3.julialang.org".to_string()
    };

    let parsed_url = Url::parse(&base_url).with_context(|| {
        format!(
            "Failed to parse the value of JULIAUP_SERVER '{}' as a uri.",
            base_url
        )
    })?;

    Ok(parsed_url)
}

pub fn get_julianightlies_base_url() -> Result<Url> {
    let base_url = if let Ok(val) = std::env::var("JULIAUP_NIGHTLY_SERVER") {
        if val.ends_with('/') {
            val
        } else {
            format!("{}/", val)
        }
    } else {
        "https://julialangnightlies-s3.julialang.org".to_string()
    };

    let parsed_url = Url::parse(&base_url).with_context(|| {
        format!(
            "Failed to parse the value of JULIAUP_NIGHTLY_SERVER '{}' as a uri.",
            base_url
        )
    })?;

    Ok(parsed_url)
}

pub fn get_bin_dir() -> Result<PathBuf> {
    let entry_sep = if std::env::consts::OS == "windows" {
        ';'
    } else {
        ':'
    };

    let path = match std::env::var("JULIAUP_BIN_DIR") {
        Ok(val) => {
            let path = PathBuf::from(val.split(entry_sep).next().unwrap()); // We can unwrap here because even when we split an empty string we should get a first element.

            if !path.is_absolute() {
                bail!("The `JULIAUP_BIN_DIR` environment variable contains a value that resolves to an an invalid path `{}`.", path.display());
            };

            path
        }
        Err(_) => {
            let mut path = std::env::current_exe()
                .with_context(|| "Could not determine the path of the running exe.")?
                .parent()
                .ok_or_else(|| anyhow!("Could not determine parent."))?
                .to_path_buf();

            if let Some(home_dir) = dirs::home_dir() {
                if !path.starts_with(&home_dir) {
                    path = home_dir.join(".local").join("bin");

                    if !path.is_absolute() {
                        bail!(
                            "The system returned an invalid home directory path `{}`.",
                            path.display()
                        );
                    };
                }
            }

            path
        }
    };

    Ok(path)
}

pub fn is_valid_julia_path(julia_path: &PathBuf) -> bool {
    std::process::Command::new(julia_path)
        .arg("-v")
        .stdout(std::process::Stdio::null())
        .spawn()
        .is_ok()
}

pub fn get_arch() -> Result<String> {
    if std::env::consts::ARCH == "x86" {
        return Ok("x86".to_string());
    } else if std::env::consts::ARCH == "x86_64" {
        return Ok("x64".to_string());
    } else if std::env::consts::ARCH == "aarch64" {
        return Ok("aarch64".to_string());
    }

    bail!("Running on an unknown arch: {}.", std::env::consts::ARCH)
}

pub fn parse_versionstring(value: &String) -> Result<(String, Version)> {
    let version = Version::parse(value).unwrap();

    let build_parts: Vec<&str> = version.build.split('.').collect();

    if build_parts.len() < 4 {
        bail!(
            "`{}` is an invalid version specifier: the build part must have at least four parts.",
            value
        );
    }

    let version_without_build = semver::Version {
        major: version.major,
        minor: version.minor,
        patch: version.patch,
        pre: version.pre,
        build: BuildMetadata::EMPTY,
    };

    let platform = build_parts[1];

    Ok((platform.to_string(), version_without_build))
}

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

    #[test]
    fn test_parse_versionstring() {
        let s = "1.1.1";
        assert!(parse_versionstring(&s.to_owned()).is_err());

        let s = "1.1.1+0.x86.apple.darwin14";
        let (p, v) = parse_versionstring(&s.to_owned()).unwrap();
        assert_eq!(p, "x86");
        assert_eq!(v, Version::new(1, 1, 1));

        let s = "1.1.1+0.x64.apple.darwin14";
        let (p, v) = parse_versionstring(&s.to_owned()).unwrap();
        assert_eq!(p, "x64");
        assert_eq!(v, Version::new(1, 1, 1));

        // FreeBSD has 5 parts in the build metadata
        let s = "1.10.10+0.x64.unknown.freebsd11.1";
        let (p, v) = parse_versionstring(&s.to_owned()).unwrap();
        assert_eq!(p, "x64");
        assert_eq!(v, Version::new(1, 10, 10));
    }
}

// Message formatting constants and functions
// Match the indent of Pkg.jl style messages
const JULIAUP_STYLE_INDENT: usize = 12; // Width of "Precompiling" in Pkg

/// Color options for styled messages
#[derive(Clone, Copy)]
pub enum JuliaupMessageType {
    Success,
    Error,
    Warning,
    Progress,
}

enum JuliaupStyleColor {
    Green,
    Red,
    Yellow,
    Cyan,
}

impl JuliaupMessageType {
    fn color(&self) -> JuliaupStyleColor {
        match self {
            JuliaupMessageType::Success => JuliaupStyleColor::Green,
            JuliaupMessageType::Progress => JuliaupStyleColor::Cyan,
            JuliaupMessageType::Warning => JuliaupStyleColor::Yellow,
            JuliaupMessageType::Error => JuliaupStyleColor::Red,
        }
    }
}

/// Print a styled message with Pkg.jl-like formatting (right-aligned prefix)
/// Format: "     [action] message"
///
/// # Message Types
/// - **Success**: Completion messages (Configure, Link, Remove, Tidyup) - Green
/// - **Progress**: Active/in-progress operations (Updating, Installing, Creating, Deleting, Checking) - Cyan
/// - **Warning**: Non-critical issues that need attention - Yellow
/// - **Error**: Critical failures - Red
///
pub fn print_juliaup_style(action: &str, message: &str, message_type: JuliaupMessageType) {
    let color = message_type.color();
    let styled_action = match color {
        JuliaupStyleColor::Green => {
            style(format!("{:>width$}", action, width = JULIAUP_STYLE_INDENT))
                .green()
                .bold()
        }
        JuliaupStyleColor::Red => {
            style(format!("{:>width$}", action, width = JULIAUP_STYLE_INDENT))
                .red()
                .bold()
        }
        JuliaupStyleColor::Yellow => {
            style(format!("{:>width$}", action, width = JULIAUP_STYLE_INDENT))
                .yellow()
                .bold()
        }
        JuliaupStyleColor::Cyan => {
            style(format!("{:>width$}", action, width = JULIAUP_STYLE_INDENT))
                .cyan()
                .bold()
        }
    };

    eprintln!("{} {}", styled_action, message);
}

/// Retry a rename with Fibonacci backoff to handle transient permission errors
/// from e.g. antivirus scanners. Similar approach to rustup.
pub fn retry_rename(src: &Path, dest: &Path) -> Result<()> {
    // 20 fib steps from 1 millisecond sums to ~18 seconds
    retry(
        Fibonacci::from_millis(1).map(jitter).take(20),
        || match std::fs::rename(src, dest) {
            Ok(()) => OperationResult::Ok(()),
            Err(e) => match e.kind() {
                std::io::ErrorKind::PermissionDenied => {
                    log::debug!("Retrying rename {} to {}.", src.display(), dest.display());
                    OperationResult::Retry(e)
                }
                _ => OperationResult::Err(e),
            },
        },
    )
    .with_context(|| {
        format!(
            "Failed to rename '{}' to '{}'.",
            src.display(),
            dest.display()
        )
    })
}