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
use cargo::util::paths;
use cargo_pack::CargoPack;
use copy_dir;
use error::*;
use handlebars::{no_escape, Handlebars};
use std::fs;
use std::fs::File;
use std::io::{BufWriter, Write};
use std::path::Path;
use std::process::Command;
use tempdir::TempDir;

#[derive(Deserialize, Debug)]
#[serde(rename_all = "kebab-case")]
pub struct PackDocker {
    entrypoint: Option<Vec<String>>,
    cmd: Option<Vec<String>>,
    base_image: String,
    bin: Option<String>,
    inject: Option<String>,
    tag: Option<String>,
}

#[derive(Deserialize, Debug)]
pub struct PackDockerConfig {
    docker: Vec<PackDocker>,
}

// assuming single bin.
pub struct Docker<'cfg> {
    config: PackDockerConfig,
    pack: CargoPack<'cfg>,
    tags: Vec<String>,
    is_release: bool,
}

#[derive(Deserialize, Serialize, Debug)]
pub struct DockerfileConfig {
    entrypoint: Option<String>,
    cmd: Option<String>,
    baseimage: String,
    files: Vec<String>,
    bin: String,
    inject: String,
}

impl PackDocker {
    fn base_name(&self, docker: &Docker) -> Result<String> {
        self.tag(docker).map(|name| {
            name.rsplitn(2, ':')
                .last()
            // should be safe but not confident
                .unwrap()
                .to_string()
        })
    }

    fn bin_name<'a>(&'a self, docker: &'a Docker) -> Result<&'a str> {
        let bins = docker
            .pack
            .package()?
            .targets()
            .iter()
            .filter(|t| t.is_bin())
            .map(|t| t.name())
            .collect::<Vec<_>>();

        if let Some(name) = self.bin.as_ref() {
            if bins.contains(&name.as_str()) {
                return Ok(name);
            } else {
                return Err(Error::BinNotFound(name.clone()).into());
            }
        }
        match bins.len() {
            0 => Err(Error::NoBins.into()),
            1 => Ok(bins.get(0).unwrap()),
            _ => Err(Error::AmbiguousBinName(bins.into_iter().map(Into::into).collect()).into()),
        }
    }

    fn tag(&self, docker: &Docker) -> Result<String> {
        if let Some(ref tag) = self.tag {
            Ok(tag.to_string())
        } else {
            let bin_name = self.bin_name(docker)?;
            let package = docker.pack.package().unwrap();
            let version = if docker.is_release {
                package.version().to_string()
            } else {
                "latest".to_string()
            };
            Ok(format!("{}:{}", bin_name, version))
        }
    }
}

impl<'cfg> Docker<'cfg> {
    pub fn new(
        config: PackDockerConfig,
        pack: CargoPack<'cfg>,
        tags: Vec<String>,
        is_release: bool,
    ) -> Self {
        Docker {
            config,
            pack,
            tags,
            is_release,
        }
    }

    pub fn pack(&self) -> Result<()> {
        debug!("tags: {:?}, config: {:?}", self.tags, self.config);
        debug!("workspace: {:?}", self.pack.package());
        debug!("preparing");
        for pack_docker in self.targets() {
            let tmpdir = self.prepare(pack_docker)?;
            debug!("building a image");
            self.build(tmpdir, pack_docker)?;
        }
        Ok(())
    }

    fn prepare(&self, pack_docker: &PackDocker) -> Result<TempDir> {
        let tmp = TempDir::new("cargo-pack-docker")?;
        debug!("created: {:?}", tmp);
        self.copy_files(&tmp)?;
        let bin = self.add_bin(&tmp, pack_docker)?;
        let data = DockerfileConfig {
            entrypoint: pack_docker.entrypoint.as_ref().map(|e| {
                e.iter()
                    .map(|s| format!("\"{}\"", s))
                    .collect::<Vec<_>>()
                    .join(", ")
            }),
            cmd: pack_docker.cmd.as_ref().map(|c| {
                c.iter()
                    .map(|s| format!("\"{}\"", s))
                    .collect::<Vec<_>>()
                    .join(", ")
            }),
            baseimage: pack_docker.base_image.clone(),
            files: self.pack.files().into(),
            bin: bin,
            inject: pack_docker
                .inject
                .as_ref()
                .map(|s| s.as_ref())
                .unwrap_or("")
                .to_string(),
        };
        self.gen_dockerfile(&tmp, &data)?;
        Ok(tmp)
    }

    fn build<P: AsRef<Path>>(&self, path: P, pack_docker: &PackDocker) -> Result<()> {
        let image_tag = pack_docker.tag(self)?;
        // FIXME: take from user
        let status = Command::new("/usr/bin/docker")
            .current_dir(&path)
            .arg("build")
            .arg(path.as_ref().to_str().unwrap())
            .args(&["-t", image_tag.as_str()])
            .spawn()?
            .wait()?;

        if status.success() {
            Ok(())
        } else {
            Err(format_err!("docker command faild"))
        }
    }

    fn copy_files<P: AsRef<Path>>(&self, path: P) -> Result<()> {
        for file in self.pack.files() {
            let to = path.as_ref().join(file);
            debug!("copying file: from {:?} to {:?}", file, to);
            copy_dir::copy_dir(file, to)?;
        }
        Ok(())
    }

    fn add_bin<P: AsRef<Path>>(&self, path: P, pack_docker: &PackDocker) -> Result<String> {
        let name = pack_docker.bin_name(self)?;
        let from = if self.is_release {
            self.pack.ws().target_dir().join("release").open_ro(
                &name,
                self.pack.ws().config(),
                "waiting for the bin",
            )?
        } else {
            self.pack.ws().target_dir().join("debug").open_ro(
                &name,
                self.pack.ws().config(),
                "waiting for the bin",
            )?
        };

        let from = from.path();
        let to = path.as_ref().join(&name);
        debug!("copying file: from {:?} to {:?}", from, to);
        fs::copy(from, to)?;
        Ok(name.into())
    }

    fn targets(&self) -> Vec<&PackDocker> {
        if self.tags.len() == 0 {
            self.config.docker.iter().collect()
        } else {
            // TODO: warn non existing tags
            self.config
                .docker
                .iter()
                .filter(|p| {
                    p.base_name(&self)
                        .map(|name| self.tags.contains(&name))
                        .unwrap_or(false)
                }).collect()
        }
    }

    fn gen_dockerfile<P: AsRef<Path>>(&self, path: P, data: &DockerfileConfig) -> Result<()> {
        let dockerfile = path.as_ref().join("Dockerfile");
        debug!("generating {:?}", dockerfile);
        let file = File::create(dockerfile)?;
        debug!("Dockerfile creation succeeded.");
        debug!("templating with {:?}", data);
        let mut buf = BufWriter::new(file);
        let template = r#"
FROM {{ baseimage }}

RUN mkdir -p /opt/app/bin
{{#each files as |file| ~}}
  COPY {{ file }} /opt/app
{{/each~}}
COPY {{bin}} /opt/app/bin
WORKDIR /opt/app

{{inject}}

{{#if entrypoint ~}}
ENTRYPOINT [{{entrypoint}}]
{{else ~}}
ENTRYPOINT ["/opt/app/bin/{{bin}}"]
{{/if ~}}
{{#if cmd ~}}
CMD [{{cmd}}]
{{/if}}
"#;
        let mut handlebars = Handlebars::new();

        handlebars.register_escape_fn(no_escape);
        handlebars
            .register_template_string("dockerfile", template)
            .expect("internal error: illegal template");

        handlebars
            .render_to_write("dockerfile", data, &mut buf)
            .unwrap();
        debug!("templating done");
        let _ = buf.flush()?;
        debug!(
            "content:{}",
            paths::read(path.as_ref().join("Dockerfile").as_ref())?
        );

        Ok(())
    }
}
// mktmpdir
// cp files to tmpdir
// output Dockerfile
// docker build -f Dockerfile ./