Checkout using Libgit2sharp on an empty repo - libgit2sharp

By using git checkout -b <branchname> I am able to create a new branch in an empty repo and the start committing files on that branch. I am not able to achieve this via libgit2sharp. By using repo.Checkout(branchName) it throws following error:
LibGit2Sharp.NotFoundException: No valid git object identified by exists in the repository.

The current version of the native libgit2 library used by libgit2sharp requires a HEAD to exist as it is used during the branch creation. Using a empty(null) committish is valid in the official git version and thus creating a new branch and checking it out works fine on a completely bare repo. Maybe this is covered in the next release and/or an already known bug.
But either way, just create an initial commit that is empty in content and it works:
using System;
using System.IO;
using LibGit2Sharp;
namespace stackoverflow
{
class MainClass
{
public static void Main (string[] args)
{
var rPath = Path.Combine (Path.GetTempPath (), "StackOverFlow");
var rootedPath = Repository.Init (rPath, false);
var repo = new Repository (rootedPath);
repo.Commit ("Initial Commit");
repo.CreateBranch ("EmptyBranch");
repo.Checkout ("EmptyBranch");
}
}
}

Related

Calling Another Project's Controller From A Project In The Same Solution (.NET Core )

There are 2 projects in the same solution. First project is a .NET Core project and it has all the codes(controllers, models etc.) related to packages. I need to get the information (id, name, description) of the packages and display it in the second project(.NET Core Web App with Razor). Is it possible to do it without changing the first project? I only want to show the package list on a single web page.
I tried calling the first project's controller but it didn't work. Maybe I missed a point. Any help is appreciated.
This requirement can be achieved, please see the gif image below.
Tips
If you want to call another project's controller from a project in the same solution, you need to make sure there is in HomeController in both project. I mean the name of any class should be unique in both projects.
Otherwise you will face the same issue like my homepage.
Test Code:
public List<PackageReference> GetPackageList5(string projectname)
{
List<PackageReference> list = new List<PackageReference>();
PackageReference p = null;
XDocument doc = XDocument.Load(_webHostEnvironment.ContentRootPath+ "/"+ projectname + ".csproj");
var packageReferences = doc.XPathSelectElements("//PackageReference")
.Select(pr => new PackageReference
{
Include = pr.Attribute("Include").Value,
Version = pr.Attribute("Version").Value
});
Console.WriteLine($"Project file contains {packageReferences.Count()} package references:");
foreach (var packageReference in packageReferences)
{
p = new PackageReference();
p.Version= packageReference.Version;
p.Include= packageReference.Include;
list.Add(packageReference);
//Console.WriteLine($"{packageReference.Include}, version {packageReference.Version}");
}
return list;
}
My Test Steps:
create two project, Net5MVC,Net6MVC
add project reference.
My .net6 project references a .net5 project. So in my HomeController (.net), I add below:
using Net5MVC.ForCore6;
using Net5MVC.Models;
Suggestion
When we reference the .net5 project in .net6 project, we can build success, but when we deploy it, it always failed. The reason is some file was multiple publish output files with the same relative path.
Found multiple publish output files with the same relative path:
D:\..\Net6\Net6\Net5MVC\appsettings.Development.json,
D:\..\Net6\Net6\Net6MVC\appsettings.Development.json,
D:\..\Net6\Net6\Net5MVC\appsettings.json,
D:\..\Net6\Net6\Net6MVC\appsettings.json.
And usually will add class library to current project, not add a web project.
As we know we can find packages info in .csproj file, so we need copy and paste .csproj file to publish folder.
I still recommend using the GetPackageList5 method above as an interface for your project, using HttpClient for requests.

Defining FOLDER level variables in Jenkins using a shared \vars library

So I'm trying to make define folder level variables by putting them in a groovy file in the \vars directory.
Alas, the documentation is so bad, that it's impossible to figure out how to do that...
Assuming we have to globals G1 and G2, is this how we define them in the groovy file?
#!Groovy
static string G1 = "G1"
static string G2 = "G2"
Assuming the Groovy file is called XYZ.Groovy, how do I define it in the folder so its available for the folder's script?
Assuming I get over that, and that that LIBXYZ is the name the folder associates with the stuff in the /vars directory, is it correct to assume that when I call
#Library("LIBXYZ") _
it will make XYZ available?
In that case, is XYZ.G1 the way to access the globals?
thanks, a.
I have a working example here as I was recently curious about this. I agree that the documentation is wretched.
The following is similar to the info in README.md.
Prep: note that folder here refers to Jenkins Folders from the CloudBees Folder plugin. It is a way to organize jobs.
Code Layout
The first part to note is src/net/codetojoy/shared/Bar.groovy :
package net.codetojoy.shared
class Bar {
static def G1 = "G1"
static def G2 = "G2"
def id
def emitLog() {
println "TRACER hello from Bar. id: ${id}"
}
}
The second part is vars/folderFoo.groovy:
def emitLog(message) {
println "TRACER folderFoo. message: ${message}"
def bar = new net.codetojoy.shared.Bar(id: 5150)
bar.emitLog()
println "TRACER test : " + net.codetojoy.shared.Bar.G1
}
Edit: To use a static/"global" variable in the vars folder, consider the following vars/Keys.groovy:
class Keys {
static def MY_GLOBAL_VAR3 = "beethoven"
}
The folderFoo.groovy script can use Keys.MY_GLOBAL_VAR3.
And then usage (in my example: Basic.Folder.Jenkinsfile):
#Library('folderFoo') _
stage "use shared library"
node {
script {
folderFoo.emitLog 'pipeline test!'
}
}
Jenkins Setup: Folder
Go to New Item and create a new Folder
configure the folder with a new Pipeline library:
Name is folderFoo
Default version is master
Retrieval Method is Modern SCM
Source Code Management in my example is this repo
Jenkins Setup: Pipeline Job
create a new Pipeline job in the folder created above
though a bit confusing (and self-referential), I create a pipeline job that uses this same this repo
specify the Jenkinsfile Basic.Folder.Jenkinsfile
the job should run and use the library

LibGit2Sharp Cloning from a network file share

I'm having issues cloning using the file transport when the remote is hosted on a network drive.
I downloaded the project and tried adding some test cases:
[Fact]
public void CanCloneALocalRepositoryFromANetworkDriveUri()
{
var networkPath = #"file:///192.168.1.1/Share/TestRepo.git";
var uri = new Uri(networkPath);
AssertLocalClone(uri.AbsoluteUri, BareTestRepoPath);
}
That fails with:
LibGit2Sharp.LibGit2SharpException : failed to resolve path 'file://192.168.1.1/Share/TestRepo.git': The filename, directory name, or volume label syntax is incorrect.
I tried mapping a drive letter (Z:) to the share, and ran this:
[Fact]
public void CanCloneALocalRepositoryFromAMappedNetworkDrive()
{
var networkPath = #"file:///Z:/TestRepo.git";
var uri = new Uri(networkPath);
AssertLocalClone(uri.AbsoluteUri, BareTestRepoPath);
}
That fails with:
LibGit2Sharp.LibGit2SharpException : failed to resolve path 'Z:/TestRepo.git': The system cannot find the path specified.
unless I set:
HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\EnableLinkedConnections
to a DWORD value of 1, as per this TechNet article - in which case the clone succeeds. However, this is not a viable solution in my situation, as it raises deployment issues in security-conscious environments.
It appears that LibGit2Sharp is not capable of cloning from a file UNC. Have I understood correctly, and if so is there any way to work around this?
The file:/// URL syntax is not appropriate for UNC paths. Just use a UNC path, eg:
\\192.168.1.1\Share\TestRepo.git
This works in LibGit2Sharp and the git command-line client as well.

Find XML file changes in all branches

I have an XML file in my main TFS branch. I have 50 branches of the main folder. Is there a quick way to check in which branches the file is modified before merging it to the main branch?
I have found that it can be done with CodeLens for code files, but I don't know how to do it for XML files.
You can refer to these steps below:
Create a new workspace
Map these branches (Do not include other mapping)
To do work (e.g. modify files)
Open Team Explorer
Switch to this workspace
Click Pending Changes, then all changes in this workspace will be list.
If these changes are already existing in different workspace, you can check in changes through TFS API (install Microsoft Team Foundation Server Extended Client package to your project).
Simple code to iterate all workspaces in a machine and check in specified changes:
NetworkCredential cred = new NetworkCredential("[username]", "[password]", "[domain]");
TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(new Uri("[collection url"), cred);
tpc.EnsureAuthenticated();
VersionControlServer versionControl = tpc.GetService<VersionControlServer>();
var spaces = versionControl.QueryWorkspaces(null, null, "[machine name, can be null]");
foreach(var currentWorkspace in spaces)
{
var libChanges= currentWorkspace.GetPendingChanges("[server or local path]",RecursionType.Full);
if (libChanges.Count() > 0)
{
currentWorkspace.CheckIn(changes: libChanges, comment: "checkInAPI");
}
}
Update:
You can compare branches.
Open Source Control Explorer
Right click a branch > Compare
Change Target path to target branch server path
Click OK.
On the other hand, there is an TFS Productivity Pack extension you can use.

Equivalent to git diff --unified=0 with libgit2sharp?

I am planning to replace the usage of git.exe from windows path by libgit2sharp for my plugin GitDiffMargin, A Visual Studio 2012 extension to display Git Diff on the margin of the current file. - https://github.com/laurentkempe/GitDiffMargin
I would like to know if there is an equivalent in libgit2sharp to get the same information as when running git diff --unified=0 on a file?
It looks like libgit2 supports changing context lines, but currently LibGit2Sharp is hard-coded to use 3: https://github.com/libgit2/libgit2sharp/blob/6a2d99ecdf35288df88c0e6fe8985969042d82a6/LibGit2Sharp/Diff.cs#L27
I've created https://github.com/libgit2/libgit2sharp/issues/423 to track the feature request.
Update:
As of v0.12 (or whatever comes after v0.11), you can do this:
var co = new CompareOptions
{
ContextLines = 0,
};
var tc = repo.Diff.Compare(new[] { filename }, co);

Resources