cranko 0.0.22

A cross-platform, cross-language release automation tool
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
// Copyright 2020 Peter Williams <peter@newton.cx> and collaborators
// Licensed under the MIT License.

//! Release automation utilities related to the GitHub service.

use anyhow::{anyhow, Context};
use json::{object, JsonValue};
use log::{error, info, warn};
use std::{env, fs::File, path::PathBuf};
use structopt::StructOpt;

use super::Command;
use crate::{
    app::AppSession,
    errors::{Error, Result},
    graph,
    project::Project,
    repository::{CommitId, ReleasedProjectInfo},
};

fn maybe_var(key: &str) -> Result<Option<String>> {
    if let Some(os_str) = env::var_os(key) {
        if let Ok(s) = os_str.into_string() {
            if s.len() > 0 {
                Ok(Some(s))
            } else {
                Ok(None)
            }
        } else {
            Err(Error::Environment(format!(
                "could not parse environment variable {} as Unicode",
                key
            )))
        }
    } else {
        Ok(None)
    }
}

fn require_var(key: &str) -> Result<String> {
    maybe_var(key)?
        .ok_or_else(|| Error::Environment(format!("environment variable {} must be provided", key)))
}

struct GitHubInformation {
    slug: String,
    token: String,
}

impl GitHubInformation {
    fn new(sess: &AppSession) -> Result<Self> {
        let token = require_var("GITHUB_TOKEN")?;

        let upstream_url = sess.repo.upstream_url()?;
        info!("upstream url: {}", upstream_url);

        let upstream_url = git_url_parse::GitUrl::parse(&upstream_url).map_err(|e| {
            Error::Environment(format!(
                "cannot parse upstream Git URL `{}`: {}",
                upstream_url, e
            ))
        })?;

        let slug = upstream_url.fullname;

        Ok(GitHubInformation { slug, token })
    }

    fn make_blocking_client(&self) -> Result<reqwest::blocking::Client> {
        use reqwest::header;
        let mut headers = header::HeaderMap::new();
        headers.insert(
            header::AUTHORIZATION,
            header::HeaderValue::from_str(&format!("token {}", self.token))?,
        );
        headers.insert(header::USER_AGENT, header::HeaderValue::from_str("cranko")?);

        Ok(reqwest::blocking::Client::builder()
            .default_headers(headers)
            .build()?)
    }

    fn api_url(&self, rest: &str) -> String {
        format!("https://api.github.com/repos/{}/{}", self.slug, rest)
    }

    /// Get information about an existing release.
    fn get_release_metadata(
        &self,
        sess: &AppSession,
        proj: &Project,
        rel: &ReleasedProjectInfo,
        client: &mut reqwest::blocking::Client,
    ) -> Result<JsonValue> {
        let tag_name = sess.repo.get_tag_name(proj, rel)?;
        let query_url = self.api_url(&format!("releases/tags/{}", tag_name));

        let resp = client.get(&query_url).send()?;
        if resp.status().is_success() {
            Ok(json::parse(&resp.text()?)?)
        } else {
            Err(Error::Environment(format!(
                "no GitHub release for tag `{}`: {}",
                tag_name,
                resp.text()
                    .unwrap_or_else(|_| "[non-textual server response]".to_owned())
            )))
        }
    }

    /// Create a new GitHub release.
    fn create_release(
        &self,
        sess: &AppSession,
        proj: &Project,
        rel: &ReleasedProjectInfo,
        cid: &CommitId,
        client: &mut reqwest::blocking::Client,
    ) -> Result<JsonValue> {
        let tag_name = sess.repo.get_tag_name(proj, rel)?;

        let changelog = proj.changelog.scan_changelog(proj, &sess.repo, cid)?;

        let release_info = object! {
            "tag_name" => tag_name.clone(),
            "name" => format!("{} {}", proj.user_facing_name, proj.version),
            "body" => changelog,
            "draft" => false,
            "prerelease" => false,
        };

        let create_url = self.api_url("releases");
        let resp = client
            .post(&create_url)
            .body(json::stringify(release_info))
            .send()?;
        let status = resp.status();
        let parsed = json::parse(&resp.text()?)?;

        if status.is_success() {
            info!("created GitHub release for {}", tag_name);
            Ok(parsed)
        } else {
            Err(Error::Environment(format!(
                "failed to create GitHub release for {}: {}",
                tag_name, parsed
            )))
        }
    }
}

/// Create new release(s) on GitHub.
#[derive(Debug, PartialEq, StructOpt)]
pub struct CreateReleasesCommand {
    #[structopt(help = "Name(s) of the project(s) to release on GitHub")]
    proj_names: Vec<String>,
}

impl Command for CreateReleasesCommand {
    fn execute(self) -> anyhow::Result<i32> {
        let mut sess = AppSession::initialize()?;
        let info = GitHubInformation::new(&sess)?;

        sess.populated_graph()?;

        let (dev_mode, rel_info) = sess.ensure_ci_release_mode()?;
        let rel_commit = rel_info
            .commit
            .as_ref()
            .ok_or_else(|| anyhow!("no commit ID for HEAD (?)"))?;

        if dev_mode {
            return Err(anyhow!("refusing to proceed in dev mode"));
        }

        // Get the list of projects that we're interested in.
        let mut q = graph::GraphQueryBuilder::default();
        q.names(self.proj_names);
        let no_names = q.no_names();
        let idents = sess
            .graph()
            .query(q)
            .context("could not select projects for GitHub release")?;

        if idents.len() == 0 {
            info!("no projects selected");
            return Ok(0);
        }

        let mut client = info.make_blocking_client()?;
        let mut n_released = 0;

        for ident in &idents {
            let proj = sess.graph().lookup(*ident);

            if let Some(rel) = rel_info.lookup_if_released(proj) {
                info.create_release(&sess, proj, &rel, rel_commit, &mut client)?;
                n_released += 1;
            } else if !no_names {
                warn!(
                    "project {} was specified but does not have a new release",
                    proj.user_facing_name
                );
            }
        }

        if no_names && n_released != 1 {
            info!(
                "created GitHub releases for {} of {} projects",
                n_released,
                idents.len()
            );
        } else if n_released != idents.len() {
            warn!(
                "created GitHub releases for {} of {} selected projects",
                n_released,
                idents.len()
            );
        }

        Ok(0)
    }
}

/// hidden Git credential helper command
#[derive(Debug, PartialEq, StructOpt)]
pub struct CredentialHelperCommand {
    #[structopt(help = "The operation")]
    operation: String,
}

impl Command for CredentialHelperCommand {
    fn execute(self) -> anyhow::Result<i32> {
        if self.operation != "get" {
            info!("ignoring Git credential operation `{}`", self.operation);
        } else {
            let token = require_var("GITHUB_TOKEN")?;
            println!("username=token");
            println!("password={}", token);
        }

        Ok(0)
    }
}

/// Install as a Git credential helper
#[derive(Debug, PartialEq, StructOpt)]
pub struct InstallCredentialHelperCommand {}

impl Command for InstallCredentialHelperCommand {
    fn execute(self) -> anyhow::Result<i32> {
        // The path given to Git must be an absolute path.
        let this_exe = std::env::current_exe()?;
        let this_exe = this_exe.to_str().ok_or_else(|| {
            anyhow!(
                "cannot install cranko as a Git \
                 credential helper because its executable path is not Unicode"
            )
        })?;
        let mut cfg = git2::Config::open_default().context("cannot open Git configuration")?;
        cfg.set_str(
            "credential.helper",
            &format!("{} github _credential-helper", this_exe),
        )
        .context("cannot update Git configuration setting `credential.helper`")?;
        Ok(0)
    }
}

/// Upload one or more artifact files to a GitHub release.
#[derive(Debug, PartialEq, StructOpt)]
pub struct UploadArtifactsCommand {
    #[structopt(
        long = "overwrite",
        help = "Overwrite artifacts if they already exist in the release (default: error out)"
    )]
    overwrite: bool,

    #[structopt(help = "The released project for which to upload content")]
    proj_name: String,

    #[structopt(help = "The path(s) to the file(s) to upload", required = true)]
    paths: Vec<PathBuf>,
}

impl Command for UploadArtifactsCommand {
    fn execute(self) -> anyhow::Result<i32> {
        let mut sess = AppSession::initialize()?;
        let info = GitHubInformation::new(&sess)?;

        sess.populated_graph()?;

        let rel_info = sess
            .repo
            .parse_release_info_from_head()
            .context("expected Cranko release metadata in the HEAD commit but could not load it")?;

        let mut client = info.make_blocking_client()?;

        let ident = sess
            .graph()
            .lookup_ident(&self.proj_name)
            .ok_or_else(|| anyhow!("no such project `{}`", self.proj_name))?;

        let rel = rel_info
            .lookup_if_released(sess.graph().lookup(ident))
            .ok_or_else(|| {
                anyhow!(
                    "project `{}` does not seem to be freshly released",
                    self.proj_name
                )
            })?;

        // Get information about the release

        let proj = sess.graph().lookup(ident);
        let mut metadata = info.get_release_metadata(&sess, proj, rel, &mut client)?;
        let upload_url = metadata["upload_url"]
            .take_string()
            .ok_or_else(|| anyhow!("no upload_url in release metadata?"))?;
        let upload_url = {
            // The returned value includes template `{?name,label}` at the end.
            let v: Vec<&str> = upload_url.split('{').collect();
            v[0].to_owned()
        };

        info!("upload url = {}", upload_url);

        // Upload artifacts

        for path in &self.paths {
            // Make sure the file exists!
            let file = File::open(path)?;

            let name = path
                .file_name()
                .ok_or_else(|| anyhow!("input file has no name component??"))?
                .to_str()
                .ok_or_else(|| anyhow!("input file name cannot be stringified"))?
                .to_owned();

            // If we're in overwrite mode, delete the artifact if it already
            // exists. This is racy, but the API doesn't give us a better method.

            if self.overwrite {
                for asset_info in metadata["assets"].members() {
                    // The `json` docs make it seem like I should just be able to
                    // write `asset_info["name"] == name`, but empirically that's
                    // not working.
                    if asset_info["name"].as_str() == Some(&name) {
                        info!("deleting preexisting asset (id {})", asset_info["id"]);

                        let del_url =
                            info.api_url(&format!("releases/assets/{}", asset_info["id"]));
                        let resp = client.delete(&del_url).send()?;
                        let status = resp.status();

                        if !status.is_success() {
                            error!("API response: {}", resp.text()?);
                            return Err(anyhow!("deletion of pre-existing asset {} failed", name));
                        }
                    }
                }
            }

            // Ready to upload now.

            info!("uploading {} => {}", path.display(), name);
            let url = reqwest::Url::parse_with_params(&upload_url, &[("name", &name)])?;
            let resp = client
                .post(url)
                .header(
                    reqwest::header::ACCEPT,
                    "application/vnd.github.manifold-preview",
                )
                .header(reqwest::header::CONTENT_TYPE, "application/octet-stream")
                .body(file)
                .send()?;
            let status = resp.status();
            let mut parsed = json::parse(&resp.text()?)?;

            if !status.is_success() {
                error!("API response: {}", parsed);
                return Err(anyhow!("creation of asset {} failed", name));
            }

            if let Some(s) = parsed["url"].take_string() {
                info!("   ... asset url = {}", s);
            }
        }

        info!("success!");
        Ok(0)
    }
}

#[derive(Debug, PartialEq, StructOpt)]
pub enum GithubCommands {
    #[structopt(name = "create-releases")]
    /// Create one or more new GitHub releases
    CreateReleases(CreateReleasesCommand),

    #[structopt(name = "_credential-helper", setting = structopt::clap::AppSettings::Hidden)]
    /// (hidden) github credential helper
    CredentialHelper(CredentialHelperCommand),

    #[structopt(name = "install-credential-helper")]
    /// Install Cranko as a Git "credential helper", using $GITHUB_TOKEN to log in
    InstallCredentialHelper(InstallCredentialHelperCommand),

    #[structopt(name = "upload-artifacts")]
    /// Upload one or more files as GitHub release artifacts
    UploadArtifacts(UploadArtifactsCommand),
}

#[derive(Debug, PartialEq, StructOpt)]
pub struct GithubCommand {
    #[structopt(subcommand)]
    command: GithubCommands,
}

impl Command for GithubCommand {
    fn execute(self) -> anyhow::Result<i32> {
        match self.command {
            GithubCommands::CreateReleases(o) => o.execute(),
            GithubCommands::CredentialHelper(o) => o.execute(),
            GithubCommands::InstallCredentialHelper(o) => o.execute(),
            GithubCommands::UploadArtifacts(o) => o.execute(),
        }
    }
}