foreman 1.7.0

Toolchain manager for simple binary tools
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
mod aliaser;
mod artifact_choosing;
mod artifactory_auth_store;
mod artifactory_path;
mod auth_store;
mod ci_string;
mod config;
mod error;
mod fs;
mod paths;
mod process;
mod tool_cache;
mod tool_provider;

use std::{
    env,
    ffi::OsStr,
    io::{stdout, Write},
};

use artifactory_auth_store::ArtifactoryAuthStore;
use paths::ForemanPaths;
use structopt::StructOpt;

use crate::{
    aliaser::add_self_alias,
    auth_store::AuthStore,
    config::ConfigFile,
    error::{ForemanError, ForemanResult},
    tool_cache::ToolCache,
    tool_provider::ToolProvider,
};

#[derive(Debug)]
struct ToolInvocation {
    name: String,
    args: Vec<String>,
}

impl ToolInvocation {
    fn from_env() -> ForemanResult<Option<Self>> {
        let app_path = env::current_exe().map_err(|err| {
            ForemanError::io_error_with_context(err, "unable to obtain foreman executable location")
        })?;
        let name = if let Some(name) = app_path
            .file_stem()
            .and_then(OsStr::to_str)
            .map(ToOwned::to_owned)
        {
            name
        } else {
            return Ok(None);
        };

        // That's us!
        if name == "foreman" {
            return Ok(None);
        }

        let args = env::args().skip(1).collect();

        Ok(Some(Self { name, args }))
    }

    fn run(self, paths: &ForemanPaths) -> ForemanResult<()> {
        let config = ConfigFile::aggregate(paths)?;

        if let Some(tool_spec) = config.tools.get(&self.name) {
            log::debug!("Found tool spec {}", tool_spec);

            let mut tool_cache = ToolCache::load(paths)?;
            let providers = ToolProvider::new(paths);
            let version = tool_cache.download_if_necessary(tool_spec, &providers)?;

            let exit_code = tool_cache.run(tool_spec, &version, self.args)?;

            if exit_code != 0 {
                std::process::exit(exit_code);
            }

            Ok(())
        } else {
            let current_dir = env::current_dir().map_err(|err| {
                ForemanError::io_error_with_context(
                    err,
                    "unable to obtain the current working directory",
                )
            })?;
            Err(ForemanError::ToolNotInstalled {
                name: self.name,
                current_path: current_dir,
                config_file: config,
            })
        }
    }
}

fn main() {
    let paths = ForemanPaths::from_env().unwrap_or_default();

    if let Err(error) = paths.create_all() {
        exit_with_error(error);
    }

    let result = ToolInvocation::from_env().and_then(|maybe_invocation| {
        if let Some(invocation) = maybe_invocation {
            let env = env_logger::Env::new().default_filter_or("foreman=info");
            env_logger::Builder::from_env(env)
                .format_module_path(false)
                .format_timestamp(None)
                .format_indent(Some(8))
                .init();

            invocation.run(&paths)
        } else {
            actual_main(paths)
        }
    });

    if let Err(error) = result {
        exit_with_error(error);
    }
}

fn exit_with_error(error: ForemanError) -> ! {
    eprintln!("{}", error);
    std::process::exit(1);
}

#[derive(Debug, StructOpt)]
struct Options {
    /// Logging verbosity. Supply multiple for more verbosity, up to -vvv
    #[structopt(short, parse(from_occurrences), global = true)]
    pub verbose: u8,

    #[structopt(subcommand)]
    subcommand: Subcommand,
}

#[derive(Debug, StructOpt)]
enum Subcommand {
    /// Install tools defined by foreman.toml.
    Install,

    /// List installed tools.
    List,

    /// Set the GitHub Personal Access Token that Foreman should use with the
    /// GitHub API.
    ///
    /// This token can also be configured by editing ~/.foreman/auth.toml.
    #[structopt(name = "github-auth")]
    GitHubAuth(GitHubAuthCommand),

    /// Set the GitLab Personal Access Token that Foreman should use with the
    /// GitLab API.
    ///
    /// This token can also be configured by editing ~/.foreman/auth.toml.
    #[structopt(name = "gitlab-auth")]
    GitLabAuth(GitLabAuthCommand),

    /// Set the Artifactory Token that Foreman should use with the
    /// Artifactory API.
    #[structopt(name = "artifactory-auth")]
    ArtifactoryAuth(ArtifactoryAuthCommand),

    /// Manage tokens in the OS credential manager
    /// (macOS Keychain, Windows Credential Manager).
    #[structopt(name = "auth-secure")]
    AuthSecure(AuthSecureCommand),

    /// Create a path to publish to artifactory
    ///
    /// Foreman does not support uploading binaries to artifactory directly, but it can generate the path where it would expect to find a given artifact. Use this command to generate paths that can be input to generic artifactory upload solutions.
    #[structopt(name = "generate-artifactory-path")]
    GenerateArtifactoryPath(GenerateArtifactoryPathCommand),
}

#[derive(Debug, StructOpt)]
struct GitHubAuthCommand {
    /// GitHub personal access token that Foreman should use.
    ///
    /// If not specified, Foreman will prompt for it.
    token: Option<String>,
}

#[derive(Debug, StructOpt)]
struct GitLabAuthCommand {
    /// GitLab personal access token that Foreman should use.
    ///
    /// If not specified, Foreman will prompt for it.
    token: Option<String>,
}

#[derive(Debug, StructOpt)]
struct AuthSecureCommand {
    #[structopt(subcommand)]
    action: AuthSecureAction,
}

#[derive(Debug, StructOpt)]
enum AuthSecureAction {
    /// Store a token in the OS credential manager.
    ///
    /// Usage: foreman auth-secure add <github|gitlab> [token]
    Add(AuthSecureAddCommand),

    /// Remove a token from the OS credential manager.
    ///
    /// Usage: foreman auth-secure remove <github|gitlab>
    ///        foreman auth-secure remove --all
    Remove(AuthSecureRemoveCommand),

    /// Migrate tokens from auth.toml to the OS credential manager.
    Migrate,
}

#[derive(Debug, StructOpt)]
struct AuthSecureAddCommand {
    /// The provider: "github" or "gitlab".
    provider: String,

    /// Personal access token. If not specified, Foreman will prompt for it.
    token: Option<String>,
}

#[derive(Debug, StructOpt)]
struct AuthSecureRemoveCommand {
    /// The provider: "github" or "gitlab". Not required if --all is set.
    provider: Option<String>,

    /// Remove tokens for all providers.
    #[structopt(long)]
    all: bool,
}

#[derive(Debug, StructOpt)]
struct ArtifactoryAuthCommand {
    url: Option<String>,
    token: Option<String>,
}

#[derive(Debug, StructOpt)]
struct GenerateArtifactoryPathCommand {
    repo: String,
    tool_name: String,
    version: String,
    operating_system: String,
    architecture: Option<String>,
}

fn actual_main(paths: ForemanPaths) -> ForemanResult<()> {
    let options = Options::from_args();

    {
        let log_filter = match options.verbose {
            0 => "warn,foreman=info",
            1 => "info,foreman=debug",
            2 => "info,foreman=trace",
            _ => "trace",
        };

        let env = env_logger::Env::default().default_filter_or(log_filter);

        env_logger::Builder::from_env(env)
            .format_module_path(false)
            .format_target(false)
            .format_timestamp(None)
            .format_indent(Some(8))
            .init();
    }

    match options.subcommand {
        Subcommand::Install => {
            let config = ConfigFile::aggregate(&paths)?;

            log::trace!("Installing from gathered config: {:#?}", config);

            let mut cache = ToolCache::load(&paths)?;

            let providers = ToolProvider::new(&paths);

            let tools_not_downloaded: Vec<String> = config
                .tools
                .iter()
                .filter_map(|(tool_alias, tool_spec)| {
                    cache
                        .download_if_necessary(tool_spec, &providers)
                        .and_then(|_| add_self_alias(tool_alias, &paths.bin_dir()))
                        .err()
                        .map(|err| {
                            log::error!(
                                "The following error occurred while trying to download tool \"{}\":\n{}",
                                tool_alias,
                                err
                            );
                            tool_alias.to_string()
                        })
                })
                .collect();

            if !tools_not_downloaded.is_empty() {
                return Err(ForemanError::ToolsNotDownloaded {
                    tools: tools_not_downloaded,
                });
            }

            if config.tools.is_empty() {
                log::info!(
                    concat!(
                        "foreman did not find any tools to install.\n\n",
                        "You can define system-wide tools in:\n  {}\n",
                        "or create a 'foreman.toml' file in your project directory.",
                    ),
                    paths.user_config().display()
                );
            }
        }
        Subcommand::List => {
            println!("Installed tools:");

            let cache = ToolCache::load(&paths)?;

            for (tool_source, tool) in &cache.tools {
                println!("  {}", tool_source);

                for version in &tool.versions {
                    println!("    - {}", version);
                }
            }
        }
        Subcommand::GitHubAuth(subcommand) => {
            let token = prompt_auth_token(
                    subcommand.token,
                    "GitHub",
                    "https://help.github.com/en/github/authenticating-to-github/creating-a-personal-access-token-for-the-command-line",
                )?;

            AuthStore::set_github_token(&paths.auth_store(), &token)?;

            println!("GitHub auth saved successfully.");
        }
        Subcommand::GitLabAuth(subcommand) => {
            let token = prompt_auth_token(
                subcommand.token,
                "GitLab",
                "https://docs.gitlab.com/ee/user/profile/personal_access_tokens.html",
            )?;

            AuthStore::set_gitlab_token(&paths.auth_store(), &token)?;

            println!("GitLab auth saved successfully.");
        }
        Subcommand::AuthSecure(subcommand) => match subcommand.action {
            AuthSecureAction::Add(cmd) => {
                let (provider, help) = parse_provider(&cmd.provider)?;
                let token = prompt_auth_token(cmd.token, provider, help)?;
                AuthStore::set_token_secure(
                    &paths.auth_store(),
                    &cmd.provider.to_lowercase(),
                    &token,
                )?;
                println!("{} auth saved to OS credential manager.", provider);
            }
            AuthSecureAction::Remove(cmd) => {
                if cmd.all {
                    AuthStore::delete_all_tokens_secure()?;
                    println!("All tokens removed from OS credential manager.");
                } else if let Some(provider_str) = &cmd.provider {
                    let (provider, _) = parse_provider(provider_str)?;
                    AuthStore::delete_token_secure(&provider_str.to_lowercase())?;
                    println!("{} token removed from OS credential manager.", provider);
                } else {
                    return Err(ForemanError::io_error_with_context(
                        std::io::Error::new(std::io::ErrorKind::InvalidInput, ""),
                        "specify a provider (github or gitlab) or use --all",
                    ));
                }
            }
            AuthSecureAction::Migrate => {
                let (github, gitlab) = AuthStore::migrate_to_keyring(&paths.auth_store())?;
                if !github && !gitlab {
                    println!("No tokens found in auth.toml to migrate.");
                } else {
                    if github {
                        println!("Migrated GitHub token to OS credential manager.");
                    }
                    if gitlab {
                        println!("Migrated GitLab token to OS credential manager.");
                    }
                    println!("Tokens removed from auth.toml.");
                }
            }
        },
        Subcommand::GenerateArtifactoryPath(subcommand) => {
            let artifactory_path = artifactory_path::generate_artifactory_path(
                subcommand.repo,
                subcommand.tool_name,
                subcommand.version,
                subcommand.operating_system,
                subcommand.architecture,
            )?;
            println!("{}", artifactory_path);
        }
        Subcommand::ArtifactoryAuth(subcommand) => {
            let url = prompt_url(subcommand.url)?;

            let token = prompt_auth_token(
                subcommand.token,
                "Artifactory",
                "https://jfrog.com/help/r/jfrog-platform-administration-documentation/access-tokens",
            )?;

            ArtifactoryAuthStore::set_token(&paths.artiaa_path()?, &url, &token)?;
        }
    }

    Ok(())
}

fn prompt_url(url: Option<String>) -> Result<String, ForemanError> {
    match url {
        Some(url) => Ok(url),
        None => {
            println!("Artifactory auth saved successfully.");
            println!("Foreman requires a specific URL to authenticate to Artifactory.");
            println!();

            loop {
                let mut input = String::new();

                print!("Artifactory URL: ");
                stdout().flush().map_err(|err| {
                    ForemanError::io_error_with_context(
                        err,
                        "an error happened trying to flush stdout",
                    )
                })?;
                std::io::stdin().read_line(&mut input).map_err(|err| {
                    ForemanError::io_error_with_context(err, "an error happened trying to read url")
                })?;

                if input.is_empty() {
                    println!("Token must be non-empty.");
                } else {
                    break Ok(input);
                }
            }
        }
    }
}

fn parse_provider(provider: &str) -> Result<(&str, &str), ForemanError> {
    match provider.to_lowercase().as_str() {
        "github" => Ok((
            "GitHub",
            "https://help.github.com/en/github/authenticating-to-github/creating-a-personal-access-token-for-the-command-line",
        )),
        "gitlab" => Ok((
            "GitLab",
            "https://docs.gitlab.com/ee/user/profile/personal_access_tokens.html",
        )),
        other => Err(ForemanError::io_error_with_context(
            std::io::Error::new(std::io::ErrorKind::InvalidInput, ""),
            format!("unknown provider '{}'. Expected 'github' or 'gitlab'", other),
        )),
    }
}

fn prompt_auth_token(
    token: Option<String>,
    provider: &str,
    help: &str,
) -> Result<String, ForemanError> {
    match token {
        Some(token) => Ok(token),
        None => {
            println!("{} auth saved successfully.", provider);
            println!(
                "Foreman authenticates to {} using Personal Access Tokens.",
                provider
            );
            println!("{}", help);
            println!();

            loop {
                let token =
                    rpassword::prompt_password(format!("{} Token: ", provider)).map_err(|err| {
                        ForemanError::io_error_with_context(
                            err,
                            "an error happened trying to read password",
                        )
                    })?;

                if token.is_empty() {
                    println!("Token must be non-empty.");
                } else {
                    break Ok(token);
                }
            }
        }
    }
}