dofigen 2.8.0

A Dockerfile generator using a simplified description in YAML or JSON format create
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
mod context;
mod insctruction;

use colored::{Color, Colorize};
use struct_patch::Patch;

use crate::{
    DockerFile, DockerFileCommand, DockerFileInsctruction, DockerFileLine, DockerIgnore,
    DockerIgnoreLine, Dofigen, Error, FromContext, MessageLevel, Result, User,
    parse::context::ParseContext,
};

impl Dofigen {
    pub fn from_dockerfile(
        dockerfile: DockerFile,
        dockerignore: Option<DockerIgnore>,
    ) -> Result<Self> {
        let mut context = ParseContext::default();

        if let Some(dockerignore) = dockerignore {
            context.parse_dockerignore(dockerignore)?;
        }

        context.parse_dockerfile(dockerfile)?;

        Ok(context.dofigen.into())
    }
}

impl ParseContext {
    pub fn parse_dockerignore(&mut self, dockerignore: DockerIgnore) -> Result<()> {
        if !self.dofigen.ignore.is_empty() {
            return Err(Error::Custom(
                "A .dockerignore have already been parsed by this context".to_string(),
            ));
        }
        // TODO: If there is a negate pattern with **, then manage context field
        let ignores: Vec<String> = dockerignore
            .lines
            .iter()
            .filter(|line| {
                matches!(line, DockerIgnoreLine::Pattern(_))
                    || matches!(line, DockerIgnoreLine::NegatePattern(_))
            })
            .map(|line| match line {
                DockerIgnoreLine::Pattern(pattern) => pattern.clone(),
                DockerIgnoreLine::NegatePattern(pattern) => format!("!{pattern}"),
                _ => unreachable!(),
            })
            .collect();
        self.dofigen.ignore = ignores;
        Ok(())
    }

    pub fn parse_dockerfile(&mut self, dockerfile: DockerFile) -> Result<()> {
        if !self.stage_names.is_empty() {
            return Err(Error::Custom(
                "A Dockerfile have already been parsed by this context".to_string(),
            ));
        }
        let instructions: Vec<_> = dockerfile
            .lines
            .iter()
            .filter(|line| matches!(line, DockerFileLine::Instruction(_)))
            .collect();

        self.stage_names = instructions
            .iter()
            .filter(|&line| {
                matches!(
                    line,
                    DockerFileLine::Instruction(DockerFileInsctruction {
                        command: DockerFileCommand::FROM,
                        ..
                    })
                )
            })
            .map(|line| match line {
                DockerFileLine::Instruction(DockerFileInsctruction {
                    command: DockerFileCommand::FROM,
                    content,
                    ..
                }) => content,
                _ => unreachable!(),
            })
            .map(|from_content| split_from(from_content).1.unwrap_or("runtime").to_string())
            .collect();

        for line in instructions {
            self.apply(line)?;
        }

        self.apply_root()?;

        // Get runtime informations
        let mut runtime_stage = self.current_stage.clone().ok_or(Error::Custom(
            "No FROM instruction found in Dockerfile".to_string(),
        ))?;
        let runtime_name = self
            .current_stage_name
            .clone()
            .unwrap_or("runtime".to_string());

        // Get base instructions in from builders
        let mut dofigen_patches = self
            .builder_dofigen_patches
            .remove(&runtime_name)
            .into_iter()
            .collect::<Vec<_>>();
        let mut searching_stage = runtime_stage.clone();
        while let FromContext::FromBuilder(builder_name) = searching_stage.from.clone() {
            if let Some(builder_dofigen_patch) = self.builder_dofigen_patches.remove(&builder_name)
            {
                dofigen_patches.insert(0, builder_dofigen_patch);
            }
            searching_stage = self
                .dofigen
                .builders
                .get(&builder_name)
                .ok_or(Error::Custom(format!(
                    "Builder '{}' not found",
                    builder_name
                )))?
                .clone();
        }

        // Apply merged patches
        if !dofigen_patches.is_empty() {
            dofigen_patches.iter().for_each(|dofigen_patch| {
                self.dofigen.apply(dofigen_patch.clone());
            });
        }

        // If user is set as default, remove it
        if let Some(user) = runtime_stage.user.as_ref() {
            let default_user = User::new("1000");
            if user.eq(&default_user) {
                runtime_stage.user = None;
            }
        }

        self.dofigen.stage = runtime_stage;

        // Handle lint messages
        self.messages.iter().for_each(|message| {
            eprintln!(
                "{}[path={}]: {}",
                match message.level {
                    MessageLevel::Error => "error".color(Color::Red).bold(),
                    MessageLevel::Warn => "warning".color(Color::Yellow).bold(),
                },
                message.path.join(".").color(Color::Blue).bold(),
                message.message
            );
        });

        Ok(())
    }
}

pub(crate) fn split_from(content: &str) -> (&str, Option<&str>) {
    let pos = content.to_lowercase().find(" as ");
    if let Some(pos) = pos {
        let (from, name) = content.split_at(pos);
        let name = name[4..].trim();
        (from, Some(name))
    } else {
        (content, None)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::DofigenContext;
    use crate::GenerationContext;
    use crate::dockerfile_struct::*;
    use crate::dofigen_struct::*;
    use pretty_assertions_sorted::assert_eq_sorted;
    use std::collections::HashMap;

    #[test]
    fn php_dockerfile() {
        let dockerfile_content = r#"# syntax=docker/dockerfile:1.19.0
# This file is generated by Dofigen v0.0.0
# See https://github.com/lenra-io/dofigen

# get-composer
FROM composer:latest AS get-composer

# install-deps
FROM php:8.3-fpm-alpine AS install-deps
USER 0:0
RUN <<EOF
apt-get update
apk add --no-cache --update ca-certificates dcron curl git supervisor tar unzip nginx libpng-dev libxml2-dev libzip-dev icu-dev mysql-client
EOF

# install-php-ext
FROM install-deps AS install-php-ext
USER 0:0
RUN <<EOF
docker-php-ext-configure zip
docker-php-ext-install bcmath gd intl pdo_mysql zip
EOF

# runtime
FROM install-php-ext AS runtime
WORKDIR /
COPY \
    --from=get-composer \
    --chown=www-data \
    --link \
    "/usr/bin/composer" "/bin/"
ADD \
    --chown=www-data \
    --link \
    "https://github.com/pelican-dev/panel.git" "/tmp/pelican"
USER www-data
RUN <<EOF
cd /tmp/pelican
cp .env.example .env
mkdir -p bootstrap/cache/ storage/logs storage/framework/sessions storage/framework/views storage/framework/cache
chmod 777 -R bootstrap storage
composer install --no-dev --optimize-autoloader
rm -rf .env bootstrap/cache/*.php
mkdir -p /app/storage/logs/
chown -R nginx:nginx .
rm /usr/local/etc/php-fpm.conf
echo "* * * * * /usr/local/bin/php /app/artisan schedule:run >> /dev/null 2>&1" >> /var/spool/cron/crontabs/root
mkdir -p /var/run/php /var/run/nginx
mv .github/docker/default.conf /etc/nginx/http.d/default.conf
mv .github/docker/supervisord.conf /etc/supervisord.conf
EOF
"#;

        let yaml = r#"builders:
  install-deps:
    fromImage: php:8.3-fpm-alpine
    root:
      run:
      - apt-get update
      - >-
        apk add --no-cache --update
        ca-certificates
        dcron
        curl
        git
        supervisor
        tar
        unzip
        nginx
        libpng-dev
        libxml2-dev
        libzip-dev
        icu-dev
        mysql-client
  install-php-ext:
    fromBuilder: install-deps
    root:
      run:
      # - docker-php-ext-configure gd --with-freetype --with-jpeg
      # - docker-php-ext-install -j$(nproc) gd zip intl curl mbstring mysqli
        - docker-php-ext-configure zip
        - docker-php-ext-install bcmath gd intl pdo_mysql zip
  get-composer:
    name: composer
    fromImage: composer:latest
fromBuilder: install-php-ext
workdir: /
user:
  user: www-data
copy:
- fromBuilder: get-composer
  paths: "/usr/bin/composer"
  target: "/bin/"
  chown:
    user: www-data
  link: true
- repo: 'https://github.com/pelican-dev/panel.git'
  target: '/tmp/pelican'
  chown:
    user: www-data
  link: true
run:
  - cd /tmp/pelican
  - cp .env.example .env
  - mkdir -p bootstrap/cache/ storage/logs storage/framework/sessions storage/framework/views storage/framework/cache
  - chmod 777 -R bootstrap storage
  - composer install --no-dev --optimize-autoloader
  - rm -rf .env bootstrap/cache/*.php
  - mkdir -p /app/storage/logs/
  - chown -R nginx:nginx .
  - rm /usr/local/etc/php-fpm.conf
  - echo "* * * * * /usr/local/bin/php /app/artisan schedule:run >> /dev/null 2>&1" >> /var/spool/cron/crontabs/root
  - mkdir -p /var/run/php /var/run/nginx
  - mv .github/docker/default.conf /etc/nginx/http.d/default.conf
  - mv .github/docker/supervisord.conf /etc/supervisord.conf
"#;

        let dockerfile: DockerFile = dockerfile_content.parse().unwrap();

        let result = Dofigen::from_dockerfile(dockerfile, None);

        let dofigen_from_dockerfile = result.unwrap();

        assert_eq_sorted!(dofigen_from_dockerfile, Dofigen {
                builders: HashMap::from([
                    ("get-composer".to_string(), Stage {
                        from: FromContext::FromImage(
                            ImageName {
                                path: "composer".to_string(),
                                version: Some(
                                    ImageVersion::Tag(
                                        "latest".to_string(),
                                    ),
                                ),
                ..Default::default()
                            },
                        ),
                ..Default::default()
                    }),
                    ("install-deps".to_string(), Stage {
                        from: FromContext::FromImage(
                            ImageName {
                                path: "php".to_string(),
                                version: Some(
                                    ImageVersion::Tag(
                                        "8.3-fpm-alpine".to_string(),
                                    ),
                                ),
                ..Default::default()
                            },
                        ),
                        root: Some(
                            Run {
                                run: vec![
                                    "apt-get update".to_string(),
                                    "apk add --no-cache --update ca-certificates dcron curl git supervisor tar unzip nginx libpng-dev libxml2-dev libzip-dev icu-dev mysql-client".to_string(),
                                ],
                ..Default::default()
                            },
                        ),
                ..Default::default()
                    }),
                    ("install-php-ext".to_string(), Stage {
                        from: FromContext::FromBuilder(
                            "install-deps".to_string(),
                        ),
                        root: Some(
                            Run {
                                run: vec![
                                    "docker-php-ext-configure zip".to_string(),
                                    "docker-php-ext-install bcmath gd intl pdo_mysql zip".to_string(),
                                ],
                ..Default::default()
                            },
                        ),
                ..Default::default()
                    })
                    ]),
                stage: Stage {
                    from: FromContext::FromBuilder(
                        "install-php-ext".to_string(),
                    ),
                    user: Some(
                        User {
                            user: "www-data".to_string(),
                            group: None,
                        },
                    ),
                    workdir: Some(
                        "/".to_string(),
                    ),
                    copy: vec![
                        CopyResource::Copy(
                            Copy {
                                from: FromContext::FromBuilder(
                                    "get-composer".to_string(),
                                ),
                                paths: vec![
                                    "/usr/bin/composer".to_string(),
                                ],
                                options: CopyOptions {
                                   target: Some(
                                       "/bin/".to_string(),
                                   ),
                                   chown: Some(
                                       User {
                                           user: "www-data".to_string(),
                                           group: None,
                                       },
                                   ),
                                   link: Some(
                                       true,
                                   ),
                                    ..Default::default()
                                },
                                ..Default::default()
                            },
                        ),
                        CopyResource::AddGitRepo(
                            AddGitRepo {
                                repo: "https://github.com/pelican-dev/panel.git".to_string(),
                                options: CopyOptions {
                                   target: Some(
                                       "/tmp/pelican".to_string(),
                                   ),
                                   chown: Some(
                                       User {
                                           user: "www-data".to_string(),
                                           group: None,
                                       },
                                   ),
                                   link: Some(
                                       true,
                                   ),
                ..Default::default()
                                },
                ..Default::default()
                            },
                        ),
                    ],
                    run: Run {
                        run: vec![
                            "cd /tmp/pelican".to_string(),
                            "cp .env.example .env".to_string(),
                            "mkdir -p bootstrap/cache/ storage/logs storage/framework/sessions storage/framework/views storage/framework/cache".to_string(),
                            "chmod 777 -R bootstrap storage".to_string(),
                            "composer install --no-dev --optimize-autoloader".to_string(),
                            "rm -rf .env bootstrap/cache/*.php".to_string(),
                            "mkdir -p /app/storage/logs/".to_string(),
                            "chown -R nginx:nginx .".to_string(),
                            "rm /usr/local/etc/php-fpm.conf".to_string(),
                            "echo \"* * * * * /usr/local/bin/php /app/artisan schedule:run >> /dev/null 2>&1\" >> /var/spool/cron/crontabs/root".to_string(),
                            "mkdir -p /var/run/php /var/run/nginx".to_string(),
                            "mv .github/docker/default.conf /etc/nginx/http.d/default.conf".to_string(),
                            "mv .github/docker/supervisord.conf /etc/supervisord.conf".to_string(),
                        ],
                ..Default::default()
                    },
                                ..Default::default()
                },
                ..Default::default()
            });

        let dofigen_from_string: Dofigen = DofigenContext::new()
            .parse_from_string(yaml)
            .map_err(Error::from)
            .unwrap();

        assert_eq_sorted!(dofigen_from_dockerfile, dofigen_from_string);

        let mut context = GenerationContext::from(dofigen_from_string.clone());

        let generated_dockerfile = context.generate_dockerfile().unwrap();

        assert_eq_sorted!(dockerfile_content.to_string(), generated_dockerfile);
    }
}