buildkite_workflow_lib/
workflow.rs

1use crate::buildkite_api::BuildkiteAPI;
2use crate::database::models::Pipeline;
3use crate::database::DbContext;
4use crate::errors::Error;
5use alfred::Item;
6
7pub struct Workflow<'a> {
8    api_key: &'a str,
9    db: DbContext,
10}
11
12impl<'a> Workflow<'a> {
13    /// Create a new Workflow
14    ///
15    /// # Errors
16    ///
17    /// Will return `Err` if database connection fails.
18    ///
19    #[inline]
20    pub fn new(api_key: &'a str, database_url: &str) -> Result<Self, Error> {
21        let db = DbContext::new(database_url)?;
22        Ok(Workflow { api_key, db })
23    }
24
25    /// Refreshes DB with all Buildkite information.
26    ///
27    /// # Errors
28    ///
29    /// Will return `Err` if database connection fails or hitting the `Buildkite` API fails
30    ///
31    #[inline]
32    pub fn refresh_cache(&mut self) -> Result<(), Error> {
33        self.db.run_migrations()?;
34        let api = BuildkiteAPI::new(self.api_key);
35        self.db.delete_pipelines()?;
36        for organizations in api.get_organizations_paginated() {
37            for org in organizations? {
38                for pipelines in api.get_pipelines_paginated(&org.slug) {
39                    let pl = pipelines?
40                        .into_iter()
41                        .map(|p| Pipeline {
42                            url: format!("https://buildkite.com/{}/{}", &org.slug, &p.name),
43                            unique_name: format!("{}/{}", &org.slug, &p.name),
44                            name: p.name,
45                        })
46                        .collect::<Vec<Pipeline>>();
47                    self.db.insert_pipelines(&pl)?;
48                }
49            }
50        }
51        // and DB cleanup work
52        self.db.optimize()?;
53        Ok(())
54    }
55
56    /// Queries the stored information using the given query.
57    ///
58    /// # Errors
59    ///
60    /// Will return `Err` if database connection fails.
61    ///
62    #[inline]
63    pub fn query<'items>(&self, repo_name: &[String]) -> Result<Vec<Item<'items>>, Error> {
64        self.db
65            .find_pipelines(repo_name, 10)?
66            .into_iter()
67            .map(|repo| {
68                Ok(alfred::ItemBuilder::new(repo.unique_name)
69                    .subtitle(repo.name.clone())
70                    .autocomplete(repo.name)
71                    .arg(format!("open {}", repo.url))
72                    .into_item())
73            })
74            .collect::<Result<Vec<_>, _>>()
75    }
76}