summaryrefslogtreecommitdiffstats
path: root/src/commands/release.rs
blob: 40daf8eb500ed6d9a39464a2936d71a193417129 (plain)
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
//
// Copyright (c) 2020-2021 science+computing ag and other contributors
//
// This program and the accompanying materials are made
// available under the terms of the Eclipse Public License 2.0
// which is available at https://www.eclipse.org/legal/epl-2.0/
//
// SPDX-License-Identifier: EPL-2.0
//

use std::io::Write;
use std::path::PathBuf;

use anyhow::anyhow;
use anyhow::Error;
use anyhow::Result;
use clap::ArgMatches;
use diesel::prelude::*;
use log::{debug, info, trace};
use tokio_stream::StreamExt;

use crate::config::Configuration;
use crate::db::models as dbmodels;
use crate::db::DbConnectionConfig;

/// Implementation of the "release" subcommand
pub async fn release(
    db_connection_config: DbConnectionConfig,
    config: &Configuration,
    matches: &ArgMatches,
) -> Result<()> {
    match matches.subcommand() {
        Some(("new", matches))  => new_release(db_connection_config, config, matches).await,
        Some(("rm", matches))   => rm_release(db_connection_config, config, matches).await,
        Some((other, _matches)) => Err(anyhow!("Unknown subcommand: {}", other)),
        None => Err(anyhow!("Missing subcommand")),
    }
}


async fn new_release(
    db_connection_config: DbConnectionConfig,
    config: &Configuration,
    matches: &ArgMatches,
) -> Result<()> {
    let release_store_name = matches.value_of("release_store_name").unwrap(); // safe by clap
    if !(config.releases_directory().exists() && config.releases_directory().is_dir()) {
        return Err(anyhow!(
            "Release directory does not exist or does not point to directory: {}",
            config.releases_directory().display()
        ));
    }

    let pname = matches.value_of("package_name").map(String::from);

    let pvers = matches.value_of("package_version").map(String::from);

    debug!("Release called for: {:?} {:?}", pname, pvers);

    let conn = crate::db::establish_connection(db_connection_config)?;
    let submit_uuid = matches
        .value_of("submit_uuid")
        .map(uuid::Uuid::parse_str)
        .transpose()?
        .unwrap(); // safe by clap
    debug!("Release called for submit: {:?}", submit_uuid);

    let submit = crate::schema::submits::dsl::submits
        .filter(crate::schema::submits::dsl::uuid.eq(submit_uuid))
        .first::<dbmodels::Submit>(&conn)?;
    debug!("Found Submit: {:?}", submit_uuid);

    let arts = {
        let sel = crate::schema::artifacts::dsl::artifacts
            .inner_join(crate::schema::jobs::table.inner_join(crate::schema::packages::table))
            .filter(crate::schema::jobs::submit_id.eq(submit.id))
            .left_outer_join(crate::schema::releases::table) // not released
            .select(crate::schema::artifacts::all_columns);

        match (pname, pvers) {
            (Some(name), Some(vers)) => {
                let query = sel
                    .filter(crate::schema::packages::name.eq(name))
                    .filter(crate::schema::packages::version.like(vers));
                debug!(
                    "Query: {:?}",
                    diesel::debug_query::<diesel::pg::Pg, _>(&query)
                );
                query.load::<dbmodels::Artifact>(&conn)?
            }
            (Some(name), None) => {
                let query = sel.filter(crate::schema::packages::name.eq(name));
                debug!(
                    "Query: {:?}",
                    diesel::debug_query::<diesel::pg::Pg, _>(&query)
                );
                query.load::<dbmodels::Artifact>(&conn)?
            }
            (None, Some(vers)) => {
                let query = sel.filter(crate::schema::packages::version.like(vers));
                debug!(
                    "Query: {:?}",
                    diesel::debug_query::<diesel::pg::Pg, _>(&query)
                );
                query.load::<dbmodels::Artifact>(&conn)?
            }
            (None, None) => {
                debug!(
                    "Query: {:?}",
                    diesel::debug_query::<diesel::pg::Pg, _>(&sel)
                );
                sel.load::<dbmodels::Artifact>(&conn)?
            }
        }
    };
    debug!("Artifacts = {:?}", arts);

    arts.iter()
        .filter_map(|art| {
            art.path_buf()
                .parent()
                .map(|p| config.releases_directory().join(release_store_name).join(p))
        })
        .map(|p| async {
            debug!("mkdir {:?}", p);
            tokio::fs::create_dir_all(p).await.map_err(Error::from)
        })
        .collect::<futures::stream::FuturesUnordered<_>>()
        .collect::<Result<()>>()
        .await?;

    let staging_base: &PathBuf = &config.staging_directory().join(submit.uuid.to_string());

    let release_store = crate::db::models::ReleaseStore::create(&conn, release_store_name)?;
    let do_update = matches.is_present("package_do_update");
    let interactive = !matches.is_present("noninteractive");

    let now = chrono::offset::Local::now().naive_local();
    arts.into_iter()
        .map(|art| async move {
            let art_path = staging_base.join(&art.path);
            let dest_path = config.releases_directory().join(release_store_name).join(&art.path);
            debug!(
                "Trying to release {} to {}",
                art_path.display(),
                dest_path.display()
            );

            if !art_path.is_file() {
                trace!(
                    "Artifact does not exist as file, cannot release it: {:?}",
                    art
                );
                Err(anyhow!("Not a file: {}", art_path.display()))
            } else {
                if dest_path.exists() && !do_update {
                    return Err(anyhow!("Does already exist: {}", dest_path.display()));
                } else if dest_path.exists() && do_update {
                    writeln!(std::io::stderr(), "Going to update: {}", dest_path.display())?;
                    if interactive && !dialoguer::Confirm::new().with_prompt("Continue?").interact()? {
                        return Err(anyhow!("Does already exist: {} and update was denied", dest_path.display()));
                    }
                }

                // else !dest_path.exists()
                tokio::fs::rename(art_path, dest_path)
                    .await
                    .map_err(Error::from)
                    .map(|_| art)
            }
        })
        .collect::<futures::stream::FuturesUnordered<_>>()
        .collect::<Result<Vec<_>>>()
        .await?
        .into_iter()
        .try_for_each(|art| {
            debug!("Updating {:?} to set released = true", art);
            let rel = crate::db::models::Release::create(&conn, &art, &now, &release_store)?;
            debug!("Release object = {:?}", rel);
            Ok(())
        })
}

pub async fn rm_release(
    db_connection_config: DbConnectionConfig,
    config: &Configuration,
    matches: &ArgMatches,
) -> Result<()> {
    let release_store_name = matches.value_of("release_store_name").map(String::from).unwrap(); // safe by clap
    if !(config.releases_directory().exists() && config.releases_directory().is_dir()) {
        return Err(anyhow!(
            "Release directory does not exist or does not point to directory: {}",
            config.releases_directory().display()
        ));
    }
    if !config.release_stores().contains(&release_store_name) {
        return Err(anyhow!("Unknown release store name: {}", release_store_name))
    }

    let pname = matches.value_of("package_name").map(String::from).unwrap(); // safe by clap
    let pvers = matches.value_of("package_version").map(String::from).unwrap(); // safe by clap
    debug!("Remove Release called for: {:?} {:?}", pname, pvers);

    let conn = crate::db::establish_connection(db_connection_config)?;

    let (release, artifact) = crate::schema::jobs::table
        .inner_join(crate::schema::packages::table)
        .inner_join(crate::schema::artifacts::table)
        .inner_join(crate::schema::releases::table
            .on(crate::schema::releases::artifact_id.eq(crate::schema::artifacts::id)))
        .inner_join(crate::schema::release_stores::table
            .on(crate::schema::release_stores::id.eq(crate::schema::releases::release_store_id)))
        .filter(crate::schema::packages::dsl::name.eq(&pname)
            .and(crate::schema::packages::dsl::version.eq(&pvers)))
        .filter(crate::schema::release_stores::dsl::store_name.eq(&release_store_name))
        .order(crate::schema::releases::dsl::release_date.desc())
        .select((crate::schema