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
/*
A command-line utility to work with Gerrit
Copyright (C) 2020 Kunal Mehta <legoktm@member.fsf.org>

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

//! `gerrit-grr` is a command-line utility to work with Gerrit. It also
//! provides a few library functions that might be convenient when building
//! tooling around Gerrit repositories and patches.
use anyhow::Result;
use ini::Ini;
use reqwest::Client;
use serde::Deserialize;
use std::collections::HashMap;
use std::path::Path;

/// gerrit-grr package version
pub const VERSION: &str = env!("CARGO_PKG_VERSION");

/// Represents metadata found in `.gitreview` files
pub struct DotGitReview {
    /// Hostname of Gerrit instance, e.g. `gerrit.wikimedia.org`
    pub host: String,
    /// Project name, with no trailing `.git` suffix
    pub project: String,
}

impl DotGitReview {
    /// Create an instance if you already know the host URL and project name
    pub fn new(host: &str, project: &str) -> DotGitReview {
        DotGitReview {
            host: host.to_string(),
            project: project.to_string(),
        }
    }
}

#[derive(Deserialize)]
struct GerritResponse {
    current_revision: String,
    revisions: HashMap<String, GerritRevision>,
}

#[derive(Deserialize)]
struct GerritRevision {
    fetch: AnonymousHttp,
}

#[derive(Deserialize)]
struct AnonymousHttp {
    #[serde(rename = "anonymous http")]
    anonymous_http: Fetch,
}

/// Information needed to fetch a Gerrit patch. Can be used as:
/// `git fetch {url} {git_ref}`.
#[derive(Deserialize, Clone)]
pub struct Fetch {
    /// URL for remote
    pub url: String,
    /// refspec to fetch
    #[serde(rename = "ref")]
    pub git_ref: String,
}

/// Get changes information from Gerrit's API
async fn rest_api_changes(
    host: String,
    patch: String,
) -> Result<GerritResponse> {
    let client = Client::builder()
        .user_agent(format!("rust-grr/{}", VERSION))
        .build()?;
    let resp = client
        .get(&format!(
            "https://{}/r/changes/{}?o=CURRENT_REVISION",
            host, patch
        ))
        .send()
        .await?;
    Ok(serde_json::from_str(&resp.text().await?[4..])?)
}

/// Get information about how to fetch a Gerrit patch. `patch` can either be
/// just the change number (`12345`) or include an optional patchset
/// (`12345:2`).
///
/// # Example
/// ```
/// # use gerrit_grr::{parse_gitreview, fetch_patch_info};
/// # async fn run() -> anyhow::Result<()> {
/// let cfg = parse_gitreview(".gitreview")?;
/// let fetch = fetch_patch_info("12345", cfg).await?;
/// # Ok(())
/// # }
/// ```
pub async fn fetch_patch_info(patch: &str, cfg: DotGitReview) -> Result<Fetch> {
    if patch.contains(':') {
        let split: Vec<&str> = patch.split(':').collect();
        let change = split[0];
        let patchset = split[1];
        Ok(Fetch {
            url: format!("https://{}/r/{}", cfg.host, cfg.project),
            git_ref: format!(
                "refs/changes/{}/{}/{}",
                &change[3..5],
                &change,
                &patchset
            ),
        })
    } else {
        let resp = rest_api_changes(cfg.host, patch.to_string()).await?;
        Ok(resp.revisions[&resp.current_revision]
            .fetch
            .anonymous_http
            .clone())
    }
}

/// Parse a .gitreview file
///
/// # Example
/// ```
/// # use gerrit_grr::parse_gitreview;
/// # fn run() -> anyhow::Result<()> {
/// let cfg = parse_gitreview(".gitreview")?;
/// println!("{}", cfg.host);
/// println!("{}", cfg.project);
/// # Ok(())
/// # }
/// ```
pub fn parse_gitreview<P: AsRef<Path>>(filename: P) -> Result<DotGitReview> {
    let conf = Ini::load_from_file(filename)?;
    let section = conf.section(Some("gerrit")).unwrap();
    let host = section.get("host").unwrap().to_string();
    // strip_suffix in the future
    let project = section.get("project").unwrap().replace(".git", "");
    Ok(DotGitReview::new(&host, &project))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_rest_api() {
        let resp = rest_api_changes(
            "gerrit.wikimedia.org".to_string(),
            "601523".to_string(),
        )
        .await
        .unwrap();
        assert_eq!(
            "373d514cc9e7fea5d05b9bf7915b70c02a42c115".to_string(),
            resp.current_revision
        );
        let fetch = resp.revisions[&resp.current_revision]
            .fetch
            .anonymous_http
            .clone();
        assert_eq!(
            "https://gerrit.wikimedia.org/r/labs/tools/newusers".to_string(),
            fetch.url
        );
        assert_eq!("refs/changes/23/601523/1".to_string(), fetch.git_ref);
    }
}