1 | import { Dockerfile, DockerfileParser } from "dockerfile-ast";
|
2 | import * as fs from "fs";
|
3 | import { normalize as normalizePath } from "path";
|
4 | import {
|
5 | getDockerfileBaseImageName,
|
6 | getLayersFromPackages,
|
7 | getPackagesFromDockerfile,
|
8 | instructionDigest,
|
9 | } from "./instruction-parser";
|
10 | import { updateDockerfileBaseImageName } from "./instruction-updater";
|
11 | import { DockerFileAnalysis } from "./types";
|
12 |
|
13 | export {
|
14 | analyseDockerfile,
|
15 | readDockerfileAndAnalyse,
|
16 | instructionDigest,
|
17 | getPackagesFromDockerfile,
|
18 | getDockerfileBaseImageName,
|
19 | updateDockerfileBaseImageName,
|
20 | DockerFileAnalysis,
|
21 | parseDockerfile,
|
22 | };
|
23 |
|
24 | async function readDockerfileAndAnalyse(
|
25 | dockerfilePath?: string,
|
26 | ): Promise<DockerFileAnalysis | undefined> {
|
27 | if (!dockerfilePath) {
|
28 | return undefined;
|
29 | }
|
30 |
|
31 | const contents = await readFile(normalizePath(dockerfilePath));
|
32 | return analyseDockerfile(contents);
|
33 | }
|
34 |
|
35 | async function analyseDockerfile(
|
36 | contents: string,
|
37 | ): Promise<DockerFileAnalysis> {
|
38 | const dockerfile = DockerfileParser.parse(contents);
|
39 | const baseImageResult = getDockerfileBaseImageName(dockerfile);
|
40 | const dockerfilePackages = getPackagesFromDockerfile(dockerfile);
|
41 | const dockerfileLayers = getLayersFromPackages(dockerfilePackages);
|
42 | return {
|
43 | baseImage: baseImageResult.baseImage,
|
44 | dockerfilePackages,
|
45 | dockerfileLayers,
|
46 | error: baseImageResult.error,
|
47 | };
|
48 | }
|
49 |
|
50 | async function readFile(path: string) {
|
51 | return new Promise((resolve, reject) => {
|
52 | fs.readFile(path, "utf8", (err, data) => {
|
53 | return err ? reject(err) : resolve(data);
|
54 | });
|
55 | }) as Promise<string>;
|
56 | }
|
57 |
|
58 | function parseDockerfile(content: string): Dockerfile {
|
59 | return DockerfileParser.parse(content);
|
60 | }
|