-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathmod.rs
811 lines (757 loc) · 26.8 KB
/
mod.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
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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
//
// Copyright:: Copyright (c) 2015 Chef Software, Inc.
// License:: Apache License, Version 2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
pub use errors;
use errors::{DeliveryError, Kind};
use project::project_path;
use regex::Regex;
use std::convert::AsRef;
use std::env;
use std::error;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use types::DeliveryResult;
use utils::path_ext::is_dir;
use utils::say::{say, sayln, Spinner};
use utils::{cmd_success_or_err, find_command};
fn cwd() -> PathBuf {
env::current_dir().unwrap()
}
pub fn get_head() -> Result<String, DeliveryError> {
let gitr = try!(git_command(&["branch"], &cwd()));
let result = try!(parse_get_head(&gitr.stdout));
Ok(result)
}
fn parse_get_head(stdout: &str) -> Result<String, DeliveryError> {
for line in stdout.lines() {
let r = Regex::new(r"(.) (.+)").unwrap();
let caps_result = r.captures(line);
let caps = match caps_result {
Some(caps) => caps,
None => {
return Err(DeliveryError {
kind: Kind::BadGitOutputMatch,
detail: Some(format!("Failed to match: {}", line)),
})
}
};
let token = caps.get(1).unwrap().as_str();
if token == "*" {
let branch = caps.get(2).unwrap().as_str();
return Ok(String::from(branch));
}
}
return Err(DeliveryError {
kind: Kind::NotOnABranch,
detail: None,
});
}
#[test]
fn test_parse_get_head() {
let stdout = " adam/review
adam/test
adam/test6
builder
first
foo
foo2
* master
snazzy
testerton";
let result = parse_get_head(stdout);
match result {
Ok(branch) => {
assert_eq!(&branch[..], "master");
}
Err(_) => panic!("No result"),
};
}
pub struct GitResult {
pub stdout: String,
pub stderr: String,
}
// What is this crazy type signature, you ask? Let me explain!
//
// Where <P: ?Sized> == Any Type (Sized or Unsized)
// Where P: AsRef<Path> == Any type that implements the AsRef<Path> trait
pub fn git_command<P>(args: &[&str], c: &P) -> Result<GitResult, DeliveryError>
where
P: AsRef<Path> + ?Sized,
{
let cwd = c.as_ref();
let spinner = Spinner::start();
let command_path = match find_command("git") {
Some(path) => path,
None => {
return Err(DeliveryError {
kind: Kind::FailedToExecute,
detail: Some("git executable not found".to_owned()),
})
}
};
let mut command = Command::new(command_path);
// SSH Agent is required on windows Hence,
// Rebuilding the command in a way; that
// Invoke an agent; Run the SSH Command and kill the agent then and there
// Pattern: \embedded\git\bash -c 'eval `ssh-agent` && ssh-add && <COMMAND> ; ssh-agent -k'
// TODO: Check for SSH type authencation may be required
if cfg!(target_os = "windows") {
command.arg("-c");
let agent_setup = "eval `ssh-agent` && ssh-add && git";
let agent_kill = "; ssh-agent -k";
let cmd_args = args.join(" ");
let command_ars = &[&[agent_setup, &cmd_args, agent_kill].join(" ")];
command.args(command_ars);
command.stderr(Stdio::inherit());
} else {
command.args(args);
}
command.current_dir(cwd);
debug!("Git command: {:?}", command);
let output = match command.output() {
Ok(o) => o,
Err(e) => {
spinner.stop();
return Err(DeliveryError {
kind: Kind::FailedToExecute,
detail: Some(format!(
"failed to execute git: {}",
error::Error::description(&e)
)),
});
}
};
debug!("Git exited: {}", output.status);
spinner.stop();
cmd_success_or_err(&output, Kind::GitFailed)?;
let stdout = String::from_utf8_lossy(&output.stdout).to_string();
debug!("Git stdout: {}", stdout);
let stderr = String::from_utf8_lossy(&output.stderr).to_string();
debug!("Git stderr: {}", stderr);
Ok(GitResult {
stdout: stdout,
stderr: stderr,
})
}
pub fn git_push_review(branch: &str, target: &str) -> Result<ReviewResult, DeliveryError> {
let gitr = try!(git_command(
&[
"push",
"--porcelain",
"--progress",
"--verbose",
"delivery",
&format!("{}:_for/{}/{}", branch, target, branch),
],
&cwd()
));
parse_git_push_output(&gitr.stdout, &gitr.stderr)
}
#[derive(Debug, Clone, PartialEq)]
pub enum PushResultFlag {
SuccessfulFastForward,
SuccessfulForcedUpdate,
SuccessfulDeletedRef,
SuccessfulPushedNewRef,
Rejected,
UpToDate,
}
impl Copy for PushResultFlag {}
/// Returned by `git_push_review`. The `push_results` field is a
/// vector of `PushResult` each indicating a `PushResultFalg` and a
/// reason message. The `messages` field is a vector of output lines
/// returned from the server managing the git protocol (as you'd see
/// on the command line prefixed with `remote: $LINE`. The `url` field
/// will contain the last line that looks like a URL returned as
/// remote data.
#[derive(Debug, PartialEq)]
pub struct ReviewResult {
pub push_results: Vec<PushResult>,
pub messages: Vec<String>,
pub url: Option<String>,
pub change_id: Option<String>,
}
impl Default for ReviewResult {
fn default() -> ReviewResult {
ReviewResult {
push_results: Vec::new(),
messages: Vec::new(),
url: None,
change_id: None,
}
}
}
#[derive(Debug, PartialEq)]
pub struct PushResult {
flag: PushResultFlag,
summary: String,
reason: Option<String>,
}
pub fn parse_git_push_output(
push_output: &str,
push_error: &str,
) -> Result<ReviewResult, DeliveryError> {
let mut review_result = ReviewResult::default();
for line in push_error.lines() {
debug!("error: {}", line);
if line.starts_with("remote") {
parse_line_from_remote(&line, &mut review_result);
}
}
for line in push_output.lines() {
debug!("output: {}", line);
if line.starts_with("To") || line.starts_with("Done") {
continue;
}
let r = Regex::new(r"^(.)\t(.*):(.+)\t(?:\[(.+)\]|([^ ]+))(?: \((.+)\))?$").unwrap();
let caps_result = r.captures(line);
let caps = match caps_result {
Some(caps) => caps,
None => {
let detail = Some(format!("Failed to match: {}", line));
return Err(DeliveryError {
kind: Kind::BadGitOutputMatch,
detail: detail,
});
}
};
let result_flag = match caps.get(1).unwrap().as_str() {
" " => PushResultFlag::SuccessfulFastForward,
"+" => PushResultFlag::SuccessfulForcedUpdate,
"-" => PushResultFlag::SuccessfulDeletedRef,
"*" => PushResultFlag::SuccessfulPushedNewRef,
"!" => PushResultFlag::Rejected,
"=" => PushResultFlag::UpToDate,
_ => {
return Err(DeliveryError {
kind: Kind::BadGitOutputMatch,
detail: Some(format!("Unknown result flag")),
})
}
};
// if it contains a space, it's in [...] (capture #4),
// if not (e.g. "oldref..newref"), it's not in [...] (capture #5)
let summary = match (caps.get(4), caps.get(5)) {
(Some(str), _) => String::from(str.as_str()),
(_, Some(str)) => String::from(str.as_str()),
(None, None) => "".to_string(),
};
let reason = match caps.get(6) {
None => None,
Some(str) => Some(String::from(str.as_str())),
};
review_result.push_results.push(PushResult {
flag: result_flag,
summary: summary,
reason: reason,
})
}
Ok(review_result)
}
/// Parses a line returned by the remote
fn parse_line_from_remote(line: &str, review_result: &mut ReviewResult) -> () {
// this weird regex accounts for the fact that some versions of git
// (at least 1.8.5.2 (Apple Git-48), but possibly others) append the
// ANSI code ESC[K to every line of the remote's answer when pushing
let r = Regex::new(r"remote: ([^\x{1b}]+)(?:\x{1b}\[K)?$").unwrap();
let caps_result = r.captures(line);
match caps_result {
Some(caps) => {
let cap = caps.get(1).unwrap().as_str();
if cap.starts_with("http") {
let change_url = cap.trim().to_string();
review_result.url = Some(change_url.clone());
let change_id_regex =
Regex::new(r"/([a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12})").unwrap();
let change_id_match = change_id_regex.captures(&change_url);
review_result.change_id = Some(String::from(
change_id_match.unwrap().get(1).unwrap().as_str(),
));
} else {
review_result.messages.push(cap.to_string());
}
}
None => {}
}
}
pub fn check_repo_init(path: &PathBuf) -> Result<(), DeliveryError> {
say("white", "Is ");
say("magenta", &format!("{} ", path.display()));
say("white", "a git repo? ");
let git_dir = path.join(".git");
if is_dir(git_dir.as_path()) {
sayln("white", "yes");
return Ok(());
} else {
sayln(
"red",
"no. Run 'git init' here and then 'delivery init' again.",
);
return Err(DeliveryError {
kind: Kind::GitSetupFailed,
detail: None,
});
}
}
// This function is not currently used, but will be when we
// add a --force option to the init command.
pub fn create_repo(path: &PathBuf) -> Result<(), DeliveryError> {
say("white", "Creating repo in: ");
say("magenta", &format!("{} ", path.display()));
let result = git_command(&["init"], path);
match result {
Ok(_) => {
sayln("white", "'git init' done.");
return Ok(());
}
Err(e) => return Err(e),
}
}
// Returns the (Git) delivery remote URL form the specified repository path
//
// ex.=> ssh://user@[email protected]:8989/ent/organization/foo
pub fn delivery_remote_from_repo<P>(path: P) -> DeliveryResult<String>
where
P: AsRef<Path>,
{
git_command(&["config", "--get", "remote.delivery.url"], path.as_ref())
.map(|g| g.stdout.trim().to_string())
// If there is no 'delivery' remote, return an empty String
.or(Ok(String::from("")))
}
// Update the (Git) delivery remote
//
// Try to add the delivery remote and if it fails adding it, try to remove
// it first and then add it. This way we ensure we are updating it with the
// provided URL no mather if it already exists or not.
pub fn update_delivery_remote<P, S>(url: S, path: P) -> DeliveryResult<()>
where
P: AsRef<Path>,
S: AsRef<str>,
{
let path = path.as_ref();
let url = url.as_ref();
git_command(&["remote", "add", "delivery", url], path)
.map(|_| ())
.or_else(|e| {
let msg = e.detail.clone().unwrap_or(String::from(""));
if msg.contains("remote delivery already exists") {
try!(git_command(&["remote", "rm", "delivery"], path));
try!(git_command(&["remote", "add", "delivery", url], path));
return Ok(());
}
return Err(e);
})
}
pub fn checkout_branch_name(change: &str, patchset: &str) -> String {
if patchset == "latest" {
return String::from(change);
} else {
return format!("{}/{}", change, patchset);
}
}
pub fn diff(
change: &str,
patchset: &str,
pipeline: &str,
local: &bool,
) -> Result<(), DeliveryError> {
try!(git_command(&["fetch", "delivery"], &cwd()));
let mut first_branch = format!("delivery/{}", pipeline);
if *local {
first_branch = String::from("HEAD");
}
let diff = try!(git_command(
&[
"diff",
"--color=always",
&first_branch,
&format!("delivery/_reviews/{}/{}/{}", pipeline, change, patchset),
],
&cwd()
));
say("white", "\n");
sayln("white", &diff.stdout);
Ok(())
}
pub fn clone(project: &str, git_url: &str) -> Result<(), DeliveryError> {
try!(git_command(&["clone", git_url, project], &cwd()));
Ok(())
}
pub fn checkout_review(change: &str, patchset: &str, pipeline: &str) -> Result<(), DeliveryError> {
try!(git_command(&["fetch", "delivery"], &cwd()));
let branchname = checkout_branch_name(change, patchset);
let result = git_command(
&[
"branch",
"--track",
&branchname,
&format!("delivery/_reviews/{}/{}/{}", pipeline, change, patchset),
],
&cwd(),
);
match result {
Ok(_) => {
try!(git_command(&["checkout", &branchname], &cwd()));
return Ok(());
}
Err(e) => match e.detail {
Some(msg) => {
if msg.contains("already exists.") {
try!(git_command(&["checkout", &branchname], &cwd()));
sayln("white", "Branch already exists, checking it out.");
let r = try!(git_command(&["status"], &cwd()));
sayln("white", &r.stdout);
return Ok(());
} else {
return Err(DeliveryError {
kind: Kind::GitFailed,
detail: Some(msg),
});
}
}
None => return Err(e),
},
}
}
// Verify the content of the repo:pipeline on the server
pub fn server_content(pipeline: &str) -> Result<bool, DeliveryError> {
let p_ref = &format!("refs/heads/{}", pipeline);
match git_command(&["ls-remote", "delivery", p_ref], &cwd()) {
Ok(msg) => {
if msg.stdout.contains(p_ref) {
return Ok(true);
} else {
return Ok(false);
}
}
Err(e) => return Err(e),
}
}
pub fn git_pull(branch: &str, rebase: bool) -> Result<GitResult, DeliveryError> {
// First, check if branch exists because for some reason rust
// will hang forever when trying to git pull a branch that doesn't exist.
match git_command(&["ls-remote", "--heads", "delivery"], &cwd()) {
Ok(result) => {
if !result.stdout.contains(&format!("refs/heads/{}", branch)) {
return Err(DeliveryError {
kind: Kind::BranchNotFoundOnDeliveryRemote,
detail: None,
});
}
}
Err(err) => return Err(err),
}
if rebase {
git_command(&["pull", "delivery", branch, "--rebase"], &cwd())
} else {
git_command(&["pull", "delivery", branch], &cwd())
}
}
pub fn git_current_sha() -> Result<String, DeliveryError> {
git_command(&["rev-parse", "HEAD"], &cwd()).and_then(|msg| Ok(msg.stdout))
}
// Push pipeline content to the Server
pub fn git_push(pipeline: &str) -> Result<(), DeliveryError> {
// Check if the pipeline branch exists and has commits.
// If the pipeline branch exists and does not have commits,
// then `git branch` will not return it, so just checking
// `git branch` output will handle both cases (pipeline does
// not exist and pipeline exists but without commits).
match git_command(&["branch"], &cwd()) {
Ok(msg) => {
if !msg.stdout.contains(pipeline) {
sayln(
"red",
&format!("A {} branch does not exist locally.", pipeline),
);
sayln(
"red",
&format!(
"A {} branch with commits is needed to create the {} \
pipeline.\n",
pipeline, pipeline
),
);
sayln(
"red",
&format!(
"If your project already has git history, you should \
pull it into {} locally.",
pipeline
),
);
sayln(
"red",
&format!(
"For example, if your remote is named origin, and your \
git history is in {} run:\n",
pipeline
),
);
sayln("red", &format!("git pull origin {}\n", pipeline));
sayln(
"red",
"However, if this is a brand new project, make an initial commit by running:\n",
);
sayln("red", &format!("git checkout -b {}", pipeline));
sayln("red", "git commit --allow-empty -m 'Initial commit.'\n");
sayln(
"red",
&format!(
"Once you have commits on the {} branch, run `delivery \
init` again.",
pipeline
),
);
return Err(DeliveryError {
kind: Kind::GitFailed,
detail: None,
});
}
true
}
Err(e) => return Err(e),
};
// Master branch exists with commits on it, push it up so the master pipeline can be made.
match git_command(
&[
"push",
"--set-upstream",
"--porcelain",
"--progress",
"--verbose",
"delivery",
pipeline,
],
&cwd(),
) {
Ok(_) => return Ok(()),
// Not expecting any errors at this point.
Err(e) => return Err(e),
}
}
// Commit content to local repo
//
// This fun will commit the changes you have loaded in the current repo,
// it will also detect if the commit failed and transform the error to a
// more specific one. (Ex. If we try to commit when nothing has changed)
pub fn git_commit(message: &str) -> Result<(), DeliveryError> {
match git_command(&["commit", "-m", message], &try!(project_path())) {
Err(DeliveryError {
kind,
detail: Some(output),
}) => {
if output.contains("nothing to commit") {
return Err(DeliveryError {
kind: Kind::EmptyGitCommit,
detail: None,
});
}
Err(DeliveryError {
kind: kind,
detail: Some(output),
})
}
Err(e) => Err(e),
Ok(_) => Ok(()),
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs::DirBuilder;
use std::path::PathBuf;
use tempdir::TempDir;
#[test]
fn test_check_repo_init_with_invalid_path() {
let path = PathBuf::from("/tmp/not_real");
assert!(check_repo_init(&path).is_err());
}
#[test]
fn test_check_repo_init_with_valid_path_no_git() {
let path = PathBuf::from("/tmp/real1");
DirBuilder::new().recursive(true).create(&path).unwrap();
assert!(check_repo_init(&path).is_err());
}
#[test]
fn test_check_repo_init_with_valid_path() {
let path = PathBuf::from("/tmp/real2/");
let full_path = path.join(".git");
DirBuilder::new()
.recursive(true)
.create(&full_path)
.unwrap();
assert!(check_repo_init(&path).is_ok());
}
#[test]
fn test_when_delivery_remote_from_repo_exist() {
let tempdir = TempDir::new("repo").ok().expect("Temp repo dir failed");
let path = tempdir.path();
// Initialize the fake repo
assert!(git_command(&["init"], path).is_ok());
assert!(git_command(&["remote", "add", "delivery", "awesome"], path).is_ok());
let remote_url = delivery_remote_from_repo(&path);
// Returns the remote URL, in this case "awesome"
assert_eq!(String::from("awesome"), remote_url.unwrap());
}
#[test]
fn test_when_delivery_remote_from_repo_not_exist() {
let tempdir = TempDir::new("repo").ok().expect("Temp repo dir failed");
let path = tempdir.path();
// Initialize the fake repo
assert!(git_command(&["init"], path).is_ok());
let remote_url = delivery_remote_from_repo(&path);
// Returns empty string
assert_eq!(String::from(""), remote_url.unwrap());
}
#[test]
fn test_parse_line_from_remote() {
test_parse_line_from_remote_with_eol("");
// older git versions add this ANSI escape code at the end of the lines
test_parse_line_from_remote_with_eol("\u{1b}[K");
}
fn test_parse_line_from_remote_with_eol(remote_msg_eol: &str) {
let mut review_result = ReviewResult::default();
// a random message line
let random_msg = "A random message";
let line1 = format!("remote: {}{}", random_msg, remote_msg_eol);
parse_line_from_remote(&line1, &mut review_result);
assert_eq!(random_msg, review_result.messages[0]);
// a change URL line
let change_id = "4bc3f44f-d81f-48a5-bd38-2c7963cb6d94";
let change_url = format!(
"https://delivery.shd.chef.co/e/Chef/#/organizations/sandbox/projects/radar/changes/{}",
change_id
);
let line2 = format!("remote: {}{}", change_url, remote_msg_eol);
parse_line_from_remote(&line2, &mut review_result);
assert_eq!(change_url, review_result.url.unwrap());
assert_eq!(change_id, review_result.change_id.unwrap());
}
#[test]
fn test_parse_git_push_output_when_fast_forward() {
// the strange line break position is because we need the leading space + tab
let stdout = "To ssh://tester@cd@localhost:8989/cd/test/test_proj17914\n \t\
refs/heads/baz:refs/heads/_for/master/baz\t6f7b537..228c615\n\
Done\n";
let ffwd = PushResult {
flag: PushResultFlag::SuccessfulFastForward,
summary: "6f7b537..228c615".to_string(),
reason: None,
};
test_parse_git_push_output(stdout, ffwd);
}
#[test]
fn test_parse_git_push_output_when_forced_update() {
let stdout = "To [email protected]:chef/delivery-cli\n\
+\trefs/heads/foo:refs/heads/foo\td3a8697...3d42f51 (forced update)\n\
Done\n";
let force_pushed = PushResult {
flag: PushResultFlag::SuccessfulForcedUpdate,
summary: "d3a8697...3d42f51".to_string(),
reason: Some("forced update".to_string()),
};
test_parse_git_push_output(stdout, force_pushed);
}
#[test]
fn test_parse_git_push_output_when_new_branch() {
let stdout = "To ssh://tester@cd@localhost:8989/cd/test/test_proj17914\n\
*\trefs/heads/baz:refs/heads/_for/master/baz\t[new branch]\n\
Done\n";
let new_branch = PushResult {
flag: PushResultFlag::SuccessfulPushedNewRef,
summary: "new branch".to_string(),
reason: None,
};
test_parse_git_push_output(stdout, new_branch);
}
#[test]
fn test_parse_git_push_output_when_deleted_ref() {
let stdout = "To [email protected]:srenatus/delivery-cli\n\
-\t:refs/heads/deleteme\t[deleted]\n\
Done\n";
let deleted_refs = PushResult {
flag: PushResultFlag::SuccessfulDeletedRef,
summary: "deleted".to_string(),
reason: None,
};
test_parse_git_push_output(stdout, deleted_refs);
}
#[test]
fn test_parse_git_push_output_when_up_to_date() {
let stdout = "To [email protected]:chef/delivery-cli\n\
=\trefs/heads/foo:refs/heads/foo\t[up to date]\n\
Done\n";
let up_to_date = PushResult {
flag: PushResultFlag::UpToDate,
summary: "up to date".to_string(),
reason: None,
};
test_parse_git_push_output(stdout, up_to_date);
}
#[test]
fn test_parse_git_push_output_when_rejected() {
let stdout = "To [email protected]:chef/delivery-cli\n\
!\trefs/heads/foo:refs/heads/foo\t[rejected] (non-fast-forward)\n\
Done\n";
let rejected = PushResult {
flag: PushResultFlag::Rejected,
summary: "rejected".to_string(),
reason: Some("non-fast-forward".to_string()),
};
test_parse_git_push_output(stdout, rejected);
}
#[test]
fn test_parse_git_push_output_when_more_than_one_thing_happened() {
let stdout = "To [email protected]:chef/delivery-cli\n\
*\trefs/heads/baz:refs/heads/_for/master/baz\t[new branch]\n\
!\trefs/heads/foo:refs/heads/foo\t[rejected] (non-fast-forward)\n\
=\trefs/heads/bar:refs/heads/bar\t[up to date]\n\
Done\n";
let new_branch = PushResult {
flag: PushResultFlag::SuccessfulPushedNewRef,
summary: "new branch".to_string(),
reason: None,
};
let rejected = PushResult {
flag: PushResultFlag::Rejected,
summary: "rejected".to_string(),
reason: Some("non-fast-forward".to_string()),
};
let up_to_date = PushResult {
flag: PushResultFlag::UpToDate,
summary: "up to date".to_string(),
reason: None,
};
let mut expected = ReviewResult::default();
expected.push_results.push(new_branch);
expected.push_results.push(rejected);
expected.push_results.push(up_to_date);
match parse_git_push_output(&stdout, "") {
Err(_) => assert!(false),
Ok(result) => assert_eq!(expected, result),
}
}
fn test_parse_git_push_output(stdout: &str, push_result: PushResult) {
let mut expected = ReviewResult::default();
expected.push_results.push(push_result);
match parse_git_push_output(&stdout, "") {
Err(_) => assert!(false),
Ok(result) => assert_eq!(expected, result),
}
}
}