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
use crate::error::{not_found_error, seek_error};
use crate::path::{ClioPathEnum, InOut};
use crate::{
    assert_is_dir, assert_not_dir, assert_writeable, impl_try_from, is_fifo, ClioPath, Error,
    Result,
};

use std::convert::TryFrom;
use std::ffi::OsStr;
use std::fmt::{self, Debug, Display};
use std::fs::{File, OpenOptions};
use std::io::{self, Result as IoResult, Seek, Stdout, Write};
use std::path::Path;
use tempfile::NamedTempFile;

#[derive(Debug)]
enum OutputStream {
    /// a [`Stdout`] when the path was `-`
    Stdout(Stdout),
    /// a [`File`] represeinting the named pipe e.g. crated with `mkfifo`
    Pipe(File),
    /// a normal [`File`] opened from the path
    File(File),
    /// A normal [`File`] opened from the path that will be writted atomically
    AtomicFile(NamedTempFile),
    #[cfg(feature = "http")]
    #[cfg_attr(docsrs, doc(cfg(feature = "http")))]
    /// a writer that will upload the body the the HTTP server
    Http(Box<HttpWriter>),
}

#[cfg(feature = "http")]
use crate::http::HttpWriter;
/// A struct that represents a command line output stream,
/// either [`Stdout`] or a [`File`] along with it's path
///
/// It is designed to be used with the [`clap` crate](https://docs.rs/clap/latest) when taking a file name as an
/// argument to CLI app
/// ```
/// # #[cfg(feature="clap-parse")]{
/// use clap::Parser;
/// use clio::Output;
///
/// #[derive(Parser)]
/// struct Opt {
///     /// path to file, use '-' for stdout
///     #[clap(value_parser)]
///     output_file: Output,
///
///     /// default name for file is user passes in a directory
///     #[clap(value_parser = clap::value_parser!(Output).default_name("run.log"))]
///     log_file: Output,
///
///     /// Write output atomically using temp file and atomic rename
///     #[clap(value_parser = clap::value_parser!(Output).atomic())]
///     config_file: Output,
/// }
/// # }
/// ```
#[derive(Debug)]
pub struct Output {
    path: ClioPath,
    stream: OutputStream,
}

/// A builder for [Output](crate::Output) that validates the path but
/// defers creating it until you call the [create](crate::OutputPath::create) method.
///
/// The [create_with_len](crate::OutputPath::create_with_len) allows setting the size before writing.
/// This is mostly usefull with the "http" feature for setting the Content-Length header
///
/// It is designed to be used with the [`clap` crate](https://docs.rs/clap/latest) when taking a file name as an
/// argument to CLI app
/// ```
/// # #[cfg(feature="clap-parse")]{
/// use clap::Parser;
/// use clio::OutputPath;
///
/// #[derive(Parser)]
/// struct Opt {
///     /// path to file, use '-' for stdout
///     #[clap(value_parser)]
///     output_file: OutputPath,
/// }
/// # }
/// ```
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct OutputPath {
    path: ClioPath,
}

impl OutputStream {
    /// Contructs a new output either by opening/creating the file or for '-' returning stdout
    fn new(path: &ClioPath, size: Option<u64>) -> Result<Self> {
        Ok(match &path.path {
            ClioPathEnum::Std(_) => OutputStream::Stdout(io::stdout()),
            ClioPathEnum::Local(local_path) => {
                if path.atomic && !path.is_fifo() {
                    assert_not_dir(path)?;
                    if let Some(parent) = path.safe_parent() {
                        assert_is_dir(parent)?;
                        let tmp = tempfile::Builder::new()
                            .prefix(".atomicwrite")
                            .tempfile_in(parent)?;
                        OutputStream::AtomicFile(tmp)
                    } else {
                        return Err(not_found_error().into());
                    }
                } else {
                    let file = open_rw(local_path)?;
                    if is_fifo(&file.metadata()?) {
                        OutputStream::Pipe(file)
                    } else {
                        if let Some(size) = size {
                            file.set_len(size)?;
                        }
                        OutputStream::File(file)
                    }
                }
            }
            #[cfg(feature = "http")]
            ClioPathEnum::Http(url) => {
                OutputStream::Http(Box::new(HttpWriter::new(url.as_str(), size)?))
            }
        })
    }
}

impl Output {
    /// Contructs a new output either by opening/creating the file or for '-' returning stdout
    pub fn new<S: TryInto<ClioPath>>(path: S) -> Result<Self>
    where
        crate::Error: From<<S as TryInto<ClioPath>>::Error>,
    {
        Output::maybe_with_len(path.try_into()?, None)
    }

    /// convert to an normal [`Output`] setting the length of the file to size if it is `Some`
    pub(crate) fn maybe_with_len(path: ClioPath, size: Option<u64>) -> Result<Self> {
        Ok(Output {
            stream: OutputStream::new(&path, size)?,
            path,
        })
    }

    /// Contructs a new output for stdout
    pub fn std() -> Self {
        Output {
            path: ClioPath::std().with_direction(InOut::Out),
            stream: OutputStream::Stdout(io::stdout()),
        }
    }

    /// Contructs a new output either by opening/creating the file or for '-' returning stdout
    ///
    /// The error is converted to a [`OsString`](std::ffi::OsString) so that [stuctopt](https://docs.rs/structopt/latest/structopt/#custom-string-parsers) can show it to the user.
    ///
    /// It is recomended that you use [`TryFrom::try_from`] and [clap 3.0](https://docs.rs/clap/latest/clap/index.html) instead.
    pub fn try_from_os_str(path: &OsStr) -> std::result::Result<Self, std::ffi::OsString> {
        TryFrom::try_from(path).map_err(|e: Error| e.to_os_string(path))
    }

    /// Syncs the file to disk or closes any HTTP connections and returns any errors
    /// or on the file if a regular file
    /// For atomic files this must be called to perform the final atomic swap
    pub fn finish(mut self) -> Result<()> {
        self.flush()?;
        match self.stream {
            OutputStream::Stdout(_) => Ok(()),
            OutputStream::Pipe(_) => Ok(()),
            OutputStream::File(file) => Ok(file.sync_data()?),
            OutputStream::AtomicFile(tmp) => {
                tmp.persist(self.path.path())?;
                Ok(())
            }
            #[cfg(feature = "http")]
            OutputStream::Http(http) => Ok(http.finish()?),
        }
    }

    /// If the output is std out [locks](std::io::Stdout::lock) it.
    /// usefull in multithreaded context to write lines consistently
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn main() -> Result<(), clio::Error> {
    /// let mut file = clio::Output::new("-")?;
    ///
    /// writeln!(file.lock(), "hello world")?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn lock<'a>(&'a mut self) -> Box<dyn Write + 'a> {
        match &mut self.stream {
            OutputStream::Stdout(stdout) => Box::new(stdout.lock()),
            OutputStream::Pipe(pipe) => Box::new(pipe),
            OutputStream::File(file) => Box::new(file),
            OutputStream::AtomicFile(file) => Box::new(file),
            #[cfg(feature = "http")]
            OutputStream::Http(http) => Box::new(http),
        }
    }

    /// If output is a file, returns a reference to the file,
    /// otherwise if output is stdout or a pipe returns none.
    pub fn get_file(&mut self) -> Option<&mut File> {
        match &mut self.stream {
            OutputStream::File(file) => Some(file),
            OutputStream::AtomicFile(file) => Some(file.as_file_mut()),
            _ => None,
        }
    }

    /// The original path used to create this [`Output`]
    pub fn path(&self) -> &ClioPath {
        &self.path
    }

    /// Returns `true` if this [`Output`] is a file,
    /// and `false` if this [`Output`] is std out or a pipe
    pub fn can_seek(&self) -> bool {
        matches!(
            self.stream,
            OutputStream::File(_) | OutputStream::AtomicFile(_)
        )
    }
}

impl_try_from!(Output);

impl Write for Output {
    fn flush(&mut self) -> IoResult<()> {
        match &mut self.stream {
            OutputStream::Stdout(stdout) => stdout.flush(),
            OutputStream::Pipe(pipe) => pipe.flush(),
            OutputStream::File(file) => file.flush(),
            OutputStream::AtomicFile(file) => file.flush(),
            #[cfg(feature = "http")]
            OutputStream::Http(http) => http.flush(),
        }
    }
    fn write(&mut self, buf: &[u8]) -> IoResult<usize> {
        match &mut self.stream {
            OutputStream::Stdout(stdout) => stdout.write(buf),
            OutputStream::Pipe(pipe) => pipe.write(buf),
            OutputStream::File(file) => file.write(buf),
            OutputStream::AtomicFile(file) => file.write(buf),
            #[cfg(feature = "http")]
            OutputStream::Http(http) => http.write(buf),
        }
    }
}

impl Seek for Output {
    fn seek(&mut self, pos: io::SeekFrom) -> IoResult<u64> {
        match &mut self.stream {
            OutputStream::File(file) => file.seek(pos),
            OutputStream::AtomicFile(file) => file.seek(pos),
            _ => Err(seek_error()),
        }
    }
}

impl OutputPath {
    /// Construct a new [`OutputPath`] from an string
    ///
    /// It checks if an output file could plausibly be created at that path
    pub fn new<S: TryInto<ClioPath>>(path: S) -> Result<Self>
    where
        crate::Error: From<<S as TryInto<ClioPath>>::Error>,
    {
        let path: ClioPath = path.try_into()?.with_direction(InOut::Out);
        if path.is_local() {
            if path.is_file() && !path.atomic {
                println!("{} is a file", path);
                assert_writeable(&path)?;
            } else {
                #[cfg(target_os = "linux")]
                if path.ends_with_slash() {
                    return Err(crate::dir_error().into());
                }
                assert_not_dir(&path)?;
                if let Some(parent) = path.safe_parent() {
                    assert_is_dir(parent)?;
                    assert_writeable(parent)?;
                } else {
                    return Err(not_found_error().into());
                }
            }
        }
        Ok(OutputPath { path })
    }

    /// Contructs a new [`OutputPath`] of `"-"` for stdout
    pub fn std() -> Self {
        OutputPath {
            path: ClioPath::std().with_direction(InOut::Out),
        }
    }

    /// convert to an normal [`Output`] setting the length of the file to size if it is `Some`
    pub fn maybe_with_len(self, size: Option<u64>) -> Result<Output> {
        Output::maybe_with_len(self.path, size)
    }

    /// Creater the file with a predetermined length, either using [`File::set_len`] or as the `content-length` header of the http put
    pub fn create_with_len(self, size: u64) -> Result<Output> {
        self.maybe_with_len(Some(size))
    }

    /// Create an [`Output`] without setting the length
    pub fn create(self) -> Result<Output> {
        self.maybe_with_len(None)
    }

    /// The original path represented by this [`OutputPath`]
    pub fn path(&self) -> &ClioPath {
        &self.path
    }

    /// Returns `true` if this [`OutputPath`] points to a file,
    /// and `false` if this [`OutputPath`] is std out or points to a pipe.
    /// Note that the file is not opened yet, so there are possible when you
    /// open the file it might have changed.
    pub fn can_seek(&self) -> bool {
        if self.path.is_local() {
            if let Ok(metadata) = self.path.metadata() {
                !is_fifo(&metadata)
            } else {
                false
            }
        } else {
            false
        }
    }
}

impl_try_from!(OutputPath: Clone);

fn open_rw(path: &Path) -> io::Result<File> {
    OpenOptions::new()
        .read(true)
        .write(true)
        .create(true)
        .truncate(true)
        .open(path)
        .or_else(|_| File::create(path))
}