mise 2026.9.4

Dev tools, env vars, and tasks in one CLI
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
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
//! Windows Scheduled Tasks for user-scope `[bootstrap.services]` entries.
//!
//! A task named `mise\<name>` is registered from a rendered task definition
//! with `schtasks /create /xml`. The rendered definition is kept under
//! `$MISE_STATE_DIR/user-services/<name>.xml` so drift is detected against
//! what mise wrote, independent of the exporter's formatting.

use std::path::{Path, PathBuf};
use std::process::Stdio;
use std::time::Duration;

use eyre::{Result, bail, eyre};
use indexmap::IndexMap;

const SCHTASKS_TIMEOUT: Duration = Duration::from_secs(30);

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ScheduledTaskRequest {
    pub name: String,
    pub task: String,
    pub description: Option<String>,
    pub command: String,
    pub restart_on_failure: bool,
    pub environment: IndexMap<String, String>,
    pub working_directory: Option<String>,
    /// Whether the task should be running now.
    pub start: bool,
    /// A niceness above zero lowers the task's priority.
    pub nice: Option<i8>,
    /// Whether the logon trigger is enabled.
    pub at_logon: bool,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum ScheduledTaskState {
    Running,
    Ready,
    Disabled,
    Differs,
    Missing,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ScheduledTaskStatus {
    pub request: ScheduledTaskRequest,
    pub path: PathBuf,
    pub state: ScheduledTaskState,
}

impl ScheduledTaskStatus {
    pub(crate) fn is_desired(&self) -> bool {
        match self.state {
            ScheduledTaskState::Running => self.request.start,
            ScheduledTaskState::Ready => !self.request.start,
            ScheduledTaskState::Disabled
            | ScheduledTaskState::Differs
            | ScheduledTaskState::Missing => false,
        }
    }
}

impl ScheduledTaskRequest {
    pub(crate) fn new(name: &str) -> Self {
        Self {
            name: name.to_string(),
            task: task_name(name),
            description: None,
            command: String::new(),
            restart_on_failure: false,
            environment: IndexMap::new(),
            working_directory: None,
            start: true,
            at_logon: true,
            nice: None,
        }
    }
}

pub(crate) fn is_available() -> bool {
    // spawnable as-is: `schtasks.exe`, which a plain lookup does not find
    cfg!(windows) && crate::file::which_spawnable("schtasks").is_some()
}

pub(crate) fn unavailable_reason() -> String {
    if cfg!(windows) {
        "`schtasks` not found".to_string()
    } else {
        "only available on windows".to_string()
    }
}

pub(crate) fn task_name(name: &str) -> String {
    format!("mise\\{name}")
}

/// Where the rendered definition mise registered is kept.
pub(crate) fn definition_path(name: &str) -> PathBuf {
    crate::dirs::STATE
        .join("user-services")
        .join(format!("{name}.xml"))
}

/// The account the task runs as and whose logon triggers it.
fn current_user_id() -> String {
    let user = crate::env::var("USERNAME").unwrap_or_else(|_| "".to_string());
    match crate::env::var("USERDOMAIN") {
        Ok(domain) if !domain.is_empty() => format!("{domain}\\{user}"),
        _ => user,
    }
}

/// Render the task definition (Task Scheduler XML, UTF-16LE with a BOM as
/// `schtasks /create /xml` expects).
pub(crate) fn render_definition(request: &ScheduledTaskRequest, user_id: &str) -> Result<Vec<u8>> {
    let xml = render_xml(request, user_id)?;
    let mut out = vec![0xFF, 0xFE];
    for unit in xml.encode_utf16() {
        out.extend_from_slice(&unit.to_le_bytes());
    }
    Ok(out)
}

pub(crate) fn render_xml(request: &ScheduledTaskRequest, user_id: &str) -> Result<String> {
    let (command, arguments) = exec_action(request)?;
    let mut out = String::new();
    out.push_str("<?xml version=\"1.0\" encoding=\"UTF-16\"?>\n");
    out.push_str(
        "<Task version=\"1.4\" xmlns=\"http://schemas.microsoft.com/windows/2004/02/mit/task\">\n",
    );
    out.push_str("  <RegistrationInfo>\n");
    out.push_str(&format!(
        "    <Description>{}</Description>\n",
        escape(
            request
                .description
                .as_deref()
                .unwrap_or("managed by mise bootstrap")
        )
    ));
    out.push_str("  </RegistrationInfo>\n");
    out.push_str("  <Triggers>\n    <LogonTrigger>\n");
    out.push_str(&format!(
        "      <Enabled>{}</Enabled>\n",
        yes_no(request.at_logon)
    ));
    out.push_str(&format!("      <UserId>{}</UserId>\n", escape(user_id)));
    out.push_str("    </LogonTrigger>\n  </Triggers>\n");
    out.push_str("  <Principals>\n    <Principal id=\"Author\">\n");
    out.push_str(&format!("      <UserId>{}</UserId>\n", escape(user_id)));
    out.push_str("      <LogonType>InteractiveToken</LogonType>\n");
    out.push_str("      <RunLevel>LeastPrivilege</RunLevel>\n");
    out.push_str("    </Principal>\n  </Principals>\n");
    out.push_str("  <Settings>\n");
    out.push_str("    <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>\n");
    out.push_str("    <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>\n");
    out.push_str("    <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>\n");
    out.push_str("    <AllowHardTerminate>true</AllowHardTerminate>\n");
    out.push_str("    <StartWhenAvailable>true</StartWhenAvailable>\n");
    out.push_str("    <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>\n");
    out.push_str("    <AllowStartOnDemand>true</AllowStartOnDemand>\n");
    out.push_str("    <Enabled>true</Enabled>\n");
    out.push_str("    <Hidden>false</Hidden>\n");
    out.push_str("    <RunOnlyIfIdle>false</RunOnlyIfIdle>\n");
    out.push_str("    <ExecutionTimeLimit>PT0S</ExecutionTimeLimit>\n");
    if request.restart_on_failure {
        out.push_str("    <RestartOnFailure>\n      <Interval>PT1M</Interval>\n      <Count>3</Count>\n    </RestartOnFailure>\n");
    }
    // 7 is the default; a nice service runs at the lowest normal priority
    let priority = if request.nice.is_some_and(|nice| nice > 0) {
        9
    } else {
        7
    };
    out.push_str(&format!("    <Priority>{priority}</Priority>\n"));
    out.push_str("  </Settings>\n");
    out.push_str("  <Actions Context=\"Author\">\n    <Exec>\n");
    out.push_str(&format!("      <Command>{}</Command>\n", escape(&command)));
    if !arguments.is_empty() {
        out.push_str(&format!(
            "      <Arguments>{}</Arguments>\n",
            escape(&arguments)
        ));
    }
    if let Some(dir) = &request.working_directory {
        out.push_str(&format!(
            "      <WorkingDirectory>{}</WorkingDirectory>\n",
            escape(&expand_path_string(dir))
        ));
    }
    out.push_str("    </Exec>\n  </Actions>\n");
    out.push_str("</Task>\n");
    Ok(out)
}

/// Split the command line into the executable and its arguments. Task
/// Scheduler has no environment block, so variables are set through
/// `cmd.exe`, which reinterprets some characters; values that it would
/// change are rejected rather than passed through differently.
fn exec_action(request: &ScheduledTaskRequest) -> Result<(String, String)> {
    let (program, args) = split_command(&request.command);
    if request.environment.is_empty() {
        return Ok((program, args));
    }
    let mut sets = vec![];
    for (key, value) in &request.environment {
        if key.is_empty() || key.contains(['=', '"', '%', '\n', '\r']) {
            bail!(
                "user service '{}': environment key {key:?} cannot be set through cmd.exe",
                request.name
            );
        }
        if let Some(c) = value
            .chars()
            .find(|c| matches!(c, '"' | '%' | '&' | '|' | '<' | '>' | '^' | '\n' | '\r'))
        {
            bail!(
                "user service '{}': environment value for {key} contains {c:?}, which cmd.exe would reinterpret; set it inside the program instead",
                request.name
            );
        }
        sets.push(format!("set \"{key}={value}\""));
    }
    // the command line goes through cmd.exe too: what it would split or
    // chain is rejected the same way, rather than run differently
    if let Some(c) = format!("{program} {args}")
        .chars()
        .find(|c| matches!(c, '%' | '&' | '|' | '<' | '>' | '^' | '\n' | '\r'))
    {
        bail!(
            "user service '{}': the command contains {c:?}, which cmd.exe would reinterpret when `environment` is set; move it into a script",
            request.name
        );
    }
    let program = if program.contains(char::is_whitespace) {
        format!("\"{program}\"")
    } else {
        program
    };
    let rest = if args.is_empty() {
        program
    } else {
        format!("{program} {args}")
    };
    Ok((
        "cmd.exe".to_string(),
        format!("/c {} && {rest}", sets.join(" && ")),
    ))
}

fn split_command(command: &str) -> (String, String) {
    let trimmed = command.trim();
    let (program, args) = if let Some(rest) = trimmed.strip_prefix('"')
        && let Some(end) = rest.find('"')
    {
        (rest[..end].to_string(), rest[end + 1..].trim().to_string())
    } else {
        match trimmed.split_once(char::is_whitespace) {
            Some((program, args)) => (program.to_string(), args.trim().to_string()),
            None => (trimmed.to_string(), String::new()),
        }
    };
    // `~` and `~/` expand on every platform, as the docs promise
    let program = if program == "~" || program.starts_with("~/") || program.starts_with("~\\") {
        expand_path_string(&program)
    } else {
        program
    };
    (program, args)
}

fn escape(value: &str) -> String {
    value
        .replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .replace('"', "&quot;")
}

fn yes_no(value: bool) -> &'static str {
    if value { "true" } else { "false" }
}

fn expand_path_string(path: &str) -> String {
    if path == "~" {
        return crate::dirs::HOME.to_string_lossy().to_string();
    }
    crate::file::replace_path(Path::new(path))
        .to_string_lossy()
        .to_string()
}

pub(crate) async fn status(requests: &[ScheduledTaskRequest]) -> Result<Vec<ScheduledTaskStatus>> {
    let user_id = current_user_id();
    let mut out = vec![];
    for req in requests {
        let path = definition_path(&req.name);
        let registered = query(&req.task).await?;
        let state = match registered {
            None => ScheduledTaskState::Missing,
            Some(query) => {
                let stored = std::fs::read(&path).unwrap_or_default();
                if stored != render_definition(req, &user_id)? {
                    ScheduledTaskState::Differs
                } else if query.running {
                    ScheduledTaskState::Running
                } else if query.disabled {
                    ScheduledTaskState::Disabled
                } else {
                    ScheduledTaskState::Ready
                }
            }
        };
        out.push(ScheduledTaskStatus {
            request: req.clone(),
            path,
            state,
        });
    }
    Ok(out)
}

pub(crate) async fn exists(name: &str) -> Result<bool> {
    Ok(query(&task_name(name)).await?.is_some())
}

pub(crate) async fn apply(requests: &[ScheduledTaskRequest], dry_run: bool) -> Result<()> {
    let user_id = current_user_id();
    for req in requests {
        let path = definition_path(&req.name);
        // the definition is registered from a staging file and stored only
        // once Task Scheduler accepted it, so a failed create never leaves a
        // definition on disk that status would take for the registered one
        let staging = path.with_extension("xml.new");
        let rendered = render_definition(req, &user_id)?;
        let create = [
            "/create".to_string(),
            "/tn".to_string(),
            req.task.clone(),
            "/xml".to_string(),
            staging.display().to_string(),
            "/f".to_string(),
        ];
        let end = [
            "/end".to_string(),
            "/tn".to_string(),
            req.task.clone(),
            "/HRESULT".to_string(),
        ];
        let run = ["/run".to_string(), "/tn".to_string(), req.task.clone()];
        // what is registered now: a running instance keeps its old process
        // (`IgnoreNew`), so a changed definition or a stop ends it first, and
        // a task that is not running is never ended (its message is
        // localized, so it is not parsed)
        let registered = query(&req.task).await?;
        let running = registered.as_ref().is_some_and(|query| query.running);
        let changed = registered.is_some()
            && std::fs::read(&path).ok().as_deref() != Some(rendered.as_slice());
        let end_first = running && (!req.start || changed);
        let start = req.start && (!running || changed);
        if dry_run {
            miseprintln!("write {}", shell_words::join([path.display().to_string()]));
            miseprintln!("schtasks {}", shell_words::join(&create));
            if end_first {
                miseprintln!("schtasks {}", shell_words::join(&end));
            }
            if start {
                miseprintln!("schtasks {}", shell_words::join(&run));
            }
            continue;
        }
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)?;
        }
        std::fs::write(&staging, &rendered)?;
        if let Err(err) = schtasks(&create).await {
            let _ = std::fs::remove_file(&staging);
            return Err(err);
        }
        // written, not renamed: a rename does not replace an existing
        // definition on Windows
        std::fs::write(&path, &rendered)?;
        let _ = std::fs::remove_file(&staging);
        if end_first {
            // it may have exited between the query and now: the HRESULT
            // says so in every locale; the message is matched as a fallback
            let (status, printed) = schtasks_output(&end).await?;
            if !status.success()
                && status.code() != Some(SCHED_E_TASK_NOT_RUNNING)
                && !end_error_is_noop(&printed)
            {
                bail!("`schtasks {}` failed: {printed}", shell_words::join(&end));
            }
        }
        if start {
            schtasks(&run).await?;
        }
    }
    Ok(())
}

/// Delete the task mise registered for `name`. Returns whether one existed.
pub(crate) async fn remove_task(name: &str, dry_run: bool) -> Result<bool> {
    let task = task_name(name);
    let path = definition_path(name);
    if !exists(name).await? {
        if path.exists() && !dry_run {
            std::fs::remove_file(&path)?;
        }
        return Ok(false);
    }
    let args = [
        "/delete".to_string(),
        "/tn".to_string(),
        task,
        "/f".to_string(),
    ];
    if dry_run {
        miseprintln!("schtasks {}", shell_words::join(&args));
        if path.exists() {
            miseprintln!(
                "{}",
                shell_words::join(["rm".to_string(), path.display().to_string()])
            );
        }
        return Ok(true);
    }
    schtasks(&args).await?;
    if path.exists() {
        std::fs::remove_file(&path)?;
    }
    Ok(true)
}

struct Query {
    running: bool,
    disabled: bool,
}

/// The task's state through the Task Scheduler API rather than the
/// localized text `schtasks /query` prints. Prints `MISSING` for an
/// unregistered task and the `TaskState` name otherwise. The name is
/// embedded in the script (arguments after `-Command` are more command
/// text, not `$args`); names are validated to letters, digits, `.`, `_`,
/// and `-` before they get here.
fn query_script(name: &str) -> String {
    format!(
        "$t = Get-ScheduledTask -TaskPath '\\mise\\' -TaskName '{name}' -ErrorAction SilentlyContinue; if ($null -eq $t) {{ 'MISSING' }} else {{ $t.State.ToString() }}"
    )
}

async fn query(task: &str) -> Result<Option<Query>> {
    let name = task.strip_prefix("mise\\").unwrap_or(task);
    if !name
        .chars()
        .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
    {
        bail!("scheduled task name {name:?} contains characters that cannot be queried");
    }
    let args = [
        "-NoProfile".to_string(),
        "-NonInteractive".to_string(),
        "-Command".to_string(),
        query_script(name),
    ];
    debug!("$ powershell {}", shell_words::join(&args));
    let mut cmd = tokio::process::Command::new("powershell.exe");
    cmd.args(&args)
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .kill_on_drop(true);
    let output = tokio::time::timeout(SCHTASKS_TIMEOUT, cmd.output())
        .await
        .map_err(|_| eyre!("querying scheduled task {task} timed out"))??;
    if !output.status.success() {
        bail!(
            "querying scheduled task {task} failed: {}",
            String::from_utf8_lossy(&output.stderr).trim()
        );
    }
    Ok(parse_query(&String::from_utf8_lossy(&output.stdout)))
}

fn parse_query(output: &str) -> Option<Query> {
    let state = output.trim();
    if state.eq_ignore_ascii_case("MISSING") || state.is_empty() {
        return None;
    }
    Some(Query {
        running: state.eq_ignore_ascii_case("Running"),
        disabled: state.eq_ignore_ascii_case("Disabled"),
    })
}

/// `SCHED_E_TASK_NOT_RUNNING`: the HRESULT `schtasks /end /HRESULT` exits
/// with when the task has no running instance.
const SCHED_E_TASK_NOT_RUNNING: i32 = 0x8004130Bu32 as i32;

fn end_error_is_noop(error: &str) -> bool {
    let error = error.to_ascii_lowercase();
    error.contains("not running") || error.contains("no running instance")
}

async fn schtasks(args: &[String]) -> Result<()> {
    let (status, printed) = schtasks_output(args).await?;
    if !status.success() {
        bail!("`schtasks {}` failed: {printed}", shell_words::join(args));
    }
    Ok(())
}

/// Runs schtasks; its exit status and what it printed (schtasks writes its
/// SUCCESS and ERROR lines to stdout).
async fn schtasks_output(args: &[String]) -> Result<(std::process::ExitStatus, String)> {
    debug!("$ schtasks {}", shell_words::join(args));
    let mut cmd = tokio::process::Command::new("schtasks");
    cmd.args(args)
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .kill_on_drop(true);
    let output = tokio::time::timeout(SCHTASKS_TIMEOUT, cmd.output())
        .await
        .map_err(|_| eyre!("`schtasks {}` timed out", shell_words::join(args)))??;
    let printed = [
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr),
    ]
    .iter()
    .map(|text| text.trim().to_string())
    .filter(|text| !text.is_empty())
    .collect::<Vec<_>>()
    .join("; ");
    Ok((output.status, printed))
}

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

    fn sample() -> ScheduledTaskRequest {
        let mut request = ScheduledTaskRequest::new("agent");
        request.command = "C:\\Tools\\agent.exe --serve".to_string();
        request.description = Some("My <agent>".to_string());
        request.restart_on_failure = true;
        request
    }

    #[test]
    fn renders_a_logon_task() {
        let xml = render_xml(&sample(), "HOST\\me").unwrap();
        assert!(xml.contains("<Description>My &lt;agent&gt;</Description>"));
        assert!(xml.contains(
            "<LogonTrigger>\n      <Enabled>true</Enabled>\n      <UserId>HOST\\me</UserId>"
        ));
        assert!(xml.contains("<Command>C:\\Tools\\agent.exe</Command>"));
        assert!(xml.contains("<Arguments>--serve</Arguments>"));
        assert!(xml.contains("<RestartOnFailure>"));
        assert!(!xml.contains("<WorkingDirectory>"));
    }

    #[test]
    fn environment_goes_through_cmd() {
        let mut request = sample();
        request.environment.insert("RUST_LOG".into(), "info".into());
        request.at_logon = false;
        request.restart_on_failure = false;
        let xml = render_xml(&request, "me").unwrap();
        assert!(xml.contains("<Command>cmd.exe</Command>"));
        assert!(xml.contains(
            "<Arguments>/c set &quot;RUST_LOG=info&quot; &amp;&amp; C:\\Tools\\agent.exe --serve</Arguments>"
        ));
        assert!(xml.contains("<Enabled>false</Enabled>\n      <UserId>me</UserId>"));
        assert!(!xml.contains("<RestartOnFailure>"));

        let mut request = sample();
        request.command = "\"C:\\Program Files\\x\\a.exe\" --serve".to_string();
        request.environment.insert("A".into(), "1".into());
        let xml = render_xml(&request, "me").unwrap();
        assert!(xml.contains(
            "<Arguments>/c set &quot;A=1&quot; &amp;&amp; &quot;C:\\Program Files\\x\\a.exe&quot; --serve</Arguments>"
        ));

        let mut request = sample();
        request
            .environment
            .insert("P".into(), "%PATH%;C:\\x".into());
        let err = render_xml(&request, "me").unwrap_err().to_string();
        assert!(err.contains("cmd.exe would reinterpret"), "{err}");
    }

    #[test]
    fn tilde_expands_in_the_program() {
        let (program, args) = split_command("~/.local/bin/agent --serve");
        assert!(!program.starts_with('~'), "{program}");
        assert!(program.ends_with("agent"), "{program}");
        assert_eq!(args, "--serve");
    }

    #[test]
    fn quoted_programs_keep_their_spaces() {
        assert_eq!(
            split_command("\"C:\\Program Files\\x\\a.exe\" --flag one"),
            (
                "C:\\Program Files\\x\\a.exe".to_string(),
                "--flag one".to_string()
            )
        );
        assert_eq!(
            split_command("agent.exe"),
            ("agent.exe".to_string(), String::new())
        );
    }

    #[test]
    fn definition_is_utf16_with_bom() {
        let bytes = render_definition(&sample(), "me").unwrap();
        assert_eq!(&bytes[..2], &[0xFF, 0xFE]);
        assert_eq!(&bytes[2..4], &[b'<', 0]);
    }

    #[test]
    fn parses_query_output() {
        let query = parse_query("Running\r\n").unwrap();
        assert!(query.running);
        assert!(!query.disabled);
        let query = parse_query("Disabled\n").unwrap();
        assert!(!query.running);
        assert!(query.disabled);
        let query = parse_query("Ready\n").unwrap();
        assert!(!query.running && !query.disabled);
        assert!(parse_query("MISSING\n").is_none());
    }

    #[test]
    fn desired_state_follows_start() {
        let mut status = ScheduledTaskStatus {
            request: sample(),
            path: PathBuf::from("x"),
            state: ScheduledTaskState::Running,
        };
        assert!(status.is_desired());
        status.request.start = false;
        assert!(!status.is_desired());
        status.state = ScheduledTaskState::Ready;
        assert!(status.is_desired());
        status.state = ScheduledTaskState::Differs;
        assert!(!status.is_desired());
    }
}