I am trying to figure out way to get source of same file from two different commits, but I just can't find any documentation about this.
I know there is Repository.Dif.Compare which is useful but I can only get Patch from it and that doesn't help much since I would like to implement my own side by side comparison.
Can someone provide an example? Is this even possible in libgit2sharp?
I am trying to figure out way to get source of same file from two different commits [...] Is this even possible in libgit2sharp?
Each Commit or Tree type exposes a string indexer that allows one to directly access a TreeEntry through its path. A TreeEntry can either be a Blob (ie. a file), another Tree (ie. a directory), or a GitLink (ie. a submodule).
The code below, gives a quick example of how to access the content of the same file in two different commits.
[Fact]
public void CanRetrieveTwoVersionsOfTheSameBlob()
{
using (var repo = new Repository(BareTestRepoPath))
{
var c1 = repo.Lookup<Commit>("8496071");
var b1 = c1["README"].Target as Blob;
var c2 = repo.Lookup<Commit>("4a202b3");
var b2 = c2["README"].Target as Blob;
Assert.NotEqual(b1.ContentAsText(), b2.ContentAsText());
}
}
I would like to implement my own side by side comparison
Depending of the size of the blob you're dealing with, you may not be willing to retrieve the whole content in memory. In that case, blob.ContentStream may be handy.
Update
I was missing the cast to blob, to figure the rest out
FWIW, you can rely on revparse expressions to directly access the Blob. As the result, the following should also work ;-)
[Fact]
public void CanRetrieveTwoVersionsOfTheSameBlob_ReduxEdition()
{
using (var repo = new Repository(BareTestRepoPath))
{
var b1 = repo.Lookup<Blob>("8496071:README");
var b2 = repo.Lookup<Blob>("4a202b3:README");
Assert.NotEqual(b1.ContentAsText(), b2.ContentAsText());
}
}
This post should answer your question, it's from another question here on this site:
How to diff the same file between two different commits on the same branch?
I hope that helps.
Related
I'm trying to build a program in which I consume an API through a client that a company has made available for its software.
Here's a link to it.
Though it does make it easier for one to establish a connection and make a call through its embedded methods, I'm having a difficult time manipulating the data once I receive it.
[Note: I know it's sort of meaningless to provide y'all with the background of the client and how I'm making the call, but I would think it'd be hard for one to get a glimpse of what's going on if I'm not even providing how the connection is happening behind the client or how the database looks.]
Previously, I tried manipulating the data directly after making the call like this (link below), but I realized this is too difficult for me since I'm still a noob at C#, and it's been hard to mess with the results (object) as a dynamic[] value.
Link
Therefore, I believe it'd be best if I pursue the route of getting the data as an object, serialize it, turn it to (json), and map it to properties. I believe once I do this it should be easier to manipulate the data because I'd have an easier time turning the data into single values, lists, etc. However, I'm having a difficult time connecting the dots at this point of the code.
This is what I have so far..
I'm only interested in the EntryID, NameFirst, and NameLast of the results, but further along the way I do see myself utilizing the info from the other fields of this table and others. If someone could help me make the connection from the results to these properties, I would very much appreciate it. This would be a huge step in the application I'm trying to build using this API data.
Thanks in advance!
Class of Properties Link
JsonData Processor Link
JSON Results from Call Link
using System;
using [Custom]Api;
using Newtonsoft.Json;
namespace testing2
{
public class Program
{
public static void Main(string[] args)
{
[CustomApi]Client connection = new [CustomApi]Client("BaseURL",
"Username", "Password");
var value =
connection.Select("Entry",Criteria.Equals("NameLast","Rincon Recio"));
string results = JsonConvert.SerializeObject(value);
///not sure if making results as string is the right call to begin
this
//[Syntax where I tell results to match properties of Class 1]
//[Create list of EntryID, NameFirst, NameLast]
//[Display list in listbox]
Console.WriteLine(results);
Console.ReadLine();
}
}
}
No, JsonConvert.SerializeObject(value) shouldn't make a difference.
Try Deserialising values to array of Class1.
Like so
var realResult = JsonConvert.DeserializeObject<Class1[]>(values);
Source
I have a scenario in which I need much of the information from the FileInfo structure -- creation time, last write time, file size, etc. I need to be able to get this information cleanly, but also be able to truly unit test without hitting the file system.
I am using System.IO.Abstractions, so that gets me 99% of the way there for most of my class, except this one. I don't know how to use it to get the information I need from my MockFileSystem object.
public void Initialize(IFileSystem fs, string fullyQualifiedFileName)
{
string pathOnly = fs.Path.GetDirectoryName(fullyQualifiedFileName);
string fileName = fs.Path.GetFileName(fullyQualifiedFileName);
// Here's what I don't know how to separate out and mock
FileInfo fi = new FileInfo(fullyQualifiedFileName);
long size = fi.LongLength;
DateTime lastWrite = fi.LastWriteTime;
...
...
}
Any help on that line would be greatly appreciated.
UPDATE:
This is not an exact duplicate of existing questions because I'm asking how do I do it with System.IO.Abstractions, not how do I do it in general.
For those who are interested, I did find a way to accomplish it:
FileInfoBase fi = fs.FileInfo.FromFileName(fullFilePath);
If I use this line, I get the same information I need in both TEST and PROD environments.
https://github.com/TestableIO/System.IO.Abstractions/blob/5f7ae53a22dffcff2b5716052e15ff2f155000fc/src/System.IO.Abstractions/IFileInfo.cs
System.IO.Abstractions provides you with an IFileInfo interface to code against, which you could create your own implementation of to return the stats you're interested in testing against.
In this case you'd want another method to return an IFileInfo to your Initialize method, which could be virtual so that in your test it just returns your fake instead of really hitting the system.
I need to dynamically generate the help for some WEB-API.
The problem is that are dynamic both in the input parameters that in the structure of output.
See the Example:
[HttpGet]
[Route("API/Individuals")]
[ActionName("Individuals")]
public HttpResponseMessage Select()
{
var Params = this.Request.RequestUri.ParseQueryString();
string UserNameCVT = Code.RemappingUser.Remap(UserName.Name);
DataSet ds = Models.Individuals.Individuals.SelectDS(UserNameCVT, Params);
List<Dictionary<string, object>> lDict = DecodeIndividualsFromDS(ds);
response = Request.CreateResponse(HttpStatusCode.OK, lDict);
return response;
}
By doing this, the API is to decouple that from FE DB below, leaving them free to modify the data structures according to their needs.
Is it possible to generate a complete Help once the structures are defined (without changing the code of the API)?
Yes, you can. The key line of code in the XML documentation provider is this (from this getting started page):
config.SetDocumentationProvider(new XmlDocumentationProvider(
HttpContext.Current.Server.MapPath("~/App_Data/XmlDocument.xml")));
As you see, the documentation is read from a file path. If you can dynamically create that file on the start of your application, and then pass in the file path, you are set. (You have to find a way to handle those end points dynamically, but that is not in the scope of this question)
Also, if you need to do more, you can create a custom implementation by taking the XmlDocumentationProvider from Github and write your own.
Stripe Transfer JSON
I'm trying to get all charge IDs associated with a transfer.
var json = new StreamReader(context.Request.InputStream).ReadToEnd();
var stripeEvent = StripeEventUtility.ParseEvent(json);
StripeTransfer stripeTransfer;
switch (stripeEvent.Type)
{
case "transfer.created":
stripeTransfer = Stripe.Mapper<StripeTransfer>.MapFromJson(stripeEvent.Data.Object.ToString());
var transferId = stripeTransfer.Id;
stripeTransfer = _stripeManager.GetTransfer(transferId);
foreach (var charge in stripeEvent.Data.Object["transactions"])
{
}
_stripeManager.ProcessTransfer(stripeTransfer);
break;
In visual studio's immediate window, stripeEvent.Data.Object["transactions"] shows the data I want so I know that the json is getting sucked in properly. Those transactions are a collection of charges, they match my .net StripeCharge object. I'm having trouble figuring out how to iterate through the transactions...all I really need is the ID for each. Would like to see "transactions" as a C# IEnumerable object.
(the json in question is linked at the top of this post) let me know if more info is needed.
I've found the specific item is under ["transactions"]["data"][0]["id"] but there may be more than one so, still working on how to get them out and cast them...think I'm close but it seems like there should be a more elegant way of doing it.
EDIT,
Thanks Andrew, so even though I have all of the charge data, it is incoming data. So what I'll be doing is using the event to just get the id and then make the call to get the charge object from my own end to prevent any event spoofs. So that means I don't have to worry about casting at this point. Here is my solution, feel free to advise if there is a better way to do it
for (int i = 0; i < Int32.Parse(stripeEvent.Data.Object["transactions"]["total_count"].ToString()); i++)
{
string chargeId = stripeEvent.Data.Object["transactions"]["data"][i]["id"].ToString();
// do stuff with it
}
just for completeness:
Data under transactions looks like an array so should be able to index into them..
If you need to access to any other fields in the future you could construct c# objects but given the webhook 3rd party dance you are already doing probably not worth it as you only need id.
Basically I would like to do something like this at the top of my class (I know this doesn't work as it isn't a constant)....
[XmlStorage(IsSingleStorageFile = false, IsSubordinate = true,
StorageLocation = "posts" + GetBlogId()]
Where GetBlogId() would be a static utility method.
I'm building an xml storage framework for a blogging engine I am writing (partly a learning excercise, partly as I want to give something back to the open source) and I thought that the tidiest way to determine the storage location would be to use custom attributes since I would be to use a datacontractserializer anyway.
My only problem at present is determining the location for subordinate type whose location would be determined by the id of their parent. e.g Post < Blog.
My storage path would be something like this...
posts\blogid\postid.xml
Where the blog id would be determined by parsing the url and returning the associated blog. This would allow me to host multiple blogs in one installation whilst keeping post storage files separate to reduce memory overheads when loading posts.
Is this a straight no or is there a better way for me to do what I am attempting?
Edit:
Following John answer I tried this....
private static string GetSubordinatePath(Type type)
{
if (typeof(ISubordinate).IsAssignableFrom(type))
{
object instance = Activator.CreateInstance(type);
return (instance as ISubordinate).ParentGuid.ToString();
}
else
{
// TODO: Localize this.
throw new ArgumentException(
String.Format(
CultureInfo.CurrentCulture,
"The specified type '{0}' does not impliment the ISubordinate interface. Please edit the source appropriately to enable storage.",
type.GetType().Name));
}
}
Which would be called from the class reading the custom attribute.
This works nicely..
It's a straight no for attributes... the values are constants baked into the metadata.
One option you could use would be to have some sort of templating built into whatever uses the attributes... so you could have a storage location of posts\{GetBlogId()} and call the method at execution time. It's not exactly elegant though... you might want to consider using an interface instead.