release-tool 0.5.0

Configuration-driven release lifecycle for computed-parameter repositories
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
use super::{
    PublicationReceipt, PublicationState, Publisher, VerificationReport, receipt, validate_manifest,
};
use crate::command::{CommandRequest, CommandRunner};
use crate::config::PublisherConfig;
use crate::doctor::Secret;
use crate::domain::{ArtifactIdentity, ArtifactManifest, PreparedArtifact, TargetPlan};
use anyhow::{Context, Result, bail};
use reqwest::StatusCode;
use sha2::{Digest, Sha256};
use std::collections::BTreeMap;
use std::path::PathBuf;
use std::sync::Arc;

pub trait MavenRemote: Send + Sync {
    fn get(&self, url: &str, actor: &str, token: &Secret) -> Result<Option<Vec<u8>>>;
}

struct ReqwestMavenRemote {
    client: reqwest::blocking::Client,
}

impl ReqwestMavenRemote {
    fn new() -> Result<Self> {
        Ok(Self {
            client: reqwest::blocking::Client::builder()
                .user_agent(concat!("release-tool/", env!("CARGO_PKG_VERSION")))
                .build()
                .context("failed to construct Maven HTTP client")?,
        })
    }
}

impl MavenRemote for ReqwestMavenRemote {
    fn get(&self, url: &str, actor: &str, token: &Secret) -> Result<Option<Vec<u8>>> {
        let response = self
            .client
            .get(url)
            .basic_auth(actor, Some(token.expose()))
            .send()
            .with_context(|| format!("failed to read Maven artifact {url}"))?;
        if response.status() == StatusCode::NOT_FOUND {
            return Ok(None);
        }
        let response = response
            .error_for_status()
            .with_context(|| format!("failed to read Maven artifact {url}"))?;
        Ok(Some(
            response
                .bytes()
                .context("failed to read Maven artifact body")?
                .to_vec(),
        ))
    }
}

pub struct GithubMavenPublisher {
    root: PathBuf,
    repository: String,
    name: String,
    settings: PathBuf,
    server_id: String,
    wrapper: PathBuf,
    actor: String,
    token: Secret,
    runner: Arc<dyn CommandRunner>,
    remote: Arc<dyn MavenRemote>,
}

impl GithubMavenPublisher {
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        root: impl Into<PathBuf>,
        repository: &str,
        name: &str,
        config: &PublisherConfig,
        wrapper: impl Into<PathBuf>,
        actor: &str,
        token: Secret,
        runner: Arc<dyn CommandRunner>,
    ) -> Result<Self> {
        Self::new_with_remote(
            root,
            repository,
            name,
            config,
            wrapper,
            actor,
            token,
            runner,
            Arc::new(ReqwestMavenRemote::new()?),
        )
    }

    #[allow(clippy::too_many_arguments)]
    pub fn new_with_remote(
        root: impl Into<PathBuf>,
        repository: &str,
        name: &str,
        config: &PublisherConfig,
        wrapper: impl Into<PathBuf>,
        actor: &str,
        token: Secret,
        runner: Arc<dyn CommandRunner>,
        remote: Arc<dyn MavenRemote>,
    ) -> Result<Self> {
        let PublisherConfig::GithubMaven {
            settings,
            server_id,
        } = config
        else {
            bail!("publisher `{name}` is not a github_maven publisher");
        };
        Ok(Self {
            root: root.into(),
            repository: repository.to_owned(),
            name: name.to_owned(),
            settings: settings.clone(),
            server_id: server_id.clone(),
            wrapper: wrapper.into(),
            actor: actor.to_owned(),
            token,
            runner,
            remote,
        })
    }

    fn base_url(&self) -> String {
        format!("https://maven.pkg.github.com/{}", self.repository)
    }

    fn url(&self, identity: &ArtifactIdentity) -> Result<String> {
        let ArtifactIdentity::MavenPackage {
            group_id,
            artifact_id,
            version,
            ..
        } = identity
        else {
            bail!("GitHub Maven publisher received a non-Maven artifact identity");
        };
        Ok(format!(
            "{}/{}/{artifact_id}/{version}/{}",
            self.base_url(),
            group_id.replace('.', "/"),
            identity.maven_file_name()?
        ))
    }

    fn state_for(&self, identities: &[ArtifactIdentity]) -> Result<PublicationState> {
        let mut present = Vec::new();
        let mut missing = Vec::new();
        for identity in identities {
            let url = self.url(identity)?;
            if self.remote.get(&url, &self.actor, &self.token)?.is_some() {
                present.push(url);
            } else {
                missing.push(url);
            }
        }
        if present.is_empty() {
            Ok(PublicationState::Absent)
        } else if missing.is_empty() {
            Ok(PublicationState::Complete)
        } else {
            Ok(PublicationState::Partial { present, missing })
        }
    }

    fn deploy(&self, manifest: &ArtifactManifest) -> Result<()> {
        // deploy-file requires no adopter model. An isolated launcher avoids evaluating
        // the source reactor or resolving the frozen artifact POM's local-only parent.
        let launcher = tempfile::tempdir().context("failed to create Maven deployment launcher")?;
        let launcher_pom = launcher.path().join("pom.xml");
        std::fs::write(
            &launcher_pom,
            "<project><modelVersion>4.0.0</modelVersion><groupId>release.tool</groupId><artifactId>deployment</artifactId><version>1</version><packaging>pom</packaging></project>\n",
        )?;
        type Gav = (String, String, String);
        let mut packages: BTreeMap<Gav, Vec<&PreparedArtifact>> = BTreeMap::new();
        for artifact in &manifest.artifacts {
            let ArtifactIdentity::MavenPackage {
                group_id,
                artifact_id,
                version,
                ..
            } = &artifact.identity
            else {
                bail!("Maven artifact manifest contains a non-Maven identity");
            };
            packages
                .entry((group_id.clone(), artifact_id.clone(), version.clone()))
                .or_default()
                .push(artifact);
        }
        let mut deployments = Vec::new();
        for ((group_id, artifact_id, version), artifacts) in &packages {
            let pom = artifacts
                .iter()
                .find(|artifact| {
                    classifier(&artifact.identity).is_none()
                        && extension(&artifact.identity) == Some("pom")
                })
                .with_context(|| format!("Maven package {group_id}:{artifact_id} has no POM"))?;
            let primary_artifacts = artifacts
                .iter()
                .filter(|artifact| {
                    classifier(&artifact.identity).is_none()
                        && extension(&artifact.identity) != Some("pom")
                })
                .copied()
                .collect::<Vec<_>>();
            if primary_artifacts.len() > 1 {
                bail!(
                    "Maven package {group_id}:{artifact_id}:{version} has more than one primary artifact"
                );
            }
            let primary = primary_artifacts.first().copied().unwrap_or(*pom);
            let mut arguments = vec![
                "--settings".to_owned(),
                self.settings.display().to_string(),
                "--batch-mode".to_owned(),
                "--no-transfer-progress".to_owned(),
                "--non-recursive".to_owned(),
                "-f".to_owned(),
                launcher_pom.display().to_string(),
                "org.apache.maven.plugins:maven-deploy-plugin:3.1.4:deploy-file".to_owned(),
                format!("-Dfile={}", primary.path.display()),
            ];
            if extension(&primary.identity) == Some("pom") {
                arguments.extend([
                    "-Dpackaging=pom".to_owned(),
                    "-DgeneratePom=false".to_owned(),
                ]);
            } else {
                arguments.push(format!("-DpomFile={}", pom.path.display()));
            }
            let attached = artifacts
                .iter()
                .filter(|artifact| classifier(&artifact.identity).is_some())
                .collect::<Vec<_>>();
            if !attached.is_empty() {
                let mut files = Vec::new();
                let mut classifiers = Vec::new();
                let mut types = Vec::new();
                for artifact in attached {
                    let path = artifact
                        .path
                        .to_str()
                        .context("Maven attachment path must be UTF-8")?;
                    if path.contains(',') {
                        bail!("Maven attachment path must not contain a comma: {path}");
                    }
                    files.push(path);
                    classifiers.push(classifier(&artifact.identity).expect("filtered attachment"));
                    types.push(extension(&artifact.identity).expect("Maven identity"));
                }
                arguments.extend([
                    format!("-Dfiles={}", files.join(",")),
                    format!("-Dclassifiers={}", classifiers.join(",")),
                    format!("-Dtypes={}", types.join(",")),
                ]);
            }
            arguments.extend([
                format!("-DrepositoryId={}", self.server_id),
                format!("-Durl={}", self.base_url()),
                format!("-DgroupId={group_id}"),
                format!("-DartifactId={artifact_id}"),
                format!("-Dversion={version}"),
            ]);
            let mut request =
                CommandRequest::new(self.wrapper.display().to_string(), arguments, &self.root);
            request
                .environment
                .insert("GITHUB_ACTOR".to_owned(), self.actor.clone());
            request
                .environment
                .insert("GITHUB_TOKEN".to_owned(), self.token.expose().to_owned());
            deployments.push((
                format!("deploy Maven package {group_id}:{artifact_id}:{version}"),
                request,
            ));
        }
        // Validate every GAV's command before the first remote write.
        for (description, request) in deployments {
            self.runner
                .execute(&request)?
                .redact([self.token.expose()])
                .require_success(&description)?;
        }
        Ok(())
    }
}

impl Publisher for GithubMavenPublisher {
    fn inspect(&self, plan: &TargetPlan) -> Result<PublicationState> {
        self.state_for(&plan.artifacts)
    }

    fn publish(&self, manifest: &ArtifactManifest) -> Result<PublicationReceipt> {
        if !manifest.release.tag_already_sealed {
            bail!(
                "release {} is not sealed on the remote",
                manifest.release.tag
            );
        }
        if manifest.publisher != self.name {
            bail!(
                "artifact manifest belongs to publisher `{}`",
                manifest.publisher
            );
        }
        validate_manifest(manifest)?;
        let identities = manifest
            .artifacts
            .iter()
            .map(|artifact| artifact.identity.clone())
            .collect::<Vec<_>>();
        match self.state_for(&identities)? {
            PublicationState::Complete => {
                self.verify(manifest)?;
                return Ok(receipt(manifest, &self.name, true));
            }
            PublicationState::Partial { .. } => {
                bail!("partial Maven publication is not recoverable automatically")
            }
            PublicationState::Invalid { reason } => bail!("invalid Maven publication: {reason}"),
            PublicationState::Absent => {}
        }
        let deploy_result = self.deploy(manifest);
        let state_after_deploy = self.state_for(&identities);
        match (deploy_result, state_after_deploy) {
            (_, Ok(PublicationState::Complete)) => {}
            (Err(deploy_error), Ok(state)) => {
                return Err(deploy_error
                    .context(format!("Maven deploy failed and remote state is {state:?}")));
            }
            (Err(deploy_error), Err(inspect_error)) => {
                return Err(deploy_error.context(format!(
                    "Maven deploy failed; remote reconciliation also failed: {inspect_error:#}"
                )));
            }
            (Ok(()), Ok(state)) => {
                bail!("Maven publication is not complete after deploy: {state:?}");
            }
            (Ok(()), Err(inspect_error)) => return Err(inspect_error),
        }
        self.verify(manifest)?;
        Ok(receipt(manifest, &self.name, false))
    }

    fn verify(&self, manifest: &ArtifactManifest) -> Result<VerificationReport> {
        let mut verified = Vec::new();
        for artifact in &manifest.artifacts {
            let url = self.url(&artifact.identity)?;
            let bytes = self
                .remote
                .get(&url, &self.actor, &self.token)?
                .with_context(|| format!("published Maven artifact is missing: {url}"))?;
            let actual = hex::encode(Sha256::digest(&bytes));
            if actual != artifact.sha256 {
                bail!(
                    "published Maven artifact digest mismatch for {url}: expected {}, found {actual}",
                    artifact.sha256
                );
            }
            verified.push(url);
        }
        Ok(VerificationReport {
            target: manifest.target.clone(),
            verified: true,
            artifacts: verified,
        })
    }

    fn verify_existing(&self, plan: &TargetPlan) -> Result<VerificationReport> {
        match self.inspect(plan)? {
            PublicationState::Complete => {}
            state => bail!("cannot verify incomplete Maven publication: {state:?}"),
        }
        let mut verified = Vec::new();
        for identity in &plan.artifacts {
            let url = self.url(identity)?;
            let bytes = self
                .remote
                .get(&url, &self.actor, &self.token)?
                .with_context(|| format!("published Maven artifact is missing: {url}"))?;
            if bytes.is_empty() {
                bail!("published Maven artifact is empty: {url}");
            }
            verified.push(url);
        }
        Ok(VerificationReport {
            target: plan.name.clone(),
            verified: true,
            artifacts: verified,
        })
    }
}

fn extension(identity: &ArtifactIdentity) -> Option<&str> {
    match identity {
        ArtifactIdentity::MavenPackage { extension, .. } => Some(extension),
        _ => None,
    }
}

fn classifier(identity: &ArtifactIdentity) -> Option<&str> {
    match identity {
        ArtifactIdentity::MavenPackage { classifier, .. } => classifier.as_deref(),
        _ => None,
    }
}