patchy/
git_commands.rs

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
use crate::{utils::display_link, INDENT};
use colored::Colorize;
use std::{
    path::{Path, PathBuf},
    process::Output,
};

use anyhow::{anyhow, Context, Result};
use once_cell::sync::Lazy;
use reqwest::Client;

use crate::{
    flags::IS_VERBOSE,
    trace,
    types::{Branch, BranchAndRemote, GitHubResponse, Remote},
    utils::{make_request, normalize_commit_msg, with_uuid},
    APP_NAME,
};

pub fn is_valid_branch_name(branch_name: &str) -> bool {
    branch_name
        .chars()
        .all(|ch| ch.is_alphanumeric() || ch == '.' || ch == '-' || ch == '/' || ch == '_')
}

pub static GITHUB_REMOTE_PREFIX: &str = "git@github.com:";
pub static GITHUB_REMOTE_SUFFIX: &str = ".git";

pub fn spawn_git(args: &[&str], git_dir: &Path) -> Result<Output, std::io::Error> {
    std::process::Command::new("git")
        .args(args)
        .current_dir(git_dir)
        .output()
}

/// Removes a remote it's branch
pub fn clean_up_remote(remote: &str, branch: &str) -> anyhow::Result<()> {
    // It's okay to do this if the script created the branch or if the user gave explicit permission
    GIT(&["branch", "--delete", "--force", branch])?;
    GIT(&["remote", "remove", remote])?;
    Ok(())
}

pub fn get_git_output(output: Output, args: &[&str]) -> anyhow::Result<String> {
    if output.status.success() {
        Ok(String::from_utf8_lossy(&output.stdout)
            .trim_end()
            .to_owned())
    } else {
        Err(anyhow::anyhow!(
            "Git command failed.\nCommand: git {}\nStdout: {}\nStderr: {}",
            args.join(" "),
            String::from_utf8_lossy(&output.stdout),
            String::from_utf8_lossy(&output.stderr),
        ))
    }
}

pub fn get_git_root() -> anyhow::Result<PathBuf> {
    let current_dir = std::env::current_dir()?;

    let args = ["rev-parse", "--show-toplevel"];

    let root = spawn_git(&args, &current_dir)?;

    get_git_output(root, &args).map(|output| output.into())
}

pub static GIT_ROOT: Lazy<PathBuf> =
    Lazy::new(|| get_git_root().expect("Failed to determine Git root directory"));

type Git = Lazy<Box<dyn Fn(&[&str]) -> Result<String> + Send + Sync>>;

pub static GIT: Git = Lazy::new(|| {
    Box::new(move |args: &[&str]| -> Result<String> {
        get_git_output(spawn_git(args, &GIT_ROOT)?, args)
    })
});

/// Fetches a branch of a remote into local. Optionally accepts a commit hash for versioning.
pub fn add_remote_branch(
    info: &BranchAndRemote,
    commit_hash: &Option<String>,
) -> anyhow::Result<()> {
    match GIT(&[
        "remote",
        "add",
        &info.remote.local_remote_alias,
        &info.remote.repository_url,
    ]) {
        Ok(_) => {
            trace!(
                "Added remote {} for repository {}",
                &info.remote.repository_url,
                &info.remote.local_remote_alias
            );

            match GIT(&[
                "fetch",
                &info.remote.repository_url,
                &format!(
                    "{}:{}",
                    info.branch.upstream_branch_name, info.branch.local_branch_name
                ),
            ]) {
                Ok(_) => {
                    trace!(
                        "Fetched branch {} as {} from repository {}",
                        info.branch.upstream_branch_name,
                        info.branch.local_branch_name,
                        &info.remote.repository_url
                    );

                    if let Some(commit_hash) = commit_hash {
                        GIT(&[
                            "branch",
                            "--force",
                            &info.branch.local_branch_name,
                            commit_hash,
                        ])
                        .map_err(|err| {
                            anyhow!(
                                "We couldn't find commit {} \
                                of branch {}. Are you sure it exists?\n{err}",
                                commit_hash,
                                info.branch.local_branch_name
                            )
                        })?;

                        trace!("...and did a hard reset to commit {commit_hash}",);
                    };
                    Ok(())
                }
                Err(err) => Err(anyhow!(
                    "We couldn't find branch {} of GitHub repository {}. Are you sure it \
                     exists?\n{err}",
                    info.branch.upstream_branch_name,
                    info.remote.repository_url
                )),
            }
        }
        Err(err) => {
            GIT(&["remote", "remove", &info.remote.local_remote_alias])?;
            Err(anyhow!("Could not fetch remote: {err}"))
        }
    }
}

pub fn checkout_from_remote(branch: &str, remote: &str) -> anyhow::Result<String> {
    let current_branch = match GIT(&["rev-parse", "--abbrev-ref", "HEAD"]) {
        Ok(current_branch) => current_branch,
        Err(err) => {
            clean_up_remote(remote, branch)?;
            return Err(anyhow!(
                "Couldn't get the current branch. This usually happens \
                when the current branch does not have any commits.\n{err}"
            ));
        }
    };

    match GIT(&["checkout", branch]) {
        Ok(_) => Ok(current_branch),
        Err(err) => {
            clean_up_remote(remote, branch)?;
            Err(anyhow::anyhow!(
                "Could not checkout branch: {branch}, which belongs to remote {remote}\n{err}"
            ))
        }
    }
}

pub fn merge_into_main(
    local_branch: &str,
    remote_branch: &str,
) -> anyhow::Result<String, anyhow::Error> {
    match GIT(&["merge", local_branch, "--no-commit", "--no-ff"]) {
        Ok(_) => Ok(format!("Merged {remote_branch} successfully")),
        Err(_) => {
            let files_with_conflicts = GIT(&["diff", "--name-only", "--diff-filter=U"])?;
            for file_with_conflict in files_with_conflicts.lines() {
                if file_with_conflict.ends_with(".md") {
                    GIT(&["checkout", "--ours", file_with_conflict])?;
                    GIT(&["add", file_with_conflict])?;
                } else {
                    GIT(&["merge", "--abort"])?;
                    return Err(anyhow::anyhow!(
                        "Unresolved conflict in {file_with_conflict}"
                    ));
                }
            }
            Ok("Merged {remote_branch} successfully and disregarded conflicts".into())
        }
    }
}

pub async fn merge_pull_request(
    info: BranchAndRemote,
    pull_request: &str,
    pr_title: &str,
    pr_url: &str,
) -> anyhow::Result<()> {
    if let Err(err) = merge_into_main(
        &info.branch.local_branch_name,
        &info.branch.upstream_branch_name,
    ) {
        let pr = display_link(
            &format!(
                "{}{} {}",
                "#".bright_blue(),
                pull_request.bright_blue(),
                pr_title.bright_blue().italic()
            ),
            pr_url,
        );

        return Err(anyhow!(
            "Could not merge branch {} into the current branch for pull request {pr} since the merge is non-trivial.\nYou will need to merge it yourself. Skipping this PR. Error \
             message from git:\n{err}",
            &info.branch.local_branch_name.bright_cyan()
        ));
    }

    let has_unstaged_changes = GIT(&["diff", "--cached", "--quiet"]).is_err();

    if has_unstaged_changes {
        GIT(&[
            "commit",
            "--message",
            &format!(
                "{APP_NAME}: auto-merge pull request {}\n`patchy` is a tool which makes it easy to declaratively manage personal forks by automatically merging pull requests.

Check it out here: https://github.com/NikitaRevenco/patchy",
                &pr_url
            ),
        ])?;
    }

    clean_up_remote(
        &info.remote.local_remote_alias,
        &info.branch.local_branch_name,
    )?;

    Ok(())
}

pub async fn fetch_pull_request(
    repo: &str,
    pull_request: &str,
    client: &Client,
    custom_branch_name: Option<&str>,
    commit_hash: &Option<String>,
) -> anyhow::Result<(GitHubResponse, BranchAndRemote)> {
    let url = format!("https://api.github.com/repos/{}/pulls/{pull_request}", repo);

    let response = match make_request(client, &url).await {
        Ok(res) => res,
        Err(res) => {
            return Err(anyhow!(
                "Could not fetch pull request #{pull_request}\n{res}\n"
            ))
        }
    };

    let info = BranchAndRemote {
        branch: Branch {
            upstream_branch_name: response.head.r#ref.clone(),
            local_branch_name: custom_branch_name
                .map(|s| s.into())
                .unwrap_or(with_uuid(&format!(
                    "{title}-{}",
                    pull_request,
                    title = normalize_commit_msg(&response.title)
                ))),
        },
        remote: Remote {
            repository_url: response.head.repo.clone_url.clone(),
            local_remote_alias: with_uuid(&format!(
                "{title}-{}",
                pull_request,
                title = normalize_commit_msg(&response.html_url)
            )),
        },
    };

    add_remote_branch(&info, commit_hash).context(format!(
        "Could not add remote branch for pull request #{pull_request}, skipping."
    ))?;

    Ok((response, info))
}