1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
use crate::target_error::TargetError;
use crate::target_scope::TargetScope;
use moon_common::{Id, ID_CHARS};
use once_cell::sync::Lazy;
use regex::Regex;
use schematic::{Schema, SchemaBuilder, Schematic};
use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
use std::{
    cmp::Ordering,
    fmt::{self, Display},
};
use tracing::instrument;

// The @ is to support npm package scopes!
pub static TARGET_PATTERN: Lazy<Regex> = Lazy::new(|| {
    Regex::new(&format!(
        r"^(?P<scope>(?:[A-Za-z@#_]{{1}}{chars}|\^|~))?:(?P<task>{chars})$",
        chars = ID_CHARS
    ))
    .unwrap()
});

#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct Target {
    pub id: String,
    pub scope: TargetScope,
    pub task_id: Id,
}

impl Target {
    pub fn new<S, T>(scope_id: S, task_id: T) -> miette::Result<Target>
    where
        S: AsRef<str>,
        T: AsRef<str>,
    {
        let scope_id = scope_id.as_ref();
        let task_id = task_id.as_ref();

        let handle_error = |_| TargetError::InvalidFormat(format!("{scope_id}:{task_id}"));
        let scope = TargetScope::Project(Id::new(scope_id).map_err(handle_error)?);

        Ok(Target {
            id: Target::format(&scope, task_id),
            scope,
            task_id: Id::new(task_id).map_err(handle_error)?,
        })
    }

    pub fn new_self<T>(task_id: T) -> miette::Result<Target>
    where
        T: AsRef<str>,
    {
        let task_id = task_id.as_ref();

        Ok(Target {
            id: Target::format(TargetScope::OwnSelf, task_id),
            scope: TargetScope::OwnSelf,
            task_id: Id::new(task_id)
                .map_err(|_| TargetError::InvalidFormat(format!("~:{task_id}")))?,
        })
    }

    pub fn format<S, T>(scope: S, task: T) -> String
    where
        S: AsRef<TargetScope>,
        T: AsRef<str>,
    {
        format!("{}:{}", scope.as_ref(), task.as_ref())
    }

    #[instrument(name = "parse_target")]
    pub fn parse(target_id: &str) -> miette::Result<Target> {
        if target_id == ":" {
            return Err(TargetError::TooWild.into());
        }

        if !target_id.contains(':') {
            return Target::new_self(target_id);
        }

        let Some(matches) = TARGET_PATTERN.captures(target_id) else {
            return Err(TargetError::InvalidFormat(target_id.to_owned()).into());
        };

        let scope = match matches.name("scope") {
            Some(value) => match value.as_str() {
                "" => TargetScope::All,
                "^" => TargetScope::Deps,
                "~" => TargetScope::OwnSelf,
                id => {
                    if let Some(tag) = id.strip_prefix('#') {
                        TargetScope::Tag(Id::raw(tag))
                    } else {
                        TargetScope::Project(Id::raw(id))
                    }
                }
            },
            None => TargetScope::All,
        };

        let task_id = Id::new(matches.name("task").unwrap().as_str())
            .map_err(|_| TargetError::InvalidFormat(target_id.to_owned()))?;

        Ok(Target {
            id: target_id.to_owned(),
            scope,
            task_id,
        })
    }

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

    pub fn is_all_task(&self, task_id: &str) -> bool {
        if matches!(&self.scope, TargetScope::All) {
            return if let Some(id) = task_id.strip_prefix(':') {
                self.task_id == id
            } else {
                self.task_id == task_id
            };
        }

        false
    }

    pub fn get_project_id(&self) -> Option<&Id> {
        match &self.scope {
            TargetScope::Project(id) => Some(id),
            _ => None,
        }
    }

    pub fn get_tag_id(&self) -> Option<&Id> {
        match &self.scope {
            TargetScope::Tag(id) => Some(id),
            _ => None,
        }
    }
}

impl Default for Target {
    fn default() -> Self {
        Target {
            id: "~:unknown".into(),
            scope: TargetScope::OwnSelf,
            task_id: Id::raw("unknown"),
        }
    }
}

impl Display for Target {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.id)
    }
}

impl AsRef<Target> for Target {
    fn as_ref(&self) -> &Target {
        self
    }
}

impl AsRef<str> for Target {
    fn as_ref(&self) -> &str {
        &self.id
    }
}

impl PartialOrd for Target {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for Target {
    fn cmp(&self, other: &Self) -> Ordering {
        self.id.cmp(&other.id)
    }
}

impl<'de> Deserialize<'de> for Target {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        Target::parse(&String::deserialize(deserializer)?).map_err(de::Error::custom)
    }
}

impl Serialize for Target {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&self.id)
    }
}

impl Schematic for Target {
    fn build_schema(mut schema: SchemaBuilder) -> Schema {
        schema.string_default()
    }
}

// This is only used by tests!

impl From<&str> for Target {
    fn from(value: &str) -> Self {
        Target::parse(value).unwrap()
    }
}