forked from git-tfs/git-tfs
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathCheckout.cs
76 lines (67 loc) · 2.78 KB
/
Checkout.cs
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
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using NDesk.Options;
using Sep.Git.Tfs.Core;
using StructureMap;
namespace Sep.Git.Tfs.Commands
{
[Pluggable("checkout")]
[RequiresValidGitRepository]
[Description("checkout changesetId [-b=branch_name]\n ex: git-tfs checkout 2365\n git-tfs checkout 2365 -b=bugfix_2365\n")]
public class Checkout : GitTfsCommand
{
private readonly Globals _globals;
private readonly TextWriter _stdout;
public Checkout(Globals globals, TextWriter stdout)
{
_globals = globals;
_stdout = stdout;
}
public OptionSet OptionSet
{
get
{
return new OptionSet
{
{ "b|branch=", "Name of the branch to create", v => BranchName = v },
{ "n|dry-run", "Don't checkout the commit, just return commit sha", v => ReturnShaOnly = v != null },
};
}
}
protected string BranchName { get; set; }
protected bool ReturnShaOnly { get; set; }
public int Run(string id)
{
long changesetId;
if(!long.TryParse(id, out changesetId))
throw new GitTfsException("error: wrong format for changeset id...");
var shas = _globals.Repository.FindCommitHashesByChangesetId(changesetId);
if (shas.Count == 0)
throw new GitTfsException("error: commit not found for " + changesetId.ToString() + " changeset id...");
if (shas.Count > 1)
throw new GitTfsException("error: found more than one commit for " + changesetId.ToString() + " changeset id...");
var sha = shas.Single();
if (ReturnShaOnly)
{
_stdout.Write(sha);
return GitTfsExitCodes.OK;
}
string commitishToCheckout = sha;
if (!string.IsNullOrEmpty(BranchName))
{
BranchName = _globals.Repository.AssertValidBranchName(BranchName);
if(!_globals.Repository.CreateBranch(BranchName.ToLocalGitRef(), sha))
throw new GitTfsException("error: can not create branch '" + BranchName + "'");
_stdout.WriteLine("Branch '" + BranchName + "' created...");
commitishToCheckout = BranchName;
}
if(!_globals.Repository.Checkout(commitishToCheckout))
throw new GitTfsException("error: unable to checkout '" + commitishToCheckout + "' due to changes in your workspace!",
new List<string> { "commit or stash your changes before retrying..."});
return GitTfsExitCodes.OK;
}
}
}