nixpacks 0.2.13

Generate an OCI compliant image based off app source
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
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
use anyhow::Context;
use nixpacks::{
    create_docker_image,
    nixpacks::{
        builder::docker::DockerBuilderOptions, environment::EnvironmentVariables, nix::pkg::Pkg,
        plan::generator::GeneratePlanOptions,
    },
};
use std::io::{BufRead, BufReader};
use std::process::{Command, Stdio};
use std::time::Duration;
use uuid::Uuid;
use wait_timeout::ChildExt;

fn get_container_ids_from_image(image: String) -> String {
    let output = Command::new("docker")
        .arg("ps")
        .arg("-a")
        .arg("-q")
        .arg("--filter")
        .arg(format!("ancestor={}", image))
        .output()
        .expect("failed to execute docker ps");

    String::from_utf8_lossy(&output.stdout).to_string()
}

fn stop_containers(container_id: &str) {
    Command::new("docker")
        .arg("stop")
        .arg(container_id)
        .spawn()
        .unwrap()
        .wait()
        .context("Stopping container")
        .unwrap();
}

fn remove_containers(container_id: &str) {
    Command::new("docker")
        .arg("rm")
        .arg(container_id)
        .spawn()
        .unwrap()
        .wait()
        .context("Removing container")
        .unwrap();
}

fn stop_and_remove_container_by_image(image: String) {
    let container_ids = get_container_ids_from_image(image);
    let container_id = container_ids.trim().split('\n').collect::<Vec<_>>()[0].to_string();

    stop_and_remove_container(container_id);
}

fn stop_and_remove_container(name: String) {
    stop_containers(&name);
    remove_containers(&name);
}

struct Config {
    environment_variables: EnvironmentVariables,
    network: Option<String>,
}
/// Runs an image with Docker and returns the output
/// The image is automatically stopped and removed after `TIMEOUT_SECONDS`
fn run_image(name: String, cfg: Option<Config>) -> String {
    let mut cmd = Command::new("docker");
    cmd.arg("run");

    if let Some(config) = cfg {
        for (key, value) in config.environment_variables {
            // arg must be processed as str or else we get extra quotes
            let arg = format!("{}={}", key, value);
            cmd.arg("-e").arg(arg);
        }
        if let Some(network) = config.network {
            cmd.arg("--net").arg(network);
        }
    }
    cmd.arg(name.clone());
    cmd.stdout(Stdio::piped());

    let mut child = cmd.spawn().unwrap();
    let secs = Duration::from_secs(20);

    let _status_code = match child.wait_timeout(secs).unwrap() {
        Some(status) => status.code(),
        None => {
            stop_and_remove_container_by_image(name);
            child.kill().unwrap();
            child.wait().unwrap().code()
        }
    };

    let reader = BufReader::new(child.stdout.unwrap());
    reader
        .lines()
        .map(|line| line.unwrap())
        .collect::<Vec<_>>()
        .join("\n")
}

/// Builds a directory with default options
/// Returns the randomly generated image name
fn simple_build(path: &str) -> String {
    let name = Uuid::new_v4().to_string();
    create_docker_image(
        path,
        Vec::new(),
        &GeneratePlanOptions {
            pin_pkgs: true,
            ..Default::default()
        },
        &DockerBuilderOptions {
            name: Some(name.clone()),
            quiet: true,
            ..Default::default()
        },
    )
    .unwrap();

    name
}
const POSTGRES_IMAGE: &str = "postgres";

struct Network {
    name: String,
}

fn attach_container_to_network(network_name: String, container_name: String) {
    Command::new("docker")
        .arg("network")
        .arg("connect")
        .arg(network_name)
        .arg(container_name)
        .spawn()
        .unwrap()
        .wait()
        .context("Setting up network")
        .unwrap();
}

fn create_network() -> Network {
    let network_name = format!("test-net-{}", Uuid::new_v4());

    Command::new("docker")
        .arg("network")
        .arg("create")
        .arg(network_name.clone())
        .spawn()
        .unwrap()
        .wait()
        .context("Setting up network")
        .unwrap();

    Network { name: network_name }
}

fn remove_network(network_name: String) {
    Command::new("docker")
        .arg("network")
        .arg("rm")
        .arg(network_name)
        .spawn()
        .unwrap()
        .wait()
        .context("Tearing down network")
        .unwrap();
}

struct Container {
    name: String,
    config: Option<Config>,
}

fn run_postgres() -> Container {
    let mut docker_cmd = Command::new("docker");

    let hash = Uuid::new_v4().to_string();
    let container_name = format!("postgres-{}", hash);
    let password = hash;
    let port = "5432";
    // run
    docker_cmd.arg("run");

    // Set Needed Envvars
    docker_cmd
        .arg("-e")
        .arg(format!("POSTGRES_PASSWORD={}", &password));

    // Run detached
    docker_cmd.arg("-d");

    // attach name
    docker_cmd.arg("--name").arg(container_name.clone());

    // Assign image
    docker_cmd.arg(POSTGRES_IMAGE);

    // Run the command
    docker_cmd
        .spawn()
        .unwrap()
        .wait()
        .context("Building postgres")
        .unwrap();

    Container {
        name: container_name.clone(),
        config: Some(Config {
            environment_variables: EnvironmentVariables::from([
                ("PGPORT".to_string(), port.to_string()),
                ("PGUSER".to_string(), "postgres".to_string()),
                ("PGDATABASE".to_string(), "postgres".to_string()),
                ("PGPASSWORD".to_string(), password),
                ("PGHOST".to_string(), container_name),
            ]),
            network: None,
        }),
    }
}

#[test]
fn test_node() {
    let name = simple_build("./examples/node");
    assert!(run_image(name, None).contains("Hello from Node"));
}

#[test]
fn test_node_custom_version() {
    let name = simple_build("./examples/node-custom-version");
    let output = run_image(name, None);
    assert!(output.contains("Node version: v18"));
}

#[test]
fn test_node_no_lockfile() {
    let name = simple_build("./examples/node-no-lockfile-canvas");
    let output = run_image(name, None);
    assert!(output.contains("Hello from Node canvas"));
}

#[test]
fn test_yarn_custom_version() {
    let name = simple_build("./examples/node-yarn-custom-node-version");
    let output = run_image(name, None);
    assert!(output.contains("Node version: v14"));
}

#[test]
fn test_yarn_berry() {
    let name = simple_build("./examples/node-yarn-berry");
    let output = run_image(name, None);

    assert!(output.contains("Hello from Yarn v2+"));
}

#[test]
fn test_yarn_prisma() {
    let name = simple_build("./examples/node-yarn-prisma");
    let output = run_image(name, None);
    assert!(output.contains("My post content"));
}

#[test]
fn test_pnpm() {
    let name = simple_build("./examples/node-pnpm");
    let output = run_image(name, None);
    assert!(output.contains("Hello from PNPM"));
}

#[test]
fn test_bun() {
    let name = simple_build("./examples/node-bun");
    let output = run_image(name, None);
    assert!(output.contains("Hello from Bun"));
}

#[test]
fn test_bun_web_server() {
    let name = simple_build("./examples/node-bun-web-server");
    let output = run_image(name, None);
    assert!(output.contains("Hello from a Bun web server!"));
}

#[test]
fn test_pnpm_custom_version() {
    let name = simple_build("./examples/node-pnpm-custom-node-version");
    let output = run_image(name, None);
    assert!(output.contains("Hello from PNPM"));
}

#[test]
fn test_csharp() {
    let name = simple_build("./examples/csharp-cli");
    let output = run_image(name, None);
    assert!(output.contains("Hello world from C#"));
}

#[test]
fn test_fsharp() {
    let name = simple_build("./examples/fsharp-cli");
    let output = run_image(name, None);
    assert!(output.contains("Hello world from F#"));
}

#[test]
fn test_python() {
    let name = simple_build("./examples/python");
    let output = run_image(name, None);
    assert!(output.contains("Hello from Python"));
}

#[test]
fn test_python_2() {
    let name = simple_build("./examples/python-2");
    let output = run_image(name, None);
    assert!(output.contains("Hello from Python 2"));
}

#[test]
fn test_django() {
    // Create the network
    let n = create_network();
    let network_name = n.name.clone();

    // Create the postgres instance
    let c = run_postgres();
    let container_name = c.name.clone();

    // Attach the postgres instance to the network
    attach_container_to_network(n.name, container_name.clone());

    // Build the Django example
    let name = simple_build("./examples/python-django");

    // Run the Django example on the attached network
    let output = run_image(
        name,
        Some(Config {
            environment_variables: c.config.unwrap().environment_variables,
            network: Some(network_name.clone()),
        }),
    );

    // Cleanup containers and networks
    stop_and_remove_container(container_name);
    remove_network(network_name);

    assert!(output.contains("Running migrations"));
}

#[test]
fn test_python_poetry() {
    let name = simple_build("./examples/python-poetry");
    let output = run_image(name, None);
    assert!(output.contains("Hello from Python-Poetry"));
}

#[test]
fn test_python_numpy() {
    let name = simple_build("./examples/python-numpy");
    let output = run_image(name, None);
    assert!(output.contains("Hello from Python numpy and pandas"));
}

#[test]
fn test_rust_custom_version() {
    let name = Uuid::new_v4().to_string();
    create_docker_image(
        "./examples/rust-custom-version",
        vec!["NIXPACKS_NO_MUSL=1"],
        &GeneratePlanOptions {
            pin_pkgs: true,
            ..Default::default()
        },
        &DockerBuilderOptions {
            name: Some(name.clone()),
            quiet: true,
            ..Default::default()
        },
    )
    .unwrap();

    let output = run_image(name, None);
    assert!(output.contains("cargo 1.56.0"));
}

#[test]
fn test_rust_ring() {
    let name = simple_build("./examples/rust-ring");
    let output = run_image(name, None);
    assert!(output.contains("Hello from rust"));
}

#[test]
fn test_rust_openssl() {
    let name = simple_build("./examples/rust-openssl");
    let output = run_image(name, None);
    assert!(output.contains("Hello from Rust openssl!"));
}

#[test]
fn test_go() {
    let name = simple_build("./examples/go");
    let output = run_image(name, None);
    assert!(output.contains("Hello from Go"));
}

#[test]
fn test_go_custom_version() {
    let name = simple_build("./examples/go-custom-version");
    let output = run_image(name, None);
    assert!(output.contains("Hello from go1.18"));
}

#[test]
fn test_haskell_stack() {
    let name = simple_build("./examples/haskell-stack");
    let output = run_image(name, None);
    assert!(output.contains("Hello from Haskell"));
}

#[test]
fn test_crystal() {
    let name = simple_build("./examples/crystal");
    let output = run_image(name, None);
    assert!(output.contains("Hello from Crystal"));
}

#[test]
fn test_cowsay() {
    let name = Uuid::new_v4().to_string();
    create_docker_image(
        "./examples/shell-hello",
        Vec::new(),
        &GeneratePlanOptions {
            pin_pkgs: true,
            custom_start_cmd: Some("./start.sh".to_string()),
            custom_pkgs: vec![Pkg::new("cowsay")],
            ..Default::default()
        },
        &DockerBuilderOptions {
            name: Some(name.clone()),
            quiet: true,
            ..Default::default()
        },
    )
    .unwrap();
    let output = run_image(name, None);
    assert!(output.contains("Hello World"));
}

#[test]
fn test_staticfile() {
    let name = simple_build("./examples/staticfile");
    let output = run_image(name, None);
    assert!(output.contains("start worker process"));
}

#[test]
fn test_swift() {
    let name = Uuid::new_v4().to_string();

    create_docker_image(
        "./examples/swift",
        Vec::new(),
        &GeneratePlanOptions {
            pin_pkgs: false,
            ..Default::default()
        },
        &DockerBuilderOptions {
            name: Some(name.clone()),
            quiet: true,
            ..Default::default()
        },
    )
    .unwrap();

    let output = run_image(name, None);
    assert!(output.contains("Hello from swift"));
}

#[test]
fn test_dart() {
    let name = simple_build("./examples/dart");
    let output = run_image(name, None);
    assert!(output.contains("Hello from Dart"));
}

#[test]
fn test_java_maven() {
    let name = simple_build("./examples/java-maven");
    let output = run_image(name, None);
    assert!(output.contains("Built with Spring Boot"));
}

#[test]
fn test_zig() {
    let name = simple_build("./examples/zig");
    let output = run_image(name, None);
    assert!(output.contains("Hello from Zig"));
}

#[test]
fn test_zig_gyro() {
    let name = simple_build("./examples/zig-gyro");
    let output = run_image(name, None);
    assert!(output.contains("Hello from Zig"));
    assert!(output.contains("The URI scheme of GitHub is https."));
}

#[test]
fn test_ruby_sinatra() {
    let name = simple_build("./examples/ruby-sinatra/");
    let output = run_image(name, None);
    assert!(output.contains("Hello from Sinatra"));
}

#[test]
fn test_ruby_rails() {
    // Create the network
    let n = create_network();
    let network_name = n.name.clone();

    // Create the postgres instance
    let c = run_postgres();
    let container_name = c.name.clone();

    // Attach the postgres instance to the network
    attach_container_to_network(n.name, container_name.clone());

    // Build the Django example
    let name = simple_build("./examples/ruby-rails-postgres");

    // Run the Rails example on the attached network
    let output = run_image(
        name,
        Some(Config {
            environment_variables: c.config.unwrap().environment_variables,
            network: Some(network_name.clone()),
        }),
    );

    // Cleanup containers and networks
    stop_and_remove_container(container_name);
    remove_network(network_name);

    assert!(output.contains("Rails 7"));
}

#[test]
fn test_clojure() {
    let name = simple_build("./examples/clojure");
    let output = run_image(name, None);
    assert_eq!(output, "Hello, World From Clojure!");
}

#[test]
fn test_clojure_ring_app() {
    let name = simple_build("./examples/clojure-ring-app");
    let output = run_image(name, None);
    assert_eq!(output, "Started server on port 3000");
}