use std::{cell::RefCell, io, path::Path, sync::Arc};

use {
    bstr::ByteSlice,
    termcolor::{HyperlinkSpec, WriteColor},
};

use crate::util::DecimalFormatter;

use self::aliases::HYPERLINK_PATTERN_ALIASES;

mod aliases;

/// Hyperlink configuration.
///
/// This configuration specifies both the [hyperlink format](HyperlinkFormat)
/// and an [environment](HyperlinkConfig) for interpolating a subset of
/// variables. The specific subset includes variables that are intended to
/// be invariant throughout the lifetime of a process, such as a machine's
/// hostname.
///
/// A hyperlink configuration can be provided to printer builders such as
/// [`StandardBuilder::hyperlink`](crate::StandardBuilder::hyperlink).
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct HyperlinkConfig(Arc<HyperlinkConfigInner>);

#[derive(Clone, Debug, Default, Eq, PartialEq)]
struct HyperlinkConfigInner {
    env: HyperlinkEnvironment,
    format: HyperlinkFormat,
}

impl HyperlinkConfig {
    /// Create a new configuration from an environment and a format.
    pub fn new(
        env: HyperlinkEnvironment,
        format: HyperlinkFormat,
    ) -> HyperlinkConfig {
        HyperlinkConfig(Arc::new(HyperlinkConfigInner { env, format }))
    }

    /// Returns the hyperlink environment in this configuration.
    pub(crate) fn environment(&self) -> &HyperlinkEnvironment {
        &self.0.env
    }

    /// Returns the hyperlink format in this configuration.
    pub(crate) fn format(&self) -> &HyperlinkFormat {
        &self.0.format
    }
}

/// A hyperlink format with variables.
///
/// This can be created by parsing a string using `HyperlinkFormat::from_str`.
///
/// The default format is empty. An empty format is valid and effectively
/// disables hyperlinks.
///
/// # Example
///
/// ```
/// use grep_printer::HyperlinkFormat;
///
/// let fmt = "vscode".parse::<HyperlinkFormat>()?;
/// assert_eq!(fmt.to_string(), "vscode://file{path}:{line}:{column}");
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct HyperlinkFormat {
    parts: Vec<Part>,
    is_line_dependent: bool,
}

impl HyperlinkFormat {
    /// Creates an empty hyperlink format.
    pub fn empty() -> HyperlinkFormat {
        HyperlinkFormat::default()
    }

    /// Returns true if this format is empty.
    pub fn is_empty(&self) -> bool {
        self.parts.is_empty()
    }

    /// Creates a [`HyperlinkConfig`] from this format and the environment
    /// given.
    pub fn into_config(self, env: HyperlinkEnvironment) -> HyperlinkConfig {
        HyperlinkConfig::new(env, self)
    }

    /// Returns true if the format can produce line-dependent hyperlinks.
    pub(crate) fn is_line_dependent(&self) -> bool {
        self.is_line_dependent
    }
}

impl std::str::FromStr for HyperlinkFormat {
    type Err = HyperlinkFormatError;

    fn from_str(s: &str) -> Result<HyperlinkFormat, HyperlinkFormatError> {
        use self::HyperlinkFormatErrorKind::*;

        #[derive(Debug)]
        enum State {
            Verbatim,
            VerbatimCloseVariable,
            OpenVariable,
            InVariable,
        }

        let mut builder = FormatBuilder::new();
        let input = match HyperlinkAlias::find(s) {
            Some(alias) => alias.format(),
            None => s,
        };
        let mut name = String::new();
        let mut state = State::Verbatim;
        let err = |kind| HyperlinkFormatError { kind };
        for ch in input.chars() {
            state = match state {
                State::Verbatim => {
                    if ch == '{' {
                        State::OpenVariable
                    } else if ch == '}' {
                        State::VerbatimCloseVariable
                    } else {
                        builder.append_char(ch);
                        State::Verbatim
                    }
                }
                State::VerbatimCloseVariable => {
                    if ch == '}' {
                        builder.append_char('}');
                        State::Verbatim
                    } else {
                        return Err(err(InvalidCloseVariable));
                    }
                }
                State::OpenVariable => {
                    if ch == '{' {
                        builder.append_char('{');
                        State::Verbatim
                    } else {
                        name.clear();
                        if ch == '}' {
                            builder.append_var(&name)?;
                            State::Verbatim
                        } else {
                            name.push(ch);
                            State::InVariable
                        }
                    }
                }
                State::InVariable => {
                    if ch == '}' {
                        builder.append_var(&name)?;
                        State::Verbatim
                    } else {
                        name.push(ch);
                        State::InVariable
                    }
                }
            };
        }
        match state {
            State::Verbatim => builder.build(),
            State::VerbatimCloseVariable => Err(err(InvalidCloseVariable)),
            State::OpenVariable | State::InVariable => {
                Err(err(UnclosedVariable))
            }
        }
    }
}

impl std::fmt::Display for HyperlinkFormat {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        for part in self.parts.iter() {
            part.fmt(f)?;
        }
        Ok(())
    }
}

/// An alias for a hyperlink format.
///
/// Hyperlink aliases are built-in formats, therefore they hold static values.
/// Some of their features are usable in const blocks.
#[derive(Clone, Debug)]
pub struct HyperlinkAlias {
    name: &'static str,
    description: &'static str,
    format: &'static str,
    display_priority: Option<i16>,
}

impl HyperlinkAlias {
    /// Returns the name of the alias.
    pub const fn name(&self) -> &str {
        self.name
    }

    /// Returns a very short description of this hyperlink alias.
    pub const fn description(&self) -> &str {
        self.description
    }

    /// Returns the display priority of this alias.
    ///
    /// If no priority is set, then `None` is returned.
    ///
    /// The display priority is meant to reflect some special status associated
    /// with an alias. For example, the `default` and `none` aliases have a
    /// display priority. This is meant to encourage listing them first in
    /// documentation.
    ///
    /// A lower display priority implies the alias should be shown before
    /// aliases with a higher (or absent) display priority.
    ///
    /// Callers cannot rely on any specific display priority value to remain
    /// stable across semver compatible releases of this crate.
    pub const fn display_priority(&self) -> Option<i16> {
        self.display_priority
    }

    /// Returns the format string of the alias.
    const fn format(&self) -> &'static str {
        self.format
    }

    /// Looks for the hyperlink alias defined by the given name.
    ///
    /// If one does not exist, `None` is returned.
    fn find(name: &str) -> Option<&HyperlinkAlias> {
        HYPERLINK_PATTERN_ALIASES
            .binary_search_by_key(&name, |alias| alias.name())
            .map(|i| &HYPERLINK_PATTERN_ALIASES[i])
            .ok()
    }
}

/// A static environment for hyperlink interpolation.
///
/// This environment permits setting the values of variables used in hyperlink
/// interpolation that are not expected to change for the lifetime of a program.
/// That is, these values are invariant.
///
/// Currently, this includes the hostname and a WSL distro prefix.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct HyperlinkEnvironment {
    host: Option<String>,
    wsl_prefix: Option<String>,
}

impl HyperlinkEnvironment {
    /// Create a new empty hyperlink environment.
    pub fn new() -> HyperlinkEnvironment {
        HyperlinkEnvironment::default()
    }

    /// Set the `{host}` variable, which fills in any hostname components of
    /// a hyperlink.
    ///
    /// One can get the hostname in the current environment via the `hostname`
    /// function in the `grep-cli` crate.
    pub fn host(&mut self, host: Option<String>) -> &mut HyperlinkEnvironment {
        self.host = host;
        self
    }

    /// Set the `{wslprefix}` variable, which contains the WSL distro prefix.
    /// An example value is `wsl$/Ubuntu`. The distro name can typically be
    /// discovered from the `WSL_DISTRO_NAME` environment variable.
    pub fn wsl_prefix(
        &mut self,
        wsl_prefix: Option<String>,
    ) -> &mut HyperlinkEnvironment {
        self.wsl_prefix = wsl_prefix;
        self
    }
}

/// An error that can occur when parsing a hyperlink format.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct HyperlinkFormatError {
    kind: HyperlinkFormatErrorKind,
}

#[derive(Clone, Debug, Eq, PartialEq)]
enum HyperlinkFormatErrorKind {
    /// This occurs when there are zero variables in the format.
    NoVariables,
    /// This occurs when the {path} variable is missing.
    NoPathVariable,
    /// This occurs when the {line} variable is missing, while the {column}
    /// variable is present.
    NoLineVariable,
    /// This occurs when an unknown variable is used.
    InvalidVariable(String),
    /// The format doesn't start with a valid scheme.
    InvalidScheme,
    /// This occurs when an unescaped `}` is found without a corresponding
    /// `{` preceding it.
    InvalidCloseVariable,
    /// This occurs when a `{` is found without a corresponding `}` following
    /// it.
    UnclosedVariable,
}

impl std::error::Error for HyperlinkFormatError {}

impl std::fmt::Display for HyperlinkFormatError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        use self::HyperlinkFormatErrorKind::*;

        match self.kind {
            NoVariables => {
                let mut aliases = hyperlink_aliases();
                aliases.sort_by_key(|alias| {
                    alias.display_priority().unwrap_or(i16::MAX)
                });
                let names: Vec<&str> =
                    aliases.iter().map(|alias| alias.name()).collect();
                write!(
                    f,
                    "at least a {{path}} variable is required in a \
                     hyperlink format, or otherwise use a valid alias: \
                     {aliases}",
                    aliases = names.join(", "),
                )
            }
            NoPathVariable => {
                write!(
                    f,
                    "the {{path}} variable is required in a hyperlink format",
                )
            }
            NoLineVariable => {
                write!(
                    f,
                    "the hyperlink format contains a {{column}} variable, \
                     but no {{line}} variable is present",
                )
            }
            InvalidVariable(ref name) => {
                write!(
                    f,
                    "invalid hyperlink format variable: '{name}', choose \
                     from: path, line, column, host, wslprefix",
                )
            }
            InvalidScheme => {
                write!(
                    f,
                    "the hyperlink format must start with a valid URL scheme, \
                     i.e., [0-9A-Za-z+-.]+:",
                )
            }
            InvalidCloseVariable => {
                write!(
                    f,
                    "unopened variable: found '}}' without a \
                     corresponding '{{' preceding it",
                )
            }
            UnclosedVariable => {
                write!(
                    f,
                    "unclosed variable: found '{{' without a \
                     corresponding '}}' following it",
                )
            }
        }
    }
}

/// A builder for `HyperlinkFormat`.
///
/// Once a `HyperlinkFormat` is built, it is immutable.
#[derive(Debug)]
struct FormatBuilder {
    parts: Vec<Part>,
}

impl FormatBuilder {
    /// Creates a new hyperlink format builder.
    fn new() -> FormatBuilder {
        FormatBuilder { parts: vec![] }
    }

    /// Appends static text.
    fn append_slice(&mut self, text: &[u8]) -> &mut FormatBuilder {
        if let Some(Part::Text(contents)) = self.parts.last_mut() {
            contents.extend_from_slice(text);
        } else if !text.is_empty() {
            self.parts.push(Part::Text(text.to_vec()));
        }
        self
    }

    /// Appends a single character.
    fn append_char(&mut self, ch: char) -> &mut FormatBuilder {
        self.append_slice(ch.encode_utf8(&mut [0; 4]).as_bytes())
    }

    /// Appends a variable with the given name. If the name isn't recognized,
    /// then this returns an error.
    fn append_var(
        &mut self,
        name: &str,
    ) -> Result<&mut FormatBuilder, HyperlinkFormatError> {
        let part = match name {
            "host" => Part::Host,
            "wslprefix" => Part::WSLPrefix,
            "path" => Part::Path,
            "line" => Part::Line,
            "column" => Part::Column,
            unknown => {
                let err = HyperlinkFormatError {
                    kind: HyperlinkFormatErrorKind::InvalidVariable(
                        unknown.to_string(),
                    ),
                };
                return Err(err);
            }
        };
        self.parts.push(part);
        Ok(self)
    }

    /// Builds the format.
    fn build(&self) -> Result<HyperlinkFormat, HyperlinkFormatError> {
        self.validate()?;
        Ok(HyperlinkFormat {
            parts: self.parts.clone(),
            is_line_dependent: self.parts.contains(&Part::Line),
        })
    }

    /// Validate that the format is well-formed.
    fn validate(&self) -> Result<(), HyperlinkFormatError> {
        use self::HyperlinkFormatErrorKind::*;

        let err = |kind| HyperlinkFormatError { kind };
        // An empty format is fine. It just means hyperlink support is
        // disabled.
        if self.parts.is_empty() {
            return Ok(());
        }
        // If all parts are just text, then there are no variables. It's
        // likely a reference to an invalid alias.
        if self.parts.iter().all(|p| matches!(*p, Part::Text(_))) {
            return Err(err(NoVariables));
        }
        // Even if we have other variables, no path variable means the
        // hyperlink can't possibly work the way it is intended.
        if !self.parts.contains(&Part::Path) {
            return Err(err(NoPathVariable));
        }
        // If the {column} variable is used, then we also need a {line}
        // variable or else {column} can't possibly work.
        if self.parts.contains(&Part::Column)
            && !self.parts.contains(&Part::Line)
        {
            return Err(err(NoLineVariable));
        }
        self.validate_scheme()
    }

    /// Validate that the format starts with a valid scheme. Validation is done
    /// according to how a scheme is defined in RFC 1738 sections 2.1[1] and
    /// 5[2]. In short, a scheme is this:
    ///
    /// scheme = 1*[ lowalpha | digit | "+" | "-" | "." ]
    ///
    /// but is case insensitive.
    ///
    /// [1]: https://datatracker.ietf.org/doc/html/rfc1738#section-2.1
    /// [2]: https://datatracker.ietf.org/doc/html/rfc1738#section-5
    fn validate_scheme(&self) -> Result<(), HyperlinkFormatError> {
        let err_invalid_scheme = HyperlinkFormatError {
            kind: HyperlinkFormatErrorKind::InvalidScheme,
        };
        let Some(Part::Text(part)) = self.parts.first() else {
            return Err(err_invalid_scheme);
        };
        let Some(colon) = part.find_byte(b':') else {
            return Err(err_invalid_scheme);
        };
        let scheme = &part[..colon];
        if scheme.is_empty() {
            return Err(err_invalid_scheme);
        }
        let is_valid_scheme_char = |byte| match byte {
            b'0'..=b'9' | b'A'..=b'Z' | b'a'..=b'z' | b'+' | b'-' | b'.' => {
                true
            }
            _ => false,
        };
        if !scheme.iter().all(|&b| is_valid_scheme_char(b)) {
            return Err(err_invalid_scheme);
        }
        Ok(())
    }
}

/// A hyperlink format part.
///
/// A sequence of these corresponds to a complete format. (Not all sequences
/// are valid.)
#[derive(Clone, Debug, Eq, PartialEq)]
enum Part {
    /// Static text.
    ///
    /// We use `Vec<u8>` here (and more generally treat a format string as a
    /// sequence of bytes) because file paths may be arbitrary bytes. A rare
    /// case, but one for which there is no good reason to choke on.
    Text(Vec<u8>),
    /// Variable for the hostname.
    Host,
    /// Variable for a WSL path prefix.
    WSLPrefix,
    /// Variable for the file path.
    Path,
    /// Variable for the line number.
    Line,
    /// Variable for the column number.
    Column,
}

impl Part {
    /// Interpolate this part using the given `env` and `values`, and write
    /// the result of interpolation to the buffer provided.
    fn interpolate_to(
        &self,
        env: &HyperlinkEnvironment,
        values: &Values,
        dest: &mut Vec<u8>,
    ) {
        match *self {
            Part::Text(ref text) => dest.extend_from_slice(text),
            Part::Host => dest.extend_from_slice(
                env.host.as_ref().map(|s| s.as_bytes()).unwrap_or(b""),
            ),
            Part::WSLPrefix => dest.extend_from_slice(
                env.wsl_prefix.as_ref().map(|s| s.as_bytes()).unwrap_or(b""),
            ),
            Part::Path => dest.extend_from_slice(&values.path.0),
            Part::Line => {
                let line = DecimalFormatter::new(values.line.unwrap_or(1));
                dest.extend_from_slice(line.as_bytes());
            }
            Part::Column => {
                let column = DecimalFormatter::new(values.column.unwrap_or(1));
                dest.extend_from_slice(column.as_bytes());
            }
        }
    }
}

impl std::fmt::Display for Part {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            Part::Text(text) => write!(f, "{}", String::from_utf8_lossy(text)),
            Part::Host => write!(f, "{{host}}"),
            Part::WSLPrefix => write!(f, "{{wslprefix}}"),
            Part::Path => write!(f, "{{path}}"),
            Part::Line => write!(f, "{{line}}"),
            Part::Column => write!(f, "{{column}}"),
        }
    }
}

/// The values to replace the format variables with.
///
/// This only consists of values that depend on each path or match printed.
/// Values that are invariant throughout the lifetime of the process are set
/// via a [`HyperlinkEnvironment`].
#[derive(Clone, Debug)]
pub(crate) struct Values<'a> {
    path: &'a HyperlinkPath,
    line: Option<u64>,
    column: Option<u64>,
}

impl<'a> Values<'a> {
    /// Creates a new set of values, starting with the path given.
    ///
    /// Callers may also set the line and column number using the mutator
    /// methods.
    pub(crate) fn new(path: &'a HyperlinkPath) -> Values<'a> {
        Values { path, line: None, column: None }
    }

    /// Sets the line number for these values.
    ///
    /// If a line number is not set and a hyperlink format contains a `{line}`
    /// variable, then it is interpolated with the value of `1` automatically.
    pub(crate) fn line(mut self, line: Option<u64>) -> Values<'a> {
        self.line = line;
        self
    }

    /// Sets the column number for these values.
    ///
    /// If a column number is not set and a hyperlink format contains a
    /// `{column}` variable, then it is interpolated with the value of `1`
    /// automatically.
    pub(crate) fn column(mut self, column: Option<u64>) -> Values<'a> {
        self.column = column;
        self
    }
}

/// An abstraction for interpolating a hyperlink format with values for every
/// variable.
///
/// Interpolation of variables occurs through two different sources. The
/// first is via a `HyperlinkEnvironment` for values that are expected to
/// be invariant. This comes from the `HyperlinkConfig` used to build this
/// interpolator. The second source is via `Values`, which is provided to
/// `Interpolator::begin`. The `Values` contains things like the file path,
/// line number and column number.
#[derive(Clone, Debug)]
pub(crate) struct Interpolator {
    config: HyperlinkConfig,
    buf: RefCell<Vec<u8>>,
}

impl Interpolator {
    /// Create a new interpolator for the given hyperlink format configuration.
    pub(crate) fn new(config: &HyperlinkConfig) -> Interpolator {
        Interpolator { config: config.clone(), buf: RefCell::new(vec![]) }
    }

    /// Start interpolation with the given values by writing a hyperlink
    /// to `wtr`. Subsequent writes to `wtr`, until `Interpolator::end` is
    /// called, are the label for the hyperlink.
    ///
    /// This returns an interpolator status which indicates whether the
    /// hyperlink was written. It might not be written, for example, if the
    /// underlying writer doesn't support hyperlinks or if the hyperlink
    /// format is empty. The status should be provided to `Interpolator::end`
    /// as an instruction for whether to close the hyperlink or not.
    pub(crate) fn begin<W: WriteColor>(
        &self,
        values: &Values,
        mut wtr: W,
    ) -> io::Result<InterpolatorStatus> {
        if self.config.format().is_empty()
            || !wtr.supports_hyperlinks()
            || !wtr.supports_color()
        {
            return Ok(InterpolatorStatus::inactive());
        }
        let mut buf = self.buf.borrow_mut();
        buf.clear();
        for part in self.config.format().parts.iter() {
            part.interpolate_to(self.config.environment(), values, &mut buf);
        }
        let spec = HyperlinkSpec::open(&buf);
        wtr.set_hyperlink(&spec)?;
        Ok(InterpolatorStatus { active: true })
    }

    /// Writes the correct escape sequences to `wtr` to close any extant
    /// hyperlink, marking the end of a hyperlink's label.
    ///
    /// The status given should be returned from a corresponding
    /// `Interpolator::begin` call. Since `begin` may not write a hyperlink
    /// (e.g., if the underlying writer doesn't support hyperlinks), it follows
    /// that `finish` must not close a hyperlink that was never opened. The
    /// status indicates whether the hyperlink was opened or not.
    pub(crate) fn finish<W: WriteColor>(
        &self,
        status: InterpolatorStatus,
        mut wtr: W,
    ) -> io::Result<()> {
        if !status.active {
            return Ok(());
        }
        wtr.set_hyperlink(&HyperlinkSpec::close())
    }
}

/// A status indicating whether a hyperlink was written or not.
///
/// This is created by `Interpolator::begin` and used by `Interpolator::finish`
/// to determine whether a hyperlink was actually opened or not. If it wasn't
/// opened, then finishing interpolation is a no-op.
#[derive(Debug)]
pub(crate) struct InterpolatorStatus {
    active: bool,
}

impl InterpolatorStatus {
    /// Create an inactive interpolator status.
    #[inline]
    pub(crate) fn inactive() -> InterpolatorStatus {
        InterpolatorStatus { active: false }
    }
}

/// Represents the `{path}` part of a hyperlink.
///
/// This is the value to use as-is in the hyperlink, converted from an OS file
/// path.
#[derive(Clone, Debug)]
pub(crate) struct HyperlinkPath(Vec<u8>);

impl HyperlinkPath {
    /// Returns a hyperlink path from an OS path.
    #[cfg(unix)]
    pub(crate) fn from_path(original_path: &Path) -> Option<HyperlinkPath> {
        use std::os::unix::ffi::OsStrExt;

        // We canonicalize the path in order to get an absolute version of it
        // without any `.` or `..` or superfluous separators. Unfortunately,
        // this does also remove symlinks, and in theory, it would be nice to
        // retain them. Perhaps even simpler, we could just join the current
        // working directory with the path and be done with it. There was
        // some discussion about this on PR#2483, and there generally appears
        // to be some uncertainty about the extent to which hyperlinks with
        // things like `..` in them actually work. So for now, we do the safest
        // thing possible even though I think it can result in worse user
        // experience. (Because it means the path you click on and the actual
        // path that gets followed are different, even though they ostensibly
        // refer to the same file.)
        //
        // There's also the potential issue that path canonicalization is
        // expensive since it can touch the file system. That is probably
        // less of an issue since hyperlinks are only created when they're
        // supported, i.e., when writing to a tty.
        //
        // [1]: https://github.com/BurntSushi/ripgrep/pull/2483
        let path = match original_path.canonicalize() {
            Ok(path) => path,
            Err(err) => {
                log::debug!(
                    "hyperlink creation for {:?} failed, error occurred \
                     during path canonicalization: {}",
                    original_path,
                    err,
                );
                return None;
            }
        };
        let bytes = path.as_os_str().as_bytes();
        // This should not be possible since one imagines that canonicalization
        // should always return an absolute path. But it doesn't actually
        // appear guaranteed by POSIX, so we check whether it's true or not and
        // refuse to create a hyperlink from a relative path if it isn't.
        if !bytes.starts_with(b"/") {
            log::debug!(
                "hyperlink creation for {:?} failed, canonicalization \
                 returned {:?}, which does not start with a slash",
                original_path,
                path,
            );
            return None;
        }
        Some(HyperlinkPath::encode(bytes))
    }

    /// Returns a hyperlink path from an OS path.
    #[cfg(windows)]
    pub(crate) fn from_path(original_path: &Path) -> Option<HyperlinkPath> {
        // On Windows, we use `std::path::absolute` instead of `Path::canonicalize`
        // as it can be much faster since it does not touch the file system.
        // It wraps the [`GetFullPathNameW`][1] API, except for verbatim paths
        // (those which start with `\\?\`, see [the documentation][2] for details).
        //
        // Here, we strip any verbatim path prefixes since we cannot use them
        // in hyperlinks anyway. This can only happen if the user explicitly
        // supplies a verbatim path as input, which already needs to be absolute:
        //
        //   \\?\C:\dir\file.txt           (local path)
        //   \\?\UNC\server\dir\file.txt   (network share)
        //
        // The `\\?\` prefix is constant for verbatim paths, and can be followed
        // by `UNC\` (universal naming convention), which denotes a network share.
        //
        // Given that the default URL format on Windows is file://{path}
        // we need to return the following from this function:
        //
        //   /C:/dir/file.txt        (local path)
        //   //server/dir/file.txt   (network share)
        //
        // Which produces the following links:
        //
        //   file:///C:/dir/file.txt        (local path)
        //   file:////server/dir/file.txt   (network share)
        //
        // This substitutes the {path} variable with the expected value for
        // the most common DOS paths, but on the other hand, network paths
        // start with a single slash, which may be unexpected. It seems to work
        // though?
        //
        // Note that the following URL syntax also seems to be valid?
        //
        //   file://server/dir/file.txt
        //
        // But the initial implementation of this routine went for the format
        // above.
        //
        // Also note that the file://C:/dir/file.txt syntax is not correct,
        // even though it often works in practice.
        //
        // In the end, this choice was confirmed by VSCode, whose format is
        //
        //   vscode://file{path}:{line}:{column}
        //
        // and which correctly understands the following URL format for network
        // drives:
        //
        //   vscode://file//server/dir/file.txt:1:1
        //
        // It doesn't parse any other number of slashes in "file//server" as a
        // network path.
        //
        // [1]: https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getfullpathnamew
        // [2]: https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file

        const WIN32_NAMESPACE_PREFIX: &str = r"\\?\";
        const UNC_PREFIX: &str = r"UNC\";

        let path = match std::path::absolute(original_path) {
            Ok(path) => path,
            Err(err) => {
                log::debug!(
                    "hyperlink creation for {:?} failed, error occurred \
                     during conversion to absolute path: {}",
                    original_path,
                    err,
                );
                return None;
            }
        };
        // We convert the path to a string for easier manipulation. If it
        // wasn't valid UTF-16 (and thus could not be non-lossily transcoded
        // to UTF-8), then we just give up. It's not clear we could make
        // a meaningful hyperlink from it anyway. And this should be an
        // exceptionally rare case.
        let mut string = match path.to_str() {
            Some(string) => string,
            None => {
                log::debug!(
                    "hyperlink creation for {:?} failed, path is not \
                     valid UTF-8",
                    original_path,
                );
                return None;
            }
        };

        // Strip verbatim path prefixes (see the comment above for details).
        if string.starts_with(WIN32_NAMESPACE_PREFIX) {
            string = &string[WIN32_NAMESPACE_PREFIX.len()..];

            // Drop the UNC prefix if there is one, but keep the leading slash.
            if string.starts_with(UNC_PREFIX) {
                string = &string[(UNC_PREFIX.len() - 1)..];
            }
        } else if string.starts_with(r"\\") || string.starts_with(r"//") {
            // Drop one of the two leading slashes of network paths, it will be added back.
            string = &string[1..];
        }

        // Finally, add a leading slash. In the local file case, this turns
        // C:\foo\bar into /C:\foo\bar (and then percent encoding turns it into
        // /C:/foo/bar). In the network share case, this turns \share\foo\bar
        // into /\share/foo/bar (and then percent encoding turns it into
        // //share/foo/bar).
        let with_slash = format!("/{string}");
        Some(HyperlinkPath::encode(with_slash.as_bytes()))
    }

    /// For other platforms (not windows, not unix), return None and log a debug message.
    #[cfg(not(any(windows, unix)))]
    pub(crate) fn from_path(original_path: &Path) -> Option<HyperlinkPath> {
        log::debug!("hyperlinks are not supported on this platform");
        None
    }

    /// Percent-encodes a path.
    ///
    /// The alphanumeric ASCII characters and "-", ".", "_", "~" are unreserved
    /// as per section 2.3 of RFC 3986 (Uniform Resource Identifier (URI):
    /// Generic Syntax), and are not encoded. The other ASCII characters except
    /// "/" and ":" are percent-encoded, and "\" is replaced by "/" on Windows.
    ///
    /// Section 4 of RFC 8089 (The "file" URI Scheme) does not mandate precise
    /// encoding requirements for non-ASCII characters, and this implementation
    /// leaves them unencoded. On Windows, the UrlCreateFromPathW function does
    /// not encode non-ASCII characters. Doing so with UTF-8 encoded paths
    /// creates invalid file:// URLs on that platform.
    fn encode(input: &[u8]) -> HyperlinkPath {
        let mut result = Vec::with_capacity(input.len());
        for &byte in input.iter() {
            match byte {
                b'0'..=b'9'
                | b'A'..=b'Z'
                | b'a'..=b'z'
                | b'/'
                | b':'
                | b'-'
                | b'.'
                | b'_'
                | b'~'
                | 128.. => {
                    result.push(byte);
                }
                #[cfg(windows)]
                b'\\' => {
                    result.push(b'/');
                }
                _ => {
                    const HEX: &[u8] = b"0123456789ABCDEF";
                    result.push(b'%');
                    result.push(HEX[(byte >> 4) as usize]);
                    result.push(HEX[(byte & 0xF) as usize]);
                }
            }
        }
        HyperlinkPath(result)
    }
}

/// Returns the set of hyperlink aliases supported by this crate.
///
/// Aliases are supported by the `FromStr` trait implementation of a
/// [`HyperlinkFormat`]. That is, if an alias is seen, then it is automatically
/// replaced with the corresponding format. For example, the `vscode` alias
/// maps to `vscode://file{path}:{line}:{column}`.
///
/// This is exposed to allow callers to include hyperlink aliases in
/// documentation in a way that is guaranteed to match what is actually
/// supported.
///
/// The list returned is guaranteed to be sorted lexicographically
/// by the alias name. Callers may want to re-sort the list using
/// [`HyperlinkAlias::display_priority`] via a stable sort when showing the
/// list to users. This will cause special aliases like `none` and `default` to
/// appear first.
pub fn hyperlink_aliases() -> Vec<HyperlinkAlias> {
    HYPERLINK_PATTERN_ALIASES.iter().cloned().collect()
}

#[cfg(test)]
mod tests {
    use std::str::FromStr;

    use super::*;

    #[test]
    fn build_format() {
        let format = FormatBuilder::new()
            .append_slice(b"foo://")
            .append_slice(b"bar-")
            .append_slice(b"baz")
            .append_var("path")
            .unwrap()
            .build()
            .unwrap();

        assert_eq!(format.to_string(), "foo://bar-baz{path}");
        assert_eq!(format.parts[0], Part::Text(b"foo://bar-baz".to_vec()));
        assert!(!format.is_empty());
    }

    #[test]
    fn build_empty_format() {
        let format = FormatBuilder::new().build().unwrap();

        assert!(format.is_empty());
        assert_eq!(format, HyperlinkFormat::empty());
        assert_eq!(format, HyperlinkFormat::default());
    }

    #[test]
    fn handle_alias() {
        assert!(HyperlinkFormat::from_str("file").is_ok());
        assert!(HyperlinkFormat::from_str("none").is_ok());
        assert!(HyperlinkFormat::from_str("none").unwrap().is_empty());
    }

    #[test]
    fn parse_format() {
        let format = HyperlinkFormat::from_str(
            "foo://{host}/bar/{path}:{line}:{column}",
        )
        .unwrap();

        assert_eq!(
            format.to_string(),
            "foo://{host}/bar/{path}:{line}:{column}"
        );
        assert_eq!(format.parts.len(), 8);
        assert!(format.parts.contains(&Part::Path));
        assert!(format.parts.contains(&Part::Line));
        assert!(format.parts.contains(&Part::Column));
    }

    #[test]
    fn parse_valid() {
        assert!(HyperlinkFormat::from_str("").unwrap().is_empty());
        assert_eq!(
            HyperlinkFormat::from_str("foo://{path}").unwrap().to_string(),
            "foo://{path}"
        );
        assert_eq!(
            HyperlinkFormat::from_str("foo://{path}/bar").unwrap().to_string(),
            "foo://{path}/bar"
        );

        HyperlinkFormat::from_str("f://{path}").unwrap();
        HyperlinkFormat::from_str("f:{path}").unwrap();
        HyperlinkFormat::from_str("f-+.:{path}").unwrap();
        HyperlinkFormat::from_str("f42:{path}").unwrap();
        HyperlinkFormat::from_str("42:{path}").unwrap();
        HyperlinkFormat::from_str("+:{path}").unwrap();
        HyperlinkFormat::from_str("F42:{path}").unwrap();
        HyperlinkFormat::from_str("F42://foo{{bar}}{path}").unwrap();
    }

    #[test]
    fn parse_invalid() {
        use super::HyperlinkFormatErrorKind::*;

        let err = |kind| HyperlinkFormatError { kind };
        assert_eq!(
            HyperlinkFormat::from_str("foo://bar").unwrap_err(),
            err(NoVariables),
        );
        assert_eq!(
            HyperlinkFormat::from_str("foo://{line}").unwrap_err(),
            err(NoPathVariable),
        );
        assert_eq!(
            HyperlinkFormat::from_str("foo://{path").unwrap_err(),
            err(UnclosedVariable),
        );
        assert_eq!(
            HyperlinkFormat::from_str("foo://{path}:{column}").unwrap_err(),
            err(NoLineVariable),
        );
        assert_eq!(
            HyperlinkFormat::from_str("{path}").unwrap_err(),
            err(InvalidScheme),
        );
        assert_eq!(
            HyperlinkFormat::from_str(":{path}").unwrap_err(),
            err(InvalidScheme),
        );
        assert_eq!(
            HyperlinkFormat::from_str("f*:{path}").unwrap_err(),
            err(InvalidScheme),
        );

        assert_eq!(
            HyperlinkFormat::from_str("foo://{bar}").unwrap_err(),
            err(InvalidVariable("bar".to_string())),
        );
        assert_eq!(
            HyperlinkFormat::from_str("foo://{}}bar}").unwrap_err(),
            err(InvalidVariable("".to_string())),
        );
        assert_eq!(
            HyperlinkFormat::from_str("foo://{b}}ar}").unwrap_err(),
            err(InvalidVariable("b".to_string())),
        );
        assert_eq!(
            HyperlinkFormat::from_str("foo://{bar}}}").unwrap_err(),
            err(InvalidVariable("bar".to_string())),
        );
        assert_eq!(
            HyperlinkFormat::from_str("foo://{{bar}").unwrap_err(),
            err(InvalidCloseVariable),
        );
        assert_eq!(
            HyperlinkFormat::from_str("foo://{{{bar}").unwrap_err(),
            err(InvalidVariable("bar".to_string())),
        );
        assert_eq!(
            HyperlinkFormat::from_str("foo://{b{{ar}").unwrap_err(),
            err(InvalidVariable("b{{ar".to_string())),
        );
        assert_eq!(
            HyperlinkFormat::from_str("foo://{bar{{}").unwrap_err(),
            err(InvalidVariable("bar{{".to_string())),
        );
    }

    #[test]
    #[cfg(windows)]
    fn convert_to_hyperlink_path() {
        let convert = |path| {
            String::from_utf8(
                HyperlinkPath::from_path(Path::new(path)).unwrap().0,
            )
            .unwrap()
        };

        assert_eq!(convert(r"C:\dir\file.txt"), "/C:/dir/file.txt");
        assert_eq!(
            convert(r"C:\foo\bar\..\other\baz.txt"),
            "/C:/foo/other/baz.txt"
        );

        assert_eq!(convert(r"\\server\dir\file.txt"), "//server/dir/file.txt");
        assert_eq!(
            convert(r"\\server\dir\foo\..\other\file.txt"),
            "//server/dir/other/file.txt"
        );

        assert_eq!(convert(r"\\?\C:\dir\file.txt"), "/C:/dir/file.txt");
        assert_eq!(
            convert(r"\\?\UNC\server\dir\file.txt"),
            "//server/dir/file.txt"
        );
    }

    #[test]
    fn aliases_are_sorted() {
        let aliases = hyperlink_aliases();
        let mut prev =
            aliases.first().expect("aliases should be non-empty").name();
        for alias in aliases.iter().skip(1) {
            let name = alias.name();
            assert!(
                name > prev,
                "'{prev}' should come before '{name}' in \
                 HYPERLINK_PATTERN_ALIASES",
            );
            prev = name;
        }
    }

    #[test]
    fn alias_names_are_reasonable() {
        for alias in hyperlink_aliases() {
            // There's no hard rule here, but if we want to define an alias
            // with a name that doesn't pass this assert, then we should
            // probably flag it as worthy of consideration. For example, we
            // really do not want to define an alias that contains `{` or `}`,
            // which might confuse it for a variable.
            assert!(alias.name().chars().all(|c| c.is_alphanumeric()
                || c == '+'
                || c == '-'
                || c == '.'));
        }
    }

    #[test]
    fn aliases_are_valid_formats() {
        for alias in hyperlink_aliases() {
            let (name, format) = (alias.name(), alias.format());
            assert!(
                format.parse::<HyperlinkFormat>().is_ok(),
                "invalid hyperlink alias '{name}': {format}",
            );
        }
    }
}


from __future__ import annotations

import ast
import collections.abc as cabc
import importlib.metadata
import inspect
import os
import platform
import re
import sys
import traceback
import typing as t
from functools import update_wrapper
from operator import itemgetter
from types import ModuleType

import click
from click.core import ParameterSource
from werkzeug import run_simple
from werkzeug.serving import is_running_from_reloader
from werkzeug.utils import import_string

from .globals import current_app
from .helpers import get_debug_flag
from .helpers import get_load_dotenv

if t.TYPE_CHECKING:
    import ssl

    from _typeshed.wsgi import StartResponse
    from _typeshed.wsgi import WSGIApplication
    from _typeshed.wsgi import WSGIEnvironment

    from .app import Flask

class NoAppException(click.UsageError):
    """Raised if an application cannot be found or loaded."""

def find_best_app(module: ModuleType) -> Flask:
    """Given a module instance this tries to find the best possible
    application in the module or raises an exception.
    """
    from . import Flask

    # Search for the most common names first.
    for attr_name in ("app", "application"):
        app = getattr(module, attr_name, None)

        if isinstance(app, Flask):
            return app

    # Otherwise find the only object that is a Flask instance.
    matches = [v for v in module.__dict__.values() if isinstance(v, Flask)]

    if len(matches) == 1:
        return matches[0]
    elif len(matches) > 1:
        raise NoAppException(
            "Detected multiple Flask applications in module"
            f" '{module.__name__}'. Use '{module.__name__}:name'"
            " to specify the correct one."
        )

    # Search for app factory functions.
    for attr_name in ("create_app", "make_app"):
        app_factory = getattr(module, attr_name, None)

        if inspect.isfunction(app_factory):
            try:
                app = app_factory()

                if isinstance(app, Flask):
                    return app
            except TypeError as e:
                if not _called_with_wrong_args(app_factory):
                    raise

                raise NoAppException(
                    f"Detected factory '{attr_name}' in module '{module.__name__}',"
                    " but could not call it without arguments. Use"
                    f" '{module.__name__}:{attr_name}(args)'"
                    " to specify arguments."
                ) from e

    raise NoAppException(
        "Failed to find Flask application or factory in module"
        f" '{module.__name__}'. Use '{module.__name__}:name'"
        " to specify one."
    )

def _called_with_wrong_args(f: t.Callable[..., Flask]) -> bool:
    """Check whether calling a function raised a ``TypeError`` because
    the call failed or because something in the factory raised the
    error.

    :param f: The function that was called.
    :return: ``True`` if the call failed.
    """
    tb = sys.exc_info()[2]

    try:
        while tb is not None:
            if tb.tb_frame.f_code is f.__code__:
                # In the function, it was called successfully.
                return False

            tb = tb.tb_next

        # Didn't reach the function.
        return True
    finally:
        # Delete tb to break a circular reference.
        # https://docs.python.org/2/library/sys.html#sys.exc_info
        del tb

def find_app_by_string(module: ModuleType, app_name: str) -> Flask:
    """Check if the given string is a variable name or a function. Call
    a function to get the app instance, or return the variable directly.
    """
    from . import Flask

    # Parse app_name as a single expression to determine if it's a valid
    # attribute name or function call.
    try:
        expr = ast.parse(app_name.strip(), mode="eval").body
    except SyntaxError:
        raise NoAppException(
            f"Failed to parse {app_name!r} as an attribute name or function call."
        ) from None

    if isinstance(expr, ast.Name):
        name = expr.id
        args = []
        kwargs = {}
    elif isinstance(expr, ast.Call):
        # Ensure the function name is an attribute name only.
        if not isinstance(expr.func, ast.Name):
            raise NoAppException(
                f"Function reference must be a simple name: {app_name!r}."
            )

        name = expr.func.id

        # Parse the positional and keyword arguments as literals.
        try:
            args = [ast.literal_eval(arg) for arg in expr.args]
            kwargs = {
                kw.arg: ast.literal_eval(kw.value)
                for kw in expr.keywords
                if kw.arg is not None
            }
        except ValueError:
            # literal_eval gives cryptic error messages, show a generic
            # message with the full expression instead.
            raise NoAppException(
                f"Failed to parse arguments as literal values: {app_name!r}."
            ) from None
    else:
        raise NoAppException(
            f"Failed to parse {app_name!r} as an attribute name or function call."
        )

    try:
        attr = getattr(module, name)
    except AttributeError as e:
        raise NoAppException(
            f"Failed to find attribute {name!r} in {module.__name__!r}."
        ) from e

    # If the attribute is a function, call it with any args and kwargs
    # to get the real application.
    if inspect.isfunction(attr):
        try:
            app = attr(*args, **kwargs)
        except TypeError as e:
            if not _called_with_wrong_args(attr):
                raise

            raise NoAppException(
                f"The factory {app_name!r} in module"
                f" {module.__name__!r} could not be called with the"
                " specified arguments."
            ) from e
    else:
        app = attr

    if isinstance(app, Flask):
        return app

    raise NoAppException(
        "A valid Flask application was not obtained from"
        f" '{module.__name__}:{app_name}'."
    )

def prepare_import(path: str) -> str:
    """Given a filename this will try to calculate the python path, add it
    to the search path and return the actual module name that is expected.
    """
    path = os.path.realpath(path)

    fname, ext = os.path.splitext(path)
    if ext == ".py":
        path = fname

    if os.path.basename(path) == "__init__":
        path = os.path.dirname(path)

    module_name = []

    # move up until outside package structure (no __init__.py)
    while True:
        path, name = os.path.split(path)
        module_name.append(name)

        if not os.path.exists(os.path.join(path, "__init__.py")):
            break

    if sys.path[0] != path:
        sys.path.insert(0, path)

    return ".".join(module_name[::-1])

@t.overload
def locate_app(
    module_name: str, app_name: str | None, raise_if_not_found: t.Literal[True] = True
) -> Flask: ...

@t.overload
def locate_app(
    module_name: str, app_name: str | None, raise_if_not_found: t.Literal[False] = ...
) -> Flask | None: ...

def locate_app(
    module_name: str, app_name: str | None, raise_if_not_found: bool = True
) -> Flask | None:
    try:
        __import__(module_name)
    except ImportError:
        # Reraise the ImportError if it occurred within the imported module.
        # Determine this by checking whether the trace has a depth > 1.
        if sys.exc_info()[2].tb_next:  # type: ignore[union-attr]
            raise NoAppException(
                f"While importing {module_name!r}, an ImportError was"
                f" raised:\n\n{traceback.format_exc()}"
            ) from None
        elif raise_if_not_found:
            raise NoAppException(f"Could not import {module_name!r}.") from None
        else:
            return None

    module = sys.modules[module_name]

    if app_name is None:
        return find_best_app(module)
    else:
        return find_app_by_string(module, app_name)

def get_version(ctx: click.Context, param: click.Parameter, value: t.Any) -> None:
    if not value or ctx.resilient_parsing:
        return

    flask_version = importlib.metadata.version("flask")
    werkzeug_version = importlib.metadata.version("werkzeug")

    click.echo(
        f"Python {platform.python_version()}\n"
        f"Flask {flask_version}\n"
        f"Werkzeug {werkzeug_version}",
        color=ctx.color,
    )
    ctx.exit()

version_option = click.Option(
    ["--version"],
    help="Show the Flask version.",
    expose_value=False,
    callback=get_version,
    is_flag=True,
    is_eager=True,
)

class ScriptInfo:
    """Helper object to deal with Flask applications.  This is usually not
    necessary to interface with as it's used internally in the dispatching
    to click.  In future versions of Flask this object will most likely play
    a bigger role.  Typically it's created automatically by the
    :class:`FlaskGroup` but you can also manually create it and pass it
    onwards as click object.

    .. versionchanged:: 3.1
        Added the ``load_dotenv_defaults`` parameter and attribute.
    """

    def __init__(
        self,
        app_import_path: str | None = None,
        create_app: t.Callable[..., Flask] | None = None,
        set_debug_flag: bool = True,
        load_dotenv_defaults: bool = True,
    ) -> None:
        #: Optionally the import path for the Flask application.
        self.app_import_path = app_import_path
        #: Optionally a function that is passed the script info to create
        #: the instance of the application.
        self.create_app = create_app
        #: A dictionary with arbitrary data that can be associated with
        #: this script info.
        self.data: dict[t.Any, t.Any] = {}
        self.set_debug_flag = set_debug_flag

        self.load_dotenv_defaults = get_load_dotenv(load_dotenv_defaults)
        """Whether default ``.flaskenv`` and ``.env`` files should be loaded.

        ``ScriptInfo`` doesn't load anything, this is for reference when doing
        the load elsewhere during processing.

        .. versionadded:: 3.1
        """

        self._loaded_app: Flask | None = None

    def load_app(self) -> Flask:
        """Loads the Flask app (if not yet loaded) and returns it.  Calling
        this multiple times will just result in the already loaded app to
        be returned.
        """
        if self._loaded_app is not None:
            return self._loaded_app
        app: Flask | None = None
        if self.create_app is not None:
            app = self.create_app()
        else:
            if self.app_import_path:
                path, name = (
                    re.split(r":(?![\\/])", self.app_import_path, maxsplit=1) + [None]
                )[:2]
                import_name = prepare_import(path)
                app = locate_app(import_name, name)
            else:
                for path in ("wsgi.py", "app.py"):
                    import_name = prepare_import(path)
                    app = locate_app(import_name, None, raise_if_not_found=False)

                    if app is not None:
                        break

        if app is None:
            raise NoAppException(
                "Could not locate a Flask application. Use the"
                " 'flask --app' option, 'FLASK_APP' environment"
                " variable, or a 'wsgi.py' or 'app.py' file in the"
                " current directory."
            )

        if self.set_debug_flag:
            # Update the app's debug flag through the descriptor so that
            # other values repopulate as well.
            app.debug = get_debug_flag()

        self._loaded_app = app
        return app

pass_script_info = click.make_pass_decorator(ScriptInfo, ensure=True)

F = t.TypeVar("F", bound=t.Callable[..., t.Any])

def with_appcontext(f: F) -> F:
    """Wraps a callback so that it's guaranteed to be executed with the
    script's application context.

    Custom commands (and their options) registered under ``app.cli`` or
    ``blueprint.cli`` will always have an app context available, this
    decorator is not required in that case.

    .. versionchanged:: 2.2
        The app context is active for subcommands as well as the
        decorated callback. The app context is always available to
        ``app.cli`` command and parameter callbacks.
    """

    @click.pass_context
    def decorator(ctx: click.Context, /, *args: t.Any, **kwargs: t.Any) -> t.Any:
        if not current_app:
            app = ctx.ensure_object(ScriptInfo).load_app()
            ctx.with_resource(app.app_context())

        return ctx.invoke(f, *args, **kwargs)

    return update_wrapper(decorator, f)  # type: ignore[return-value]

class AppGroup(click.Group):
    """This works similar to a regular click :class:`~click.Group` but it
    changes the behavior of the :meth:`command` decorator so that it
    automatically wraps the functions in :func:`with_appcontext`.

    Not to be confused with :class:`FlaskGroup`.
    """

    def command(  # type: ignore[override]
        self, *args: t.Any, **kwargs: t.Any
    ) -> t.Callable[[t.Callable[..., t.Any]], click.Command]:
        """This works exactly like the method of the same name on a regular
        :class:`click.Group` but it wraps callbacks in :func:`with_appcontext`
        unless it's disabled by passing ``with_appcontext=False``.
        """
        wrap_for_ctx = kwargs.pop("with_appcontext", True)

        def decorator(f: t.Callable[..., t.Any]) -> click.Command:
            if wrap_for_ctx:
                f = with_appcontext(f)
            return super(AppGroup, self).command(*args, **kwargs)(f)  # type: ignore[no-any-return]

        return decorator

    def group(  # type: ignore[override]
        self, *args: t.Any, **kwargs: t.Any
    ) -> t.Callable[[t.Callable[..., t.Any]], click.Group]:
        """This works exactly like the method of the same name on a regular
        :class:`click.Group` but it defaults the group class to
        :class:`AppGroup`.
        """
        kwargs.setdefault("cls", AppGroup)
        return super().group(*args, **kwargs)  # type: ignore[no-any-return]

def _set_app(ctx: click.Context, param: click.Option, value: str | None) -> str | None:
    if value is None:
        return None

    info = ctx.ensure_object(ScriptInfo)
    info.app_import_path = value
    return value

# This option is eager so the app will be available if --help is given.
# --help is also eager, so --app must be before it in the param list.
# no_args_is_help bypasses eager processing, so this option must be
# processed manually in that case to ensure FLASK_APP gets picked up.
_app_option = click.Option(
    ["-A", "--app"],
    metavar="IMPORT",
    help=(
        "The Flask application or factory function to load, in the form 'module:name'."
        " Module can be a dotted import or file path. Name is not required if it is"
        " 'app', 'application', 'create_app', or 'make_app', and can be 'name(args)' to"
        " pass arguments."
    ),
    is_eager=True,
    expose_value=False,
    callback=_set_app,
)

def _set_debug(ctx: click.Context, param: click.Option, value: bool) -> bool | None:
    # If the flag isn't provided, it will default to False. Don't use
    # that, let debug be set by env in that case.
    source = ctx.get_parameter_source(param.name)

    if source is not None and source in (
        ParameterSource.DEFAULT,
        ParameterSource.DEFAULT_MAP,
    ):
        return None

    # Set with env var instead of ScriptInfo.load so that it can be
    # accessed early during a factory function.
    os.environ["FLASK_DEBUG"] = "1" if value else "0"
    return value

_debug_option = click.Option(
    ["--debug/--no-debug"],
    help="Set debug mode.",
    expose_value=False,
    callback=_set_debug,
)

def _env_file_callback(
    ctx: click.Context, param: click.Option, value: str | None
) -> str | None:
    try:
        import dotenv  # noqa: F401
    except ImportError:
        # Only show an error if a value was passed, otherwise we still want to
        # call load_dotenv and show a message without exiting.
        if value is not None:
            raise click.BadParameter(
                "python-dotenv must be installed to load an env file.",
                ctx=ctx,
                param=param,
            ) from None

    # Load if a value was passed, or we want to load default files, or both.
    if value is not None or ctx.obj.load_dotenv_defaults:
        load_dotenv(value, load_defaults=ctx.obj.load_dotenv_defaults)

    return value

# This option is eager so env vars are loaded as early as possible to be
# used by other options.
_env_file_option = click.Option(
    ["-e", "--env-file"],
    type=click.Path(exists=True, dir_okay=False),
    help=(
        "Load environment variables from this file, taking precedence over"
        " those set by '.env' and '.flaskenv'. Variables set directly in the"
        " environment take highest precedence. python-dotenv must be installed."
    ),
    is_eager=True,
    expose_value=False,
    callback=_env_file_callback,
)

class FlaskGroup(AppGroup):
    """Special subclass of the :class:`AppGroup` group that supports
    loading more commands from the configured Flask app.  Normally a
    developer does not have to interface with this class but there are
    some very advanced use cases for which it makes sense to create an
    instance of this. see :ref:`custom-scripts`.

    :param add_default_commands: if this is True then the default run and
        shell commands will be added.
    :param add_version_option: adds the ``--version`` option.
    :param create_app: an optional callback that is passed the script info and
        returns the loaded app.
    :param load_dotenv: Load the nearest :file:`.env` and :file:`.flaskenv`
        files to set environment variables. Will also change the working
        directory to the directory containing the first file found.
    :param set_debug_flag: Set the app's debug flag.

    .. versionchanged:: 3.1
        ``-e path`` takes precedence over default ``.env`` and ``.flaskenv`` files.

    .. versionchanged:: 2.2
        Added the ``-A/--app``, ``--debug/--no-debug``, ``-e/--env-file`` options.

    .. versionchanged:: 2.2
        An app context is pushed when running ``app.cli`` commands, so
        ``@with_appcontext`` is no longer required for those commands.

    .. versionchanged:: 1.0
        If installed, python-dotenv will be used to load environment variables
        from :file:`.env` and :file:`.flaskenv` files.
    """

    def __init__(
        self,
        add_default_commands: bool = True,
        create_app: t.Callable[..., Flask] | None = None,
        add_version_option: bool = True,
        load_dotenv: bool = True,
        set_debug_flag: bool = True,
        **extra: t.Any,
    ) -> None:
        params: list[click.Parameter] = list(extra.pop("params", None) or ())
        # Processing is done with option callbacks instead of a group
        # callback. This allows users to make a custom group callback
        # without losing the behavior. --env-file must come first so
        # that it is eagerly evaluated before --app.
        params.extend((_env_file_option, _app_option, _debug_option))

        if add_version_option:
            params.append(version_option)

        if "context_settings" not in extra:
            extra["context_settings"] = {}

        extra["context_settings"].setdefault("auto_envvar_prefix", "FLASK")

        super().__init__(params=params, **extra)

        self.create_app = create_app
        self.load_dotenv = load_dotenv
        self.set_debug_flag = set_debug_flag

        if add_default_commands:
            self.add_command(run_command)
            self.add_command(shell_command)
            self.add_command(routes_command)

        self._loaded_plugin_commands = False

    def _load_plugin_commands(self) -> None:
        if self._loaded_plugin_commands:
            return

        for ep in importlib.metadata.entry_points(group="flask.commands"):
            self.add_command(ep.load(), ep.name)

        self._loaded_plugin_commands = True

    def get_command(self, ctx: click.Context, name: str) -> click.Command | None:
        self._load_plugin_commands()
        # Look up built-in and plugin commands, which should be
        # available even if the app fails to load.
        rv = super().get_command(ctx, name)

        if rv is not None:
            return rv

        info = ctx.ensure_object(ScriptInfo)

        # Look up commands provided by the app, showing an error and
        # continuing if the app couldn't be loaded.
        try:
            app = info.load_app()
        except NoAppException as e:
            click.secho(f"Error: {e.format_message()}\n", err=True, fg="red")
            return None

        # Push an app context for the loaded app unless it is already
        # active somehow. This makes the context available to parameter
        # and command callbacks without needing @with_appcontext.
        if not current_app or current_app._get_current_object() is not app:
            ctx.with_resource(app.app_context())

        return app.cli.get_command(ctx, name)

    def list_commands(self, ctx: click.Context) -> list[str]:
        self._load_plugin_commands()
        # Start with the built-in and plugin commands.
        rv = set(super().list_commands(ctx))
        info = ctx.ensure_object(ScriptInfo)

        # Add commands provided by the app, showing an error and
        # continuing if the app couldn't be loaded.
        try:
            rv.update(info.load_app().cli.list_commands(ctx))
        except NoAppException as e:
            # When an app couldn't be loaded, show the error message
            # without the traceback.
            click.secho(f"Error: {e.format_message()}\n", err=True, fg="red")
        except Exception:
            # When any other errors occurred during loading, show the
            # full traceback.
            click.secho(f"{traceback.format_exc()}\n", err=True, fg="red")

        return sorted(rv)

    def make_context(
        self,
        info_name: str | None,
        args: list[str],
        parent: click.Context | None = None,
        **extra: t.Any,
    ) -> click.Context:
        # Set a flag to tell app.run to become a no-op. If app.run was
        # not in a __name__ == __main__ guard, it would start the server
        # when importing, blocking whatever command is being called.
        os.environ["FLASK_RUN_FROM_CLI"] = "true"

        if "obj" not in extra and "obj" not in self.context_settings:
            extra["obj"] = ScriptInfo(
                create_app=self.create_app,
                set_debug_flag=self.set_debug_flag,
                load_dotenv_defaults=self.load_dotenv,
            )

        return super().make_context(info_name, args, parent=parent, **extra)

    def parse_args(self, ctx: click.Context, args: list[str]) -> list[str]:
        if (not args and self.no_args_is_help) or (
            len(args) == 1 and args[0] in self.get_help_option_names(ctx)
        ):
            # Attempt to load --env-file and --app early in case they
            # were given as env vars. Otherwise no_args_is_help will not
            # see commands from app.cli.
            _env_file_option.handle_parse_result(ctx, {}, [])
            _app_option.handle_parse_result(ctx, {}, [])

        return super().parse_args(ctx, args)

def _path_is_ancestor(path: str, other: str) -> bool:
    """Take ``other`` and remove the length of ``path`` from it. Then join it
    to ``path``. If it is the original value, ``path`` is an ancestor of
    ``other``."""
    return os.path.join(path, other[len(path) :].lstrip(os.sep)) == other

def load_dotenv(
    path: str | os.PathLike[str] | None = None, load_defaults: bool = True
) -> bool:
    """Load "dotenv" files to set environment variables. A given path takes
    precedence over ``.env``, which takes precedence over ``.flaskenv``. After
    loading and combining these files, values are only set if the key is not
    already set in ``os.environ``.

    This is a no-op if `python-dotenv`_ is not installed.

    .. _python-dotenv: https://github.com/theskumar/python-dotenv#readme

    :param path: Load the file at this location.
    :param load_defaults: Search for and load the default ``.flaskenv`` and
        ``.env`` files.
    :return: ``True`` if at least one env var was loaded.

    .. versionchanged:: 3.1
        Added the ``load_defaults`` parameter. A given path takes precedence
        over default files.

    .. versionchanged:: 2.0
        The current directory is not changed to the location of the
        loaded file.

    .. versionchanged:: 2.0
        When loading the env files, set the default encoding to UTF-8.

    .. versionchanged:: 1.1.0
        Returns ``False`` when python-dotenv is not installed, or when
        the given path isn't a file.

    .. versionadded:: 1.0
    """
    try:
        import dotenv
    except ImportError:
        if path or os.path.isfile(".env") or os.path.isfile(".flaskenv"):
            click.secho(
                " * Tip: There are .env files present. Install python-dotenv"
                " to use them.",
                fg="yellow",
                err=True,
            )

        return False

    data: dict[str, str | None] = {}

    if load_defaults:
        for default_name in (".flaskenv", ".env"):
            if not (default_path := dotenv.find_dotenv(default_name, usecwd=True)):
                continue

            data |= dotenv.dotenv_values(default_path, encoding="utf-8")

    if path is not None and os.path.isfile(path):
        data |= dotenv.dotenv_values(path, encoding="utf-8")

    for key, value in data.items():
        if key in os.environ or value is None:
            continue

        os.environ[key] = value

    return bool(data)  # True if at least one env var was loaded.

def show_server_banner(debug: bool, app_import_path: str | None) -> None:
    """Show extra startup messages the first time the server is run,
    ignoring the reloader.
    """
    if is_running_from_reloader():
        return

    if app_import_path is not None:
        click.echo(f" * Serving Flask app '{app_import_path}'")

    if debug is not None:
        click.echo(f" * Debug mode: {'on' if debug else 'off'}")

class CertParamType(click.ParamType):  # type: ignore[type-arg]
    """Click option type for the ``--cert`` option. Allows either an
    existing file, the string ``'adhoc'``, or an import for a
    :class:`~ssl.SSLContext` object.
    """

    name = "path"

    def __init__(self) -> None:
        self.path_type = click.Path(exists=True, dir_okay=False, resolve_path=True)

    def convert(
        self, value: t.Any, param: click.Parameter | None, ctx: click.Context | None
    ) -> t.Any:
        try:
            import ssl
        except ImportError:
            raise click.BadParameter(
                'Using "--cert" requires Python to be compiled with SSL support.',
                ctx,
                param,
            ) from None

        try:
            return self.path_type(value, param, ctx)
        except click.BadParameter:
            value = click.STRING(value, param, ctx).lower()  # type: ignore[union-attr]

            if value == "adhoc":
                try:
                    import cryptography  # noqa: F401
                except ImportError:
                    raise click.BadParameter(
                        "Using ad-hoc certificates requires the cryptography library.",
                        ctx,
                        param,
                    ) from None

                return value

            obj = import_string(value, silent=True)

            if isinstance(obj, ssl.SSLContext):
                return obj

            raise

def _validate_key(ctx: click.Context, param: click.Parameter, value: t.Any) -> t.Any:
    """The ``--key`` option must be specified when ``--cert`` is a file.
    Modifies the ``cert`` param to be a ``(cert, key)`` pair if needed.
    """
    cert = ctx.params.get("cert")
    is_adhoc = cert == "adhoc"

    try:
        import ssl
    except ImportError:
        is_context = False
    else:
        is_context = isinstance(cert, ssl.SSLContext)

    if value is not None:
        if is_adhoc:
            raise click.BadParameter(
                'When "--cert" is "adhoc", "--key" is not used.', ctx, param
            )

        if is_context:
            raise click.BadParameter(
                'When "--cert" is an SSLContext object, "--key" is not used.',
                ctx,
                param,
            )

        if not cert:
            raise click.BadParameter('"--cert" must also be specified.', ctx, param)

        ctx.params["cert"] = cert, value

    else:
        if cert and not (is_adhoc or is_context):
            raise click.BadParameter('Required when using "--cert".', ctx, param)

    return value

class SeparatedPathType(click.Path):
    """Click option type that accepts a list of values separated by the
    OS's path separator (``:``, ``;`` on Windows). Each value is
    validated as a :class:`click.Path` type.
    """

    def convert(
        self, value: t.Any, param: click.Parameter | None, ctx: click.Context | None
    ) -> t.Any:
        items = self.split_envvar_value(value)
        # can't call no-arg super() inside list comprehension until Python 3.12
        super_convert = super().convert
        return [super_convert(item, param, ctx) for item in items]

@click.command("run", short_help="Run a development server.")
@click.option("--host", "-h", default="127.0.0.1", help="The interface to bind to.")
@click.option("--port", "-p", default=5000, help="The port to bind to.")
@click.option(
    "--cert",
    type=CertParamType(),
    help="Specify a certificate file to use HTTPS.",
    is_eager=True,
)
@click.option(
    "--key",
    type=click.Path(exists=True, dir_okay=False, resolve_path=True),
    callback=_validate_key,
    expose_value=False,
    help="The key file to use when specifying a certificate.",
)
@click.option(
    "--reload/--no-reload",
    default=None,
    help="Enable or disable the reloader. By default the reloader "
    "is active if debug is enabled.",
)
@click.option(
    "--debugger/--no-debugger",
    default=None,
    help="Enable or disable the debugger. By default the debugger "
    "is active if debug is enabled.",
)
@click.option(
    "--with-threads/--without-threads",
    default=True,
    help="Enable or disable multithreading.",
)
@click.option(
    "--extra-files",
    default=None,
    type=SeparatedPathType(),
    help=(
        "Extra files that trigger a reload on change. Multiple paths"
        f" are separated by {os.path.pathsep!r}."
    ),
)
@click.option(
    "--exclude-patterns",
    default=None,
    type=SeparatedPathType(),
    help=(
        "Files matching these fnmatch patterns will not trigger a reload"
        " on change. Multiple patterns are separated by"
        f" {os.path.pathsep!r}."
    ),
)
@pass_script_info
def run_command(
    info: ScriptInfo,
    host: str,
    port: int,
    reload: bool,
    debugger: bool,
    with_threads: bool,
    cert: ssl.SSLContext | tuple[str, str | None] | t.Literal["adhoc"] | None,
    extra_files: list[str] | None,
    exclude_patterns: list[str] | None,
) -> None:
    """Run a local development server.

    This server is for development purposes only. It does not provide
    the stability, security, or performance of production WSGI servers.

    The reloader and debugger are enabled by default with the '--debug'
    option.
    """
    try:
        app: WSGIApplication = info.load_app()  # pyright: ignore
    except Exception as e:
        if is_running_from_reloader():
            # When reloading, print out the error immediately, but raise
            # it later so the debugger or server can handle it.
            traceback.print_exc()
            err = e

            def app(
                environ: WSGIEnvironment, start_response: StartResponse
            ) -> cabc.Iterable[bytes]:
                raise err from None

        else:
            # When not reloading, raise the error immediately so the
            # command fails.
            raise e from None

    debug = get_debug_flag()

    if reload is None:
        reload = debug

    if debugger is None:
        debugger = debug

    show_server_banner(debug, info.app_import_path)

    run_simple(
        host,
        port,
        app,
        use_reloader=reload,
        use_debugger=debugger,
        threaded=with_threads,
        ssl_context=cert,
        extra_files=extra_files,
        exclude_patterns=exclude_patterns,
    )

run_command.params.insert(0, _debug_option)

@click.command("shell", short_help="Run a shell in the app context.")
@with_appcontext
def shell_command() -> None:
    """Run an interactive Python shell in the context of a given
    Flask application.  The application will populate the default
    namespace of this shell according to its configuration.

    This is useful for executing small snippets of management code
    without having to manually configure the application.
    """
    import code

    banner = (
        f"Python {sys.version} on {sys.platform}\n"
        f"App: {current_app.import_name}\n"
        f"Instance: {current_app.instance_path}"
    )
    ctx: dict[str, t.Any] = {}

    # Support the regular Python interpreter startup script if someone
    # is using it.
    startup = os.environ.get("PYTHONSTARTUP")
    if startup and os.path.isfile(startup):
        with open(startup) as f:
            eval(compile(f.read(), startup, "exec"), ctx)

    ctx.update(current_app.make_shell_context())

    # Site, customize, or startup script can set a hook to call when
    # entering interactive mode. The default one sets up readline with
    # tab and history completion.
    interactive_hook = getattr(sys, "__interactivehook__", None)

    if interactive_hook is not None:
        try:
            import readline
            from rlcompleter import Completer
        except ImportError:
            pass
        else:
            # rlcompleter uses __main__.__dict__ by default, which is
            # flask.__main__. Use the shell context instead.
            readline.set_completer(Completer(ctx).complete)

        interactive_hook()

    code.interact(banner=banner, local=ctx)

@click.command("routes", short_help="Show the routes for the app.")
@click.option(
    "--sort",
    "-s",
    type=click.Choice(("endpoint", "methods", "domain", "rule", "match")),
    default="endpoint",
    help=(
        "Method to sort routes by. 'match' is the order that Flask will match routes"
        " when dispatching a request."
    ),
)
@click.option("--all-methods", is_flag=True, help="Show HEAD and OPTIONS methods.")
@with_appcontext
def routes_command(sort: str, all_methods: bool) -> None:
    """Show all registered routes with endpoints and methods."""
    rules = list(current_app.url_map.iter_rules())

    if not rules:
        click.echo("No routes were registered.")
        return

    ignored_methods = set() if all_methods else {"HEAD", "OPTIONS"}
    host_matching = current_app.url_map.host_matching
    has_domain = any(rule.host if host_matching else rule.subdomain for rule in rules)
    rows = []

    for rule in rules:
        row = [
            rule.endpoint,
            ", ".join(sorted((rule.methods or set()) - ignored_methods)),
        ]

        if has_domain:
            row.append((rule.host if host_matching else rule.subdomain) or "")

        row.append(rule.rule)
        rows.append(row)

    headers = ["Endpoint", "Methods"]
    sorts = ["endpoint", "methods"]

    if has_domain:
        headers.append("Host" if host_matching else "Subdomain")
        sorts.append("domain")

    headers.append("Rule")
    sorts.append("rule")

    try:
        rows.sort(key=itemgetter(sorts.index(sort)))
    except ValueError:
        pass

    rows.insert(0, headers)
    widths = [max(len(row[i]) for row in rows) for i in range(len(headers))]
    rows.insert(1, ["-" * w for w in widths])
    template = "  ".join(f"{{{i}:<{w}}}" for i, w in enumerate(widths))

    for row in rows:
        click.echo(template.format(*row))

cli = FlaskGroup(
    name="flask",
    help="""\
A general utility script for Flask applications.

An application to load must be given with the '--app' option,
'FLASK_APP' environment variable, or with a 'wsgi.py' or 'app.py' file
in the current directory.
""",
)

def main() -> None:
    cli.main()

if __name__ == "__main__":
    main()


import { describe, expect, test } from 'vitest'
import { findAssetFile, getColor, isBuild, readManifest } from '~utils'

test.skip('should load both stylesheets', async () => {
  expect(await getColor('h1')).toBe('red')
  expect(await getColor('h2')).toBe('blue')
})

describe.runIf(isBuild).skip('build', () => {
  test('should remove empty chunk', async () => {
    expect(findAssetFile(/style.*\.js$/)).toBeUndefined()
    expect(findAssetFile('main.*.js$')).toMatch(`/* empty css`)
    expect(findAssetFile('other.*.js$')).toMatch(`/* empty css`)
  })

  test('should generate correct manifest', async () => {
    const manifest = readManifest()
    expect(manifest['index.html'].css.length).toBe(2)
    expect(manifest['other.js'].css.length).toBe(1)
  })
})


# <small>nlohmann::basic_json::</small>is_boolean

```cpp
constexpr bool is_boolean() const noexcept;
```

This function returns `#!cpp true` if and only if the JSON value is `#!json true` or `#!json false`.

## Return value

`#!cpp true` if type is boolean, `#!cpp false` otherwise.

## Exception safety

No-throw guarantee: this member function never throws exceptions.

## Complexity

Constant.

## Examples

??? example

    The following code exemplifies `is_boolean()` for all JSON types.

    ```cpp
    --8<-- "examples/is_boolean.cpp"
    ```

    Output:

    ```json
    --8<-- "examples/is_boolean.output"
    ```

## Version history

- Added in version 1.0.0.


import path from 'node:path'
import { defineConfig } from 'vite'
import svgVirtualModulePlugin from './svgVirtualModulePlugin.ts'
import matrixTestResultPlugin from './matrixTestResultPlugin.ts'
import { getWindows83ShortNameForDotEnv } from './windows83Filename.ts'

const BASE = '/base/'

export default defineConfig({
  base: BASE,
  input: {
    main: path.resolve(import.meta.dirname, 'src/index.html'),
  },
  build: {
    outDir: 'dist/base',
  },
  server: {
    fs: {
      strict: true,
      allow: [path.resolve(import.meta.dirname, 'src')],
    },
    hmr: {
      overlay: false,
    },
    headers: {
      'x-served-by': 'vite',
    },
  },
  preview: {
    headers: {
      'x-served-by': 'vite',
    },
  },
  define: {
    ROOT: JSON.stringify(path.dirname(import.meta.dirname).replace(/\\/g, '/')),
    BASE: JSON.stringify(BASE),
    DOTENV83SHORTNAME: JSON.stringify(getWindows83ShortNameForDotEnv()),
  },
  plugins: [svgVirtualModulePlugin(), matrixTestResultPlugin()],
})


- `test1` - `test5`

Cyclic import example based on https://github.com/vitejs/vite/issues/14048#issuecomment-2354774156

```mermaid
flowchart TD
    B(dep1.js) -->|dep1| A(index.js)
    A -->|dep1| C(dep2.js)
    C -->|dep2| A
    A -->|dep1, dep2| entry.js
```

---

- `test6`

```mermaid
flowchart TD
    A(dep1.js) -->|dep1| B
    B(dep2.js) -->|dep2| A
    A -->|dep1| C(index.js)
```