git-bug 0.2.4

A rust library for interfacing with git-bug repositories
Documentation
// git-bug-rs - A rust library for interfacing with git-bug repositories
//
// Copyright (C) 2025 Benedikt Peetz <benedikt.peetz@b-peetz.de>
// SPDX-License-Identifier: GPL-3.0-or-later
//
// This file is part of git-bug-rs/git-gub.
//
// You should have received a copy of the License along with this program.
// If not, see <https://www.gnu.org/licenses/agpl.txt>.

//! Normalization of a [`Query`].

use std::fmt::Display;

use super::{Matcher, Query, queryable::Queryable};
use crate::query::queryable::QueryKeyValue;

impl<E: Queryable> Query<E> {
    /// Turn this [`Query`] into it's normal representations, that actually
    /// conforms to the EBNF given in the module documentation.
    ///
    /// # Note
    /// This is just calling the [`Display`] implementation.
    #[must_use]
    pub fn into_normal_representation(self) -> String {
        self.to_string()
    }
}

impl<E: Queryable> Display for Query<E> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if let Some(root) = &self.root {
            root.fmt(f)
        } else {
            write!(f, "")
        }
    }
}

impl<E: Queryable> Display for Matcher<E> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Matcher::Or { lhs, rhs } => write!(f, r"({lhs} OR {rhs})"),
            Matcher::And { lhs, rhs } => write!(f, r"({lhs} AND {rhs})"),
            Matcher::Match { key_value } => {
                let (key, value) = key_value.to_key_and_value();
                let (key, value) = (key.to_string(), value.to_string());

                match (
                    key.contains(char::is_whitespace),
                    value.contains(char::is_whitespace),
                ) {
                    (true, true) => write!(f, r#""{key}:{value}""#),
                    (true, false) => write!(f, r#""{key}":{value}"#),
                    (false, true) => write!(f, r#"{key}:"{value}"#),
                    (false, false) => write!(f, "{key}:{value}"),
                }
            }
        }
    }
}