radicle-ci-broker 0.24.0

add integration to CI engins or systems to a Radicle node
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
// Implementations of Subplot scenario steps for the CI broker.

use std::{
    fs::{metadata, set_permissions},
    io::Write,
    os::unix::fs::PermissionsExt,
    path::{Path, PathBuf},
    process::Command,
    str::FromStr,
};

use radicle::{
    git::Oid,
    git::RefString,
    node::{Event, NodeId},
    prelude::RepoId,
    storage::RefUpdate,
};

use subplotlib::steplibrary::datadir::Datadir;
use subplotlib::steplibrary::runcmd::Runcmd;

#[derive(Debug, Default)]
struct SubplotContext {}

impl ContextElement for SubplotContext {}

#[step]
#[context(SubplotContext)]
#[context(Datadir)]
#[context(Runcmd)]
fn setup_node(context: &ScenarioContext, config: SubplotDataFile, adapter: SubplotDataFile) {
    // Install binaries.
    let target_path = bindir();
    println!("check CI broker binaries are in {}", target_path.display());
    assert!(target_path.join("cib").exists());
    assert!(target_path.join("cibtool").exists());
    assert!(target_path.join("synthetic-events").exists());
    context.with_mut(
        |context: &mut Runcmd| {
            context.prepend_to_path(target_path);
            Ok(())
        },
        false,
    )?;

    // Create configuration file.
    if let Some(parent) = config.name().parent() {
        if parent != Path::new("") {
            println!(
                "create directory for configuration file: {:?}",
                parent.display()
            );
            context.with_mut(
                |context: &mut Datadir| {
                    context.create_dir_all(parent)?;
                    Ok(())
                },
                false,
            )?;
        }
    }

    println!("write configuration file {}", config.name().display());
    context.with_mut(
        |context: &mut Datadir| {
            context
                .open_write(config.name())?
                .write_all(config.data())?;
            Ok(())
        },
        false,
    )?;

    // Create an executable adapter.
    if let Some(parent) = adapter.name().parent() {
        if parent != Path::new("") {
            println!("create directory for adapter: {}", parent.display());
            context.with_mut(
                |context: &mut Datadir| {
                    context.create_dir_all(parent)?;
                    Ok(())
                },
                false,
            )?;
        }
    }

    context.with_mut(
        |context: &mut Datadir| {
            // Unix mode bits for an executable file: read/write/exec for
            // owner, read/exec for group and others
            const EXECUTABLE: u32 = 0o755;

            println!("create env file");
            let home = context.canonicalise_filename(".")?;
            let home_str = home.display().to_string();

            let rad_home = context.canonicalise_filename(".radicle")?;
            let rad_home_str = rad_home.display().to_string();

            let envs = &[
                ("HOME", home_str.as_str()),
                ("RAD_HOME", rad_home_str.as_str()),
                ("RAD_PASSPHRASE", "secret"),
                ("RAD_SOCKET", "synt.sock"),
            ];
            {
                let mut file = context.open_write("env")?;
                for (k, v) in envs.iter() {
                    file.write_all(format!("export {k}='{v}'\n").as_bytes())?;
                }
            }

            println!("create env.sh script");
            {
                const SCRIPT: &str = r#"#!/bin/sh
echo "env.sh starts"
if [ -e env ]; then . ./env; fi
exec "$@"
"#;
                let mut file = context.open_write("env.sh")?;
                file.write_all(SCRIPT.as_bytes())?;
            }

            println!("make env.sh executable");
            let filename = context.canonicalise_filename("env.sh")?;
            let meta = metadata(&filename)?;
            let mut perm = meta.permissions();
            perm.set_mode(EXECUTABLE);
            set_permissions(&filename, perm)?;

            let filename = Path::new("adapter.sh");

            println!(
                "write adapter file {} from {}",
                filename.display(),
                adapter.name().display()
            );
            context.open_write(filename)?.write_all(adapter.data())?;

            println!("make {} executable", filename.display());
            let filename = context.canonicalise_filename("adapter.sh")?;
            let meta = metadata(&filename)?;
            let mut perm = meta.permissions();
            perm.set_mode(EXECUTABLE);
            set_permissions(&filename, perm)?;

            Ok(())
        },
        false,
    )?;

    // Create node by running "rad auth".

    context.with_mut(
        |context: &mut Datadir| {
            let home = context.canonicalise_filename(".")?;
            let rad_home = context.canonicalise_filename(".radicle")?;

            rad_in(
                &["auth", "--alias=brokertest"],
                &[
                    ("RAD_HOME", &rad_home.display().to_string()),
                    ("RAD_PASSPHRASE", "secret"),
                    ("RAD_SOCKET", "synt.sock"),
                ],
                &home,
            )?;

            Ok(())
        },
        false,
    )?;
}

#[step]
#[context(SubplotContext)]
#[context(Datadir)]
#[context(Runcmd)]
fn create_repo(context: &ScenarioContext, name: &str) {
    // Create a Git repository and add it to the Radicle node.
    context.with_mut(
        |context: &mut Datadir| {
            let home = context.canonicalise_filename(".")?;
            let home_str = home.display().to_string();

            let rad_home = context.canonicalise_filename(".radicle")?;
            let rad_home_str = rad_home.display().to_string();

            let envs = &[
                ("HOME", home_str.as_str()),
                ("RAD_HOME", rad_home_str.as_str()),
                ("RAD_PASSPHRASE", "secret"),
                ("RAD_SOCKET", "synt.sock"),
            ];

            git_in(
                &["config", "--global", "user.email", "radicle@example.com"],
                envs,
                &home,
            )?;

            git_in(
                &["config", "--global", "user.name", "TestyMcTestFace"],
                envs,
                &home,
            )?;

            git_in(&["init", "-b", "main", name], envs, &home)?;

            {
                let filename = Path::new(name).join("file.dat");
                let mut file = context.open_write(filename)?;
                file.write_all(b"hello, world")?;
            }

            let repodir = context.canonicalise_filename(name)?;
            git_in(&["add", "."], envs, &repodir)?;
            git_in(&["commit", "-am", "test"], envs, &repodir)?;

            rad_in(
                &[
                    "init",
                    "--name",
                    name,
                    "--description=test",
                    "--default-branch=main",
                    "--private",
                    "--no-confirm",
                    "--no-seed",
                ],
                envs,
                &repodir,
            )?;

            // rad init --name testy --description test --default-branch main --private --no-confirm --no-seed
            // rad inspect --identity
            // rad id list

            Ok(())
        },
        false,
    )?;
}

fn rad_in(args: &[&str], envs: &[(&str, &str)], cwd: &Path) -> Result<(), std::io::Error> {
    run_in("rad", args, envs, cwd)
}

fn git_in(args: &[&str], envs: &[(&str, &str)], cwd: &Path) -> Result<(), std::io::Error> {
    run_in("git", args, envs, cwd)
}

fn run_in(
    argv0: &str,
    args: &[&str],
    envs: &[(&str, &str)],
    cwd: &Path,
) -> Result<(), std::io::Error> {
    println!("running command {argv0} {args:?}");
    println!("envs: {envs:?}");
    println!("cwd: {cwd:?}; exists? {}", cwd.exists());

    let output = Command::new(argv0)
        .args(args)
        .envs(envs.iter().copied())
        .current_dir(cwd)
        .output()?;
    println!("{argv0} exit code: {:?}", output.status.code());
    println!(
        "{argv0}: stdout:\n{}\n====================",
        String::from_utf8_lossy(&output.stdout)
    );
    println!(
        "{argv0}: stderr:\n{}\n=====================",
        String::from_utf8_lossy(&output.stderr)
    );
    if !output.status.success() {
        panic!("command failed");
    }
    Ok(())
}

#[step]
#[context(SubplotContext)]
#[context(Datadir)]
#[context(Runcmd)]
fn add_event_file(context: &ScenarioContext, repodir: &Path) {
    // Write embedded file to "event.json". We only need one, at least for now.

    context.with_mut(
        |datadir: &mut Datadir| {
            let rad_home = datadir.canonicalise_filename(".radicle")?;
            println!("rad_home: {rad_home:#?}");

            let nid = nid(&rad_home)?;
            println!("nid: {nid:#?}");

            let repodir = datadir.canonicalise_filename(repodir)?;
            let rid = rid(&rad_home, &repodir)?;
            println!("rid: {rid:#?}");

            let head = head(&rad_home, &repodir)?;

            let node_event = Event::RefsFetched {
                remote: nid,
                rid,
                updated: vec![RefUpdate::Updated {
                    name: RefString::try_from(
                        format!("refs/namespaces/{nid}/refs/heads/main").as_str(),
                    )?,
                    old: head,
                    new: head,
                }],
            };

            println!("node_event: {node_event:#?}");
            let node_event = serde_json::to_string(&node_event)?;

            let event_json = Path::new("event.json");
            let filename = datadir.canonicalise_filename(event_json)?;
            assert!(!filename.exists());

            let mut file = datadir.open_write(event_json)?;
            file.write_all(node_event.as_bytes())?;
            Ok(())
        },
        false,
    )?;
}

fn nid(rad_home: &Path) -> Result<NodeId, Box<dyn std::error::Error>> {
    let output = Command::new("rad")
        .arg("self")
        .arg("--nid")
        .env("RAD_HOME", rad_home.display().to_string().as_str())
        .output()?;
    if !output.status.success() {
        panic!("rad self --nid failed");
    }

    Ok(NodeId::from_str(
        String::from_utf8_lossy(&output.stdout).to_string().trim(),
    )?)
}

fn rid(rad_home: &Path, repo: &Path) -> Result<RepoId, Box<dyn std::error::Error>> {
    let output = Command::new("rad")
        .arg(".")
        .env("RAD_HOME", rad_home.display().to_string().as_str())
        .current_dir(repo)
        .output()?;
    if !output.status.success() {
        panic!("rad . failed");
    }

    Ok(RepoId::from_str(
        String::from_utf8_lossy(&output.stdout).to_string().trim(),
    )?)
}

fn head(rad_home: &Path, repo: &Path) -> Result<Oid, Box<dyn std::error::Error>> {
    let output = Command::new("git")
        .arg("rev-parse")
        .arg("HEAD")
        .env("RAD_HOME", rad_home.display().to_string().as_str())
        .current_dir(repo)
        .output()?;
    if !output.status.success() {
        panic!("git rev-parse HEAD failed");
    }

    Ok(Oid::from_str(
        String::from_utf8_lossy(&output.stdout).to_string().trim(),
    )?)
}

fn bindir() -> PathBuf {
    let path = if let Ok(target) = std::env::var("CARGO_TARGET_DIR") {
        Path::new(&target).join("debug")
    } else {
        PathBuf::from("target/debug")
    };
    path.canonicalize().unwrap()
}

#[step]
#[context(SubplotContext)]
#[context(Runcmd)]
fn stdout_has_one_line(runcmd: &Runcmd) {
    let linecount = runcmd.stdout_as_string().lines().count();
    if linecount != 1 {
        throw!(format!("stdout had {linecount} lines, expected 1"));
    }
}

#[step]
#[context(SubplotContext)]
#[context(Runcmd)]
fn stdout_has_n_lines_containing(runcmd: &Runcmd, n: usize, text: &str) {
    let linecount = runcmd
        .stdout_as_string()
        .lines()
        .filter(|line| line.contains(text))
        .count();
    if linecount != n {
        throw!(format!("stdout had {linecount} lines, expected {n}"));
    }
}

#[step]
#[context(SubplotContext)]
#[context(Runcmd)]
fn stdout_is_empty(runcmd: &Runcmd) {
    let stdout = runcmd.stdout_as_string();
    if !stdout.is_empty() {
        throw!(format!(
            "expected stdout to be empty, is actually {stdout:?}"
        ));
    }
}