本文整理汇总了C#中LibGit2Sharp.Repository.RetrieveStatus方法的典型用法代码示例。如果您正苦于以下问题:C# Repository.RetrieveStatus方法的具体用法?C# Repository.RetrieveStatus怎么用?C# Repository.RetrieveStatus使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类LibGit2Sharp.Repository
的用法示例。
在下文中一共展示了Repository.RetrieveStatus方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Get
// GET api/values
public HttpResponseMessage Get(string path)
{
using (var repo = new Repository(path))
{
var files = repo
.RetrieveStatus(new StatusOptions() { IncludeUnaltered = true })
.Where(s => s.State != FileStatus.Ignored && s.State != FileStatus.NewInWorkdir)
.Select(s => s.FilePath)
.ToList();
var diffs =
files.Select(f => new { path = f, history = repo.Commits.QueryBy(f).Select(x => x.Commit).ToList() })
.ToList();
var patches =
diffs.Select(
d =>
new
{
d.path,
history =
d.history.Where(p => p.Parents.Any())
.SelectMany(
c =>
repo.Diff.Compare<Patch>(c.Parents.First().Tree,c.Tree)
.Where(p => p.Path == d.path)
.Select(p => new { p.LinesAdded, p.LinesDeleted, c.Author.When })
.ToArray())
.ToArray()
}).ToArray();
return Request.CreateResponse(HttpStatusCode.OK, patches);
}
}
示例2: CheckChangesInGitRepo
void CheckChangesInGitRepo(DirectoryInfo rootFolder)
{
try
{
var repo = new Repository(rootFolder.FullName);
var options = new StatusOptions();
var repositoryStatus = repo.RetrieveStatus(options);
if (repositoryStatus.IsDirty)
Console.WriteLine("Repo [{0} in {1}] is dirty", rootFolder.Name, rootFolder.Parent.FullName);
}
catch (Exception ex)
{
Console.WriteLine("Repo [{0}] cannot be read: [{1}]", rootFolder.Name, ex.Message);
}
}
示例3: Commit
public static void Commit(FileInfo file)
{
using (var repository = new LibGit2Sharp.Repository(file.DirectoryName))
{
try
{
var status = repository.RetrieveStatus(file.FullName);
switch (status)
{
case FileStatus.Unaltered:
Log.Add($"Commit, FileStatus: {status}");
return;
case FileStatus.Nonexistent:
case FileStatus.Added:
case FileStatus.Staged:
case FileStatus.Removed:
case FileStatus.RenamedInIndex:
case FileStatus.StagedTypeChange:
case FileStatus.Untracked:
case FileStatus.Modified:
case FileStatus.Missing:
case FileStatus.TypeChanged:
case FileStatus.RenamedInWorkDir:
{
var commit = repository.Commit("Update", CommitOptions);
Log.Add($"Commit: {commit.Message}");
break;
}
case FileStatus.Unreadable:
case FileStatus.Ignored:
throw new InvalidOperationException($"FileStatus: {status}");
default:
throw new ArgumentOutOfRangeException();
}
}
catch (Exception e)
{
Log.Add(e.Message);
}
}
}
示例4: Main
static void Main(string[] args)
{
var enkiPath = @"C:\Users\r.iscu\Documents\GitHub\enki.js";
var beetleMailPath = @"C:\Work\BeetleMailer";
var enkiPath2 = @"C:\Users\linke\Documents\GitHub\enki.js";
using (var repo = new Repository(enkiPath2))
{
var files = repo
.RetrieveStatus(new StatusOptions() {IncludeUnaltered = true})
.Where(s => s.State != FileStatus.Ignored && s.State != FileStatus.NewInWorkdir)
.Select(s => s.FilePath)
.ToList();
var diffs =
files.Select(f => new {path = f, history = repo.Commits.QueryBy(f).Select(x => x.Commit).ToList()})
.ToList();
var patches =
diffs.Select(
d =>
new
{
path = d.path,
history =
d.history.Where(p => p.Parents.Any())
.SelectMany(
c =>
repo.Diff.Compare<Patch>(c.Tree, c.Parents.First().Tree)
.Where(p => p.Path == d.path)
.ToArray())
.ToArray(),
commits=d.history,
notes=d.history.Select(c=>c.Notes).ToArray()
}).ToArray();
}
Console.ReadKey();
}
示例5: 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;
}
}
示例6: 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);
}
repo.Commit("Intial Commit");
}
return repository;
}
示例7: RunLibGit2SharpCode
private static void RunLibGit2SharpCode(TextWriter log)
{
// TODO: enter your VSTS alternate credentials
string userName = "";
string password = "";
// TODO: enter your VSTS account name
string accountRoot = "yourroot";
// TODO: enter the name of a clean VSTS team project
// with an emptry default Git repo
string teamProjectName = "yourteamproject";
try
{
var co = new CloneOptions();
co.CredentialsProvider = (_url, _user, _cred) =>
new UsernamePasswordCredentials
{
Username = userName,
Password = password
};
string reposRoot = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"repos");
if (Directory.Exists(reposRoot))
{
// directory exists, delete
log.WriteLine("Cleaning reposRoot: " + reposRoot);
DeleteReadOnlyDirectory(reposRoot);
}
string repoRoot = Path.Combine(reposRoot, teamProjectName);
string accountUrl = string.Format("https://{0}.visualstudio.com/DefaultCollection", accountRoot);
Repository.Clone(accountUrl + "/_git/" + teamProjectName, repoRoot, co);
log.WriteLine("Clone Done!");
using (Repository repo = new Repository(repoRoot))
{
log.WriteLine("Repo aquired");
//// Write file
string newFilePath = System.IO.Path.Combine(repoRoot, "test.txt");
System.IO.File.WriteAllText(newFilePath, "Some great text.");
log.WriteLine("New text file written");
log.WriteLine("repo.RetrieveStatus()");
var status = repo.RetrieveStatus();
foreach (var item in status)
{
if (item.State == FileStatus.Untracked)
{
// *** Warning ***
// this line of code causes the Azure Web Job to blow up
repo.Index.Add(item.FilePath);
log.WriteLine(item.FilePath + " added to index");
}
}
}
}
catch (Exception ex)
{
log.WriteLine("Failure in LoadCodeIntoGitRepo");
log.WriteLine(ex.ToString());
}
}
示例8: 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;
}
示例9: GetGitDiffFor
public IEnumerable<HunkRangeInfo> GetGitDiffFor(ITextDocument textDocument, ITextSnapshot snapshot)
{
var filename = textDocument.FilePath;
var repositoryPath = GetGitRepository(Path.GetFullPath(filename));
if (repositoryPath == null)
yield break;
using (var repo = new Repository(repositoryPath))
{
var workingDirectory = repo.Info.WorkingDirectory;
if (workingDirectory == null)
yield break;
var retrieveStatus = repo.RetrieveStatus(filename);
if (retrieveStatus == FileStatus.Nonexistent)
{
// this occurs if a file within the repository itself (not the working copy) is opened.
yield break;
}
if ((retrieveStatus & FileStatus.Ignored) != 0)
{
// pointless to show diffs for ignored files
yield break;
}
if (retrieveStatus == FileStatus.Unaltered && !textDocument.IsDirty)
{
// truly unaltered
yield break;
}
var content = GetCompleteContent(textDocument, snapshot);
if (content == null) yield break;
using (var currentContent = new MemoryStream(content))
{
var relativeFilepath = filename;
if (relativeFilepath.StartsWith(workingDirectory, StringComparison.OrdinalIgnoreCase))
relativeFilepath = relativeFilepath.Substring(workingDirectory.Length);
var newBlob = repo.ObjectDatabase.CreateBlob(currentContent, relativeFilepath);
bool suppressRollback;
Blob blob;
if ((retrieveStatus & FileStatus.NewInWorkdir) != 0 || (retrieveStatus & FileStatus.NewInIndex) != 0)
{
suppressRollback = true;
// special handling for added files (would need updating to compare against index)
using (var emptyContent = new MemoryStream())
{
blob = repo.ObjectDatabase.CreateBlob(emptyContent, relativeFilepath);
}
}
else
{
suppressRollback = false;
Commit from = repo.Head.Tip;
TreeEntry fromEntry = from[relativeFilepath];
if (fromEntry == null)
{
// try again using case-insensitive comparison
Tree tree = from.Tree;
foreach (string segment in relativeFilepath.Split(Path.DirectorySeparatorChar))
{
if (tree == null)
yield break;
fromEntry = tree.FirstOrDefault(i => string.Equals(segment, i.Name, StringComparison.OrdinalIgnoreCase));
if (fromEntry == null)
yield break;
tree = fromEntry.Target as Tree;
}
}
blob = fromEntry.Target as Blob;
if (blob == null)
yield break;
}
var treeChanges = repo.Diff.Compare(blob, newBlob, new CompareOptions { ContextLines = ContextLines, InterhunkLines = 0 });
var gitDiffParser = new GitDiffParser(treeChanges.Patch, ContextLines, suppressRollback);
var hunkRangeInfos = gitDiffParser.Parse();
foreach (var hunkRangeInfo in hunkRangeInfos)
{
yield return hunkRangeInfo;
}
}
}
}
示例10: GetFilesInIndex
/// <summary>
/// Gets all files that are dirty in index
/// </summary>
/// <param name="repoPath">Repository main path</param>
/// <returns>A list of files that have status dirt in index</returns>
public static SysVersionControlTmpItem GetFilesInIndex(string repoPath)
{
SysVersionControlTmpItem tmpItem = new SysVersionControlTmpItem();
using (Repository repo = new Repository(repoPath))
{
if (!repo.RetrieveStatus().IsDirty)
return tmpItem;
var allDirtFiles = repo.RetrieveStatus(new StatusOptions { Show = StatusShowOption.IndexAndWorkDir }).
Where(t => t.State != FileStatus.Unaltered && t.State != FileStatus.Ignored);
foreach (var dirtFile in allDirtFiles)
{
FileInfo fileInfo = new FileInfo(Path.Combine(repoPath, dirtFile.FilePath));
IndexEntry indexEntry = repo.Index[dirtFile.FilePath];
//No index entry means new file, untracked content
if (indexEntry != null)
{
tmpItem.GTXShaShort = indexEntry.Id.Sha.Substring(0, 7);
tmpItem.GTXSha = indexEntry.Id.Sha;
tmpItem.Filename_ = FileGetVersion(repoPath, fileInfo.FullName, indexEntry.Id.Sha, Path.Combine(Path.GetTempPath(), string.Format("{0}_{1}", indexEntry.Id.Sha.Substring(0, 7), fileInfo.Name)));
tmpItem.InternalFilename = fileInfo.FullName;
tmpItem.ItemPath = indexEntry.Path;
tmpItem.GTXFileRepoStatus = GetFileStatus(repoPath, fileInfo.FullName);
}
else
{
var tempFileName = Path.Combine(Path.GetTempPath(), fileInfo.Name);
File.Copy(fileInfo.FullName, tempFileName, true);
tmpItem.Filename_ = tempFileName;
tmpItem.InternalFilename = fileInfo.FullName;
tmpItem.ItemPath = dirtFile.FilePath;
tmpItem.GTXFileRepoStatus = GetFileStatus(repoPath, fileInfo.FullName);
}
tmpItem.insert();
}
}
return tmpItem;
}
示例11: Changes
public List<string> Changes(RepositoryItem repository)
{
var repo = new LibGit2Sharp.Repository(repository.Path);
return repo.RetrieveStatus().Where(x => x.State != FileStatus.Ignored).Select(x => x.FilePath).ToList();
}
示例12: ComputeIsDirty
bool ComputeIsDirty( Repository r, Commit commit, RepositoryInfoOptions options )
{
bool isDirty = false;
RepositoryStatus repositoryStatus = r.RetrieveStatus();
if( repositoryStatus.Added.Any()
|| repositoryStatus.Missing.Any()
|| repositoryStatus.Removed.Any()
|| repositoryStatus.Staged.Any() ) return true;
foreach( StatusEntry m in repositoryStatus.Modified )
{
if( !options.IgnoreModifiedFiles.Contains( m.FilePath )
&& (options.IgnoreModifiedFilePredicate == null || !options.IgnoreModifiedFilePredicate( new ModifiedFile( r, commit, m ) )) )
{
isDirty = true;
if( !options.IgnoreModifiedFileFullProcess ) break;
}
}
return isDirty;
}
示例13: DownloadAddon
private void DownloadAddon()
{
bool updated = false;
bool cloned = false;
if (!Directory.Exists(info.packedPath))
{
Directory.CreateDirectory(info.packedPath);
}
if (Directory.Exists(info.dlPath) && Repository.IsValid(info.dlPath))
{
using (Repository repo = new Repository(info.dlPath))
{
RepositoryStatus status = repo.RetrieveStatus();
string commit = repo.Head.Tip.Id.Sha;
// reset local changes
if (status.IsDirty)
{
repo.Reset(ResetMode.Hard);
}
// fetch & merge from origin
repo.Network.Fetch(repo.Network.Remotes["origin"]);
repo.MergeFetchedRefs(new Signature("meldii", "[email protected]", new DateTimeOffset()), new MergeOptions());
// updated
if (!repo.Head.Tip.Id.Sha.Equals(commit))
{
updated = true;
}
}
}
else
{
if (Directory.Exists(info.dlPath))
{
ForceDeleteDirectory(info.dlPath);
}
CloneOptions co = new CloneOptions();
co.BranchName = info.branch;
Repository.Clone(info.url, info.dlPath, co);
updated = true;
cloned = true;
}
//Pack & ship it
if (updated)
{
if (File.Exists(info.packedFile))
{
File.Delete(info.packedFile);
}
ZipFile zip = new ZipFile(info.packedFile);
foreach (string file in Directory.EnumerateFiles(info.dlPath, "*.*", SearchOption.AllDirectories))
{
string rPath = file.Replace(info.dlPath, "").TrimStart(new char[] { '\\', '/' });
if (!rPath.StartsWith(".git", StringComparison.CurrentCultureIgnoreCase) && !rPath.Equals("README.md", StringComparison.CurrentCultureIgnoreCase))
{
string[] split = rPath.Split(new char[] { '\\', '/' });
string zipPath = split.Length == 1 ? "" : string.Join("\\", split, 0, split.Length - 1);
zip.AddFile(file, zipPath);
}
}
zip.Save();
}
if (cloned)
{
_Copy(Path.Combine(MeldiiSettings.Self.AddonLibaryPath, info.repoName) + ".zip", info.packedFile);
}
}
示例14: ProcessDirectory
public void ProcessDirectory(RepositoryConfigurationInfo config)
{
if (!Repository.IsValid(config.BaseDir))
{
Repository.Init(config.BaseDir);
}
using (var repo = new Repository(config.BaseDir))
{
// todo, if user.name or user.email are not set in config, set them now!
if (string.IsNullOrEmpty(repo.Config.Get<string>("user.name").Value))
repo.Config.Set("user.name", "gitpusher");
if (string.IsNullOrEmpty(repo.Config.Get<string>("user.email").Value))
repo.Config.Set("user.email", "[email protected]");
repo.Config.Set("diff.renames", "copies");
repo.Config.Set("http.postBuffer", 524288000);
var retrievalOptions = new StatusOptions {DetectRenamesInWorkDir = true, DetectRenamesInIndex = true};
RepositoryStatus status = repo.RetrieveStatus(retrievalOptions);
if (status.IsDirty)
{
bool toCommit = false;
foreach (var renamed in status.RenamedInWorkDir)
{
var oldFileName = renamed.IndexToWorkDirRenameDetails.OldFilePath;
repo.Stage(renamed.FilePath);
repo.Stage(oldFileName);
toCommit = true;
}
foreach (var untracked in status.Untracked)
{
repo.Stage(untracked.FilePath);
toCommit = true;
}
foreach (var modified in status.Modified)
{
repo.Stage(modified.FilePath);
toCommit = true;
}
foreach (var added in status.Added)
{
repo.Stage(added.FilePath);
toCommit = true;
}
foreach (var missing in status.Missing)
{
repo.Remove(missing.FilePath);
toCommit = true;
}
if (toCommit || status.Staged.Any())
{
repo.Commit("GitPusher commit.");
foreach (var rmt in config.Remotes)
{
if (!repo.Network.Remotes.Any(r => r.Name == rmt))
{
FormatLoggerAccessor.Instance().Error($"Remote '{rmt}' not found in git repository. Please check the name with 'git remote -v' and try again.");
continue;
}
var remote = repo.Network.Remotes[rmt];
var options = new PushOptions();
//options.CredentialsProvider = new CredentialsHandler((url, usernameFromUrl, types) =>
// new DefaultCredentials());
//new UsernamePasswordCredentials()
//{
// Username = "myusername",
// Password = "mypassword"
//});
var pushRefSpec = @"refs/heads/master";
repo.Network.Push(remote, pushRefSpec, options, null, "GitPusher push");
}
}
}
}
}
示例15: Status
/// <summary>
/// "git status" in a nutshell.
/// </summary>
/// <returns>Dictionary with a KEY:VALUE structure of FileName:FileStatus</returns>
public IDictionary<string, FileStatus> Status()
{
var files = new Dictionary<string, FileStatus>();
using (var repo = new Repository(_LocalRepo))
{
foreach (var file in repo.RetrieveStatus().Where(file => file.State != FileStatus.Ignored))
{
files.Add(file.FilePath, file.State);
}
}
return files;
}