labt 0.1.0

Lab-t Lightweight Android build tool
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
use anyhow::Context;
use anyhow::Result;
use quick_xml::{events::Event, Reader};
use serde::Serialize;
use std::io::BufReader;
use std::io::Read;
use tokio::io::AsyncRead;

/// constants for common tags
mod tags {
    pub const ARTIFACT_ID: &[u8] = b"artifactId";
    pub const GROUP_ID: &[u8] = b"groupId";
    pub const VERSION: &[u8] = b"version";
    pub const DEPENDENCIES: &[u8] = b"dependencies";
    pub const PROJECT: &[u8] = b"project";
    pub const DEPENDENCY: &[u8] = b"dependency";
    pub const EXCLUSIONS: &[u8] = b"exclusions";
    pub const EXCLUSION: &[u8] = b"exclusion";
    pub const PACKAGING: &[u8] = b"packaging";
    pub const SCOPE: &[u8] = b"scope";
}

#[derive(Clone, Default, Debug, PartialEq, Eq, Serialize)]
pub enum Scope {
    #[default]
    COMPILE,
    TEST,
    RUNTIME,
    SYSTEM,
    PROVIDED,
    IMPORT,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Project {
    /// The actual project name
    artifact_id: String,
    /// The project version number
    version: String,
    /// The organization name/package name
    group_id: String,
    /// The project main dependencies
    dependencies: Vec<Project>,
    /// This module excludes
    excludes: Vec<Exclusion>,
    /// The scope of the project
    scope: Scope,
    /// The packaging of the project
    packaging: String,
}

#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Exclusion {
    /// The actual project name
    pub artifact_id: String,
    /// The organization name/package name
    pub group_id: String,
}
impl Exclusion {
    pub fn new(group_id: &str, artifact_id: &str) -> Self {
        Exclusion {
            artifact_id: artifact_id.to_string(),
            group_id: group_id.to_string(),
        }
    }
    pub fn qualified_name(&self) -> String {
        format!("{}:{}", self.group_id, self.artifact_id)
    }
}
impl Default for Project {
    fn default() -> Self {
        // FIXME remove these funny default and use ones provided by maven
        Project {
            artifact_id: "my_app".to_string(),
            version: "1.0.0".to_string(),
            group_id: "com.my_organization.name".to_string(),
            dependencies: vec![],
            excludes: vec![],
            scope: Scope::COMPILE,
            packaging: String::from("jar"),
        }
    }
}

impl Project {
    /// Initializes a new project with the provided arguments
    pub fn new(group_id: &str, artifact_id: &str, version: &str) -> Self {
        Project {
            group_id: String::from(group_id),
            artifact_id: String::from(artifact_id),
            version: String::from(version),
            ..Default::default()
        }
    }
    /// Returns the artifact id of the project
    pub fn get_artifact_id(&self) -> String {
        self.artifact_id.clone()
    }
    /// Returns the version of the project
    pub fn get_version(&self) -> String {
        self.version.clone()
    }
    /// Returns the group id of the project
    pub fn get_group_id(&self) -> String {
        self.group_id.clone()
    }
    /// Adds a dependency to this project
    pub fn add_dependency(&mut self, dep: Project) {
        self.dependencies.push(dep);
    }
    pub fn get_dependencies(&self) -> &Vec<Project> {
        &self.dependencies
    }
    pub fn get_dependencies_mut(&mut self) -> &mut Vec<Project> {
        &mut self.dependencies
    }
    pub fn qualified_name(&self) -> String {
        format!("{}:{}:{}", self.group_id, self.artifact_id, self.version)
    }
    pub fn get_excludes(&self) -> &Vec<Exclusion> {
        &self.excludes
    }
    pub fn add_exclusion(&mut self, exclude: Exclusion) {
        self.excludes.push(exclude);
    }
    pub fn get_scope(&self) -> Scope {
        self.scope.clone()
    }
    pub fn get_packaging(&self) -> String {
        self.packaging.clone()
    }
    pub fn set_packaging(&mut self, packaging: String) {
        self.packaging = packaging;
    }
}

/// Parser states, helps in keeping track of the current event
/// and its corresponding start and end tags
#[derive(Clone, Debug)]
enum ParserState {
    /// Root of the pom xml file
    /// <project></project>
    Project,
    /// The project artifactId/name
    /// <artifactId><)artifactId>
    ReadArtifactId,
    /// The project groupId/package name
    /// <groupId></groupId>
    ReadGroupId,
    /// The project version number
    /// <version></version>
    ReadVersion,
    /// Indicates that the state machine is handling a dependency
    /// <dependencies></dependencies>
    Dependencies(DependencyState),
    /// The packaging of this project
    /// <packaging></packaging>
    ReadPackaging,
}

/// Keeps track of the dependency specific events
#[derive(Clone, Debug)]
enum DependencyState {
    /// Root of the dependency tree
    /// <dependencies></dependencies>
    Dependencies,
    /// A single dependency node
    /// <dependency></dependency>
    Dependency,
    /// The Dependency artifactId/name
    /// <artifactId><)artifactId>
    ReadArtifactId,
    /// The Dependency groupId/package name
    /// <groupId></groupId>
    ReadGroupId,
    /// The Dependency version number
    /// <version></version>
    ReadVersion,
    /// The dependency exclusions
    /// <exclusions></exclusions>
    Exclusions(ExclusionsState),
    /// The scope
    /// <scope></scope>
    ReadScope,
}

/// Keeps track of the exclusions specific events
#[derive(Clone, Debug)]
enum ExclusionsState {
    /// The dependency exclusions
    /// <exclusions></exclusions>
    Exclusions,
    /// The dependency exclusion
    /// <exclusion></exclusion>
    Exclusion(Exclusion),
    /// The Dependency artifactId/name
    /// <artifactId><)artifactId>
    ReadArtifactId(Exclusion),
    /// The Dependency groupId/package name
    /// <groupId></groupId>
    ReadGroupId(Exclusion),
}

struct Parser {
    state: ParserState,
    project: Project,
    /// Used to keep track of a dependency while parsing xml
    current_dependency: Option<Project>,
}

impl Parser {
    /// Initializes a new project
    pub fn new(project: Project) -> Self {
        Parser {
            state: ParserState::Project,
            project,
            current_dependency: None,
        }
    }
    /// Filters through xml stream events matching through accepted dependency tags
    /// triggered when <dependencies></dependencies> tag is encountered
    fn parse_deps(&mut self, event: Event, state: DependencyState) -> Result<DependencyState> {
        let new_state = match state {
            DependencyState::Dependencies => match event {
                // check for dependencies
                Event::Start(tag) => match tag.local_name().into_inner() {
                    tags::DEPENDENCY => {
                        self.current_dependency = Some(Project::default());
                        DependencyState::Dependency
                    }
                    _ => DependencyState::Dependencies,
                },
                _ => DependencyState::Dependencies,
            },
            // <dependency> </dependency>
            DependencyState::Dependency => match event {
                Event::Start(tag) => match tag.local_name().into_inner() {
                    tags::ARTIFACT_ID => DependencyState::ReadArtifactId,
                    tags::GROUP_ID => DependencyState::ReadGroupId,
                    tags::VERSION => DependencyState::ReadVersion,
                    tags::EXCLUSIONS => DependencyState::Exclusions(ExclusionsState::Exclusions),
                    tags::SCOPE => DependencyState::ReadScope,
                    _ => DependencyState::Dependency,
                },
                Event::End(end) if end.local_name().into_inner() == tags::DEPENDENCY => {
                    // FIXME It doesn't feel correct that i had to clone this field
                    if let Some(dep) = self.current_dependency.clone() {
                        self.project.add_dependency(dep);
                        self.current_dependency = None;
                    }
                    DependencyState::Dependencies
                }
                _ => DependencyState::Dependency,
            },
            // <artifactId> </artifactId>
            DependencyState::ReadArtifactId => match event {
                Event::End(end) if end.local_name().into_inner() == tags::ARTIFACT_ID => {
                    DependencyState::Dependency
                }
                Event::Text(e) => {
                    if let Some(dep) = &mut self.current_dependency {
                        dep.artifact_id = e.unescape()?.to_string();
                    }
                    DependencyState::ReadArtifactId
                }
                _ => DependencyState::ReadArtifactId,
            },
            // <groupId></groupId>
            DependencyState::ReadGroupId => match event {
                Event::End(end) if end.local_name().into_inner() == tags::GROUP_ID => {
                    DependencyState::Dependency
                }

                Event::Text(e) => {
                    if let Some(dep) = &mut self.current_dependency {
                        dep.group_id = e.unescape()?.to_string();
                    }
                    DependencyState::ReadGroupId
                }
                _ => DependencyState::ReadGroupId,
            },
            // <version></version>
            DependencyState::ReadVersion => match event {
                Event::End(end) if end.local_name().into_inner() == tags::VERSION => {
                    DependencyState::Dependency
                }
                Event::Text(e) => {
                    if let Some(dep) = &mut self.current_dependency {
                        dep.version = e.unescape()?.to_string();
                    }
                    DependencyState::ReadVersion
                }
                _ => DependencyState::ReadVersion,
            },

            // <scope></scope>
            DependencyState::ReadScope => match event {
                Event::End(end) if end.local_name().into_inner() == tags::SCOPE => {
                    DependencyState::Dependency
                }
                Event::Text(e) => {
                    if let Some(dep) = &mut self.current_dependency {
                        let scope = e.unescape()?;
                        // FIXME fix this conversion from Cow<_, str> to str without
                        // unnecessary cloning
                        dep.scope = match scope.to_string().as_str() {
                            "compile" => Scope::COMPILE,
                            "test" => Scope::TEST,
                            "provided" => Scope::PROVIDED,
                            "import" => Scope::IMPORT,
                            "system" => Scope::SYSTEM,
                            "runtime" => Scope::RUNTIME,
                            _ => Scope::COMPILE,
                        }
                    }
                    DependencyState::ReadScope
                }
                _ => DependencyState::ReadScope,
            },

            // <exclusions></exclusions>
            DependencyState::Exclusions(exclu_state) => match event {
                Event::End(end) if end.local_name().into_inner() == tags::EXCLUSIONS => {
                    DependencyState::Dependency
                }
                event => DependencyState::Exclusions(self.parse_exclusions(event, exclu_state)?),
            },
        };
        Ok(new_state)
    }

    fn parse_exclusions(
        &mut self,
        event: Event,
        state: ExclusionsState,
    ) -> Result<ExclusionsState> {
        let new_state = match state {
            // <exclusions></exclusions>
            ExclusionsState::Exclusions => match event {
                Event::Start(start) => match start.local_name().into_inner() {
                    tags::EXCLUSION => ExclusionsState::Exclusion(Exclusion::default()),
                    _ => ExclusionsState::Exclusions,
                },
                _ => ExclusionsState::Exclusions,
            },

            // <exclusion></exclusion>
            ExclusionsState::Exclusion(exclusion) => match event {
                Event::End(end) if end.local_name().into_inner() == tags::EXCLUSION => {
                    if let Some(mut dependency) = self.current_dependency.clone() {
                        dependency.add_exclusion(exclusion);
                        self.current_dependency = Some(dependency);
                    }
                    ExclusionsState::Exclusions
                }
                Event::Start(start) => match start.local_name().into_inner() {
                    tags::ARTIFACT_ID => ExclusionsState::ReadArtifactId(exclusion),
                    tags::GROUP_ID => ExclusionsState::ReadGroupId(exclusion),
                    _ => ExclusionsState::Exclusion(exclusion),
                },
                _ => ExclusionsState::Exclusion(exclusion),
            },

            // <artifactId> </artifactId>
            ExclusionsState::ReadArtifactId(mut exclusion) => match event {
                Event::End(end) if end.local_name().into_inner() == tags::ARTIFACT_ID => {
                    ExclusionsState::Exclusion(exclusion)
                }
                Event::Text(e) => {
                    let artifact_id = e.unescape()?.to_string();
                    exclusion.artifact_id = artifact_id;
                    ExclusionsState::ReadArtifactId(exclusion)
                }
                _ => ExclusionsState::ReadArtifactId(exclusion),
            },

            // <groupId></groupId>
            ExclusionsState::ReadGroupId(mut exclusion) => match event {
                Event::End(end) if end.local_name().into_inner() == tags::GROUP_ID => {
                    ExclusionsState::Exclusion(exclusion)
                }
                Event::Text(e) => {
                    let group_id = e.unescape()?.to_string();
                    exclusion.group_id = group_id;
                    ExclusionsState::ReadGroupId(exclusion)
                }
                _ => ExclusionsState::ReadGroupId(exclusion),
            },
        };

        Ok(new_state)
    }

    /// Processes the xml stream events into its respective tags.
    /// The matched tags are used to update the state machine.
    pub fn process(&mut self, event: Event) -> Result<()> {
        self.state = match self.state.clone() {
            ParserState::Project => match event {
                // check for project level start tags
                Event::Start(tag) => match tag.local_name().into_inner() {
                    tags::PROJECT => ParserState::Project,
                    tags::DEPENDENCIES => ParserState::Dependencies(DependencyState::Dependencies),
                    tags::ARTIFACT_ID => ParserState::ReadArtifactId,
                    tags::GROUP_ID => ParserState::ReadGroupId,
                    tags::VERSION => ParserState::ReadVersion,
                    tags::PACKAGING => ParserState::ReadPackaging,
                    _ => ParserState::Project,
                },
                _ => ParserState::Project,
            },

            // <artifactId> </artifactId>
            ParserState::ReadArtifactId => match event {
                // exit the tag state
                Event::End(end) if end.local_name().into_inner() == tags::ARTIFACT_ID => {
                    ParserState::Project
                }
                Event::Text(e) => {
                    self.project.artifact_id = e.unescape()?.to_string();
                    ParserState::ReadArtifactId
                }
                _ => ParserState::ReadArtifactId,
            },

            // <groupId></groupId>
            ParserState::ReadGroupId => match event {
                Event::End(end) if end.local_name().into_inner() == tags::GROUP_ID => {
                    ParserState::Project
                }
                Event::Text(e) => {
                    self.project.group_id = e.unescape()?.to_string();
                    ParserState::ReadGroupId
                }
                _ => ParserState::ReadGroupId,
            },

            // <version></version>
            ParserState::ReadVersion => match event {
                Event::End(end) if end.local_name().into_inner() == tags::VERSION => {
                    ParserState::Project
                }
                Event::Text(e) => {
                    self.project.version = e.unescape()?.to_string();
                    ParserState::ReadVersion
                }
                _ => ParserState::ReadVersion,
            },
            ParserState::ReadPackaging => match event {
                Event::End(end) if end.local_name().into_inner() == tags::PACKAGING => {
                    ParserState::Project
                }
                Event::Text(e) => {
                    self.project.packaging = e.unescape()?.to_string();
                    ParserState::ReadPackaging
                }
                _ => ParserState::ReadPackaging,
            },

            // <dependencies></dependencies>
            ParserState::Dependencies(dep_state) => match event {
                Event::End(end) if end.local_name().into_inner() == tags::DEPENDENCIES => {
                    ParserState::Project
                }
                event => ParserState::Dependencies(self.parse_deps(event, dep_state)?),
            },
        };
        Ok(())
    }
    // pub fn get_project(&self) -> &Project {
    //     return &self.project;
    // }
}

/// Parses a pom xml file from a given stream and produces a Result
/// containing the Project object
pub fn parse_pom<R>(r: BufReader<R>, project: Project) -> anyhow::Result<Project>
where
    R: Read,
{
    let mut reader = Reader::from_reader(r);
    const BUFFER_SIZE: usize = 4096;
    let mut buf = Vec::with_capacity(BUFFER_SIZE);

    let mut parser = Parser::new(project);

    loop {
        match reader
            .read_event_into(&mut buf)
            .context("Reading xml events")?
        {
            Event::Eof => {
                break;
            }
            ev => parser.process(ev).context("Processing xml events")?,
        }
        buf.clear()
    }

    Ok(parser.project)
}

pub async fn parse_pom_async<R: AsyncRead + Unpin>(
    r: tokio::io::BufReader<R>,
    project: Project,
) -> anyhow::Result<Project> {
    let mut reader = Reader::from_reader(r);
    const BUFFER_SIZE: usize = 4096;
    let mut buf = Vec::with_capacity(BUFFER_SIZE);

    let mut parser = Parser::new(project);

    loop {
        match reader
            .read_event_into_async(&mut buf)
            .await
            .context("Reading xml events")?
        {
            Event::Eof => {
                break;
            }
            ev => parser.process(ev).context("Processing xml events")?,
        }
        buf.clear()
    }

    Ok(parser.project)
}
// su