blue-build 0.9.35

A CLI tool built for creating Containerfile templates for ostree based atomic distros
Documentation
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
use std::{
    env,
    fmt::{Display, Write as FmtWrite},
    fs::{self, OpenOptions},
    io::{BufWriter, Write as IoWrite},
    path::PathBuf,
    str::FromStr,
};

use blue_build_process_management::drivers::{
    CiDriver, Driver, DriverArgs, GitlabDriver, SigningDriver, opts::GenerateKeyPairOpts,
};
use blue_build_template::{GitlabCiTemplate, InitReadmeTemplate, Template};
use blue_build_utils::constants::{COSIGN_PUB_PATH, RECIPE_FILE, RECIPE_PATH, TEMPLATE_REPO_URL};
use bon::Builder;
use clap::{Args, ValueEnum, crate_version};
use comlexr::cmd;
use log::{debug, info, trace};
use miette::{Context, IntoDiagnostic, Report, Result, bail, miette};
use requestty::{Answer, Answers, OnEsc, questions};
use semver::Version;

use crate::commands::BlueBuildCommand;

#[derive(Debug, Default, Clone, Copy, ValueEnum)]
pub enum CiProvider {
    #[default]
    Github,
    Gitlab,
    None,
}

impl CiProvider {
    fn default_ci_file_path(self) -> std::path::PathBuf {
        match self {
            Self::Gitlab => GitlabDriver::default_ci_file_path(),
            Self::None | Self::Github => unimplemented!(),
        }
    }

    fn render_file(self) -> Result<String> {
        match self {
            Self::Gitlab => GitlabCiTemplate::builder()
                .version({
                    let version = crate_version!();
                    let version: Version = version.parse().into_diagnostic()?;

                    format!("v{}.{}", version.major, version.minor)
                })
                .build()
                .render()
                .into_diagnostic(),
            Self::None | Self::Github => unimplemented!(),
        }
    }
}

impl TryFrom<&str> for CiProvider {
    type Error = Report;

    fn try_from(value: &str) -> std::result::Result<Self, Self::Error> {
        Ok(match value {
            "Gitlab" => Self::Gitlab,
            "Github" => Self::Github,
            "None" => Self::None,
            _ => bail!("Unable to parse for CiProvider"),
        })
    }
}

impl TryFrom<&String> for CiProvider {
    type Error = Report;

    fn try_from(value: &String) -> std::result::Result<Self, Self::Error> {
        Self::try_from(value.as_str())
    }
}

impl FromStr for CiProvider {
    type Err = Report;

    fn from_str(s: &str) -> std::prelude::v1::Result<Self, Self::Err> {
        Self::try_from(s)
    }
}

impl Display for CiProvider {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}",
            match *self {
                Self::Github => "Github",
                Self::Gitlab => "Gitlab",
                Self::None => "None",
            }
        )
    }
}

#[derive(Debug, Clone, Default, Args, Builder)]
#[builder(on(String, into))]
pub struct NewInitCommon {
    /// The name of the image for the recipe.
    #[arg(long)]
    image_name: Option<String>,

    /// The name of the org where your repo will be located.
    /// This could end up being your username.
    #[arg(long)]
    org_name: Option<String>,

    /// Optional description for the GitHub repository.
    #[arg(long)]
    description: Option<String>,

    /// The registry to store the image.
    #[arg(long)]
    registry: Option<String>,

    /// The CI provider that will be building the image.
    ///
    /// GitHub Actions and Gitlab CI are currently the
    /// officially supported CI providers.
    #[arg(long, short)]
    ci_provider: Option<CiProvider>,

    /// Disable setting up git.
    #[arg(long)]
    no_git: bool,

    #[clap(flatten)]
    #[builder(default)]
    drivers: DriverArgs,
}

#[derive(Debug, Clone, Args, Builder)]
pub struct NewCommand {
    #[arg()]
    dir: PathBuf,

    #[clap(flatten)]
    common: NewInitCommon,
}

impl BlueBuildCommand for NewCommand {
    fn try_run(&mut self) -> Result<()> {
        InitCommand::builder()
            .dir(self.dir.clone())
            .common(self.common.clone())
            .build()
            .try_run()
    }
}

#[derive(Debug, Clone, Args, Builder)]
pub struct InitCommand {
    #[clap(skip)]
    #[builder(into)]
    dir: Option<PathBuf>,

    #[clap(flatten)]
    common: NewInitCommon,
}

impl BlueBuildCommand for InitCommand {
    fn try_run(&mut self) -> Result<()> {
        Driver::init(self.common.drivers);

        let base_dir = self
            .dir
            .get_or_insert(env::current_dir().into_diagnostic()?);

        if base_dir.exists() && fs::read_dir(base_dir).is_ok_and(|dir| dir.count() != 0) {
            bail!("Must be in an empty directory!");
        }

        self.start(&self.questions()?)
    }
}

macro_rules! when {
    ($check:expr) => {
        |_answers: &::requestty::Answers| $check
    };
}

impl InitCommand {
    const CI_PROVIDER: &str = "ci_provider";
    const REGISTRY: &str = "registry";
    const IMAGE_NAME: &str = "image_name";
    const ORG_NAME: &str = "org_name";
    const DESCRIPTION: &str = "description";

    fn questions(&self) -> Result<Answers> {
        let questions = questions![
            Input {
                name: Self::IMAGE_NAME,
                message: "What would you like to name your image?",
                when: when!(self.common.image_name.is_none()),
                on_esc: OnEsc::Terminate,
            },
            Input {
                name: Self::REGISTRY,
                message: "What is the registry for the image? (e.g. ghcr.io or registry.gitlab.com)",
                when: when!(self.common.registry.is_none()),
                on_esc: OnEsc::Terminate,
            },
            Input {
                name: Self::ORG_NAME,
                message: "What is the name of your org/username?",
                when: when!(self.common.org_name.is_none()),
                on_esc: OnEsc::Terminate,
            },
            Input {
                name: Self::DESCRIPTION,
                message: "Write a short description of your image:",
                when: when!(self.common.description.is_none()),
                on_esc: OnEsc::Terminate,
            },
            Select {
                name: Self::CI_PROVIDER,
                message: "Are you building on Github or Gitlab?",
                when: when!(!self.common.no_git && self.common.ci_provider.is_none()),
                on_esc: OnEsc::Terminate,
                choices: vec!["Github", "Gitlab", "None"],
            }
        ];

        requestty::prompt(questions).into_diagnostic()
    }

    fn start(&self, answers: &Answers) -> Result<()> {
        self.clone_repository()?;
        self.remove_git_directory()?;
        self.template_readme(answers)?;
        self.template_ci_file(answers)?;
        self.update_recipe_file(answers)?;
        self.generate_signing_files()?;

        if !self.common.no_git {
            self.initialize_git()?;
            self.add_files()?;
            self.initial_commit()?;
        }

        info!(
            "Created new BlueBuild project in {}",
            self.dir.as_ref().unwrap().display()
        );

        Ok(())
    }

    fn clone_repository(&self) -> Result<()> {
        let dir = self.dir.as_ref().unwrap();
        trace!("clone_repository()");

        let mut command = cmd!("git", "clone", "-q", TEMPLATE_REPO_URL, dir);
        trace!("{command:?}");

        let status = command
            .status()
            .into_diagnostic()
            .context("Failed to execute git clone")?;

        if !status.success() {
            bail!("Failed to clone template repo");
        }

        Ok(())
    }

    fn remove_git_directory(&self) -> Result<()> {
        trace!("remove_git_directory()");

        let dir = self.dir.as_ref().unwrap();
        let git_path = dir.join(".git");

        if git_path.exists() {
            fs::remove_dir_all(&git_path)
                .into_diagnostic()
                .context("Failed to remove .git directory")?;
            debug!(".git directory removed.");
        }
        Ok(())
    }

    fn initialize_git(&self) -> Result<()> {
        trace!("initialize_git()");

        let dir = self.dir.as_ref().unwrap();

        let mut command = cmd!("git", "init", "-q", "-b", "main", dir);
        trace!("{command:?}");

        let status = command
            .status()
            .into_diagnostic()
            .context("Failed to execute git init")?;

        if !status.success() {
            bail!("Error initializing git");
        }

        debug!("Initialized git in {}", dir.display());

        Ok(())
    }

    fn initial_commit(&self) -> Result<()> {
        trace!("initial_commit()");

        let dir = self.dir.as_ref().unwrap();

        let mut command = cmd!(cd dir; "git", "commit", "-a", "-m", "chore: Initial Commit");
        trace!("{command:?}");

        let status = command
            .status()
            .into_diagnostic()
            .context("Failed to run git commit")?;

        if !status.success() {
            bail!("Failed to commit initial changes");
        }

        debug!("Created initial commit");

        Ok(())
    }

    fn add_files(&self) -> Result<()> {
        trace!("add_files()");

        let dir = self.dir.as_ref().unwrap();

        let mut command = cmd!(cd dir; "git", "add", ".");
        trace!("{command:?}");

        let status = command
            .status()
            .into_diagnostic()
            .context("Failed to run git add")?;

        if !status.success() {
            bail!("Failed to add files to initial commit");
        }

        debug!("Added files for initial commit");

        Ok(())
    }

    fn template_readme(&self, answers: &Answers) -> Result<()> {
        trace!("template_readme()");

        let readme_path = self.dir.as_ref().unwrap().join("README.md");

        let readme = InitReadmeTemplate::builder()
            .repo_name(
                self.common
                    .org_name
                    .as_deref()
                    .or_else(|| answers.get(Self::ORG_NAME).and_then(Answer::as_string))
                    .ok_or_else(|| miette!("Failed to get organization name"))?,
            )
            .image_name(
                self.common
                    .image_name
                    .as_deref()
                    .or_else(|| answers.get(Self::IMAGE_NAME).and_then(Answer::as_string))
                    .ok_or_else(|| miette!("Failed to get image name"))?,
            )
            .registry(
                self.common
                    .registry
                    .as_deref()
                    .or_else(|| answers.get(Self::REGISTRY).and_then(Answer::as_string))
                    .ok_or_else(|| miette!("Failed to get registry"))?,
            )
            .build();

        debug!("Templating README");
        let readme = readme.render().into_diagnostic()?;

        debug!("Writing README to {}", readme_path.display());
        fs::write(readme_path, readme).into_diagnostic()
    }

    fn template_ci_file(&self, answers: &Answers) -> Result<()> {
        trace!("template_ci_file()");

        let ci_provider = self
            .common
            .ci_provider
            .ok_or("CLI Arg not set")
            .or_else(|e| {
                answers
                    .get(Self::CI_PROVIDER)
                    .and_then(Answer::as_list_item)
                    .map(|li| &li.text)
                    .ok_or_else(|| miette!("Failed to get CI Provider answer:\n{e}"))
                    .and_then(CiProvider::try_from)
            })?;

        if matches!(ci_provider, CiProvider::Github) {
            fs::remove_file(self.dir.as_ref().unwrap().join(".github/CODEOWNERS"))
                .into_diagnostic()?;
            return Ok(());
        }

        fs::remove_dir_all(self.dir.as_ref().unwrap().join(".github")).into_diagnostic()?;

        // Never run for None
        if matches!(ci_provider, CiProvider::None) {
            return Ok(());
        }

        let ci_file_path = self
            .dir
            .as_ref()
            .unwrap()
            .join(ci_provider.default_ci_file_path());
        let parent_path = ci_file_path
            .parent()
            .ok_or_else(|| miette!("Couldn't get parent directory from {ci_file_path:?}"))?;
        fs::create_dir_all(parent_path)
            .into_diagnostic()
            .with_context(|| format!("Couldn't create directory path {}", parent_path.display()))?;

        let file = &mut BufWriter::new(
            OpenOptions::new()
                .truncate(true)
                .create(true)
                .write(true)
                .open(&ci_file_path)
                .into_diagnostic()
                .with_context(|| format!("Failed to open file at {}", ci_file_path.display()))?,
        );

        let template = ci_provider.render_file()?;

        writeln!(file, "{template}")
            .into_diagnostic()
            .with_context(|| format!("Failed to write CI file {}", ci_file_path.display()))
    }

    fn update_recipe_file(&self, answers: &Answers) -> Result<()> {
        trace!("update_recipe_file()");

        let recipe_path = self
            .dir
            .as_ref()
            .unwrap()
            .join(RECIPE_PATH)
            .join(RECIPE_FILE);

        debug!("Reading {}", recipe_path.display());
        let file = fs::read_to_string(&recipe_path)
            .into_diagnostic()
            .with_context(|| format!("Failed to read {}", recipe_path.display()))?;

        let description = self
            .common
            .description
            .as_deref()
            .ok_or("Description arg not set")
            .or_else(|e| {
                answers
                    .get(Self::DESCRIPTION)
                    .and_then(Answer::as_string)
                    .ok_or_else(|| miette!("Failed to get description:\n{e}"))
            })?;
        let name = self
            .common
            .image_name
            .as_deref()
            .ok_or("Description arg not set")
            .or_else(|e| {
                answers
                    .get(Self::IMAGE_NAME)
                    .and_then(Answer::as_string)
                    .ok_or_else(|| miette!("Failed to get description:\n{e}"))
            })?;

        let mut new_file_str = String::with_capacity(file.capacity());

        for line in file.lines() {
            if line.starts_with("description:") {
                writeln!(&mut new_file_str, "description: {description}").into_diagnostic()?;
            } else if line.starts_with("name: ") {
                writeln!(&mut new_file_str, "name: {name}").into_diagnostic()?;
            } else {
                writeln!(&mut new_file_str, "{line}").into_diagnostic()?;
            }
        }

        let file = &mut BufWriter::new(
            OpenOptions::new()
                .truncate(true)
                .write(true)
                .open(&recipe_path)
                .into_diagnostic()
                .with_context(|| format!("Failed to open {}", recipe_path.display()))?,
        );
        write!(file, "{new_file_str}")
            .into_diagnostic()
            .with_context(|| format!("Failed to write to file {}", recipe_path.display()))
    }

    fn generate_signing_files(&self) -> Result<()> {
        trace!("generate_signing_files()");

        debug!("Removing old cosign files {COSIGN_PUB_PATH}");
        fs::remove_file(self.dir.as_ref().unwrap().join(COSIGN_PUB_PATH))
            .into_diagnostic()
            .with_context(|| format!("Failed to delete old public file {COSIGN_PUB_PATH}"))?;

        Driver::generate_key_pair(
            GenerateKeyPairOpts::builder()
                .maybe_dir(self.dir.as_deref())
                .build(),
        )
    }
}