Switch / Checkout Branch ist not working - libgit2

I'm using Version 0.19
I've a remote branch named 'dev'
after cloning i want to switch to this branch.
i found some code which performs an update to the branch. but for me it doesn't work.
I also try to run a checkout after this which also doesnt work.
When viewing the git log after the code i see the changesets of the master branch. But the local branch name is the name of the given name for the created branch (e.G. "dev")
what am i doing wrong?
private static Branch SwitchBranch(Repository repo, RepositoryProperties properties)
{
string branchname = properties.Branch;
Branch result = null;
if (!string.IsNullOrWhiteSpace(properties.Branch))
{
Branch remote = null;
foreach (var branch in repo.Branches)
{
if (string.Equals(branch.Name, "origin/" + branchname))
{
remote = branch;
break;
}
}
string localBranchName = properties.Branch;
Branch localbranch = repo.CreateBranch(localBranchName);
Branch updatedBranch = repo.Branches.Update(localbranch,
b =>
{
b.TrackedBranch = remote.CanonicalName;
});
repo.Checkout(updatedBranch);
result = updatedBranch;
}
return result;
}

The xml documentation of the CreateBranch() overload you're using states "Creates a branch with the specified name. This branch will point at the commit pointed at by Repository.Head".
From your question, it looks like you'd like this branch to also point to the same Commit than the remote tracking one.
As such, I'd suggest you to change your code as follows:
Branch localbranch = repo.CreateBranch(localBranchName, remote.Tip);

Be aware that you can only create the local branch once. So you're going to get an error the second time. At least, I did.
Branch localbranch = repo.Branches.FirstOrDefault(x => !x.IsRemote && x.FriendlyName.Equals(localBranchName));
if (localbranch == null)
{
localbranch = repo.CreateBranch(localBranchName, remote.Tip);
}
Branch updatedBranch = repo.Branches.Update(localbranch,
b =>
{
b.TrackedBranch = remote.CanonicalName;
});
repo.Checkout(updatedBranch);

Related

How do I force rebuild of all snapshot dependencies in my teamcity build trigger?

I have a list of build types in my settings.kts:
val buildChain = listOf(build1, build2, build3, ...)
I define the following chain of snapshot dependencies:
for ((previous, current) in buildChain.zip(buildChain.drop(1))) {
current.dependencies {
snapshot(previous) {
reuseBuilds = ReuseBuilds.NO
onDependencyFailure = FailureAction.FAIL_TO_START
onDependencyCancel = FailureAction.FAIL_TO_START
}
}
}
With that, build<N> depends on build<N-1>. Then I define the following build type that runs the whole build chain:
val buildChainRunner = BuildChainRunner(headOfBuildChain = buildChain.last())
where
class BuildChainRunner(
headOfBuildChain: BuildType,
) : BuildType({
name = "Build Chain Runner"
dependencies {
snapshot(headOfBuildChain) {
reuseBuilds = ReuseBuilds.NO
onDependencyFailure = FailureAction.ADD_PROBLEM
onDependencyCancel = FailureAction.ADD_PROBLEM
}
}
triggers {
schedule {
schedulingPolicy = daily {
hour = 2
minute = 0
timezone = "Europe/Amsterdam"
}
branchFilter = "+:<default>"
triggerBuild = always()
withPendingChangesOnly = false
}
}
[...]
}
Now, when the build gets triggered by the schedule trigger, it doesn't necessarily rebuilds all builds from the chain. What I would like to do is the very same as this:
I thought that would be automatically the case because of
reuseBuilds = ReuseBuilds.NO
but unfortunately, it doesn't work. When I trigger the build manually and set "rebuild snapshot dependencies" to "all", then it works as I expect. What am I doing wrong in my kotlin DSL configuration?

Call fetchgit without SSL Verify

I'm trying to use fetchgit to download source repos from my lab's private GitLab server, which currently self-signs its SSL certificate.
default.nix:
with (import <nixpkgs> {});
{ test-pkg = callPackage ./test-pkg.nix {
buildPythonPackage = python35Packages.buildPythonPackage;
};
}
test-pkg.nix:
{ buildPythonPackage,fetchgit }:
buildPythonPackage rec {
pname = "test-pkg";
version = "0.2.1";
src = fetchgit {
url = "https://gitlabserver/experiment-deployment/test-pkg";
rev = "refs/tags/v${version}";
sha256 = "43c2c9e5e7a16b6c88ba3088a9bfc82f7db8e13378be7c78d6c14a5f8ed05afd";
};
}
Which results in the error when I call nix-shell
fatal: unable to access 'https://gitlabserver/experiment-deployment/test-pkg/': SSL certificate problem: self signed certificate
Looking at, build-support/fetchgit, it seems that fetchgit is made with mkDerivation, so I tried to make a new fetchgit using overrideAttrs. I pass in the git environment variable to make git ignore SSL verification, expecting that the variable will be initialized during the setup phase.
revised default.nix:
with (import <nixpkgs> {});
let fetchgit-no-verify = fetchgit.overrideAttrs { GIT_SSL_NO_VERIFY=true;} ;
in rec {
test-pkg = callPackage ./test-pkg.nix {
buildPythonPackage = python35Packages.buildPythonPackage;
fetchgit = fetchgit-no-verify;
};
}
I thought I was really clever when I thought of this over the weekend, only to discover that when implemented my new error states that
error: attribute 'overrideAttrs' missing, at [...]/default.nix:2:26
Inspecting fetchgit in nix repl shows that it is a functor attribute set. I tried for a little bit to get to the overrideAttrs, without success. Trying again I saw that git could be passed to to fetchGit,
re-revised default.nix:
with (import <nixpkgs> {});
let git = git.overrideAttrs { GIT_SSL_NO_VERIFY=true;} ;
fetchgit-no-verify = fetchgit.override { git=git-no-verify;} ;
in rec {
test-pkg = callPackage ./test-pkg.nix {
buildPythonPackage = python35Packages.buildPythonPackage;
fetchgit = fetchgit-no-verify;
};
}
but the new error:
error: attempt to call something which is not a function but a set, at /nix/store/jmynn33vcn3mcscsch0zf46fz9wsw05y-nixpkgs-20.03pre193309.c4196cca9ac/nixpkgs/pkgs/stdenv/generic/make-derivation.nix:318:55
Finally, onto my questions. Is there a way to add the environment variable to the fetchgit or git derivations? Is there perhaps another way to connect--some builtin option I missed? I could use a private repository, using ssh and avoiding https, however due to how we deploy experiments I'd like to avoid that.
I was able to make this work with this ugly thing.
default.nix:
with (import <nixpkgs> {});
let fetchgit-no-verify = fetchgit // {
__functor = self : args :
(fetchgit.__functor self args).overrideAttrs (oldAttrs:{GIT_SSL_NO_VERIFY=true;});
} ;
in rec {
test-pkg = callPackage ./test-pkg.nix {
buildPythonPackage = python35Packages.buildPythonPackage;
fetchgit = fetchgit-no-verify;
};
}
fetchgit-no-verify uses the fetchgit functor set to begin with and overwrites the __functor attribute with a new function. The new functor just applies its arguments and then calls overrideAttrs.
This works, but I'm happy to award the answer to anybody who can add some insight or comes with another solution. For one, I'd like to know how the fetchgit derivation becomes a functor. Is this something callPackage does?.

Unable to branch my tests using a variable in Postman

I have a collection with two folders, one for POSTs and one for GETs
At the collection level, I have set variables
And the following collection-level scripts to be run after every request:
requestLast = pm.variables.get("requestLast");
requestCurrent = pm.variables.get("requestCurrent");
statusGet = pm.variables.get("statusGet");
requestLast = requestCurrent;
requestCurrent = pm.request.name;
I want to always be keeping track of the previously run request, so I can return to it when necessary.
In the 'positivePosts' folder I have the following test script:
if(statusGet === 0) {
postman.setNextRequest("resultsPositive");
}
else {
statusGet = 0;
}
pm.variables.set("requestLast", requestLast);
pm.variables.set("requestCurrent", requestCurrent);
pm.variables.set("statusGet", statusGet);
The individual POST requests have no test scripts.
The results folder does not have any tests, but the resultsPositive GET has this test script:
var jsonData = JSON.parse(responseBody);
schema = pm.variables.get("schemaPositive");
tests["Valid Schema"] = tv4.validate(jsonData, schema);
tests["Status code is 200"] = responseCode.code === 200;
statusGet = 1;
postman.setNextRequest(requestLast);
pm.variables.set("requestLast", requestLast);
pm.variables.set("requestCurrent", requestCurrent);
pm.variables.set("statusGet", statusGet);
There are no pre-request scripts anywhere in the collection.
When running the collection, I would expect this order:
postRich
resultsPositive
postAllProperties
resultsPositive
postMinimum
resultsPositive
However, what I actually see is:
postRich
postAllProperties
postPositive
I also don't understand why postPositive is not run after postRich.

JGit log strange behavior after merge

Found a strange behavior (bug?) in a log command.
The below test creates a repo, creates a branch, does some commits either to the created branch and to master, then merges master to the created branch. After merge it tries to calculate the number of commits between the branch and master. Because master has been already merged -- the branch is not behind the master, i.e. corresponding commit count should be 0.
public class JGitBugTest {
#Rule
public TemporaryFolder tempFolder = new TemporaryFolder();
#Test
public void testJGitLogBug() throws Exception {
final String BRANCH_NAME = "TST-2";
final String MASTER_BRANCH_NAME = Constants.MASTER;
File folder = tempFolder.newFolder();
// Create a Git repository
Git api = Git.init().setBare( false ).setDirectory( folder ).call();
Repository repository = api.getRepository();
// Add an initial commit
api.commit().setMessage( "Initial commit" ).call();
// Create a new branch and add some commits to it
api.checkout().setCreateBranch( true ).setName( BRANCH_NAME ).call();
api.commit().setMessage( "TST-2 Added files 1" ).call();
// Add some commits to master branch too
api.checkout().setName( MASTER_BRANCH_NAME ).call();
api.commit().setMessage( "TST-1 Added files 1" ).call();
api.commit().setMessage( "TST-1 Added files 2" ).call();
// If this delay is commented out -- test fails and
// 'behind' is equal to "the number of commits to master - 1".
// Thread.sleep(1000);
// Checkout the branch and merge master to it
api.checkout().setName( BRANCH_NAME ).call();
api.merge()
.include( repository.resolve( MASTER_BRANCH_NAME ) )
.setStrategy( MergeStrategy.RECURSIVE )
.call()
.getNewHead()
.name();
// Calculate the number of commits the branch behind of the master
// It should be zero because we have merged master into the branch already.
Iterable<RevCommit> iterable = api.log()
.add( repository.resolve( MASTER_BRANCH_NAME ) )
.not( repository.resolve( BRANCH_NAME ) )
.call();
int behind = 0;
for( RevCommit commit : iterable ) {
behind++;
}
Assert.assertEquals( 0, behind );
}
}
The above test fails, behind yields the number of commits in the master minus 1.
Moreover, if 'sleep' in line 43 is uncommented -- the bug will go away, and 'behind' is equal to 0.
What do I do wrong? Is it a bug in JGit library or in my code?
Running the code on Windows, I can reproduce what you describe.
This looks like a bug in JGit to me. I recommend to open a bugzilla or post your findings to the mailing list.

Update a DynamicContent item of a dynamic module in Sitefinity

I am trying to update a DynamicContent Property of a module using the following:
DynamicModuleManager dynamicModuleManager = DynamicModuleManager.GetManager();
Type pollanswerType = TypeResolutionService.ResolveType("Telerik.Sitefinity.DynamicTypes.Model.Poll.Pollanswer");
Guid pollanswerID = new Guid(answerID);
// This is how we get the pollanswer item by ID
DynamicContent pollanswerItem = dynamicModuleManager.GetDataItem(pollanswerType, pollanswerID);
pollanswerItem.SetValue("VoteCount", int.Parse(pollanswerItem.GetValue("VoteCount").ToString()) + 1);
dynamicModuleManager.SaveChanges();
Basically getting the current Property value and incrementing it by 1
and calling SaveChanges()
the code runs without errors but it doesn't update the value when I check it from the Back End of Sitefinity.
Any suggestions?
The problem might be caused by the pollanswerID that you are passing.
If the pollanswerID is the id of the live version of the content item then the value wouldn't be set.
Make sure you set the field value to the of master version of the content type not the live one.
In case you don't know the id of the master version of the content type you can get the master content item by the id of the live version of the content type
var masterItem = dynamicModuleManager.GetDataItems(pollanswerType).Where(dynItem => dynItem.Id == pollanswerItem.OriginalContentId).FirstOrDefault();
if (masterItem != null)
{
masterItem.SetValue("VoteCount", int.Parse(masterItem.GetValue("VoteCount").ToString()) + 5);
}
you should be always doing this
Get Master
Checkout Master
Checkin Master
Save Changes
Publish changes – this will update live.
bookingItemLive is the live record
var bookingItemMaster = dynamicModuleManager.Lifecycle.Edit(bookingItemLive) as DynamicContent;
//Check out the master to get a temp version.
DynamicContent bookingItemTemp = dynamicModuleManager.Lifecycle.CheckOut(bookingItemMaster) as DynamicContent;
//Make the modifications to the temp version.
bookingItemTemp.SetValue("CleanerId", cleanerId);
bookingItemTemp.SetValue("SubCleanerId", subCleanerId);
bookingItemTemp.LastModified = DateTime.UtcNow;
//Checkin the temp and get the updated master version.
//After the check in the temp version is deleted.
bookingItemMaster = dynamicModuleManager.Lifecycle.CheckIn(bookingItemTemp) as DynamicContent;
dynamicModuleManager.SaveChanges();
//Publish the item now
ILifecycleDataItem publishedBookingItem = dynamicModuleManager.Lifecycle.Publish(bookingItemMaster);
bookingItemMaster.SetWorkflowStatus(dynamicModuleManager.Provider.ApplicationName, "Published");
#Joseph Ghassan: You can follow below step.
Step 1: Get Live
var bookingItemLive= manager.GetDataItem(ModuleType, GuidId);
Step 2: Get Master
var bookingItemMaster = manager.Lifecycle.GetMaster(bookingItemLive) as DynamicContent;
Step 2: Checkout Master --> will be created a draft item( you will update data by draft)
if (bookingItemMaster == null)
{
return new HttpResponseMessage
{
Content = new JsonContent(new { Result = false })
};
}
var bookingItemDraff = manager.Lifecycle.CheckOut(bookingItemMaster) as DynamicContent;
//Make the modifications to the temp version.
bookingItemDraff.SetValue("CleanerId", cleanerId);
bookingItemDraff.SetValue("SubCleanerId", subCleanerId);
bookingItemDraff.LastModified = DateTime.UtcNow;
Step 3: Checkin Master
// Now we need to check in, so the changes apply
var checkInItem = manager.Lifecycle.CheckIn(bookingItemDraff);
Step 4: Publish changes
manager.Lifecycle.Publish(checkInItem);
Step 5: Save Changes - this will save to Database and update live.
bookingItemDraff.SetWorkflowStatus(manager.Provider.ApplicationName, CustomFieldName.PublishedStatus);
manager.SaveChanges();