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
//! This library wraps around the [bspc](https://github.com/bnoordhuis/bspc) Quake utility tool
//! to make it easier to use it from Rust.
//! It does so by spawning a child process and asynchronously waiting for its output.
//!
//! Some features include:
//! - setting up a temporary directory to store input/output files in
//! - parsing output logs to look for errors/warnings
//! - streaming the output logs in real-time (via `OptionsBuilder::log_stream`)
//!
//! # Links
//!
//! The BSPC tool itself is not included with the library.
//! Instead, it needs to already exist in the filesystem before the library is used.
//!
//! - Old binary downloads for v1.2: [link](https://web.archive.org/web/20011023020820/http://www.botepidemic.com:80/gladiator/download.shtml)
//! - Source: [bnoordhuis/bspc](https://github.com/bnoordhuis/bspc)
//! - Fork with more recent commits: [TTimo/bspc](https://github.com/TTimo/bspc)
//!
//! # Example
//!
//! Basic example showing the conversion of a Quake BSP file to a MAP file:
//!
//! ```rust
//! use bspc::{Command, Options};
//! use tokio_util::sync::CancellationToken;
//!
//! # tokio_test::block_on(async {
//! let bsp_contents = b"...";
//! let result = bspc::convert(
//!     "./test_resources/bspci386",
//!     Command::BspToMap(bsp_contents),
//!     Options::builder()
//!         .verbose(true)
//!         .build(),
//! )
//! .await;
//! match result {
//!     Ok(output) => {
//!         assert_eq!(output.files.len(), 1);
//!         println!("{}", output.files[0].name);
//!         println!("{}", String::from_utf8_lossy(&output.files[0].contents));
//!     }
//!     Err(err) => {
//!         println!("Conversion failed: {}", err);
//!     }
//! }
//! # })
//! ```
//!
//! ## Example with cancellation
//!
//! The following snippet demonstrates how to cancel the conversion (in this
//! case, using a timeout) via the cancellation token. Note that the
//! cancellation is not done simply by dropping the future (as is normally done),
//! since we want to ensure that the child process is killed and the temporary
//! directory deleted before the future completes.
//!
//! ```rust
//! use bspc::{Command, Options, ConversionError};
//! use tokio_util::sync::CancellationToken;
//!
//! # tokio_test::block_on(async {
//! let bsp_contents = b"...";
//! let cancel_token = CancellationToken::new();
//! let cancel_task = {
//!     let cancel_token = cancel_token.clone();
//!     tokio::spawn(async move {
//!         tokio::time::sleep(std::time::Duration::from_millis(10)).await;
//!         cancel_token.cancel();
//!     })
//! };
//! let result = bspc::convert(
//!     "./test_resources/bspci386",
//!     Command::BspToMap(bsp_contents),
//!     Options::builder()
//!         .verbose(true)
//!         .cancellation_token(cancel_token)
//!         .build(),
//! )
//! .await;
//! match result {
//!     Ok(output) => {
//!         assert_eq!(output.files.len(), 1);
//!         println!("{}", output.files[0].name);
//!         println!("{}", String::from_utf8_lossy(&output.files[0].contents));
//!     }
//!     Err(ConversionError::Cancelled) => {
//!         println!("Conversion timed out after 10 seconds");
//!     }
//!     Err(err) => {
//!         println!("Conversion failed: {}", err);
//!     }
//! }
//! # })
//! ```
//!

#![warn(clippy::all, clippy::pedantic, clippy::nursery)]
#![warn(
    clippy::unwrap_used,
    clippy::unimplemented,
    clippy::todo,
    clippy::str_to_string
)]
#![allow(clippy::module_name_repetitions)]

pub mod logs;

use crate::logs::{LogLine, UnknownArgumentLine};
use abort_on_drop::ChildTask;
use derive_builder::UninitializedFieldError;
use std::ffi::OsString;
use std::future::Future;
use std::io::Error as IoError;
use std::path::{Path, PathBuf};
use std::process::{ExitStatus, Stdio};
use tempfile::{Builder as TempFileBuilder, TempDir};
use tokio::process::Command as TokioCommand;
use tokio::sync::mpsc::Sender as MpscSender;
use tokio_util::sync::CancellationToken;

/// Callback used by [`Command::Other`].
///
/// Accepts a the temporary directory that can be used to write files to.
pub type CommandArgumentBuilder = Box<
    dyn FnOnce(
            &TempDir,
        ) -> Box<
            dyn Future<Output = Result<Vec<OsString>, ConversionError>>
                + Send
                + Sync
                + Unpin
                // The builder function can't borrow the TempDir argument, but
                // this is fine because any operations on it are synchronous.
                + 'static,
        > + Send
        + Sync,
>;

/// The subcommand to pass to the BSPC executable.
///
/// If this is one of the standard subcommands (i.e. not `Other`), then the
/// command accepts a byte slice containing the contents of the input file
/// that should be converted. This library handles writing the input file to
/// a temporary directory before invoking the BSPC executable.
pub enum Command<'a> {
    /// Corresponds to the `-map2bsp` subcommand.
    MapToBsp(&'a [u8]),
    /// Corresponds to the `-map2aas` subcommand.
    MapToAas(&'a [u8]),
    /// Corresponds to the `-bsp2map` subcommand.
    BspToMap(&'a [u8]),
    /// Corresponds to the `-bsp2bsp` subcommand.
    BspToBsp(&'a [u8]),
    /// Corresponds to the `-bsp2aas` subcommand.
    BspToAas(&'a [u8]),
    /// Allows sending an arbitrary command to the BSPC executable.
    /// This is an asynchronous callback that accepts the temporary directory
    /// that can be used to write files to, and returns a future that resolves
    /// to a list of arguments to pass to the BSPC executable (or an error).
    Other(CommandArgumentBuilder),
}

impl<'a> Command<'a> {
    async fn try_into_args(self, temp_dir: &TempDir) -> Result<Vec<OsString>, ConversionError> {
        if let Command::Other(build_arguments) = self {
            build_arguments(temp_dir).await
        } else {
            let input_file_extension = match self {
                Command::MapToBsp(_) | Command::MapToAas(_) => "map",
                Command::BspToMap(_) | Command::BspToBsp(_) | Command::BspToAas(_) => "bsp",
                Command::Other(_) => unreachable!(),
            };
            let input_file_contents = match self {
                Command::MapToBsp(contents)
                | Command::MapToAas(contents)
                | Command::BspToMap(contents)
                | Command::BspToBsp(contents)
                | Command::BspToAas(contents) => contents,
                Command::Other(_) => unreachable!(),
            };
            let subcommand = match self {
                Command::MapToBsp(_) => "-map2bsp",
                Command::MapToAas(_) => "-map2aas",
                Command::BspToMap(_) => "-bsp2map",
                Command::BspToBsp(_) => "-bsp2bsp",
                Command::BspToAas(_) => "-bsp2aas",
                Command::Other { .. } => unreachable!(),
            };

            // Write the input file to a temporary file.
            let input_file_path = temp_dir
                .path()
                .join(format!("input.{}", input_file_extension));
            tokio::fs::write(&input_file_path, input_file_contents)
                .await
                .map_err(|err| ConversionError::TempDirectoryIo(err, input_file_path.clone()))?;

            let args = vec![subcommand.into(), input_file_path.clone().into()];
            Ok(args)
        }
    }
}

/// Options for the conversion process.
///
/// Some of these are passed directly to the BSPC executable.
#[allow(clippy::struct_excessive_bools)]
#[derive(derive_builder::Builder)]
#[builder(build_fn(private, name = "fallible_build", error = "PrivateOptionsBuilderError"))]
pub struct Options {
    /// Whether to use verbose logging.
    ///
    /// If this is `false`, then the `-noverbose` flag will be passed to the
    /// BSPC executable.
    #[builder(default = "false")]
    pub verbose: bool,
    /// The number of threads to use for the conversion. By default,
    /// multi-threading is disabled (equivalent to setting this to `1`).
    ///
    /// This is passed to the BSPC executable via the `-threads` flag.
    #[builder(default, setter(strip_option))]
    pub threads: Option<usize>,
    /// A cancellation token that can be used to cancel the conversion
    /// (instead of dropping the future). See the docs on [`convert`] for
    /// more information.
    #[builder(default, setter(strip_option))]
    pub cancellation_token: Option<CancellationToken>,
    /// An optional channel to send log lines to as they get logged.
    #[builder(default, setter(strip_option))]
    pub log_stream: Option<MpscSender<LogLine>>,
    /// Additional command-line arguments to pass to the BSPC executable.
    /// These are added at the end, after all other arguments.
    #[builder(default, setter(custom))]
    pub additional_args: Vec<OsString>,
}

#[derive(Debug)]
struct PrivateOptionsBuilderError(UninitializedFieldError);

impl From<UninitializedFieldError> for PrivateOptionsBuilderError {
    fn from(err: UninitializedFieldError) -> Self {
        Self(err)
    }
}

impl Options {
    #[must_use]
    pub fn builder() -> OptionsBuilder {
        OptionsBuilder::default()
    }
}

impl OptionsBuilder {
    #[must_use]
    pub fn build(&mut self) -> Options {
        self.fallible_build()
            .expect("OptionsBuilder::build() should not fail")
    }

    /// Adds additional command-line arguments to pass to the BSPC executable.
    /// These are added at the end, after all other arguments.
    pub fn additional_args<I, S>(&mut self, args: I) -> &mut Self
    where
        I: IntoIterator<Item = S>,
        S: Into<OsString>,
    {
        self.additional_args
            .get_or_insert_with(Vec::new)
            .extend(args.into_iter().map(Into::into));
        self
    }

    /// Adds an additional command-line argument to pass to the BSPC executable.
    /// This is added at the end, after all other arguments.
    pub fn additional_arg<S>(&mut self, arg: S) -> &mut Self
    where
        S: Into<OsString>,
    {
        self.additional_args
            .get_or_insert_with(Vec::new)
            .push(arg.into());
        self
    }
}

impl Options {
    #[must_use]
    fn into_args(self) -> Vec<OsString> {
        // Available arguments on bspc 1.2
        // Switches:
        //    map2bsp <[pakfilefilter/]filefilter> = convert MAP to BSP
        //    map2aas <[pakfilefilter/]filefilter> = convert MAP to AAS
        //    bsp2map <[pakfilefilter/]filefilter> = convert BSP to MAP
        //    bsp2bsp <[pakfilefilter/]filefilter> = convert BSP to BSP
        //    bsp2aas <[pakfilefilter/]filefilter> = convert BSP to AAS
        //    output <output path>                 = set output path
        //    noverbose                            = disable verbose output
        //    threads                              = number of threads to use
        //    ... the remaining arguments depend on the version used
        let mut args: Vec<OsString> = Vec::new();
        if !self.verbose {
            args.push("-noverbose".into());
        }
        if let Some(threads) = self.threads {
            args.push("-threads".into());
            args.push(threads.to_string().into());
        }
        args.extend(self.additional_args);
        args
    }
}

/// Full output of the child process, including the exit code, log, and any
/// output files.
///
/// This also includes the command-line arguments that were passed, for
/// diagnostic purposes.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Output {
    /// The exit status of the child process.
    pub exit: ExitStatus,
    /// The exit code corresponding to the exit status, if one exists.
    ///
    /// See the docs on [`std::process::ExitStatus::code`].
    pub exit_code: Option<i32>,
    /// All output files that the child process produced.
    pub files: Vec<OutputFile>,
    /// The command-line arguments that were passed to the child process.
    pub args: Vec<String>,
    /// The log output of the child process, as a list of parsed log lines.
    pub logs: Vec<LogLine>,
}

/// Error type returned by [`convert`].
#[derive(Debug, thiserror::Error)]
pub enum ConversionError {
    /// The provided path to the BSPC executable does not exist or is not a
    /// file.
    #[error("provided path to bspc executable (\"{0}\") does not exist or is not a file")]
    ExecutableNotFound(PathBuf),
    /// Failed to create a temporary directory to store inputs/outputs.
    #[error("failed to create a temporary directory to store inputs/outputs")]
    TempDirectoryCreationFailed(#[source] IoError),
    /// Failed to read/write to the temporary directory storing inputs/outputs.
    #[error("failed to read/write to the temporary directory (at \"{1}\") storing inputs/outputs")]
    TempDirectoryIo(#[source] IoError, PathBuf),
    /// Failed to start the child BSPC process.
    #[error("failed to start child \"bspc\" process")]
    ProcessStartFailure(#[source] IoError),
    /// Failed to wait for the child BSPC process to exit.
    #[error("failed to wait for child \"bspc\" process to exit")]
    ProcessWaitFailure(#[source] IoError),
    /// The conversion process was cancelled via the cancellation token.
    #[error("conversion was cancelled by the cancellation token")]
    Cancelled,
    /// The child BSPC process was provided an unknown argument.
    #[error("child \"bspc\" process was provided unknown argument '{unknown_argument}': full argument list: {args:?}")]
    UnknownArgument {
        /// The offending argument.
        unknown_argument: String,
        /// All arguments passed to the child BSPC process.
        args: Vec<String>,
    },
    /// The child BSPC process did find any input files when it ran.
    ///
    /// If a standard command was used, then this indicates that the temporary
    /// file may have been deleted before BPSC ran.
    #[error("\"bspc\" did not find any files when it ran the conversion process. If a standard command was used, then this indicates that the temporary file may have been deleted before \"bspc\" ran: {0:?}")]
    NoInputFilesFound(Output),
    /// The child BSPC process exited with a non-zero exit code.
    #[error("child \"bspc\" process exited with a non-zero exit code: {0:?}")]
    ProcessExitFailure(Output),
    /// The child BSPC process resulted in no output files.
    #[error("child \"bspc\" process resulted in no output files: {0:?}")]
    NoOutputFiles(Output),
}

/// A single output file produced by the BSPC process.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OutputFile {
    pub name: String,
    pub extension: Option<String>,
    pub contents: Vec<u8>,
}

/// Runs the BSPC executable with the given arguments, converting a single file
/// to a different format, returning the complete output of the process
/// (all output files, logs, and exit code).
///
/// The future returned by this function should be polled to completion, in
/// order to best ensure that the temporary directory is cleaned up after the
/// child process exits.
///
/// To time-out the child process operation (or otherwise cancel it), pass a
/// [`CancellationToken`] to the [`Options`] argument.
///
/// # Executable
///
/// The BSPC executable must already exist in the filesystem before calling
/// this function.
///
/// # Errors
///
/// See the variants on the [`ConversionError`] enum for more information.
#[allow(clippy::too_many_lines)]
pub async fn convert(
    executable_path: impl AsRef<Path> + Send,
    cmd: Command<'_>,
    mut options: Options,
) -> Result<Output, ConversionError> {
    let cancellation_token = options
        .cancellation_token
        .take()
        .unwrap_or_else(CancellationToken::new);
    let log_stream = options.log_stream.take();
    let option_args = options.into_args();

    // Check to make sure that the executable path exists and is a file,
    // asynchronously.
    let executable_path = executable_path.as_ref();
    let executable_path = tokio::fs::canonicalize(executable_path)
        .await
        .map_err(|_| ConversionError::ExecutableNotFound(executable_path.to_owned()))?;
    let executable_metadata = tokio::fs::metadata(&executable_path)
        .await
        .map_err(|_| ConversionError::ExecutableNotFound(executable_path.clone()))?;
    if !executable_metadata.is_file() {
        return Err(ConversionError::ExecutableNotFound(executable_path));
    }

    // Create a temporary directory to store the input and output files,
    // and to run the executable in.
    // This may invoke synchronous I/O, but it should be very fast.
    let temp_dir = TempFileBuilder::new()
        .prefix("bspc-rs")
        .tempdir()
        .map_err(ConversionError::TempDirectoryCreationFailed)?;

    // Create the output subdirectory.
    let output_directory_path = temp_dir.path().join("output");
    tokio::fs::create_dir(&output_directory_path)
        .await
        .map_err(|e| ConversionError::TempDirectoryIo(e, output_directory_path.clone()))?;

    let mut args: Vec<OsString> = Vec::new();
    let command_args = cmd.try_into_args(&temp_dir).await?;
    args.extend(command_args);
    args.push("-output".into());
    args.push(output_directory_path.as_os_str().to_owned());
    args.extend(option_args);

    let debug_args: Vec<String> = args
        .iter()
        .map(|arg| arg.to_string_lossy().into_owned())
        .collect::<Vec<_>>();

    // Spawn the child process
    let mut child = TokioCommand::new(executable_path)
        .env_clear()
        // Use the temporary directory as the working directory, since BSPC
        // also writes a log file to the working directory.
        .current_dir(temp_dir.path())
        .stdin(Stdio::null())
        // BSPC writes all logs to stdout
        .stdout(Stdio::piped())
        .stderr(Stdio::null())
        .args(args)
        .spawn()
        .map_err(ConversionError::ProcessStartFailure)?;

    let stdout = child
        .stdout
        .take()
        .expect("child should have a piped stdout stream");
    let consume_log_task: ChildTask<Result<Vec<LogLine>, IoError>> =
        ChildTask::from(tokio::spawn(async move {
            crate::logs::collect_logs(stdout, log_stream).await
        }));

    // Wait for the child process to exit, or for the cancellation token to be
    // cancelled. Use `wait` instead of `wait_with_output` because the latter
    // requires moving the child process into the future, which is incompatible
    // with cancellation.
    let exit: ExitStatus = {
        #[allow(clippy::redundant_pub_crate)]
        let cancellation_result: Result<Result<ExitStatus, IoError>, ()> = tokio::select! {
            result = child.wait() => Ok(result),
            _ = cancellation_token.cancelled() => Err(()),
        };
        match cancellation_result {
            Ok(Ok(exit)) => exit,
            Ok(Err(wait_err)) => {
                // Try to ensure the child process is killed before returning
                let _err = child.kill().await;
                return Err(ConversionError::ProcessWaitFailure(wait_err));
            }
            Err(_) => {
                // The cancellation token was cancelled, so we should kill the child
                // process.
                let _err = child.kill().await;
                return Err(ConversionError::Cancelled);
            }
        }
    };
    let log_lines = consume_log_task
        .await
        .expect("log collection task should not panic")
        .map_err(ConversionError::ProcessWaitFailure)?;

    let mut no_files_found: bool = false;
    let mut unknown_argument: Option<UnknownArgumentLine> = None;
    for line in &log_lines {
        match line {
            LogLine::UnknownArgument(unknown_argument_line) => {
                unknown_argument = Some(unknown_argument_line.clone());
            }
            LogLine::NoFilesFound(_) => {
                no_files_found = true;
            }
            _ => {}
        }
    }

    // If there was an unknown argument, return an error immediately without
    // bothering to read in the output files or return the logs/exit code.
    if let Some(line) = unknown_argument {
        return Err(ConversionError::UnknownArgument {
            unknown_argument: line.argument,
            args: debug_args,
        });
    }

    // Read in all files in the output directory
    let mut output_files: Vec<OutputFile> = Vec::new();
    let mut read_dir = tokio::fs::read_dir(&output_directory_path)
        .await
        .map_err(|err| ConversionError::TempDirectoryIo(err, output_directory_path.clone()))?;
    while let Some(entry) = read_dir
        .next_entry()
        .await
        .map_err(|err| ConversionError::TempDirectoryIo(err, output_directory_path.clone()))?
    {
        let file_name = entry.file_name().to_string_lossy().into_owned();
        let file_path = entry.path();
        let file_extension = file_path
            .extension()
            .map(|ext| ext.to_string_lossy().into_owned());

        let file_contents = tokio::fs::read(&file_path)
            .await
            .map_err(|err| ConversionError::TempDirectoryIo(err, file_path))?;
        output_files.push(OutputFile {
            name: file_name,
            extension: file_extension,
            contents: file_contents,
        });
    }

    let output = Output {
        exit_code: exit.code(),
        exit,
        files: output_files,
        args: debug_args,
        logs: log_lines,
    };

    if no_files_found {
        return Err(ConversionError::NoInputFilesFound(output));
    }

    if !output.exit.success() {
        return Err(ConversionError::ProcessExitFailure(output));
    }

    if output.files.is_empty() {
        return Err(ConversionError::NoOutputFiles(output));
    }

    Ok(output)
}