~matthiasbeyer/butido

ref: 1a6511b138c86dd1304555d9b1ddccf716aa7ce1 butido/src/main.rs -rw-r--r-- 8.8 KiB
1a6511b1Matthias Beyer Merge branch 'source-download-timeout' into next 1 year, 24 days ago
                                                                                
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
//
// 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
//

#![deny(
    anonymous_parameters,
    bad_style,
    const_err,
    dead_code,
    deprecated_in_future,
    explicit_outlives_requirements,
    improper_ctypes,
    keyword_idents,
    no_mangle_generic_items,
    non_ascii_idents,
    non_camel_case_types,
    non_shorthand_field_patterns,
    non_snake_case,
    overflowing_literals,
    path_statements,
    patterns_in_fns_without_body,
    private_in_public,
    trivial_numeric_casts,
    unconditional_recursion,
    unsafe_code,
    unstable_features,
    unused,
    unused_allocation,
    unused_comparisons,
    unused_crate_dependencies,
    unused_extern_crates,
    unused_import_braces,
    unused_imports,
    unused_must_use,
    unused_mut,
    unused_parens,
    while_true,
)]
#![allow(macro_use_extern_crate)]

extern crate log as logcrate;
#[macro_use]
extern crate diesel;
#[macro_use]
extern crate diesel_migrations;

use std::path::PathBuf;

use anyhow::anyhow;
use anyhow::Context;
use anyhow::Error;
use anyhow::Result;
use clap::ArgMatches;
use logcrate::debug;
use logcrate::error;
use rand as _; // Required to make lints happy
use aquamarine as _; // doc-helper crate
use funty as _; // doc-helper crate
use zeroize as _; // Required to make lints happy

mod cli;
mod commands;
mod config;
mod consts;
mod db;
mod endpoint;
mod filestore;
mod job;
mod log;
mod orchestrator;
mod package;
mod repository;
mod schema;
mod source;
mod ui;
mod util;

use crate::config::*;
use crate::repository::Repository;
use crate::util::progress::ProgressBars;

#[tokio::main]
async fn main() -> Result<()> {
    human_panic::setup_panic!(Metadata {
        name: env!("CARGO_PKG_NAME").into(),
        version: env!("CARGO_PKG_VERSION").into(),
        authors: "Matthias Beyer <matthias.beyer@atos.net>".into(),
        homepage: "atos.net/de/deutschland/sc".into(),
    });

    let _ = env_logger::try_init()?;
    debug!("Debugging enabled");

    let app = cli::cli();
    let cli = app.get_matches();

    let repo = git2::Repository::discover(PathBuf::from("."))
        .map_err(|e| match e.code() {
            git2::ErrorCode::NotFound => {
                eprintln!("Butido must be executed within the package repository");
                std::process::exit(1)
            },
            _ => Error::from(e),
        })?;

    let repo_path = repo
        .workdir()
        .ok_or_else(|| anyhow!("Not a repository with working directory. Cannot do my job!"))?;

    let mut config = ::config::Config::default();
    config.merge(::config::File::from(repo_path.join("config.toml")).required(true))
        .context("Failed to load config.toml from repository")?;

    {
        let xdg = xdg::BaseDirectories::with_prefix("butido")?;
        let xdg_config_file = xdg.find_config_file("config.toml");
        if let Some(xdg_config) = xdg_config_file {
            debug!("Configuration file found with XDG: {}", xdg_config.display());
            config.merge(::config::File::from(xdg_config).required(false))
                .context("Failed to load config.toml from XDG configuration directory")?;
        } else {
            debug!("No configuration file found with XDG: {}", xdg.get_config_home().display());
        }
    }

    config.merge(::config::Environment::with_prefix("BUTIDO"))?;

    let config = config.try_into::<NotValidatedConfiguration>()
        .context("Failed to load Configuration object")?
        .validate()
        .context("Failed to validate configuration")?;

    let hide_bars = cli.is_present("hide_bars") || crate::util::stdout_is_pipe();
    let progressbars = ProgressBars::setup(
        config.progress_format().clone(),
        config.spinner_format().clone(),
        hide_bars,
    );

    let load_repo = || -> Result<Repository> {
        let bar = progressbars.bar();
        let repo = Repository::load(repo_path, &bar)
            .context("Loading the repository")?;
        bar.finish_with_message("Repository loading finished");
        Ok(repo)
    };

    let db_connection_config = crate::db::DbConnectionConfig::parse(&config, &cli)?;
    match cli.subcommand() {
        Some(("generate-completions", matches)) => generate_completions(matches),
        Some(("db", matches)) => crate::commands::db(db_connection_config, &config, matches)?,
        Some(("build", matches)) => {
            let conn = db_connection_config.establish_connection()?;

            let repo = load_repo()?;

            crate::commands::build(
                repo_path,
                matches,
                progressbars,
                conn,
                &config,
                repo,
                repo_path,
            )
            .await
            .context("build command failed")?
        }
        Some(("what-depends", matches)) => {
            let repo = load_repo()?;
            crate::commands::what_depends(matches, &config, repo)
                .await
                .context("what-depends command failed")?
        }

        Some(("dependencies-of", matches)) => {
            let repo = load_repo()?;
            crate::commands::dependencies_of(matches, &config, repo)
                .await
                .context("dependencies-of command failed")?
        }

        Some(("versions-of", matches)) => {
            let repo = load_repo()?;
            crate::commands::versions_of(matches, repo)
                .await
                .context("versions-of command failed")?
        }

        Some(("env-of", matches)) => {
            let repo = load_repo()?;
            crate::commands::env_of(matches, repo)
                .await
                .context("env-of command failed")?
        }

        Some(("find-artifact", matches)) => {
            let repo = load_repo()?;
            let conn = db_connection_config.establish_connection()?;
            crate::commands::find_artifact(matches, &config, progressbars, repo, conn)
                .await
                .context("find-artifact command failed")?
        }

        Some(("find-pkg", matches)) => {
            let repo = load_repo()?;
            crate::commands::find_pkg(matches, &config, repo)
                .await
                .context("find-pkg command failed")?
        }

        Some(("source", matches)) => {
            let repo = load_repo()?;
            crate::commands::source(matches, &config, repo, progressbars)
                .await
                .context("source command failed")?
        }

        Some(("release", matches)) => {
            crate::commands::release(db_connection_config, &config, matches)
                .await
                .context("release command failed")?
        }

        Some(("lint", matches)) => {
            let repo = load_repo()?;
            crate::commands::lint(repo_path, matches, progressbars, &config, repo)
                .await
                .context("lint command failed")?
        }

        Some(("tree-of", matches)) => {
            let repo = load_repo()?;
            crate::commands::tree_of(matches, repo)
                .await
                .context("tree-of command failed")?
        }

        Some(("metrics", _)) => {
            let repo = load_repo()?;
            let conn = db_connection_config.establish_connection()?;
            crate::commands::metrics(repo_path, &config, repo, conn)
                .await
                .context("metrics command failed")?
        }

        Some(("endpoint", matches)) => {
            crate::commands::endpoint(matches, &config, progressbars)
                .await
                .context("endpoint command failed")?
        },
        Some((other, _)) => {
            error!("Unknown subcommand: {}", other);
            error!("Use --help to find available subcommands");
            return Err(anyhow!("Unknown subcommand: {}", other))
        },
        None => {
            error!("No subcommand.");
            error!("Use --help to find available subcommands");
            return Err(anyhow!("No subcommand"))
        },
    }

    Ok(())
}

fn generate_completions(matches: &ArgMatches) {
    use clap_generate::generate;
    use clap_generate::generators::{Bash, Elvish, Fish, Zsh};

    let appname = "butido";
    match matches.value_of("shell").unwrap() { // unwrap safe by clap
        "bash"   => generate::<Bash, _>(&mut cli::cli(), appname, &mut std::io::stdout()),
        "elvish" => generate::<Elvish, _>(&mut cli::cli(), appname, &mut std::io::stdout()),
        "fish"   => generate::<Fish, _>(&mut cli::cli(), appname, &mut std::io::stdout()),
        "zsh"    => generate::<Zsh, _>(&mut cli::cli(), appname, &mut std::io::stdout()),
        _ => unreachable!(),
    }
}