本文整理汇总了C#中LibGit2Sharp.Repository.Stage方法的典型用法代码示例。如果您正苦于以下问题:C# Repository.Stage方法的具体用法?C# Repository.Stage怎么用?C# Repository.Stage使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类LibGit2Sharp.Repository
的用法示例。
在下文中一共展示了Repository.Stage方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: SaveFile
public void SaveFile(string fileName, string content, string username, string email)
{
using (var repo = new Repository(_basePath))
{
File.WriteAllText(Path.Combine(repo.Info.WorkingDirectory, fileName), content);
// stage the file
repo.Stage(fileName);
// Create the committer's signature and commit
//var user = repo.Config.Get<string>("user", "name", null);
//var email = repo.Config.Get<string>("user", "email", null);
var author = new Signature(username, email, DateTime.Now);
var committer = author;
// Commit to the repo
var commitMessage = string.Format("Revision: {0}", GetRevisionCount(repo, fileName));
try
{
var commit = repo.Commit(commitMessage, author, committer);
foreach (var parent in commit.Parents)
{
Console.WriteLine("Id: {0}, Sha: {1}", parent.Id, parent.Sha);
}
}
catch (EmptyCommitException) { } // I don't care if the user didn't change anything at this time
}
}
示例2: Add
/// <summary>
/// Add and stage specified file.
/// </summary>
/// <param name="fileName">Name of the file to be added to Lib2GitSharp, then staged ready for commit.</param>
public void Add(string fileName, FileStatus status)
{
using (var repo = new Repository(_LocalRepo))
{
if (status != FileStatus.Removed && status != FileStatus.Missing)
{
repo.Index.Add(fileName);
}
repo.Stage(fileName);
}
}
示例3: InitializeRepository
/// <summary>
/// Initializes a new bare repository at the specified location, adds a repository info file to the root directory
/// and tags the initial commit with he value of <see cref="InitialCommitTagName"/>
/// </summary>
public static void InitializeRepository(string location)
{
// initialize a bare repository
Repository.Init(location, true);
var directoryCreator = new LocalItemCreator();
// clone the repository, add initial commit and push the changes back to the actual repository
using (var tempDirectory = directoryCreator.CreateTemporaryDirectory())
{
var clonedRepoPath = Repository.Clone(location, tempDirectory.Directory.Location);
var repositoryInfoFile = new RepositoryInfoFile(tempDirectory.Directory);
// add a empty file to the repository
directoryCreator.CreateFile(repositoryInfoFile, tempDirectory.Directory.Location);
// commit and push the file to the bare repository we created
using (var clonedRepo = new Repository(clonedRepoPath))
{
var signature = SignatureHelper.NewSignature();
clonedRepo.Stage(repositoryInfoFile.Name);
clonedRepo.Commit("Initial Commit", signature, signature, new CommitOptions());
clonedRepo.Network.Push(clonedRepo.Network.Remotes["origin"], @"refs/heads/master");
}
}
//create the configuration branch pointing to the initial commit
using (var repository = new Repository(location))
{
repository.CreateBranch(ConfigurationBranchName.ToString(), repository.GetAllCommits().Single());
repository.Tags.Add(InitialCommitTagName, repository.GetAllCommits().Single());
}
}
示例4: btnAdd_Click
private void btnAdd_Click(object sender, EventArgs e)
{
// get the new entryname
InputBoxValidation validation = delegate(string val)
{
if (val == "")
return "Value cannot be empty.";
if (new Regex(@"[a-zA-Z0-9-\\_]+/g").IsMatch(val))
return "Not a valid name, can only use characters or numbers and - \\.";
if (File.Exists(Properties.Settings.Default.PassDirectory + "\\" + @val + ".gpg"))
return "Entry already exists.";
return "";
};
string value = "";
if (InputBox.Show("Enter a new name", "Name:", ref value, validation) == DialogResult.OK)
{
// parse path
string tmpPath = Properties.Settings.Default.PassDirectory + "\\" + @value + ".gpg";;
Directory.CreateDirectory(Path.GetDirectoryName(tmpPath));
using (File.Create(tmpPath)) { }
ResetDatagrid();
// set the selected item.
foreach (DataGridViewRow row in dataPass.Rows)
{
if (row.Cells[1].Value.ToString().Equals(value))
{
dataPass.CurrentCell = row.Cells[1];
row.Selected = true;
break;
}
}
// add to git
using (var repo = new Repository(Properties.Settings.Default.PassDirectory))
{
// Stage the file
repo.Stage(tmpPath);
}
// dispose timer thread and clear ui.
if (_timer != null) _timer.Dispose();
statusPB.Visible = false;
statusTxt.Text = "Ready";
// Set the text detail to the correct state
txtPassDetail.Text = "";
txtPassDetail.ReadOnly = false;
txtPassDetail.BackColor = Color.White;
// dataPass.Enabled = false;
txtPassDetail.Focus();
}
}
示例5: Encrypt_Callback
// Callback for the encrypt thread
public void Encrypt_Callback(GpgInterfaceResult result, string tmpFile, string tmpFile2, string path)
{
if (result.Status == GpgInterfaceStatus.Success)
{
File.Delete(tmpFile);
File.Delete(path);
File.Move(tmpFile2, path);
// add to git
using (var repo = new Repository(Properties.Settings.Default.PassDirectory))
{
// Stage the file
repo.Stage(path);
// Commit
repo.Commit("password changes", new Signature("pass4win", "pass4win", System.DateTimeOffset.Now), new Signature("pass4win", "pass4win", System.DateTimeOffset.Now));
var remote = repo.Network.Remotes["origin"];
var options = new PushOptions();
options.CredentialsProvider = (_url, _user, _cred) => new UsernamePasswordCredentials
{
Username = GitUsername,
Password = GitPassword
};
var pushRefSpec = @"refs/heads/master";
repo.Network.Push(remote, pushRefSpec, options, new Signature("pass4win", "[email protected]", DateTimeOffset.Now),
"pushed changes");
}
}
else
{
MessageBox.Show("You shouldn't see this.... Awkward right... Encryption failed", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
示例6: TryCommit
private static bool TryCommit(string gitRepoPath, string message)
{
try
{
using (var r = new Repository(gitRepoPath))
{
var status = r.RetrieveStatus();
var toStage =
status.Where(s =>
(s.State & FileStatus.Untracked) != 0
|| (s.State & FileStatus.Modified) != 0
|| (s.State & FileStatus.RenamedInWorkDir) != 0);
var toRemove =
status.Where(s =>
(s.State & FileStatus.Missing) != 0);
foreach (var item in toStage)
{
r.Stage(item.FilePath);
}
foreach (var item in toRemove)
{
r.Remove(item.FilePath);
}
r.Commit(message);
}
return true;
}
catch (Exception ex)
{
Console.WriteLine(ex);
return false;
}
}
示例7: InitVBAProject
/// <summary>
/// Exports files from VBProject to the file system, initalizes the repository, and creates an inital commit of those files to the repo.
/// </summary>
/// <param name="directory">Local file path of the directory where the new repository will be created.</param>
/// <returns>Newly initialized repository.</returns>
public override IRepository InitVBAProject(string directory)
{
var repository = base.InitVBAProject(directory);
Init(repository.LocalLocation);
//add a master branch to newly created repo
using (var repo = new LibGit2Sharp.Repository(repository.LocalLocation))
{
var status = repo.RetrieveStatus(new StatusOptions());
foreach (var stat in status.Untracked)
{
repo.Stage(stat.FilePath);
}
try
{
//The default behavior of LibGit2Sharp.Repo.Commit is to throw an exception if no signature is found,
// but BuildSignature() does not throw if a signature is not found, it returns "unknown" instead.
// so we pass a signature that won't throw along to the commit.
repo.Commit("Intial Commit", GetSignature(repo));
}
catch(LibGit2SharpException ex)
{
throw new SourceControlException(SourceControlText.GitNoInitialCommit, ex);
}
}
return repository;
}
示例8: ToolStripbtnAddClick
private void ToolStripbtnAddClick(object sender, EventArgs e)
{
SaveFileDialog newFileDialog = new SaveFileDialog
{
AddExtension = true,
AutoUpgradeEnabled = true,
CreatePrompt = false,
DefaultExt = "gpg",
InitialDirectory = Cfg["PassDirectory"],
Title = Strings.Info_add_dialog
};
if (newFileDialog.ShowDialog() == DialogResult.Cancel)
{
return;
}
string tmpFileName = newFileDialog.FileName;
newFileDialog.Dispose();
using (File.Create(tmpFileName))
{
}
// add to git
using (var repo = new Repository(Cfg["PassDirectory"]))
{
// Stage the file
repo.Stage(tmpFileName);
}
// dispose timer thread and clear ui.
KillTimer();
this.CreateNodes();
}
示例9: RenameToolStripMenuItemClick
/// <summary>
/// rename the entry with all the hassle that accompanies it.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void RenameToolStripMenuItemClick(object sender, EventArgs e)
{
SaveFileDialog newFileDialog = new SaveFileDialog
{
AddExtension = true,
AutoUpgradeEnabled = true,
CreatePrompt = false,
DefaultExt = "gpg",
InitialDirectory = Cfg["PassDirectory"],
Title = Strings.FrmMain_RenameToolStripMenuItemClick_Rename
};
if (newFileDialog.ShowDialog() == DialogResult.Cancel)
{
return;
}
string tmpFileName = newFileDialog.FileName;
newFileDialog.Dispose();
// ReSharper disable once AssignNullToNotNullAttribute
Directory.CreateDirectory(path: Path.GetDirectoryName(tmpFileName));
File.Copy(dirTreeView.SelectedNode.Tag + "\\" + listFileView.SelectedItem + ".gpg", tmpFileName);
using (var repo = new Repository(Cfg["PassDirectory"]))
{
// add the file
repo.Remove(listFileView.SelectedItem.ToString());
repo.Stage(tmpFileName);
// Commit
repo.Commit("password moved", new Signature("pass4win", "pass4win", DateTimeOffset.Now),
new Signature("pass4win", "pass4win", DateTimeOffset.Now));
if (Cfg["UseGitRemote"] == true && this.gitRepoOffline == false)
{
//push
toolStripOffline.Visible = false;
var remote = repo.Network.Remotes["origin"];
var options = new PushOptions
{
CredentialsProvider = (url, user, cred) => new UsernamePasswordCredentials
{
Username = Cfg["GitUser"],
Password = DecryptConfig(Cfg["GitPass"], "pass4win")
}
};
var pushRefSpec = @"refs/heads/master";
repo.Network.Push(remote, pushRefSpec, options);
}
}
this.CreateNodes();
}
示例10: GetAQuoteViaGit
public IActionResult GetAQuoteViaGit(QuoteViewModel model)
{
var watch = Stopwatch.StartNew();
string rootedPath = Repository.Init("C:\\temp\\rooted\\path");
string jsondata = new JavaScriptSerializer().Serialize(model);
using (var repo = new Repository("C:\\temp\\rooted\\path"))
{
// Write content to file system
System.IO.File.WriteAllText(System.IO.Path.Combine(repo.Info.WorkingDirectory, "output.json"), jsondata);
// Stage the file
repo.Stage("output.json");
// Create the committer's signature and commit
Signature author = new Signature(model.FirstName, model.Email, DateTime.Now);
Signature committer = author;
// Commit to the repository
try {
Commit commit = repo.Commit("Quote committed", author, committer);
watch.Stop();
var elapsedMs = watch.ElapsedMilliseconds;
if (ModelState.IsValid)
{
ViewBag.Message = "Quote number is: " + commit.Id + " Time taken: " + elapsedMs + "ms";
}
}
catch(Exception ex)
{
ViewBag.Message = "Nothing to commit";
}
}
return View();
}
示例11: Main
public static void Main(string[] args)
{
try
{
log("started...");
var repoUrl = args[0];
var branchName = "master";
var username = args[1];
var password = "";
if (args.Length == 3)
{
password = args[2];
}
var fileSpec = args[3];
if (fileSpec.Contains('/'))
{
fileSpec = fileSpec.Replace("/", "\\");
}
var pathSplit = repoUrl.Split('/');
var repoName = pathSplit.Last();
var fileInfo = new FileInfo(Path.Combine(Directory.GetCurrentDirectory(), repoName, fileSpec));
var author = new Signature("scarletapi", "@gmail", DateTime.Now);
var repoDir = new DirectoryInfo(Path.Combine(Directory.GetCurrentDirectory(), repoName));
var repoPath = repoDir.FullName;
if (String.IsNullOrEmpty(username))
{
throw new Exception("Must have username");
}
if (String.IsNullOrEmpty(password))
{
repoUrl = repoUrl.Replace(pathSplit[2], String.Format("{0}@{2}", username, password, pathSplit[2]));
}
else
{
repoUrl = repoUrl.Replace(pathSplit[2], String.Format("{0}:{1}@{2}", username, password, pathSplit[2]));
}
log("checking if repo is valid");
if (Repository.IsValid(repoPath))
{
log("repo is valid");
using (var repo = new LibGit2Sharp.Repository(repoPath))
{
var remoteBranch = repo.Branches[branchName];
repo.Stage(fileInfo.FullName);
repo.Checkout(remoteBranch, new CheckoutOptions());
repo.Network.Pull( author, new PullOptions());
repo.Unstage(fileInfo.FullName);
if (!fileInfo.Exists)
{
log("WARNING: file does not exist {0}", fileInfo.FullName);
}
log("attempting to get latest, add, commit and pushing to {0}", repoName);
var uri = new Uri(repo.Info.WorkingDirectory);
log("working directory uri: {0}", uri.OriginalString);
log("adding file: {0}", fileInfo.FullName);
uri = uri.MakeRelativeUri(new Uri(fileInfo.FullName));
repo.Index.Add(uri.OriginalString);
var commit = repo.Commit("API Auto Commit", author, author);
repo.Refs.UpdateTarget(repo.Refs.Head, commit.Id);
var options = new LibGit2Sharp.PushOptions();
repo.Network.Push(remoteBranch, options);
log("file {0} was pushed to {1}", fileSpec, repoName);
}
}
else
{
log("repo is NOT valid");
}
}
catch (Exception e)
{
log("ERROR: {0}", e.Message);
}
}
示例12: removeToolStripMenuItem_Click
private void removeToolStripMenuItem_Click(object sender, EventArgs e)
{
if (listBox1.Items[0].ToString() != "There are no specific keys set")
if (listBox1.Items.Count > 1)
{
listBox1.Items.Remove(listBox1.SelectedItem);
listBox1.Refresh();
string tmpFile = Path.GetDirectoryName(Properties.Settings.Default.PassDirectory) + "\\" + treeView1.SelectedNode.FullPath + "\\.gpg-id";
File.Delete(tmpFile);
using (StreamWriter w = new StreamWriter(tmpFile))
{
foreach (var line in listBox1.Items)
{
w.WriteLine(line.ToString());
}
}
using (var repo = new Repository(Properties.Settings.Default.PassDirectory))
{
repo.Stage(tmpFile);
repo.Commit("gpgid changed", new Signature("pass4win", "pass4win", System.DateTimeOffset.Now), new Signature("pass4win", "pass4win", System.DateTimeOffset.Now));
}
}
DirectoryInfo path = new DirectoryInfo(Path.GetDirectoryName(Properties.Settings.Default.PassDirectory) + "\\" + treeView1.SelectedNode.FullPath);
foreach (var ffile in path.GetFiles())
{
if (!ffile.Name.StartsWith("."))
recrypt(ffile.FullName);
}
ScanDirectory(path);
}
示例13: ToolStripbtnAdd_Click
private void ToolStripbtnAdd_Click(object sender, EventArgs e)
{
// get the new entryname
InputBoxValidation validation = delegate(string val)
{
if (val == "")
return "Value cannot be empty.";
if (new Regex(@"[a-zA-Z0-9-\\_]+/g").IsMatch(val))
return Strings.Error_valid_filename;
if (File.Exists(Cfg["PassDirectory"] + "\\" + @val + ".gpg"))
return Strings.Error_already_exists;
return "";
};
var value = "";
if (InputBox.Show(Strings.Input_new_name, Strings.Input_new_name_label, ref value, validation) ==
DialogResult.OK)
{
// parse path
string tmpPath = Cfg["PassDirectory"] + "\\" + @value + ".gpg";
// ReSharper disable once AssignNullToNotNullAttribute
Directory.CreateDirectory(Path.GetDirectoryName(tmpPath));
using (File.Create(tmpPath))
{
}
ResetDatagrid();
// set the selected item.
foreach (DataGridViewRow row in dataPass.Rows)
{
if (row.Cells[1].Value.ToString().Equals(value))
{
dataPass.CurrentCell = row.Cells[1];
row.Selected = true;
dataPass.FirstDisplayedScrollingRowIndex = row.Index;
break;
}
}
// add to git
using (var repo = new Repository(Cfg["PassDirectory"]))
{
// Stage the file
repo.Stage(tmpPath);
}
// dispose timer thread and clear ui.
KillTimer();
// Set the text detail to the correct state
txtPassDetail.Text = "";
txtPassDetail.ReadOnly = false;
txtPassDetail.BackColor = Color.White;
txtPassDetail.Visible = true;
btnMakeVisible.Visible = false;
txtPassDetail.Focus();
}
}
示例14: renameToolStripMenuItem_Click
/// <summary>
/// rename the entry with all the hassle that accompanies it.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void renameToolStripMenuItem_Click(object sender, EventArgs e)
{
// rename the entry
InputBoxValidation validation = delegate(string val)
{
if (val == "")
return Strings.Error_not_empty;
if (new Regex(@"[a-zA-Z0-9-\\_]+/g").IsMatch(val))
return Strings.Error_valid_filename;
if (File.Exists(Cfg["PassDirectory"] + "\\" + @val + ".gpg"))
return Strings.Error_already_exists;
return "";
};
var value = dataPass.Rows[dataPass.CurrentCell.RowIndex].Cells[1].Value.ToString();
if (InputBox.Show(Strings.Input_new_name, Strings.Input_new_name_label, ref value, validation) ==
DialogResult.OK)
{
// parse path
string tmpPath = Cfg["PassDirectory"] + "\\" + @value + ".gpg";
// ReSharper disable once AssignNullToNotNullAttribute
Directory.CreateDirectory(Path.GetDirectoryName(tmpPath));
File.Copy(dataPass.Rows[dataPass.CurrentCell.RowIndex].Cells[0].Value.ToString(), tmpPath);
using (var repo = new Repository(Cfg["PassDirectory"]))
{
// add the file
repo.Remove(dataPass.Rows[dataPass.CurrentCell.RowIndex].Cells[0].Value.ToString());
repo.Stage(tmpPath);
// Commit
repo.Commit("password moved", new Signature("pass4win", "pass4win", DateTimeOffset.Now),
new Signature("pass4win", "pass4win", DateTimeOffset.Now));
if (Cfg["UseGitRemote"] == true && _gitRepoOffline == false)
{
//push
toolStripOffline.Visible = false;
var remote = repo.Network.Remotes["origin"];
var options = new PushOptions
{
CredentialsProvider = (url, user, cred) => new UsernamePasswordCredentials
{
Username = Cfg["GitUser"],
Password = DecryptConfig(Cfg["GitPass"], "pass4win")
}
};
var pushRefSpec = @"refs/heads/master";
repo.Network.Push(remote, pushRefSpec, options);
}
}
ResetDatagrid();
}
}
示例15: RemoveToolStripMenuItemClick
/// <summary>
/// Remove a GPG key from a directory
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void RemoveToolStripMenuItemClick(object sender, EventArgs e)
{
if (listBox1.Items[0].ToString() != Strings.Error_keys_set)
if (listBox1.Items.Count > 1)
{
listBox1.Items.Remove(listBox1.SelectedItem);
listBox1.Refresh();
string tmpFile = Path.GetDirectoryName(_config["PassDirectory"]) + "\\" + treeView1.SelectedNode.FullPath + "\\.gpg-id";
File.Delete(tmpFile);
using (StreamWriter w = new StreamWriter(tmpFile))
{
foreach (var line in listBox1.Items)
{
w.WriteLine(line.ToString());
}
}
using (var repo = new Repository(_config["PassDirectory"]))
{
repo.Stage(tmpFile);
repo.Commit("gpgid changed", new Signature("pass4win", "pass4win", DateTimeOffset.Now), new Signature("pass4win", "pass4win", DateTimeOffset.Now));
}
}
DirectoryInfo path = new DirectoryInfo(Path.GetDirectoryName(_config["PassDirectory"]) + "\\" + treeView1.SelectedNode.FullPath);
foreach (var ffile in path.GetFiles().Where(ffile => !ffile.Name.StartsWith(".")))
{
this.Recrypt(ffile.FullName);
}
ScanDirectory(path);
}