-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgit.rs
313 lines (239 loc) · 6.75 KB
/
git.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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
use std::path::PathBuf;
use dirs::home_dir;
use git2::{
BranchType,
CredentialType,
Cred,
Delta,
DiffFile,
DiffOptions,
Error,
ErrorCode,
FetchOptions,
FetchPrune,
IndexAddOption,
ObjectType,
PushOptions,
Reference,
RemoteCallbacks,
Repository,
ResetType,
Signature,
};
use reqwest::blocking::Client;
use std::env;
use crate::regex::replace;
pub fn current_branch() -> Option<String> {
let repo = repo();
let branches = repo.branches(None).unwrap();
for item in branches {
let (branch, typ) = item.unwrap();
if branch.is_head() && typ == BranchType::Local {
let name = branch.name().unwrap().unwrap();
return Some(name.to_string());
}
}
return None;
}
pub fn list_changes_main() -> Vec<String> {
list_changes(
repo().find_branch("origin/main", BranchType::Remote)
.unwrap()
.get(),
false
)
}
fn list_stashable_changes_head() -> Vec<String> {
list_changes(&repo().head().unwrap(), true)
}
fn list_changes(reference: &Reference, stashable_only: bool) -> Vec<String> {
let tree = reference.peel_to_tree().unwrap();
let repo = repo();
let mut options = DiffOptions::new();
options.include_untracked(true);
let diff = repo.diff_tree_to_workdir(
Some(&tree), Some(&mut options)
).unwrap();
let deltas = diff.deltas();
let mut result: Vec<String> = Vec::new();
for delta in deltas {
if stashable_only && delta.status() == Delta::Untracked {
continue;
}
let old = get_path(delta.old_file());
if !result.contains(&old) {
result.push(old);
}
let new = get_path(delta.new_file());
if !result.contains(&new) {
result.push(new);
}
}
return result;
}
fn get_path(file: DiffFile) -> String {
return file.path().unwrap().to_str().unwrap().to_string();
}
pub fn has_pull_request(version: String) -> bool {
let url_repo = url_repo();
let url_api = url_api(&url_repo, version);
let client = Client::new().get(&url_api).header("User-Agent", "");
let response = client.send().unwrap();
let body = response.text().unwrap();
return body != "[]";
}
fn url_repo() -> String {
return repo().find_remote("origin").unwrap()
.url().unwrap().to_string();
}
fn url_api(url_repo: &str, version: String) -> String {
let pattern = r"[email protected]:(\w+)/(\w+).git";
let replacer = r"https://api.github.com/repos/$1/$2/pulls?state=open&head=$1:";
let replaced = replace(url_repo, pattern, replacer).unwrap();
return format!("{}{}", replaced, version);
}
pub fn update_local() {
let repo = repo();
let mut remote = repo.find_remote("origin").unwrap();
let mut callbacks = RemoteCallbacks::new();
callbacks.credentials(&git_credentials_callback);
let mut options = FetchOptions::new();
options.remote_callbacks(callbacks);
options.prune(FetchPrune::On);
remote.fetch(
&[] as &[&str],
Some(&mut options),
Some("updating local")
).unwrap();
}
fn git_credentials_callback(
_url: &str,
username: Option<&str>,
_cred_type: CredentialType,
) -> Result<Cred, Error> {
let public = get_key_path(Some("pub"));
let private = get_key_path(None);
return Cred::ssh_key(
username.unwrap(),
Some(public.as_path()),
private.as_path(),
None,
);
}
fn get_key_path(extension: Option<&str>) -> PathBuf {
let ssh_key = env::var("GIT_SSH_KEY_NAME")
.expect("No GIT_SSH_KEY_NAME environment variable found");
let mut path = home_dir().unwrap();
path.push(".ssh");
path.push(ssh_key);
if let Some(extension_value) = extension {
path.set_extension(extension_value);
}
return path;
}
pub fn go_to_main() {
let repo = repo();
let commit = repo.find_commit(
repo.find_branch(
"origin/main", BranchType::Remote
).unwrap()
.get().target().unwrap()
).unwrap();
repo.branch("main", &commit, false).unwrap();
let obj = repo.revparse_single("refs/heads/main").unwrap();
repo.checkout_tree(&obj, None).unwrap();
repo.set_head("refs/heads/main").unwrap();
}
pub fn create_tag(name: &str, annotation: &str) {
let repo = repo();
let head = repo.head().unwrap().peel(ObjectType::Commit).unwrap();
repo.tag(&name, &head, &signature(), &annotation, false).unwrap();
}
pub fn create_branch(branch_name: &str) {
let repo = repo();
create_branch_if_not_exists(&repo, branch_name);
let obj = repo.revparse_single(
&("refs/heads/".to_owned() + &branch_name)
).unwrap();
repo.checkout_tree(&obj, None).unwrap();
repo.set_head(&("refs/heads/".to_owned() + &branch_name)).unwrap();
}
fn create_branch_if_not_exists(repo: &Repository, branch_name: &str) {
if let Err(err) = repo.find_branch(&branch_name, BranchType::Local) {
if err.code() == ErrorCode::NotFound {
let head = repo.head().unwrap();
let oid = head.target().unwrap();
let commit = repo.find_commit(oid).unwrap();
repo.branch(&branch_name, &commit, false).unwrap();
return;
}
}
println!("... Branch {} already exists ...", &branch_name);
}
pub fn remove_branch(name: &str) {
repo().find_branch(&name, BranchType::Local).unwrap()
.delete().unwrap();
}
pub fn update_remote(tag: &str, branch: &str) {
let repo = repo();
let mut remote = repo.find_remote("origin").unwrap();
let mut callbacks = RemoteCallbacks::new();
callbacks.credentials(&git_credentials_callback);
let mut options = PushOptions::new();
options.remote_callbacks(callbacks);
let refs = [
format!("refs/tags/{}", tag),
format!("refs/heads/{}", branch),
];
remote.push(
&refs,
Some(&mut options)
).unwrap();
}
pub fn connect_local_and_remote_branch(branch_name: &str) {
let repo = repo();
let mut branch = repo.find_branch(&branch_name, BranchType::Local).unwrap();
let remote = format!("origin/{}", &branch_name);
branch.set_upstream(Some(&remote)).unwrap();
}
static mut STASHED: bool = false;
pub fn stash(message: &str) {
unsafe {
STASHED = list_stashable_changes_head().len() != 0;
if STASHED {
repo().stash_save(&signature(), message, None).unwrap();
}
}
}
pub fn reset_all() {
let repo = repo();
let head = repo.head().unwrap().peel(ObjectType::Commit).unwrap();
repo.reset(&head, ResetType::Hard, None).unwrap();
}
pub fn commit(message: &str) {
let repo = repo();
let mut index = repo.index().unwrap();
index.add_all(["*"].iter(), IndexAddOption::CHECK_PATHSPEC, None).unwrap();
index.write().unwrap();
let sign = signature();
let tree = repo.find_tree(index.write_tree().unwrap()).unwrap();
let parent = repo.head().unwrap().peel_to_commit().unwrap();
repo.commit(Some("HEAD"), &sign, &sign, message, &tree, &[&parent]).unwrap();
}
pub fn stash_pop() {
unsafe {
if STASHED {
repo().stash_pop(0, None).unwrap();
}
}
}
fn signature() -> Signature<'static> {
let name = env::var("GIT_NAME")
.expect("No GIT_NAME environment variable found");
let email = env::var("GIT_EMAIL")
.expect("No GIT_EMAIL environment variable found");
return Signature::now(&name, &email).unwrap();
}
fn repo() -> Repository {
Repository::open("..").unwrap()
}