<commit_before>use std::cmp;
use std::error;
use std::fmt;
use std::result;

use ast;
use hir;

/// A type alias for dealing with errors returned by this crate.
pub type Result<T> = result::Result<T, Error>;

/// This error type encompasses any error that can be returned by this crate.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Error {
    /// An error that occurred while translating concrete syntax into abstract
    /// syntax (AST).
    Parse(ast::Error),
    /// An error that occurred while translating abstract syntax into a high
    /// level intermediate representation (HIR).
    Translate(hir::Error),
    /// Hints that destructuring should not be exhaustive.
    ///
    /// This enum may grow additional variants, so this makes sure clients
    /// don't count on exhaustive matching. (Otherwise, adding a new variant
    /// could break existing code.)
    #[doc(hidden)]
    __Nonexhaustive,
}

impl From<ast::Error> for Error {
    fn from(err: ast::Error) -> Error {
        Error::Parse(err)
    }
}

impl From<hir::Error> for Error {
    fn from(err: hir::Error) -> Error {
        Error::Translate(err)
    }
}

impl error::Error for Error {
    fn description(&self) -> &str {
        match *self {
            Error::Parse(ref x) => x.description(),
            Error::Translate(ref x) => x.description(),
            _ => unreachable!(),
        }
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Error::Parse(ref x) => x.fmt(f),
            Error::Translate(ref x) => x.fmt(f),
            _ => unreachable!(),
        }
    }
}

/// A helper type for formatting nice error messages.
///
/// This type is responsible for reporting regex parse errors in a nice human
/// readable format. Most of its complexity is from interspersing notational
/// markers pointing out the position where an error occurred.
#[derive(Debug)]
pub struct Formatter<'e, E: 'e> {
    /// The original regex pattern in which the error occurred.
    pattern: &'e str,
    /// The error kind. It must impl fmt::Display.
    err: &'e E,
    /// The primary span of the error.
    span: &'e ast::Span,
    /// An auxiliary and optional span, in case the error needs to point to
    /// two locations (e.g., when reporting a duplicate capture group name).
    aux_span: Option<&'e ast::Span>,
}

impl<'e> From<&'e ast::Error> for Formatter<'e, ast::ErrorKind> {
    fn from(err: &'e ast::Error) -> Self {
        Formatter {
            pattern: err.pattern(),
            err: err.kind(),
            span: err.span(),
            aux_span: err.auxiliary_span(),
        }
    }
}

impl<'e> From<&'e hir::Error> for Formatter<'e, hir::ErrorKind> {
    fn from(err: &'e hir::Error) -> Self {
        Formatter {
            pattern: err.pattern(),
            err: err.kind(),
            span: err.span(),
            aux_span: None,
        }
    }
}

impl<'e, E: fmt::Display> fmt::Display for Formatter<'e, E> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let spans = Spans::from_formatter(self);
        if self.pattern.contains('\n') {
            let divider = repeat_char('~', 79);

            try!(writeln!(f, "regex parse error:"));
            try!(writeln!(f, "{}", divider));
            let notated = spans.notate();
            try!(write!(f, "{}", notated));
            try!(writeln!(f, "{}", divider));
            // If we have error spans that cover multiple lines, then we just
            // note the line numbers.
            if !spans.multi_line.is_empty() {
                let mut notes = vec![];
                for span in &spans.multi_line {
                    notes.push(format!(
                        "on line {} (column {}) through line {} (column {})",
                        span.start.line, span.start.column,
                        span.end.line, span.end.column - 1));
                }
                try!(writeln!(f, "{}", notes.join("\n")));
            }
            try!(write!(f, "error: {}", self.err));
        } else {
            try!(writeln!(f, "regex parse error:"));
            let notated = Spans::from_formatter(self).notate();
            try!(write!(f, "{}", notated));
            try!(write!(f, "error: {}", self.err));
        }
        Ok(())
    }
}

/// This type represents an arbitrary number of error spans in a way that makes
/// it convenient to notate the regex pattern. ("Notate" means "point out
/// exactly where the error occurred in the regex pattern.")
///
/// Technically, we can only ever have two spans given our current error
/// structure. However, after toiling with a specific algorithm for handling
/// two spans, it became obvious that an algorithm to handle an arbitrary
/// number of spans was actually much simpler.
struct Spans<'p> {
    /// The original regex pattern string.
    pattern: &'p str,
    /// The total width that should be used for line numbers. The width is
    /// used for left padding the line numbers for alignment.
    ///
    /// A value of `0` means line numbers should not be displayed. That is,
    /// the pattern is itself only one line.
    line_number_width: usize,
    /// All error spans that occur on a single line. This sequence always has
    /// length equivalent to the number of lines in `pattern`, where the index
    /// of the sequence represents a line number, starting at `0`. The spans
    /// in each line are sorted in ascending order.
    by_line: Vec<Vec<ast::Span>>,
    /// All error spans that occur over one or more lines. That is, the start
    /// and end position of the span have different line numbers. The spans are
    /// sorted in ascending order.
    multi_line: Vec<ast::Span>,
}

impl<'p> Spans<'p> {
    /// Build a sequence of spans from a formatter.
    fn from_formatter<'e, E: fmt::Display>(
        fmter: &'p Formatter<'e, E>,
    ) -> Spans<'p> {
        let line_count = fmter.pattern.lines().count();
        let line_number_width =
            if line_count <= 1 {
                0
            } else {
                line_count.to_string().len()
            };
        let mut spans = Spans {
            pattern: &fmter.pattern,
            line_number_width: line_number_width,
            by_line: vec![vec![]; line_count],
            multi_line: vec![],
        };
        spans.add(fmter.span.clone());
        if let Some(span) = fmter.aux_span {
            spans.add(span.clone());
        }
        spans
    }

    /// Add the given span to this sequence, putting it in the right place.
    fn add(&mut self, span: ast::Span) {
        // This is grossly inefficient since we sort after each add, but right
        // now, we only ever add two spans at most.
        if span.is_one_line() {
            let i = span.start.line - 1; // because lines are 1-indexed
            self.by_line[i].push(span);
            self.by_line[i].sort();
        } else {
            self.multi_line.push(span);
            self.multi_line.sort();
        }
    }

    /// Notate the pattern string with carents (`^`) pointing at each span
    /// location. This only applies to spans that occur within a single line.
    fn notate(&self) -> String {
        let mut notated = String::new();
        for (i, line) in self.pattern.lines().enumerate() {
            if self.line_number_width > 0 {
                notated.push_str(&self.left_pad_line_number(i + 1));
                notated.push_str(": ");
            } else {
                notated.push_str("    ");
            }
            notated.push_str(line);
            notated.push('\n');
            if let Some(notes) = self.notate_line(i) {
                notated.push_str(&notes);
                notated.push('\n');
            }
        }
        notated
    }

    /// Return notes for the line indexed at `i` (zero-based). If there are no
    /// spans for the given line, then `None` is returned. Otherwise, an
    /// appropriately space padded string with correctly positioned `^` is
    /// returned, accounting for line numbers.
    fn notate_line(&self, i: usize) -> Option<String> {
        let spans = &self.by_line[i];
        if spans.is_empty() {
            return None;
        }
        let mut notes = String::new();
        for _ in 0..self.line_number_padding() {
            notes.push(' ');
        }
        let mut pos = 0;
        for span in spans {
            for _ in pos..(span.start.column - 1) {
                notes.push(' ');
                pos += 1;
            }
            let note_len = span.end.column.saturating_sub(span.start.column);
            for _ in 0..cmp::max(1, note_len) {
                notes.push('^');
                pos += 1;
            }
        }
        Some(notes)
    }

    /// Left pad the given line number with spaces such that it is aligned with
    /// other line numbers.
    fn left_pad_line_number(&self, n: usize) -> String {
        let n = n.to_string();
        let pad = self.line_number_width.checked_sub(n.len()).unwrap();
        let mut result = repeat_char(' ', pad);
        result.push_str(&n);
        result
    }

    /// Return the line number padding beginning at the start of each line of
    /// the pattern.
    ///
    /// If the pattern is only one line, then this returns a fixed padding
    /// for visual indentation.
    fn line_number_padding(&self) -> usize {
        if self.line_number_width == 0 {
            4
        } else {
            2 + self.line_number_width
        }
    }
}

fn repeat_char(c: char, count: usize) -> String {
    ::std::iter::repeat(c).take(count).collect()
}
<commit_msg>syntax: fix bug in error printer<commit_after>use std::cmp;
use std::error;
use std::fmt;
use std::result;

use ast;
use hir;

/// A type alias for dealing with errors returned by this crate.
pub type Result<T> = result::Result<T, Error>;

/// This error type encompasses any error that can be returned by this crate.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Error {
    /// An error that occurred while translating concrete syntax into abstract
    /// syntax (AST).
    Parse(ast::Error),
    /// An error that occurred while translating abstract syntax into a high
    /// level intermediate representation (HIR).
    Translate(hir::Error),
    /// Hints that destructuring should not be exhaustive.
    ///
    /// This enum may grow additional variants, so this makes sure clients
    /// don't count on exhaustive matching. (Otherwise, adding a new variant
    /// could break existing code.)
    #[doc(hidden)]
    __Nonexhaustive,
}

impl From<ast::Error> for Error {
    fn from(err: ast::Error) -> Error {
        Error::Parse(err)
    }
}

impl From<hir::Error> for Error {
    fn from(err: hir::Error) -> Error {
        Error::Translate(err)
    }
}

impl error::Error for Error {
    fn description(&self) -> &str {
        match *self {
            Error::Parse(ref x) => x.description(),
            Error::Translate(ref x) => x.description(),
            _ => unreachable!(),
        }
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Error::Parse(ref x) => x.fmt(f),
            Error::Translate(ref x) => x.fmt(f),
            _ => unreachable!(),
        }
    }
}

/// A helper type for formatting nice error messages.
///
/// This type is responsible for reporting regex parse errors in a nice human
/// readable format. Most of its complexity is from interspersing notational
/// markers pointing out the position where an error occurred.
#[derive(Debug)]
pub struct Formatter<'e, E: 'e> {
    /// The original regex pattern in which the error occurred.
    pattern: &'e str,
    /// The error kind. It must impl fmt::Display.
    err: &'e E,
    /// The primary span of the error.
    span: &'e ast::Span,
    /// An auxiliary and optional span, in case the error needs to point to
    /// two locations (e.g., when reporting a duplicate capture group name).
    aux_span: Option<&'e ast::Span>,
}

impl<'e> From<&'e ast::Error> for Formatter<'e, ast::ErrorKind> {
    fn from(err: &'e ast::Error) -> Self {
        Formatter {
            pattern: err.pattern(),
            err: err.kind(),
            span: err.span(),
            aux_span: err.auxiliary_span(),
        }
    }
}

impl<'e> From<&'e hir::Error> for Formatter<'e, hir::ErrorKind> {
    fn from(err: &'e hir::Error) -> Self {
        Formatter {
            pattern: err.pattern(),
            err: err.kind(),
            span: err.span(),
            aux_span: None,
        }
    }
}

impl<'e, E: fmt::Display> fmt::Display for Formatter<'e, E> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let spans = Spans::from_formatter(self);
        if self.pattern.contains('\n') {
            let divider = repeat_char('~', 79);

            try!(writeln!(f, "regex parse error:"));
            try!(writeln!(f, "{}", divider));
            let notated = spans.notate();
            try!(write!(f, "{}", notated));
            try!(writeln!(f, "{}", divider));
            // If we have error spans that cover multiple lines, then we just
            // note the line numbers.
            if !spans.multi_line.is_empty() {
                let mut notes = vec![];
                for span in &spans.multi_line {
                    notes.push(format!(
                        "on line {} (column {}) through line {} (column {})",
                        span.start.line, span.start.column,
                        span.end.line, span.end.column - 1));
                }
                try!(writeln!(f, "{}", notes.join("\n")));
            }
            try!(write!(f, "error: {}", self.err));
        } else {
            try!(writeln!(f, "regex parse error:"));
            let notated = Spans::from_formatter(self).notate();
            try!(write!(f, "{}", notated));
            try!(write!(f, "error: {}", self.err));
        }
        Ok(())
    }
}

/// This type represents an arbitrary number of error spans in a way that makes
/// it convenient to notate the regex pattern. ("Notate" means "point out
/// exactly where the error occurred in the regex pattern.")
///
/// Technically, we can only ever have two spans given our current error
/// structure. However, after toiling with a specific algorithm for handling
/// two spans, it became obvious that an algorithm to handle an arbitrary
/// number of spans was actually much simpler.
struct Spans<'p> {
    /// The original regex pattern string.
    pattern: &'p str,
    /// The total width that should be used for line numbers. The width is
    /// used for left padding the line numbers for alignment.
    ///
    /// A value of `0` means line numbers should not be displayed. That is,
    /// the pattern is itself only one line.
    line_number_width: usize,
    /// All error spans that occur on a single line. This sequence always has
    /// length equivalent to the number of lines in `pattern`, where the index
    /// of the sequence represents a line number, starting at `0`. The spans
    /// in each line are sorted in ascending order.
    by_line: Vec<Vec<ast::Span>>,
    /// All error spans that occur over one or more lines. That is, the start
    /// and end position of the span have different line numbers. The spans are
    /// sorted in ascending order.
    multi_line: Vec<ast::Span>,
}

impl<'p> Spans<'p> {
    /// Build a sequence of spans from a formatter.
    fn from_formatter<'e, E: fmt::Display>(
        fmter: &'p Formatter<'e, E>,
    ) -> Spans<'p> {
        let mut line_count = fmter.pattern.lines().count();
        // If the pattern ends with a `\n` literal, then our line count is
        // off by one, since a span can occur immediately after the last `\n`,
        // which is consider to be an additional line.
        if fmter.pattern.ends_with('\n') {
            line_count += 1;
        }
        let line_number_width =
            if line_count <= 1 {
                0
            } else {
                line_count.to_string().len()
            };
        let mut spans = Spans {
            pattern: &fmter.pattern,
            line_number_width: line_number_width,
            by_line: vec![vec![]; line_count],
            multi_line: vec![],
        };
        spans.add(fmter.span.clone());
        if let Some(span) = fmter.aux_span {
            spans.add(span.clone());
        }
        spans
    }

    /// Add the given span to this sequence, putting it in the right place.
    fn add(&mut self, span: ast::Span) {
        // This is grossly inefficient since we sort after each add, but right
        // now, we only ever add two spans at most.
        if span.is_one_line() {
            let i = span.start.line - 1; // because lines are 1-indexed
            self.by_line[i].push(span);
            self.by_line[i].sort();
        } else {
            self.multi_line.push(span);
            self.multi_line.sort();
        }
    }

    /// Notate the pattern string with carents (`^`) pointing at each span
    /// location. This only applies to spans that occur within a single line.
    fn notate(&self) -> String {
        let mut notated = String::new();
        for (i, line) in self.pattern.lines().enumerate() {
            if self.line_number_width > 0 {
                notated.push_str(&self.left_pad_line_number(i + 1));
                notated.push_str(": ");
            } else {
                notated.push_str("    ");
            }
            notated.push_str(line);
            notated.push('\n');
            if let Some(notes) = self.notate_line(i) {
                notated.push_str(&notes);
                notated.push('\n');
            }
        }
        notated
    }

    /// Return notes for the line indexed at `i` (zero-based). If there are no
    /// spans for the given line, then `None` is returned. Otherwise, an
    /// appropriately space padded string with correctly positioned `^` is
    /// returned, accounting for line numbers.
    fn notate_line(&self, i: usize) -> Option<String> {
        let spans = &self.by_line[i];
        if spans.is_empty() {
            return None;
        }
        let mut notes = String::new();
        for _ in 0..self.line_number_padding() {
            notes.push(' ');
        }
        let mut pos = 0;
        for span in spans {
            for _ in pos..(span.start.column - 1) {
                notes.push(' ');
                pos += 1;
            }
            let note_len = span.end.column.saturating_sub(span.start.column);
            for _ in 0..cmp::max(1, note_len) {
                notes.push('^');
                pos += 1;
            }
        }
        Some(notes)
    }

    /// Left pad the given line number with spaces such that it is aligned with
    /// other line numbers.
    fn left_pad_line_number(&self, n: usize) -> String {
        let n = n.to_string();
        let pad = self.line_number_width.checked_sub(n.len()).unwrap();
        let mut result = repeat_char(' ', pad);
        result.push_str(&n);
        result
    }

    /// Return the line number padding beginning at the start of each line of
    /// the pattern.
    ///
    /// If the pattern is only one line, then this returns a fixed padding
    /// for visual indentation.
    fn line_number_padding(&self) -> usize {
        if self.line_number_width == 0 {
            4
        } else {
            2 + self.line_number_width
        }
    }
}

fn repeat_char(c: char, count: usize) -> String {
    ::std::iter::repeat(c).take(count).collect()
}

#[cfg(test)]
mod tests {
    use ast::parse::Parser;

    // See: https://github.com/rust-lang/regex/issues/464
    #[test]
    fn regression_464() {
        let err = Parser::new().parse("a{\n").unwrap_err();
        // This test checks that the error formatter doesn't panic.
        assert!(!err.to_string().is_empty());
    }
}
<|endoftext|>


<commit_before>use super::*;
use std::fs::File;
use std::path::Path;

pub struct VapoursynthWriter {
    opts: AvsOptions,
    audio_filename: Option<PathBuf>,
}

impl ScriptFormat for VapoursynthWriter {
    fn build_video_filter_string(&self, current_filename: &Path, is_preload: bool) -> String {
        let video_filter = self.get_video_filter_full_name(&current_filename);
        let timecodes_path = current_filename.with_extension("timecodes.txt");
        if self.opts.to_cfr && !timecodes_path.exists() {
            File::create(&timecodes_path).ok();
        }
        let mut filter_opts = String::new();
        if self.opts.to_cfr && is_preload {
            filter_opts.push_str(&format!(
                ", timecodes=\"{}\"",
                escape_python_string(timecodes_path.canonicalize().unwrap().to_str().unwrap()),
            ));
        }

        format!(
            "{}({}{})",
            video_filter,
            format!(
                "source='{}'",
                escape_python_string(current_filename.canonicalize().unwrap().to_str().unwrap())
            ),
            filter_opts
        )
    }

    fn build_vfr_string(&self, timecodes_path: &Path) -> String {
        format!(
            "core.vfrtocfr.VFRToCFR(\"{}\", 120000, 1001)",
            escape_python_string(timecodes_path.canonicalize().unwrap().to_str().unwrap())
        )
    }

    fn build_downsample_string(&self) -> Option<String> {
        Some("core.resize.Spline36(format = vs.YUV420P8)".to_string())
    }

    #[inline(always)]
    fn get_opts(&self) -> &AvsOptions {
        &self.opts
    }

    #[inline(always)]
    fn get_script_extension(&self) -> &'static str {
        "vpy"
    }

    fn build_audio_dub_string(&mut self, audio_filename: &Path) -> String {
        format!(
            "core.damb.Read(\'{}\')",
            escape_python_string(audio_filename.to_str().unwrap())
        )
    }

    fn build_subtitle_string(&self, subtitle_filename: &Path) -> String {
        format!(
            "core.sub.TextFile(\'{}\')",
            escape_python_string(subtitle_filename.to_str().unwrap())
        )
    }

    fn build_resize_string(&self, width: u32, height: u32) -> String {
        format!("core.resize.Spline36({}, {})", width, height)
    }

    fn build_trim_string(&self, breakpoint: BreakPoint) -> String {
        format!(
            "core.std.Trim({}, {})",
            breakpoint.start_frame, breakpoint.end_frame
        )
    }

    fn write_script_header(&self, script: &mut File) -> Result<(), String> {
        writeln!(script, "import vapoursynth as vs").map_err(|e| e.to_string())?;
        writeln!(script, "core = vs.get_core()").map_err(|e| e.to_string())?;
        writeln!(script).map_err(|e| e.to_string())?;
        Ok(())
    }

    fn write_segments(&self, segments: &[Vec<String>], script: &mut File) -> Result<(), String> {
        for (i, segment) in segments.iter().enumerate() {
            let video_label = format!("video{}", i + 1);
            for (j, mut filter) in segment.clone().into_iter().enumerate() {
                if j > 0 {
                    filter = if filter.contains("()") {
                        filter.replacen("()", &format!("({})", video_label), 1)
                    } else {
                        filter.replacen("(", &&format!("({}, ", video_label), 1)
                    };
                }
                writeln!(script, "{} = {}", video_label, filter).map_err(|e| e.to_string())?;
            }
            writeln!(script).map_err(|e| e.to_string())?;
        }
        writeln!(
            script,
            "video = {}",
            (0..segments.len())
                .map(|i| format!("video{}", i + 1))
                .collect::<Vec<String>>()
                .join(" + ")
        )
        .map_err(|e| e.to_string())?;
        writeln!(script).map_err(|e| e.to_string())?;
        if let Some(ref audio_filename) = self.audio_filename {
            writeln!(
                script,
                "core.damb.Write(video, \'{}\').set_output()",
                escape_python_string(audio_filename.with_extension("flac").to_str().unwrap())
            )
            .map_err(|e| e.to_string())?;
        } else {
            writeln!(script, "video.set_output()").map_err(|e| e.to_string())?;
        }

        Ok(())
    }
}

fn escape_python_string(input: &str) -> String {
    input.replace(r"\", r"\\").replace(r"'", r"\'")
}

impl VapoursynthWriter {
    pub fn new(
        mut opts: AvsOptions,
        apply_default_filters: bool,
        audio_filename: Option<PathBuf>,
    ) -> Self {
        let default_filters: &[String] = &["core.rgvs.RemoveGrain(1)".to_string()];
        if apply_default_filters {
            opts.filters.extend_from_slice(default_filters);
        }
        VapoursynthWriter {
            opts,
            audio_filename,
        }
    }

    fn determine_video_source_filter(&self, path: &Path) -> &'static str {
        match determine_input_type(path) {
            Some(InputTypes::DgIndex) => "core.d2v.Source",
            Some(InputTypes::DgAvc) => unimplemented!(),
            Some(_) => "core.ffms2.Source",
            None => panic!("Invalid input type"),
        }
    }

    fn get_video_filter_full_name(&self, current_filename: &Path) -> &'static str {
        self.determine_video_source_filter(&current_filename)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs::File;
    use std::io::BufReader;
    use std::io::Read;
    use std::path::Path;

    fn read_file(path: &Path) -> String {
        let file = File::open(path).unwrap();
        let mut reader = BufReader::new(file);
        let mut output = String::new();
        reader.read_to_string(&mut output).unwrap();
        output.replace("\r\n", "\n")
    }

    #[test]
    fn create_script_vps_basic() {
        let in_file = Path::new("files/example.mkv");
        let out_file = Path::new("files/vps_basic.vpy");
        let expected = Path::new("files/vps_basic.vpy.expected");
        let opts = AvsOptions {
            filters: vec![],
            ass: false,
            ass_extract: None,
            audio: (false, None),
            resize: None,
            to_cfr: false,
            downsample: false,
        };
        let mut writer = VapoursynthWriter::new(opts, true);
        writer.create_script(in_file, out_file).unwrap();
        assert_eq!(&read_file(out_file), &read_file(expected));
    }

    #[test]
    fn create_script_vps_audio() {
        let in_file = Path::new("files/example.mkv");
        let out_file = Path::new("files/vps_audio.vpy");
        let expected = Path::new("files/vps_audio.vpy.expected");
        let opts = AvsOptions {
            filters: vec![],
            ass: false,
            ass_extract: None,
            audio: (true, None),
            resize: None,
            to_cfr: false,
            downsample: false,
        };
        let mut writer = VapoursynthWriter::new(opts, true);
        writer.create_script(in_file, out_file).unwrap();
        assert_eq!(&read_file(out_file), &read_file(expected));
    }

    #[test]
    fn create_script_vps_downsample() {
        let in_file = Path::new("files/example.mkv");
        let out_file = Path::new("files/vps_downsample.vpy");
        let expected = Path::new("files/vps_downsample.vpy.expected");
        let opts = AvsOptions {
            filters: vec![],
            ass: false,
            ass_extract: None,
            audio: (false, None),
            resize: None,
            to_cfr: false,
            downsample: true,
        };
        let mut writer = VapoursynthWriter::new(opts, true);
        writer.create_script(in_file, out_file).unwrap();
        assert_eq!(&read_file(out_file), &read_file(expected));
    }

    #[test]
    fn create_script_vps_cfr() {
        let in_file = Path::new("files/example.mkv");
        let out_file = Path::new("files/vps_cfr.vpy");
        let expected = Path::new("files/vps_cfr.vpy.expected");
        let opts = AvsOptions {
            filters: vec![],
            ass: false,
            ass_extract: None,
            audio: (false, None),
            resize: None,
            to_cfr: true,
            downsample: false,
        };
        let mut writer = VapoursynthWriter::new(opts, true);
        writer.create_script(in_file, out_file).unwrap();
        assert_eq!(&read_file(out_file), &read_file(expected));
    }

    #[test]
    fn create_script_vps_resize() {
        let in_file = Path::new("files/example.mkv");
        let out_file = Path::new("files/vps_resize.vpy");
        let expected = Path::new("files/vps_resize.vpy.expected");
        let opts = AvsOptions {
            filters: vec![],
            ass: false,
            ass_extract: None,
            audio: (false, None),
            resize: Some((640, 480)),
            to_cfr: false,
            downsample: false,
        };
        let mut writer = VapoursynthWriter::new(opts, true);
        writer.create_script(in_file, out_file).unwrap();
        assert_eq!(&read_file(out_file), &read_file(expected));
    }

    #[test]
    fn create_script_vps_ass() {
        let in_file = Path::new("files/example.mkv");
        let out_file = Path::new("files/vps_ass.vpy");
        let expected = Path::new("files/vps_ass.vpy.expected");
        let opts = AvsOptions {
            filters: vec![],
            ass: true,
            ass_extract: None,
            audio: (false, None),
            resize: None,
            to_cfr: false,
            downsample: false,
        };
        let mut writer = VapoursynthWriter::new(opts, true);
        writer.create_script(in_file, out_file).unwrap();
        assert_eq!(&read_file(out_file), &read_file(expected));
    }
}
<commit_msg>Prefer LWLibavSource from LSmash<commit_after>use super::*;
use std::fs::File;
use std::path::Path;

pub struct VapoursynthWriter {
    opts: AvsOptions,
    audio_filename: Option<PathBuf>,
}

impl ScriptFormat for VapoursynthWriter {
    fn build_video_filter_string(&self, current_filename: &Path, is_preload: bool) -> String {
        let video_filter = self.get_video_filter_full_name(&current_filename);
        let timecodes_path = current_filename.with_extension("timecodes.txt");
        if self.opts.to_cfr && !timecodes_path.exists() {
            File::create(&timecodes_path).ok();
        }
        let mut filter_opts = String::new();
        if self.opts.to_cfr && is_preload {
            filter_opts.push_str(&format!(
                ", timecodes=\"{}\"",
                escape_python_string(timecodes_path.canonicalize().unwrap().to_str().unwrap()),
            ));
        }

        format!(
            "{}({}{})",
            video_filter,
            format!(
                "source='{}'",
                escape_python_string(current_filename.canonicalize().unwrap().to_str().unwrap())
            ),
            filter_opts
        )
    }

    fn build_vfr_string(&self, timecodes_path: &Path) -> String {
        format!(
            "core.vfrtocfr.VFRToCFR(\"{}\", 120000, 1001)",
            escape_python_string(timecodes_path.canonicalize().unwrap().to_str().unwrap())
        )
    }

    fn build_downsample_string(&self) -> Option<String> {
        Some("core.resize.Spline36(format = vs.YUV420P8)".to_string())
    }

    #[inline(always)]
    fn get_opts(&self) -> &AvsOptions {
        &self.opts
    }

    #[inline(always)]
    fn get_script_extension(&self) -> &'static str {
        "vpy"
    }

    fn build_audio_dub_string(&mut self, audio_filename: &Path) -> String {
        format!(
            "core.damb.Read(\'{}\')",
            escape_python_string(audio_filename.to_str().unwrap())
        )
    }

    fn build_subtitle_string(&self, subtitle_filename: &Path) -> String {
        format!(
            "core.sub.TextFile(\'{}\')",
            escape_python_string(subtitle_filename.to_str().unwrap())
        )
    }

    fn build_resize_string(&self, width: u32, height: u32) -> String {
        format!("core.resize.Spline36({}, {})", width, height)
    }

    fn build_trim_string(&self, breakpoint: BreakPoint) -> String {
        format!(
            "core.std.Trim({}, {})",
            breakpoint.start_frame, breakpoint.end_frame
        )
    }

    fn write_script_header(&self, script: &mut File) -> Result<(), String> {
        writeln!(script, "import vapoursynth as vs").map_err(|e| e.to_string())?;
        writeln!(script, "core = vs.get_core()").map_err(|e| e.to_string())?;
        writeln!(script).map_err(|e| e.to_string())?;
        Ok(())
    }

    fn write_segments(&self, segments: &[Vec<String>], script: &mut File) -> Result<(), String> {
        for (i, segment) in segments.iter().enumerate() {
            let video_label = format!("video{}", i + 1);
            for (j, mut filter) in segment.clone().into_iter().enumerate() {
                if j > 0 {
                    filter = if filter.contains("()") {
                        filter.replacen("()", &format!("({})", video_label), 1)
                    } else {
                        filter.replacen("(", &&format!("({}, ", video_label), 1)
                    };
                }
                writeln!(script, "{} = {}", video_label, filter).map_err(|e| e.to_string())?;
            }
            writeln!(script).map_err(|e| e.to_string())?;
        }
        writeln!(
            script,
            "video = {}",
            (0..segments.len())
                .map(|i| format!("video{}", i + 1))
                .collect::<Vec<String>>()
                .join(" + ")
        )
        .map_err(|e| e.to_string())?;
        writeln!(script).map_err(|e| e.to_string())?;
        if let Some(ref audio_filename) = self.audio_filename {
            writeln!(
                script,
                "core.damb.Write(video, \'{}\').set_output()",
                escape_python_string(audio_filename.with_extension("flac").to_str().unwrap())
            )
            .map_err(|e| e.to_string())?;
        } else {
            writeln!(script, "video.set_output()").map_err(|e| e.to_string())?;
        }

        Ok(())
    }
}

fn escape_python_string(input: &str) -> String {
    input.replace(r"\", r"\\").replace(r"'", r"\'")
}

impl VapoursynthWriter {
    pub fn new(
        mut opts: AvsOptions,
        apply_default_filters: bool,
        audio_filename: Option<PathBuf>,
    ) -> Self {
        let default_filters: &[String] = &["core.rgvs.RemoveGrain(1)".to_string()];
        if apply_default_filters {
            opts.filters.extend_from_slice(default_filters);
        }
        VapoursynthWriter {
            opts,
            audio_filename,
        }
    }

    fn determine_video_source_filter(&self, path: &Path) -> &'static str {
        match determine_input_type(path) {
            Some(InputTypes::DgIndex) => "core.d2v.Source",
            Some(InputTypes::DgAvc) => unimplemented!(),
            Some(_) => "core.lsmas.LWLibavSource",
            None => panic!("Invalid input type"),
        }
    }

    fn get_video_filter_full_name(&self, current_filename: &Path) -> &'static str {
        self.determine_video_source_filter(&current_filename)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs::File;
    use std::io::BufReader;
    use std::io::Read;
    use std::path::Path;

    fn read_file(path: &Path) -> String {
        let file = File::open(path).unwrap();
        let mut reader = BufReader::new(file);
        let mut output = String::new();
        reader.read_to_string(&mut output).unwrap();
        output.replace("\r\n", "\n")
    }

    #[test]
    fn create_script_vps_basic() {
        let in_file = Path::new("files/example.mkv");
        let out_file = Path::new("files/vps_basic.vpy");
        let expected = Path::new("files/vps_basic.vpy.expected");
        let opts = AvsOptions {
            filters: vec![],
            ass: false,
            ass_extract: None,
            audio: (false, None),
            resize: None,
            to_cfr: false,
            downsample: false,
        };
        let mut writer = VapoursynthWriter::new(opts, true);
        writer.create_script(in_file, out_file).unwrap();
        assert_eq!(&read_file(out_file), &read_file(expected));
    }

    #[test]
    fn create_script_vps_audio() {
        let in_file = Path::new("files/example.mkv");
        let out_file = Path::new("files/vps_audio.vpy");
        let expected = Path::new("files/vps_audio.vpy.expected");
        let opts = AvsOptions {
            filters: vec![],
            ass: false,
            ass_extract: None,
            audio: (true, None),
            resize: None,
            to_cfr: false,
            downsample: false,
        };
        let mut writer = VapoursynthWriter::new(opts, true);
        writer.create_script(in_file, out_file).unwrap();
        assert_eq!(&read_file(out_file), &read_file(expected));
    }

    #[test]
    fn create_script_vps_downsample() {
        let in_file = Path::new("files/example.mkv");
        let out_file = Path::new("files/vps_downsample.vpy");
        let expected = Path::new("files/vps_downsample.vpy.expected");
        let opts = AvsOptions {
            filters: vec![],
            ass: false,
            ass_extract: None,
            audio: (false, None),
            resize: None,
            to_cfr: false,
            downsample: true,
        };
        let mut writer = VapoursynthWriter::new(opts, true);
        writer.create_script(in_file, out_file).unwrap();
        assert_eq!(&read_file(out_file), &read_file(expected));
    }

    #[test]
    fn create_script_vps_cfr() {
        let in_file = Path::new("files/example.mkv");
        let out_file = Path::new("files/vps_cfr.vpy");
        let expected = Path::new("files/vps_cfr.vpy.expected");
        let opts = AvsOptions {
            filters: vec![],
            ass: false,
            ass_extract: None,
            audio: (false, None),
            resize: None,
            to_cfr: true,
            downsample: false,
        };
        let mut writer = VapoursynthWriter::new(opts, true);
        writer.create_script(in_file, out_file).unwrap();
        assert_eq!(&read_file(out_file), &read_file(expected));
    }

    #[test]
    fn create_script_vps_resize() {
        let in_file = Path::new("files/example.mkv");
        let out_file = Path::new("files/vps_resize.vpy");
        let expected = Path::new("files/vps_resize.vpy.expected");
        let opts = AvsOptions {
            filters: vec![],
            ass: false,
            ass_extract: None,
            audio: (false, None),
            resize: Some((640, 480)),
            to_cfr: false,
            downsample: false,
        };
        let mut writer = VapoursynthWriter::new(opts, true);
        writer.create_script(in_file, out_file).unwrap();
        assert_eq!(&read_file(out_file), &read_file(expected));
    }

    #[test]
    fn create_script_vps_ass() {
        let in_file = Path::new("files/example.mkv");
        let out_file = Path::new("files/vps_ass.vpy");
        let expected = Path::new("files/vps_ass.vpy.expected");
        let opts = AvsOptions {
            filters: vec![],
            ass: true,
            ass_extract: None,
            audio: (false, None),
            resize: None,
            to_cfr: false,
            downsample: false,
        };
        let mut writer = VapoursynthWriter::new(opts, true);
        writer.create_script(in_file, out_file).unwrap();
        assert_eq!(&read_file(out_file), &read_file(expected));
    }
}
<|endoftext|>


<commit_before>// mod error
use std::error::{self, Error as Err};
use std::fmt::{self, Display};
use std::io;
use std::convert::From;
use std::net::AddrParseError;
use std::sync::PoisonError;
use std::result;
use escaping::unescape;

pub type Result<T> = result::Result<T, Error>;

/// # Example
/// ```
/// use sqlib::error::SQError;
///
/// let line = "error id=0 msg=ok".to_string();
///
/// let err_option = SQError::parse(&line);
/// let err = match err_option {
///     Some(err) => err,
///     None => { panic!("no error found"); },
/// };
/// assert_eq!(0, err.id());
/// ```
#[derive(Debug)]
pub struct SQError {
    id: u32,
    msg: String,
    full_msg: String,
}

// helping function for SQError::parse
fn is_seperator(c: char) -> bool {
    c == '=' || c.is_whitespace()
}

impl SQError {
    pub fn new(id: u32, msg: String) -> SQError {
        let full_msg_str = format!("error id={} msg={}", id, &msg);
        SQError {
            id: id,
            msg: msg,
            full_msg: full_msg_str,
        }
    }

    pub fn ok() -> SQError {
        SQError::new(0, "ok".to_string())
    }

    pub fn parse_is_ok(s: &str) -> Result<bool> {
        let err = match SQError::parse(s) {
            None => {
                return Ok(false);
            }
            Some(err) => err,
        };
        if err == SQError::ok() {
            Ok(true)
        } else {
            Err(Error::from(err))
        }
    }

    /// try to parse a String to a SQError
    pub fn parse(s: &str) -> Option<SQError> {
        // the str shouldn't be trimmed, because a real error is without
        // whitespace in the beginning
        let parts: Vec<&str> = s.splitn(6, is_seperator).collect();
        if parts.len() < 5 {
            return None;
        }
        if parts[0] != "error" {
            return None;
        }
        if parts[1] != "id" {
            return None;
        }
        let id_result = parts[2].clone().parse::<u32>();
        let id = match id_result {
            Err(_) => {
                return None;
            }
            Ok(val) => val,
        };
        if parts[3] != "msg" {
            return None;
        }
        let msg = parts[4].to_string().clone();
        Some(SQError::new(id, unescape(&msg)))
    }

    pub fn id(&self) -> u32 {
        self.id
    }

    pub fn msg(&self) -> String {
        self.msg.clone()
    }
}

impl PartialEq for SQError {
    fn eq(&self, other: &Self) -> bool {
        self.id == other.id
    }
}

impl Eq for SQError {}

impl Display for SQError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.full_msg)
    }
}

impl error::Error for SQError {
    fn description(&self) -> &str {
        &self.full_msg
    }
}

/// SQError is a custom Error type for the sqlib.
#[derive(Debug)]
pub enum Error {
    /// wraps io::Error
    Io(io::Error),
    /// server query error messages
    SQ(SQError),
    /// other errors
    Other(String),
}

impl error::Error for Error {
    fn description(&self) -> &str {
        match self {
            &Error::Io(ref err) => err.description(),
            &Error::SQ(ref err) => err.description(),
            &Error::Other(ref s) => s,
        }
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.description())
    }
}

impl<'a> From<&'a str> for Error {
    fn from(err: &'a str) -> Error {
        Error::Other(err.to_string())
    }
}

impl From<String> for Error {
    fn from(err: String) -> Error {
        Error::Other(err)
    }
}

impl From<io::Error> for Error {
    fn from(err: io::Error) -> Error {
        Error::Io(err)
    }
}

impl From<SQError> for Error {
    fn from(err: SQError) -> Error {
        Error::SQ(err)
    }
}

impl From<AddrParseError> for Error {
    fn from(err: AddrParseError) -> Error {
        Error::Other(err.description().to_string())
    }
}

impl<T> From<PoisonError<T>> for Error {
    fn from(err: PoisonError<T>) -> Error {
        Error::Other(format!("{}", err))
    }
}
<commit_msg>adding comments and examples to sqlib::error::SQError<commit_after>// mod error
use std::error::{self, Error as Err};
use std::fmt::{self, Display};
use std::io;
use std::convert::From;
use std::net::AddrParseError;
use std::sync::PoisonError;
use std::result;
use escaping::unescape;

/// The standart result type of sqlib.
pub type Result<T> = result::Result<T, Error>;

/// A SQError contains a TS3 Server Query error.
///
/// # Example
/// ```
/// use sqlib::error::SQError;
///
/// let line = "error id=0 msg=ok".to_string();
///
/// let err_option = SQError::parse(&line);
/// let err = match err_option {
///     Some(err) => err,
///     None => { panic!("no error found"); },
/// };
/// assert_eq!(0, err.id());
/// ```
#[derive(Debug)]
pub struct SQError {
    id: u32,
    msg: String,
    full_msg: String,
}

// helping function for SQError::parse
fn is_seperator(c: char) -> bool {
    c == '=' || c.is_whitespace()
}

impl SQError {
    pub fn new(id: u32, msg: String) -> SQError {
        let full_msg_str = format!("error id={} msg={}", id, &msg);
        SQError {
            id: id,
            msg: msg,
            full_msg: full_msg_str,
        }
    }

    /// Creates an OK error.
    pub fn ok() -> SQError {
        SQError::new(0, "ok".to_string())
    }

    /// This function tries to parse a string into an Error.
    ///
    /// # Return values
    ///
    /// - If it fails to parse it returns Ok(false).
    /// - If it parses the string as an OK error it returns Ok(true).
    /// - If it parses the string as another error it returns Err(error).
    ///
    /// # Example
    /// ```
    /// use sqlib::error::{Error, SQError};
    ///
    /// let ok_str = "error id=0 msg=ok";
    /// let no_err_str = "this is no error";
    /// let err_str = "error id=1 msg=test";
    ///
    /// let test_err = SQError::new(1, "test".to_string());
    /// let to_test_error = match SQError::parse_is_ok(err_str).unwrap_err() {
    ///     Error::SQ(e) => e,
    ///     _ => SQError::ok(),
    /// };
    ///
    /// assert_eq!(SQError::parse_is_ok(ok_str).unwrap(), true);
    /// assert_eq!(SQError::parse_is_ok(no_err_str).unwrap(), false);
    /// assert_eq!(to_test_error, test_err);
    /// ```
    pub fn parse_is_ok(s: &str) -> Result<bool> {
        let err = match SQError::parse(s) {
            None => {
                return Ok(false);
            }
            Some(err) => err,
        };
        if err == SQError::ok() {
            Ok(true)
        } else {
            Err(Error::from(err))
        }
    }

    /// try to parse a String to a SQError
    pub fn parse(s: &str) -> Option<SQError> {
        // the str shouldn't be trimmed, because a real error is without
        // whitespace in the beginning
        let parts: Vec<&str> = s.splitn(6, is_seperator).collect();
        if parts.len() < 5 {
            return None;
        }
        if parts[0] != "error" {
            return None;
        }
        if parts[1] != "id" {
            return None;
        }
        let id_result = parts[2].clone().parse::<u32>();
        let id = match id_result {
            Err(_) => {
                return None;
            }
            Ok(val) => val,
        };
        if parts[3] != "msg" {
            return None;
        }
        let msg = parts[4].to_string().clone();
        Some(SQError::new(id, unescape(&msg)))
    }

    pub fn id(&self) -> u32 {
        self.id
    }

    pub fn msg(&self) -> String {
        self.msg.clone()
    }
}

impl PartialEq for SQError {
    fn eq(&self, other: &Self) -> bool {
        self.id == other.id
    }
}

impl Eq for SQError {}

impl Display for SQError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.full_msg)
    }
}

impl error::Error for SQError {
    fn description(&self) -> &str {
        &self.full_msg
    }
}

/// Error is a custom Error type for the sqlib.
#[derive(Debug)]
pub enum Error {
    /// wraps io::Error
    Io(io::Error),
    /// server query error messages
    SQ(SQError),
    /// other errors
    Other(String),
}

impl error::Error for Error {
    fn description(&self) -> &str {
        match self {
            &Error::Io(ref err) => err.description(),
            &Error::SQ(ref err) => err.description(),
            &Error::Other(ref s) => s,
        }
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.description())
    }
}

impl<'a> From<&'a str> for Error {
    fn from(err: &'a str) -> Error {
        Error::Other(err.to_string())
    }
}

impl From<String> for Error {
    fn from(err: String) -> Error {
        Error::Other(err)
    }
}

impl From<io::Error> for Error {
    fn from(err: io::Error) -> Error {
        Error::Io(err)
    }
}

impl From<SQError> for Error {
    fn from(err: SQError) -> Error {
        Error::SQ(err)
    }
}

impl From<AddrParseError> for Error {
    fn from(err: AddrParseError) -> Error {
        Error::Other(err.description().to_string())
    }
}

impl<T> From<PoisonError<T>> for Error {
    fn from(err: PoisonError<T>) -> Error {
        Error::Other(format!("{}", err))
    }
}
<|endoftext|>


<commit_before>use crate::backtrace::Backtrace;
use crate::context::ContextError;
use std::any::TypeId;
use std::error::Error as StdError;
use std::fmt::{self, Debug, Display};
use std::mem;
use std::ops::{Deref, DerefMut};
use std::ptr;

/// The `Error` type, a wrapper around a dynamic error type.
///
/// `Error` works a lot like `Box<dyn std::error::Error>`, but with these
/// differences:
///
/// - `Error` requires that the error is `Send`, `Sync`, and `'static`.
/// - `Error` guarantees that a backtrace is available, even if the underlying
///   error type does not provide one.
/// - `Error` is represented as a narrow pointer — exactly one word in
///   size instead of two.
pub struct Error {
    inner: Box<ErrorImpl<()>>,
}

impl Error {
    /// Create a new error object from any error type.
    ///
    /// The error type must be threadsafe and `'static`, so that the `Error`
    /// will be as well.
    ///
    /// If the error type does not provide a backtrace, a backtrace will be
    /// created here to ensure that a backtrace exists.
    pub fn new<E>(error: E) -> Self
    where
        E: StdError + Send + Sync + 'static,
    {
        let type_id = TypeId::of::<E>();
        let backtrace = backtrace_if_absent!(error);

        // Safety: passing typeid of the right type E.
        unsafe {
            Error::construct(error, type_id, backtrace)
        }
    }

    pub(crate) fn new_adhoc<M>(message: M, backtrace: Option<Backtrace>) -> Self
    where
        M: Display + Debug + Send + Sync + 'static,
    {
        let error = MessageError(message);
        let type_id = TypeId::of::<M>();

        // Safety: MessageError is repr(transparent) so MessageError<M> has the
        // same layout as the typeid specifies.
        unsafe {
            Error::construct(error, type_id, backtrace)
        }
    }

    // Takes backtrace as argument rather than capturing it here so that the
    // user sees one fewer layer of wrapping noise in the backtrace.
    //
    // Unsafe because the type represented by type_id must have the same layout
    // as E or else we allow invalid downcasts.
    unsafe fn construct<E>(error: E, type_id: TypeId, backtrace: Option<Backtrace>) -> Self
    where
        E: StdError + Send + Sync + 'static,
    {
        let vtable = &ErrorVTable {
            object: object_raw::<E>,
            object_mut: object_mut_raw::<E>,
        };
        let inner = Box::new(ErrorImpl {
            vtable,
            type_id,
            backtrace,
            error,
        });
        Error {
            inner: mem::transmute::<Box<ErrorImpl<E>>, Box<ErrorImpl<()>>>(inner),
        }
    }

    /// Wrap the error value with additional context.
    ///
    /// For attaching context to a `Result` as it is propagated, the
    /// [`Context`][crate::Context] extension trait may be more convenient than
    /// this function.
    ///
    /// The primary reason to use `error.context(...)` instead of
    /// `result.context(...)` via the `Context` trait would be if the context
    /// needs to depend on some data held by the underlying error:
    ///
    /// ```
    /// # use std::fmt::{self, Debug, Display};
    /// #
    /// # type T = ();
    /// #
    /// # impl std::error::Error for ParseError {}
    /// # impl Debug for ParseError {
    /// #     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
    /// #         unimplemented!()
    /// #     }
    /// # }
    /// # impl Display for ParseError {
    /// #     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
    /// #         unimplemented!()
    /// #     }
    /// # }
    /// #
    /// use std::fs::File;
    /// use std::path::Path;
    ///
    /// struct ParseError {
    ///     line: usize,
    ///     column: usize,
    /// }
    ///
    /// fn parse_impl(file: File) -> Result<T, ParseError> {
    ///     # const IGNORE: &str = stringify! {
    ///     ...
    ///     # };
    ///     # unimplemented!()
    /// }
    ///
    /// pub fn parse(path: impl AsRef<Path>) -> anyhow::Result<T> {
    ///     let file = File::open(&path)?;
    ///     parse_impl(file).map_err(|error| {
    ///         let context = format!(
    ///             "only the first {} lines of {} are valid",
    ///             error.line, path.as_ref().display(),
    ///         );
    ///         anyhow::Error::new(error).context(context)
    ///     })
    /// }
    /// ```
    pub fn context<C>(self, context: C) -> Self
    where
        C: Display + Send + Sync + 'static,
    {
        Error::new(ContextError {
            error: self,
            context,
        })
    }

    /// Get the backtrace for this Error.
    ///
    /// Backtraces are only available on the nightly channel. Tracking issue:
    /// [rust-lang/rust#53487][tracking].
    ///
    /// In order for the backtrace to be meaningful, the environment variable
    /// `RUST_LIB_BACKTRACE=1` must be defined. Backtraces are somewhat
    /// expensive to capture in Rust, so we don't necessarily want to be
    /// capturing them all over the place all the time.
    ///
    /// [tracking]: https://github.com/rust-lang/rust/issues/53487
    #[cfg(backtrace)]
    pub fn backtrace(&self) -> &Backtrace {
        // NB: this unwrap can only fail if the underlying error's backtrace
        // method is nondeterministic, which would only happen in maliciously
        // constructed code
        self.inner
            .backtrace
            .as_ref()
            .or_else(|| self.inner.error().backtrace())
            .expect("backtrace capture failed")
    }

    /// An iterator of the chain of source errors contained by this Error.
    ///
    /// This iterator will visit every error in the cause chain of this error
    /// object, beginning with the error that this error object was created
    /// from.
    ///
    /// # Example
    ///
    /// ```
    /// use anyhow::Error;
    /// use std::io;
    ///
    /// pub fn underlying_io_error_kind(error: &Error) -> Option<io::ErrorKind> {
    ///     for cause in error.chain() {
    ///         if let Some(io_error) = cause.downcast_ref::<io::Error>() {
    ///             return Some(io_error.kind());
    ///         }
    ///     }
    ///     None
    /// }
    /// ```
    pub fn chain(&self) -> Chain {
        Chain {
            next: Some(self.inner.error()),
        }
    }

    /// The lowest level cause of this error — this error's cause's
    /// cause's cause etc.
    ///
    /// The root cause is the last error in the iterator produced by
    /// [`chain()`][Error::chain].
    pub fn root_cause(&self) -> &(dyn StdError + 'static) {
        let mut chain = self.chain();
        let mut root_cause = chain.next().unwrap();
        for cause in chain {
            root_cause = cause;
        }
        root_cause
    }

    /// Returns `true` if `E` is the type wrapped by this error object.
    pub fn is<E>(&self) -> bool
    where
        E: Display + Debug + Send + Sync + 'static,
    {
        TypeId::of::<E>() == self.inner.type_id
    }

    /// Attempt to downcast the error object to a concrete type.
    pub fn downcast<E>(self) -> Result<E, Self>
    where
        E: Display + Debug + Send + Sync + 'static,
    {
        if let Some(error) = self.downcast_ref::<E>() {
            unsafe {
                let error = ptr::read(error);
                drop(ptr::read(&self.inner));
                mem::forget(self);
                Ok(error)
            }
        } else {
            Err(self)
        }
    }

    /// Downcast this error object by reference.
    ///
    /// # Example
    ///
    /// ```
    /// # use anyhow::anyhow;
    /// # use std::fmt::{self, Display};
    /// # use std::task::Poll;
    /// #
    /// # #[derive(Debug)]
    /// # enum DataStoreError {
    /// #     Censored(()),
    /// # }
    /// #
    /// # impl Display for DataStoreError {
    /// #     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
    /// #         unimplemented!()
    /// #     }
    /// # }
    /// #
    /// # impl std::error::Error for DataStoreError {}
    /// #
    /// # const REDACTED_CONTENT: () = ();
    /// #
    /// # let error = anyhow!("...");
    /// # let root_cause = &error;
    /// #
    /// # let ret =
    /// // If the error was caused by redaction, then return a tombstone instead
    /// // of the content.
    /// match root_cause.downcast_ref::<DataStoreError>() {
    ///     Some(DataStoreError::Censored(_)) => Ok(Poll::Ready(REDACTED_CONTENT)),
    ///     None => Err(error),
    /// }
    /// # ;
    /// ```
    pub fn downcast_ref<E>(&self) -> Option<&E>
    where
        E: Display + Debug + Send + Sync + 'static,
    {
        if self.is::<E>() {
            unsafe { Some(&*(self.inner.error() as *const dyn StdError as *const E)) }
        } else {
            None
        }
    }

    /// Downcast this error object by mutable reference.
    pub fn downcast_mut<E>(&mut self) -> Option<&mut E>
    where
        E: Display + Debug + Send + Sync + 'static,
    {
        if self.is::<E>() {
            unsafe { Some(&mut *(self.inner.error_mut() as *mut dyn StdError as *mut E)) }
        } else {
            None
        }
    }
}

impl<E> From<E> for Error
where
    E: StdError + Send + Sync + 'static,
{
    fn from(error: E) -> Self {
        Error::new(error)
    }
}

impl Deref for Error {
    type Target = dyn StdError + Send + Sync + 'static;

    fn deref(&self) -> &Self::Target {
        self.inner.error()
    }
}

impl DerefMut for Error {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.inner.error_mut()
    }
}

impl Debug for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        writeln!(f, "{}", self.inner.error())?;

        let mut chain = self.chain().skip(1).enumerate().peekable();
        if let Some((n, error)) = chain.next() {
            write!(f, "\nCaused by:\n    ")?;
            if chain.peek().is_some() {
                write!(f, "{}: ", n)?;
            }
            writeln!(f, "{}", error)?;
            for (n, error) in chain {
                writeln!(f, "    {}: {}", n, error)?;
            }
        }

        #[cfg(backtrace)]
        {
            use std::backtrace::BacktraceStatus;

            let backtrace = self.backtrace();
            match backtrace.status() {
                BacktraceStatus::Captured => {
                    writeln!(f, "\n{}", backtrace)?;
                }
                BacktraceStatus::Disabled => {
                    writeln!(
                        f,
                        "\nBacktrace disabled; run with RUST_LIB_BACKTRACE=1 environment variable to display a backtrace"
                    )?;
                }
                _ => {}
            }
        }

        Ok(())
    }
}

impl Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.inner.error())
    }
}

unsafe impl Send for Error {}
unsafe impl Sync for Error {}

impl Drop for Error {
    fn drop(&mut self) {
        unsafe { ptr::drop_in_place(self.inner.error_mut()) }
    }
}

struct ErrorVTable {
    object: unsafe fn(*const ()) -> *const (dyn StdError + Send + Sync + 'static),
    object_mut: unsafe fn(*mut ()) -> *mut (dyn StdError + Send + Sync + 'static),
}

unsafe fn object_raw<E>(e: *const ()) -> *const (dyn StdError + Send + Sync + 'static)
where
    E: StdError + Send + Sync + 'static,
{
    e as *const E
}

unsafe fn object_mut_raw<E>(e: *mut ()) -> *mut (dyn StdError + Send + Sync + 'static)
where
    E: StdError + Send + Sync + 'static,
{
    e as *mut E
}

// repr C to ensure that `E` remains in the final position
#[repr(C)]
struct ErrorImpl<E> {
    vtable: &'static ErrorVTable,
    type_id: TypeId,
    backtrace: Option<Backtrace>,
    error: E,
}

#[repr(transparent)]
struct MessageError<M>(M);

impl<M> Debug for MessageError<M>
where
    M: Display + Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        Debug::fmt(&self.0, f)
    }
}

impl<M> Display for MessageError<M>
where
    M: Display + Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        Display::fmt(&self.0, f)
    }
}

impl<M> StdError for MessageError<M> where M: Display + Debug + 'static {}

impl ErrorImpl<()> {
    fn error(&self) -> &(dyn StdError + Send + Sync + 'static) {
        unsafe { &*(self.vtable.object)(&self.error) }
    }

    fn error_mut(&mut self) -> &mut (dyn StdError + Send + Sync + 'static) {
        unsafe { &mut *(self.vtable.object_mut)(&mut self.error) }
    }
}

/// Iterator of a chain of source errors.
///
/// This type is the iterator returned by [`Error::chain`].
///
/// # Example
///
/// ```
/// use anyhow::Error;
/// use std::io;
///
/// pub fn underlying_io_error_kind(error: &Error) -> Option<io::ErrorKind> {
///     for cause in error.chain() {
///         if let Some(io_error) = cause.downcast_ref::<io::Error>() {
///             return Some(io_error.kind());
///         }
///     }
///     None
/// }
/// ```
pub struct Chain<'a> {
    next: Option<&'a (dyn StdError + 'static)>,
}

impl<'a> Iterator for Chain<'a> {
    type Item = &'a (dyn StdError + 'static);

    fn next(&mut self) -> Option<Self::Item> {
        let next = self.next.take()?;
        self.next = next.source();
        Some(next)
    }
}

#[cfg(test)]
mod repr_correctness {
    use super::*;
    use std::marker::Unpin;
    use std::mem;
    use std::sync::atomic::AtomicBool;
    use std::sync::atomic::Ordering::SeqCst;
    use std::sync::Arc;

    #[test]
    fn size_of_error() {
        assert_eq!(mem::size_of::<Error>(), mem::size_of::<usize>());
    }

    #[test]
    fn error_autotraits() {
        fn assert<E: Unpin + Send + Sync + 'static>() {}
        assert::<Error>();
    }

    #[test]
    fn drop_works() {
        #[derive(Debug)]
        struct DetectDrop {
            has_dropped: Arc<AtomicBool>,
        }

        impl StdError for DetectDrop {}

        impl Display for DetectDrop {
            fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
                write!(f, "does something")
            }
        }

        impl Drop for DetectDrop {
            fn drop(&mut self) {
                let already_dropped = self.has_dropped.swap(true, SeqCst);
                assert!(!already_dropped);
            }
        }

        let has_dropped = Arc::new(AtomicBool::new(false));

        drop(Error::new(DetectDrop {
            has_dropped: has_dropped.clone(),
        }));

        assert!(has_dropped.load(SeqCst));
    }
}
<commit_msg>Format with rustfmt 2019-09-08<commit_after>use crate::backtrace::Backtrace;
use crate::context::ContextError;
use std::any::TypeId;
use std::error::Error as StdError;
use std::fmt::{self, Debug, Display};
use std::mem;
use std::ops::{Deref, DerefMut};
use std::ptr;

/// The `Error` type, a wrapper around a dynamic error type.
///
/// `Error` works a lot like `Box<dyn std::error::Error>`, but with these
/// differences:
///
/// - `Error` requires that the error is `Send`, `Sync`, and `'static`.
/// - `Error` guarantees that a backtrace is available, even if the underlying
///   error type does not provide one.
/// - `Error` is represented as a narrow pointer — exactly one word in
///   size instead of two.
pub struct Error {
    inner: Box<ErrorImpl<()>>,
}

impl Error {
    /// Create a new error object from any error type.
    ///
    /// The error type must be threadsafe and `'static`, so that the `Error`
    /// will be as well.
    ///
    /// If the error type does not provide a backtrace, a backtrace will be
    /// created here to ensure that a backtrace exists.
    pub fn new<E>(error: E) -> Self
    where
        E: StdError + Send + Sync + 'static,
    {
        let type_id = TypeId::of::<E>();
        let backtrace = backtrace_if_absent!(error);

        // Safety: passing typeid of the right type E.
        unsafe { Error::construct(error, type_id, backtrace) }
    }

    pub(crate) fn new_adhoc<M>(message: M, backtrace: Option<Backtrace>) -> Self
    where
        M: Display + Debug + Send + Sync + 'static,
    {
        let error = MessageError(message);
        let type_id = TypeId::of::<M>();

        // Safety: MessageError is repr(transparent) so MessageError<M> has the
        // same layout as the typeid specifies.
        unsafe { Error::construct(error, type_id, backtrace) }
    }

    // Takes backtrace as argument rather than capturing it here so that the
    // user sees one fewer layer of wrapping noise in the backtrace.
    //
    // Unsafe because the type represented by type_id must have the same layout
    // as E or else we allow invalid downcasts.
    unsafe fn construct<E>(error: E, type_id: TypeId, backtrace: Option<Backtrace>) -> Self
    where
        E: StdError + Send + Sync + 'static,
    {
        let vtable = &ErrorVTable {
            object: object_raw::<E>,
            object_mut: object_mut_raw::<E>,
        };
        let inner = Box::new(ErrorImpl {
            vtable,
            type_id,
            backtrace,
            error,
        });
        Error {
            inner: mem::transmute::<Box<ErrorImpl<E>>, Box<ErrorImpl<()>>>(inner),
        }
    }

    /// Wrap the error value with additional context.
    ///
    /// For attaching context to a `Result` as it is propagated, the
    /// [`Context`][crate::Context] extension trait may be more convenient than
    /// this function.
    ///
    /// The primary reason to use `error.context(...)` instead of
    /// `result.context(...)` via the `Context` trait would be if the context
    /// needs to depend on some data held by the underlying error:
    ///
    /// ```
    /// # use std::fmt::{self, Debug, Display};
    /// #
    /// # type T = ();
    /// #
    /// # impl std::error::Error for ParseError {}
    /// # impl Debug for ParseError {
    /// #     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
    /// #         unimplemented!()
    /// #     }
    /// # }
    /// # impl Display for ParseError {
    /// #     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
    /// #         unimplemented!()
    /// #     }
    /// # }
    /// #
    /// use std::fs::File;
    /// use std::path::Path;
    ///
    /// struct ParseError {
    ///     line: usize,
    ///     column: usize,
    /// }
    ///
    /// fn parse_impl(file: File) -> Result<T, ParseError> {
    ///     # const IGNORE: &str = stringify! {
    ///     ...
    ///     # };
    ///     # unimplemented!()
    /// }
    ///
    /// pub fn parse(path: impl AsRef<Path>) -> anyhow::Result<T> {
    ///     let file = File::open(&path)?;
    ///     parse_impl(file).map_err(|error| {
    ///         let context = format!(
    ///             "only the first {} lines of {} are valid",
    ///             error.line, path.as_ref().display(),
    ///         );
    ///         anyhow::Error::new(error).context(context)
    ///     })
    /// }
    /// ```
    pub fn context<C>(self, context: C) -> Self
    where
        C: Display + Send + Sync + 'static,
    {
        Error::new(ContextError {
            error: self,
            context,
        })
    }

    /// Get the backtrace for this Error.
    ///
    /// Backtraces are only available on the nightly channel. Tracking issue:
    /// [rust-lang/rust#53487][tracking].
    ///
    /// In order for the backtrace to be meaningful, the environment variable
    /// `RUST_LIB_BACKTRACE=1` must be defined. Backtraces are somewhat
    /// expensive to capture in Rust, so we don't necessarily want to be
    /// capturing them all over the place all the time.
    ///
    /// [tracking]: https://github.com/rust-lang/rust/issues/53487
    #[cfg(backtrace)]
    pub fn backtrace(&self) -> &Backtrace {
        // NB: this unwrap can only fail if the underlying error's backtrace
        // method is nondeterministic, which would only happen in maliciously
        // constructed code
        self.inner
            .backtrace
            .as_ref()
            .or_else(|| self.inner.error().backtrace())
            .expect("backtrace capture failed")
    }

    /// An iterator of the chain of source errors contained by this Error.
    ///
    /// This iterator will visit every error in the cause chain of this error
    /// object, beginning with the error that this error object was created
    /// from.
    ///
    /// # Example
    ///
    /// ```
    /// use anyhow::Error;
    /// use std::io;
    ///
    /// pub fn underlying_io_error_kind(error: &Error) -> Option<io::ErrorKind> {
    ///     for cause in error.chain() {
    ///         if let Some(io_error) = cause.downcast_ref::<io::Error>() {
    ///             return Some(io_error.kind());
    ///         }
    ///     }
    ///     None
    /// }
    /// ```
    pub fn chain(&self) -> Chain {
        Chain {
            next: Some(self.inner.error()),
        }
    }

    /// The lowest level cause of this error — this error's cause's
    /// cause's cause etc.
    ///
    /// The root cause is the last error in the iterator produced by
    /// [`chain()`][Error::chain].
    pub fn root_cause(&self) -> &(dyn StdError + 'static) {
        let mut chain = self.chain();
        let mut root_cause = chain.next().unwrap();
        for cause in chain {
            root_cause = cause;
        }
        root_cause
    }

    /// Returns `true` if `E` is the type wrapped by this error object.
    pub fn is<E>(&self) -> bool
    where
        E: Display + Debug + Send + Sync + 'static,
    {
        TypeId::of::<E>() == self.inner.type_id
    }

    /// Attempt to downcast the error object to a concrete type.
    pub fn downcast<E>(self) -> Result<E, Self>
    where
        E: Display + Debug + Send + Sync + 'static,
    {
        if let Some(error) = self.downcast_ref::<E>() {
            unsafe {
                let error = ptr::read(error);
                drop(ptr::read(&self.inner));
                mem::forget(self);
                Ok(error)
            }
        } else {
            Err(self)
        }
    }

    /// Downcast this error object by reference.
    ///
    /// # Example
    ///
    /// ```
    /// # use anyhow::anyhow;
    /// # use std::fmt::{self, Display};
    /// # use std::task::Poll;
    /// #
    /// # #[derive(Debug)]
    /// # enum DataStoreError {
    /// #     Censored(()),
    /// # }
    /// #
    /// # impl Display for DataStoreError {
    /// #     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
    /// #         unimplemented!()
    /// #     }
    /// # }
    /// #
    /// # impl std::error::Error for DataStoreError {}
    /// #
    /// # const REDACTED_CONTENT: () = ();
    /// #
    /// # let error = anyhow!("...");
    /// # let root_cause = &error;
    /// #
    /// # let ret =
    /// // If the error was caused by redaction, then return a tombstone instead
    /// // of the content.
    /// match root_cause.downcast_ref::<DataStoreError>() {
    ///     Some(DataStoreError::Censored(_)) => Ok(Poll::Ready(REDACTED_CONTENT)),
    ///     None => Err(error),
    /// }
    /// # ;
    /// ```
    pub fn downcast_ref<E>(&self) -> Option<&E>
    where
        E: Display + Debug + Send + Sync + 'static,
    {
        if self.is::<E>() {
            unsafe { Some(&*(self.inner.error() as *const dyn StdError as *const E)) }
        } else {
            None
        }
    }

    /// Downcast this error object by mutable reference.
    pub fn downcast_mut<E>(&mut self) -> Option<&mut E>
    where
        E: Display + Debug + Send + Sync + 'static,
    {
        if self.is::<E>() {
            unsafe { Some(&mut *(self.inner.error_mut() as *mut dyn StdError as *mut E)) }
        } else {
            None
        }
    }
}

impl<E> From<E> for Error
where
    E: StdError + Send + Sync + 'static,
{
    fn from(error: E) -> Self {
        Error::new(error)
    }
}

impl Deref for Error {
    type Target = dyn StdError + Send + Sync + 'static;

    fn deref(&self) -> &Self::Target {
        self.inner.error()
    }
}

impl DerefMut for Error {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.inner.error_mut()
    }
}

impl Debug for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        writeln!(f, "{}", self.inner.error())?;

        let mut chain = self.chain().skip(1).enumerate().peekable();
        if let Some((n, error)) = chain.next() {
            write!(f, "\nCaused by:\n    ")?;
            if chain.peek().is_some() {
                write!(f, "{}: ", n)?;
            }
            writeln!(f, "{}", error)?;
            for (n, error) in chain {
                writeln!(f, "    {}: {}", n, error)?;
            }
        }

        #[cfg(backtrace)]
        {
            use std::backtrace::BacktraceStatus;

            let backtrace = self.backtrace();
            match backtrace.status() {
                BacktraceStatus::Captured => {
                    writeln!(f, "\n{}", backtrace)?;
                }
                BacktraceStatus::Disabled => {
                    writeln!(
                        f,
                        "\nBacktrace disabled; run with RUST_LIB_BACKTRACE=1 environment variable to display a backtrace"
                    )?;
                }
                _ => {}
            }
        }

        Ok(())
    }
}

impl Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.inner.error())
    }
}

unsafe impl Send for Error {}
unsafe impl Sync for Error {}

impl Drop for Error {
    fn drop(&mut self) {
        unsafe { ptr::drop_in_place(self.inner.error_mut()) }
    }
}

struct ErrorVTable {
    object: unsafe fn(*const ()) -> *const (dyn StdError + Send + Sync + 'static),
    object_mut: unsafe fn(*mut ()) -> *mut (dyn StdError + Send + Sync + 'static),
}

unsafe fn object_raw<E>(e: *const ()) -> *const (dyn StdError + Send + Sync + 'static)
where
    E: StdError + Send + Sync + 'static,
{
    e as *const E
}

unsafe fn object_mut_raw<E>(e: *mut ()) -> *mut (dyn StdError + Send + Sync + 'static)
where
    E: StdError + Send + Sync + 'static,
{
    e as *mut E
}

// repr C to ensure that `E` remains in the final position
#[repr(C)]
struct ErrorImpl<E> {
    vtable: &'static ErrorVTable,
    type_id: TypeId,
    backtrace: Option<Backtrace>,
    error: E,
}

#[repr(transparent)]
struct MessageError<M>(M);

impl<M> Debug for MessageError<M>
where
    M: Display + Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        Debug::fmt(&self.0, f)
    }
}

impl<M> Display for MessageError<M>
where
    M: Display + Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        Display::fmt(&self.0, f)
    }
}

impl<M> StdError for MessageError<M> where M: Display + Debug + 'static {}

impl ErrorImpl<()> {
    fn error(&self) -> &(dyn StdError + Send + Sync + 'static) {
        unsafe { &*(self.vtable.object)(&self.error) }
    }

    fn error_mut(&mut self) -> &mut (dyn StdError + Send + Sync + 'static) {
        unsafe { &mut *(self.vtable.object_mut)(&mut self.error) }
    }
}

/// Iterator of a chain of source errors.
///
/// This type is the iterator returned by [`Error::chain`].
///
/// # Example
///
/// ```
/// use anyhow::Error;
/// use std::io;
///
/// pub fn underlying_io_error_kind(error: &Error) -> Option<io::ErrorKind> {
///     for cause in error.chain() {
///         if let Some(io_error) = cause.downcast_ref::<io::Error>() {
///             return Some(io_error.kind());
///         }
///     }
///     None
/// }
/// ```
pub struct Chain<'a> {
    next: Option<&'a (dyn StdError + 'static)>,
}

impl<'a> Iterator for Chain<'a> {
    type Item = &'a (dyn StdError + 'static);

    fn next(&mut self) -> Option<Self::Item> {
        let next = self.next.take()?;
        self.next = next.source();
        Some(next)
    }
}

#[cfg(test)]
mod repr_correctness {
    use super::*;
    use std::marker::Unpin;
    use std::mem;
    use std::sync::atomic::AtomicBool;
    use std::sync::atomic::Ordering::SeqCst;
    use std::sync::Arc;

    #[test]
    fn size_of_error() {
        assert_eq!(mem::size_of::<Error>(), mem::size_of::<usize>());
    }

    #[test]
    fn error_autotraits() {
        fn assert<E: Unpin + Send + Sync + 'static>() {}
        assert::<Error>();
    }

    #[test]
    fn drop_works() {
        #[derive(Debug)]
        struct DetectDrop {
            has_dropped: Arc<AtomicBool>,
        }

        impl StdError for DetectDrop {}

        impl Display for DetectDrop {
            fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
                write!(f, "does something")
            }
        }

        impl Drop for DetectDrop {
            fn drop(&mut self) {
                let already_dropped = self.has_dropped.swap(true, SeqCst);
                assert!(!already_dropped);
            }
        }

        let has_dropped = Arc::new(AtomicBool::new(false));

        drop(Error::new(DetectDrop {
            has_dropped: has_dropped.clone(),
        }));

        assert!(has_dropped.load(SeqCst));
    }
}
<|endoftext|>


<commit_before>// Copyright (c) 2016 Chef Software Inc. and/or applicable contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::collections::BTreeMap;
use std::fs::{self, File};
use std::io::Write;
use std::path::{Path, PathBuf};
use std::time::{UNIX_EPOCH, SystemTime};
use std::fmt;
use rustc_serialize::json::{ToJson, Json};
use fs::svc_var_path;

// Supported events
#[derive(Debug, Clone)]
pub enum Event<'a> {
    ProjectCreate { origin: &'a str, package: &'a str },
}

impl<'a> fmt::Display for Event<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let msg = match *self {
            Event::ProjectCreate { origin: _, package: _ } => "project-create",
        };
        write!(f, "{}", msg)
    }
}

impl<'a> ToJson for Event<'a> {
    fn to_json(&self) -> Json {
        let mut m = BTreeMap::new();
        m.insert("name".to_string(), self.to_string().to_json());

        match *self {
            Event::ProjectCreate { origin: ref o, package: ref p } => {
                m.insert("origin".to_string(), o.to_json());
                m.insert("package".to_string(), p.to_json());
            }
        };
        Json::Object(m)
    }
}

// Sample envelope JSON payload
// {
//   "timestamp": "1479330000.13442404",
//   "version": 1,
//   "event": {
//     "name": "project-create",
//     "origin" : "myorigin"
//     "package" : "mypackage"
//   }
// }

pub const SCHEMA_VERSION: u32 = 1;

#[derive(Debug, Clone)]
pub struct Envelope<'a> {
    version: u32,
    timestamp: String,
    event: Event<'a>,
}

impl<'a> Envelope<'a> {
    pub fn new(event: &Event<'a>) -> Self {
        Envelope {
            version: SCHEMA_VERSION,
            timestamp: timestamp(),
            event: event.clone(),
        }
    }
}

impl<'a> ToJson for Envelope<'a> {
    fn to_json(&self) -> Json {
        let mut m = BTreeMap::new();
        m.insert("version".to_string(), self.version.to_json());
        m.insert("timestamp".to_string(), self.timestamp.to_json());
        m.insert("event".to_string(), self.event.to_json());

        Json::Object(m)
    }
}

fn write_file(parent_dir: &Path, file_path: &Path, content: &str) {
    fs::create_dir_all(parent_dir).expect("Unable to create directory");
    let mut file = File::create(&file_path).expect("Unable to create file");
    file.write_all(content.as_bytes()).expect("Unable to write file");
}

fn timestamp() -> String {
    let (secs, subsec_nanos) = match SystemTime::now().duration_since(UNIX_EPOCH) {
        Ok(duration) => (duration.as_secs(), duration.subsec_nanos()),
        Err(e) => {
            error!("Cannot generate system time: {}", e);
            return "0.0".to_string();
        }
    };
    format!("{}.{}", secs, subsec_nanos)
}

pub struct EventLogger {
    log_dir: PathBuf,
}

impl EventLogger {
    pub fn new(service_name: &str) -> Self {
        EventLogger { log_dir: svc_var_path(&service_name) }
    }

    pub fn record_event(&self, event: Event) {
        let envelope = Envelope::new(&event);
        let file_path = self.log_dir.join(format!("event-{}.json", &envelope.timestamp));
        write_file(&self.log_dir, &file_path, &envelope.to_json().to_string());
    }
}

#[cfg(test)]
mod test {
    use super::{EventLogger, Envelope, Event};
    use rustc_serialize::json::ToJson;

    #[test]
    fn event_to_json() {
        let event: Event = Event::ProjectCreate {
            origin: "myorigin",
            package: "mypackage",
        };

        let expected = r#"{"name":"project-create","origin":"myorigin","package":"mypackage"}"#;
        assert!(event.to_json().to_string() == expected.to_string());
    }

    #[test]
    fn envelope_to_json() {
        let event: Event = Event::ProjectCreate {
            origin: "myorigin",
            package: "mypackage",
        };

        let envelope = Envelope::new(&event);
        let expected =
            r#"{"event":{"name":"project-create","origin":"myorigin","package":"mypackage"}"#;
        assert!(envelope.to_json().to_string().starts_with(expected));
    }

    #[test]
    fn event_logger_path() {
        let event_logger: EventLogger = EventLogger::new("foo");
        let expected = r#"foo"#;
        match event_logger.log_dir.to_str() {
            Some(s) => assert!(s.contains(expected)),
            None => assert!(false),
        }
    }
}
<commit_msg>More events infra work<commit_after>// Copyright (c) 2016 Chef Software Inc. and/or applicable contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::collections::BTreeMap;
use std::fs::{self, File};
use std::io::Write;
use std::path::{Path, PathBuf};
use std::time::{UNIX_EPOCH, SystemTime};
use std::fmt;
use rustc_serialize::json::{ToJson, Json};
use fs::svc_var_path;

// Macros to help hooking in the event logger into an Iron chain,
// and calling into the chained event logger.
#[macro_export]
macro_rules! define_event_log {
    () => {
        pub struct EventLog;
        impl typemap::Key for EventLog {
            type Value = EventLogger;
        }
    }
}

#[macro_export]
macro_rules! log_event {
    ($req:ident, $evt:expr) => {{
        let el = ($req).get::<persistent::Read<EventLog>>().unwrap();
        el.record_event($evt)
    }};
}

// Supported events
#[derive(Debug, Clone)]
pub enum Event<'a> {
    ProjectCreate {
        origin: &'a str,
        package: &'a str,
        account: &'a str,
    },
}

impl<'a> fmt::Display for Event<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let msg = match *self {
            Event::ProjectCreate { origin: _, package: _, account: _ } => "project-create",
        };
        write!(f, "{}", msg)
    }
}

impl<'a> ToJson for Event<'a> {
    fn to_json(&self) -> Json {
        let mut m = BTreeMap::new();
        m.insert("name".to_string(), self.to_string().to_json());

        match *self {
            Event::ProjectCreate { origin: ref o, package: ref p, account: ref a } => {
                m.insert("origin".to_string(), o.to_json());
                m.insert("package".to_string(), p.to_json());
                m.insert("account".to_string(), a.to_json());
            }
        };
        Json::Object(m)
    }
}

// Sample envelope JSON payload
// {
//   "timestamp": "1479330000.13442404",
//   "version": 1,
//   "event": {
//     "name": "project-create",
//     "origin" : "myorigin"
//     "package" : "mypackage"
//     "account" : "133508078967455744"
//   }
// }

pub const SCHEMA_VERSION: u32 = 1;

#[derive(Debug, Clone)]
pub struct Envelope<'a> {
    version: u32,
    timestamp: String,
    event: Event<'a>,
}

impl<'a> Envelope<'a> {
    pub fn new(event: &Event<'a>) -> Self {
        Envelope {
            version: SCHEMA_VERSION,
            timestamp: timestamp(),
            event: event.clone(),
        }
    }
}

impl<'a> ToJson for Envelope<'a> {
    fn to_json(&self) -> Json {
        let mut m = BTreeMap::new();
        m.insert("version".to_string(), self.version.to_json());
        m.insert("timestamp".to_string(), self.timestamp.to_json());
        m.insert("event".to_string(), self.event.to_json());

        Json::Object(m)
    }
}

fn write_file(parent_dir: &Path, file_path: &Path, content: &str) {
    fs::create_dir_all(parent_dir).expect("Unable to create directory");
    let mut file = File::create(&file_path).expect("Unable to create file");
    file.write_all(content.as_bytes()).expect("Unable to write file");
}

fn timestamp() -> String {
    let (secs, subsec_nanos) = match SystemTime::now().duration_since(UNIX_EPOCH) {
        Ok(duration) => (duration.as_secs(), duration.subsec_nanos()),
        Err(e) => {
            error!("Cannot generate system time: {}", e);
            return "0.0".to_string();
        }
    };
    format!("{}.{}", secs, subsec_nanos)
}

pub struct EventLogger {
    log_dir: PathBuf,
    enabled: bool,
}

impl EventLogger {
    pub fn new(service_name: &str, enabled: bool) -> Self {
        EventLogger {
            log_dir: svc_var_path(&service_name),
            enabled: enabled,
        }
    }

    pub fn record_event(&self, event: Event) {
        if self.enabled {
            let envelope = Envelope::new(&event);
            let file_path = self.log_dir.join(format!("event-{}.json", &envelope.timestamp));
            write_file(&self.log_dir, &file_path, &envelope.to_json().to_string());
        }
    }
}

#[cfg(test)]
mod test {
    use super::{EventLogger, Envelope, Event};
    use rustc_serialize::json::ToJson;

    #[test]
    fn event_to_json() {
        let event: Event = Event::ProjectCreate {
            origin: "myorigin",
            package: "mypackage",
            account: "myaccount",
        };

        let expected = r#"{"account":"myaccount","name":"project-create","origin":"myorigin","package":"mypackage"}"#;
        assert!(event.to_json().to_string() == expected.to_string());
    }

    #[test]
    fn envelope_to_json() {
        let event: Event = Event::ProjectCreate {
            origin: "myorigin",
            package: "mypackage",
            account: "myaccount",
        };

        let envelope = Envelope::new(&event);
        let expected =
            r#"{"event":{"account":"myaccount","name":"project-create","origin":"myorigin","package":"mypackage"}"#;
        assert!(envelope.to_json().to_string().starts_with(expected));
    }

    #[test]
    fn event_logger_path() {
        let event_logger: EventLogger = EventLogger::new("foo", true);
        let expected = r#"foo"#;
        match event_logger.log_dir.to_str() {
            Some(s) => assert!(s.contains(expected)),
            None => assert!(false),
        }
    }
}
<|endoftext|>