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
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
use crate::DockerError;
use crate::config::docker_file::{DockerCommand, DockerfileConfig};
use crate::test_fixtures::get_tangle_dockerfile;
use std::collections::HashMap;

#[tokio::test]
async fn test_dockerfile_parsing() {
    let config = DockerfileConfig::parse_from_path(get_tangle_dockerfile()).unwrap();

    assert_eq!(config.base_image, "ubuntu:22.04");
    assert_eq!(config.commands.len(), 11);

    let commands = &config.commands;

    // Test COPY
    match &commands[2] {
        DockerCommand::Copy {
            source,
            dest,
            chown,
        } => {
            assert_eq!(source, "./target/release/tangle");
            assert_eq!(dest, "/usr/local/bin/");
            assert!(chown.is_none());
        }
        _ => panic!("Expected COPY command"),
    }

    // Verify RUN command with multiple operations
    match &commands[3] {
        DockerCommand::Run { command } => {
            assert!(command.contains("useradd -m -u 5000"));
            assert!(command.contains("mkdir -p /data /tangle/.local/share"));
            assert!(command.contains("chown -R tangle:tangle /data"));
        }
        _ => panic!("Expected RUN command"),
    }

    // Verify USER command
    match &commands[4] {
        DockerCommand::User { user, group } => {
            assert_eq!(user, "tangle");
            assert!(group.is_none());
        }
        _ => panic!("Expected USER command"),
    }

    // Verify EXPOSE commands
    let expected_ports = [30333, 9933, 9944, 9615];
    for (i, port) in expected_ports.iter().enumerate() {
        match &commands[i + 5] {
            DockerCommand::Expose { port: p, protocol } => {
                assert_eq!(p, port);
                assert!(protocol.is_none());
            }
            _ => panic!("Expected EXPOSE command"),
        }
    }
}

#[tokio::test]
async fn test_dockerfile_content_generation() {
    let config = DockerfileConfig {
        base_image: "rust:1.70".to_string(),
        commands: vec![
            DockerCommand::Run {
                command: "cargo build".to_string(),
            },
            DockerCommand::Copy {
                source: "./target".to_string(),
                dest: "/app".to_string(),
                chown: None,
            },
            DockerCommand::Env {
                key: "RUST_LOG".to_string(),
                value: "debug".to_string(),
            },
            DockerCommand::Workdir {
                path: "/app".to_string(),
            },
            DockerCommand::Expose {
                port: 8080,
                protocol: None,
            },
        ],
    };

    let content = config.to_string();
    let expected = r"FROM rust:1.70
RUN cargo build
COPY ./target /app
ENV RUST_LOG=debug
WORKDIR /app
EXPOSE 8080
";

    assert_eq!(content, expected);
}

#[tokio::test]
async fn test_all_dockerfile_commands() {
    let content = r#"
        FROM ubuntu:22.04
        LABEL version="1.0" description="Test image"
        MAINTAINER Test User <test@example.com>
        ARG BUILD_VERSION
        ARG DEBUG=false
        ENV APP_VERSION=${BUILD_VERSION}
        ENV DEBUG_MODE=${DEBUG}
        WORKDIR /app
        ADD --chown=user:group http://example.com/file.tar.gz /app/
        ADD ["file1.txt", "file2.txt", "/app/"]
        COPY --chown=user:group src/ /app/
        RUN apt-get update && \
            apt-get install -y python3
        EXPOSE 8080/tcp
        EXPOSE 8081
        USER myuser:mygroup
        VOLUME ["/data", "/config"]
        HEALTHCHECK --interval=30s --timeout=10s --retries=3 CMD curl -f http://localhost/ || exit 1
        SHELL ["/bin/bash", "-c"]
        STOPSIGNAL SIGTERM
        ONBUILD ADD . /app/src
        ENTRYPOINT ["./entrypoint.sh"]
        CMD ["--help"]
    "#;

    let config = DockerfileConfig::parse(content).unwrap();
    assert_eq!(config.base_image, "ubuntu:22.04");

    let mut commands_iter = config.commands.iter();

    // Test LABEL
    if let Some(DockerCommand::Label { labels }) = commands_iter.next() {
        assert_eq!(labels.get("version").unwrap(), "1.0");
        assert_eq!(labels.get("description").unwrap(), "Test image");
    } else {
        panic!("Expected LABEL command");
    }

    // Test MAINTAINER
    if let Some(DockerCommand::Maintainer { name }) = commands_iter.next() {
        assert_eq!(name, "Test User <test@example.com>");
    } else {
        panic!("Expected MAINTAINER command");
    }

    // Test ARGs
    if let Some(DockerCommand::Arg {
        name,
        default_value,
    }) = commands_iter.next()
    {
        assert_eq!(name, "BUILD_VERSION");
        assert!(default_value.is_none());
    } else {
        panic!("Expected ARG command");
    }

    if let Some(DockerCommand::Arg {
        name,
        default_value,
    }) = commands_iter.next()
    {
        assert_eq!(name, "DEBUG");
        assert_eq!(default_value.as_deref(), Some("false"));
    } else {
        panic!("Expected ARG command");
    }

    // Test ENVs
    if let Some(DockerCommand::Env { key, value }) = commands_iter.next() {
        assert_eq!(key, "APP_VERSION");
        assert_eq!(value, "${BUILD_VERSION}");
    } else {
        panic!("Expected ENV command");
    }

    if let Some(DockerCommand::Env { key, value }) = commands_iter.next() {
        assert_eq!(key, "DEBUG_MODE");
        assert_eq!(value, "${DEBUG}");
    } else {
        panic!("Expected ENV command");
    }

    // Test WORKDIR
    if let Some(DockerCommand::Workdir { path }) = commands_iter.next() {
        assert_eq!(path, "/app");
    } else {
        panic!("Expected WORKDIR command");
    }

    // Test ADD
    if let Some(DockerCommand::Add {
        sources,
        dest,
        chown,
    }) = commands_iter.next()
    {
        assert_eq!(*sources, vec!["http://example.com/file.tar.gz"]);
        assert_eq!(dest, "/app/");
        assert_eq!(chown.as_deref(), Some("user:group"));
    } else {
        panic!("Expected ADD command");
    }

    if let Some(DockerCommand::Add {
        sources,
        dest,
        chown,
    }) = commands_iter.next()
    {
        assert_eq!(*sources, vec!["file1.txt", "file2.txt"]);
        assert_eq!(dest, "/app/");
        assert!(chown.is_none());
    } else {
        panic!("Expected ADD command");
    }

    // Test COPY
    if let Some(DockerCommand::Copy {
        source,
        dest,
        chown,
    }) = commands_iter.next()
    {
        assert_eq!(source, "src/");
        assert_eq!(dest, "/app/");
        assert_eq!(chown.as_deref(), Some("user:group"));
    } else {
        panic!("Expected COPY command");
    }

    // Test RUN
    if let Some(DockerCommand::Run { command }) = commands_iter.next() {
        assert_eq!(command, "apt-get update &&  apt-get install -y python3");
    } else {
        panic!("Expected RUN command");
    }

    // Test EXPOSE
    if let Some(DockerCommand::Expose { port, protocol }) = commands_iter.next() {
        assert_eq!(*port, 8080);
        assert_eq!(protocol.as_deref(), Some("tcp"));
    } else {
        panic!("Expected EXPOSE command");
    }

    if let Some(DockerCommand::Expose { port, protocol }) = commands_iter.next() {
        assert_eq!(*port, 8081);
        assert!(protocol.is_none());
    } else {
        panic!("Expected EXPOSE command");
    }

    // Test USER
    if let Some(DockerCommand::User { user, group }) = commands_iter.next() {
        assert_eq!(user, "myuser");
        assert_eq!(group.as_deref(), Some("mygroup"));
    } else {
        panic!("Expected USER command");
    }

    // Test VOLUME
    if let Some(DockerCommand::Volume { paths }) = commands_iter.next() {
        assert_eq!(*paths, vec!["/data", "/config"]);
    } else {
        panic!("Expected VOLUME command");
    }

    // Test HEALTHCHECK
    if let Some(DockerCommand::Healthcheck {
        command,
        interval,
        timeout,
        retries,
        ..
    }) = commands_iter.next()
    {
        assert_eq!(
            *command,
            vec!["curl", "-f", "http://localhost/", "||", "exit", "1"]
        );
        assert_eq!(interval.as_deref(), Some("30s"));
        assert_eq!(timeout.as_deref(), Some("10s"));
        assert_eq!(*retries, Some(3));
    } else {
        panic!("Expected HEALTHCHECK command");
    }

    // Test SHELL
    if let Some(DockerCommand::Shell { shell }) = commands_iter.next() {
        assert_eq!(*shell, vec!["/bin/bash", "-c"]);
    } else {
        panic!("Expected SHELL command");
    }

    // Test STOPSIGNAL
    if let Some(DockerCommand::StopSignal { signal }) = commands_iter.next() {
        assert_eq!(signal, "SIGTERM");
    } else {
        panic!("Expected STOPSIGNAL command");
    }

    // Test ONBUILD
    if let Some(DockerCommand::Onbuild { command }) = commands_iter.next() {
        match command.as_ref() {
            DockerCommand::Add {
                sources,
                dest,
                chown,
            } => {
                assert_eq!(*sources, vec!["."]);
                assert_eq!(dest, "/app/src");
                assert!(chown.is_none());
            }
            _ => panic!("Expected ONBUILD ADD command"),
        }
    } else {
        panic!("Expected ONBUILD command");
    }

    // Test ENTRYPOINT
    if let Some(DockerCommand::Entrypoint { command }) = commands_iter.next() {
        assert_eq!(*command, vec!["./entrypoint.sh"]);
    } else {
        panic!("Expected ENTRYPOINT command");
    }

    // Test CMD
    if let Some(DockerCommand::Cmd { command }) = commands_iter.next() {
        assert_eq!(*command, vec!["--help"]);
    } else {
        panic!("Expected CMD command");
    }
}

#[tokio::test]
async fn test_invalid_dockerfile_syntax() {
    let content = "COPY";
    let result = DockerfileConfig::parse(content);
    assert!(matches!(
        result,
        Err(DockerError::DockerfileError(msg)) if msg == "Invalid command syntax"
    ));

    let content = "COPY src";
    let result = DockerfileConfig::parse(content);
    assert!(matches!(
        result,
        Err(DockerError::DockerfileError(msg)) if msg == "COPY requires source and destination"
    ));

    let content = "UNKNOWN command";
    let result = DockerfileConfig::parse(content);
    assert!(matches!(
        result,
        Err(DockerError::DockerfileError(msg)) if msg == "Unknown command: UNKNOWN"
    ));
}

#[tokio::test]
async fn test_invalid_onbuild() {
    let content = "ONBUILD";
    let result = DockerfileConfig::parse(content);
    assert!(matches!(
        result,
        Err(DockerError::DockerfileError(msg)) if msg == "Invalid command syntax"
    ));

    let content = "ONBUILD INVALID something";
    let result = DockerfileConfig::parse(content);
    assert!(matches!(
        result,
        Err(DockerError::DockerfileError(msg)) if msg == "Unknown command: INVALID"
    ));

    // Test valid ONBUILD commands
    let content = "ONBUILD ADD . /usr/src/app";
    let config = DockerfileConfig::parse(content).unwrap();
    match &config.commands[0] {
        DockerCommand::Onbuild { command } => match command.as_ref() {
            DockerCommand::Add {
                sources,
                dest,
                chown,
            } => {
                assert_eq!(sources, &vec!["."]);
                assert_eq!(dest, "/usr/src/app");
                assert!(chown.is_none());
            }
            _ => panic!("Expected ADD command inside ONBUILD"),
        },
        _ => panic!("Expected ONBUILD command"),
    }

    let content = "ONBUILD RUN mvn install";
    let config = DockerfileConfig::parse(content).unwrap();
    match &config.commands[0] {
        DockerCommand::Onbuild { command } => match command.as_ref() {
            DockerCommand::Run { command } => {
                assert_eq!(command, "mvn install");
            }
            _ => panic!("Expected RUN command inside ONBUILD"),
        },
        _ => panic!("Expected ONBUILD command"),
    }
}

#[tokio::test]
async fn test_invalid_healthcheck() {
    let content = "HEALTHCHECK --invalid-flag CMD curl localhost";
    let result = DockerfileConfig::parse(content);
    assert!(matches!(
        result,
        Err(DockerError::DockerfileError(msg)) if msg == "Invalid HEALTHCHECK flag: --invalid-flag"
    ));

    let content = "HEALTHCHECK --interval";
    let result = DockerfileConfig::parse(content);
    assert!(matches!(
        result,
        Err(DockerError::DockerfileError(msg)) if msg == "Missing value for --interval flag"
    ));

    let content = "HEALTHCHECK --interval 30s";
    let result = DockerfileConfig::parse(content);
    assert!(matches!(
        result,
        Err(DockerError::DockerfileError(msg)) if msg == "HEALTHCHECK must include CMD"
    ));
}

#[tokio::test]
async fn test_empty_dockerfile() {
    let content = "";
    let config = DockerfileConfig::parse(content).unwrap();
    assert!(config.base_image.is_empty());
    assert!(config.commands.is_empty());
}

#[tokio::test]
async fn test_comments_and_empty_lines() {
    let content = r#"
        # This is a comment
        FROM ubuntu:22.04

        # Another comment
        RUN echo "test"

        # Final comment
    "#;

    let config = DockerfileConfig::parse(content).unwrap();
    assert_eq!(config.base_image, "ubuntu:22.04");
    assert_eq!(config.commands.len(), 1);
}

#[tokio::test]
async fn test_expose_multiple_ports() {
    let content = "EXPOSE 30333 9933 9944 9615";
    let config = DockerfileConfig::parse(content).unwrap();

    let expected_ports = [30333, 9933, 9944, 9615];
    assert_eq!(config.commands.len(), expected_ports.len());

    for (i, port) in expected_ports.iter().enumerate() {
        match &config.commands[i] {
            DockerCommand::Expose { port: p, protocol } => {
                assert_eq!(p, port);
                assert!(protocol.is_none());
            }
            _ => panic!("Expected EXPOSE command"),
        }
    }

    // Test mixed format
    let content = "EXPOSE 80/tcp 443 8080/udp 9000";
    let config = DockerfileConfig::parse(content).unwrap();
    assert_eq!(config.commands.len(), 4);

    let expected = [
        (80, Some("tcp")),
        (443, None),
        (8080, Some("udp")),
        (9000, None),
    ];

    for (i, (port, protocol)) in expected.iter().enumerate() {
        match &config.commands[i] {
            DockerCommand::Expose {
                port: p,
                protocol: proto,
            } => {
                assert_eq!(p, port);
                assert_eq!(proto.as_deref(), *protocol);
            }
            _ => panic!("Expected EXPOSE command"),
        }
    }
}

#[tokio::test]
async fn test_tangle_expose_format() {
    let content = "EXPOSE 30333 9933 9944 9615";
    let config = DockerfileConfig::parse(content).unwrap();

    let expected_ports = [30333, 9933, 9944, 9615];
    assert_eq!(config.commands.len(), expected_ports.len());

    for (i, expected_port) in expected_ports.iter().enumerate() {
        match &config.commands[i] {
            DockerCommand::Expose { port, protocol } => {
                assert_eq!(port, expected_port);
                assert!(protocol.is_none());
            }
            _ => panic!("Expected EXPOSE command"),
        }
    }

    // Test error case
    let content = "EXPOSE 30333 invalid 9944";
    let result = DockerfileConfig::parse(content);
    assert!(matches!(
        result,
        Err(DockerError::DockerfileError(msg)) if msg == "Invalid port number: invalid"
    ));
}

#[tokio::test]
async fn test_onbuild_commands() {
    // Test all possible ONBUILD combinations
    let test_cases = vec![
        (
            "ONBUILD ADD . /app",
            DockerCommand::Add {
                sources: vec![".".to_string()],
                dest: "/app".to_string(),
                chown: None,
            },
        ),
        (
            "ONBUILD COPY --chown=user:group src/ /app/",
            DockerCommand::Copy {
                source: "src/".to_string(),
                dest: "/app/".to_string(),
                chown: Some("user:group".to_string()),
            },
        ),
        (
            "ONBUILD RUN cargo build",
            DockerCommand::Run {
                command: "cargo build".to_string(),
            },
        ),
        (
            "ONBUILD ENV APP_VERSION=1.0",
            DockerCommand::Env {
                key: "APP_VERSION".to_string(),
                value: "1.0".to_string(),
            },
        ),
        (
            "ONBUILD WORKDIR /app",
            DockerCommand::Workdir {
                path: "/app".to_string(),
            },
        ),
        (
            "ONBUILD EXPOSE 8080",
            DockerCommand::Expose {
                port: 8080,
                protocol: None,
            },
        ),
        (
            "ONBUILD USER app:app",
            DockerCommand::User {
                user: "app".to_string(),
                group: Some("app".to_string()),
            },
        ),
        (
            "ONBUILD VOLUME /data",
            DockerCommand::Volume {
                paths: vec!["/data".to_string()],
            },
        ),
        (
            "ONBUILD LABEL version=1.0",
            DockerCommand::Label {
                labels: {
                    let mut map = HashMap::new();
                    map.insert("version".to_string(), "1.0".to_string());
                    map
                },
            },
        ),
    ];

    for (content, expected_cmd) in test_cases {
        let config = DockerfileConfig::parse(content).unwrap();
        match &config.commands[0] {
            DockerCommand::Onbuild { command } => {
                assert_eq!(command.as_ref(), &expected_cmd);
            }
            _ => panic!("Expected ONBUILD command"),
        }
    }
}

#[tokio::test]
async fn test_volume_formats() {
    // Test space-separated format
    let content = "VOLUME /data /config /cache";
    let config = DockerfileConfig::parse(content).unwrap();
    match &config.commands[0] {
        DockerCommand::Volume { paths } => {
            assert_eq!(paths, &vec!["/data", "/config", "/cache"]);
        }
        _ => panic!("Expected VOLUME command"),
    }

    // Test JSON array format
    let content = r#"VOLUME ["/data", "/config"]"#;
    let config = DockerfileConfig::parse(content).unwrap();
    match &config.commands[0] {
        DockerCommand::Volume { paths } => {
            assert_eq!(paths, &vec!["/data", "/config"]);
        }
        _ => panic!("Expected VOLUME command"),
    }

    // Test error case
    let content = "VOLUME [invalid json";
    let result = DockerfileConfig::parse(content);
    assert!(matches!(
        result,
        Err(DockerError::DockerfileError(msg)) if msg.contains("Invalid JSON array")
    ));
}