/// <summary> /// <para>Merge the right token into the left</para> /// </summary> /// <param name="left">Token to be merged into</param> /// <param name="right">Token to merge, overwriting the left</param> /// <param name="options">Options for merge</param> public static void MergeInto( this JContainer left, JToken right, MergeOptions options) { foreach (var rightChild in right.Children<JProperty>()) { var rightChildProperty = rightChild; var leftPropertyValue = left.SelectToken(rightChildProperty.Name); // add on demand only. This will keep low memory usage. if (leftPropertyValue == null && options.ADD_NONE_EXISTING) { // no matching property, just add left.Add(rightChild); } else { if (leftPropertyValue == null && !options.ADD_NONE_EXISTING) { // becoz we don't want to add so continue checking for next property. continue; } var leftProperty = (JProperty)leftPropertyValue.Parent; var leftArray = leftPropertyValue as JArray; var rightArray = rightChildProperty.Value as JArray; if (leftArray != null && rightArray != null) { switch (options.ArrayHandling) { case MergeOptionArrayHandling.Concat: foreach (var rightValue in rightArray) { leftArray.Add(rightValue); } break; case MergeOptionArrayHandling.Overwrite: leftProperty.Value = rightChildProperty.Value; break; } } else { var leftObject = leftPropertyValue as JObject; //only set property if it not null if (leftObject == null && !string.IsNullOrEmpty(rightChildProperty.Value.ToString())) { // replace value leftProperty.Value = rightChildProperty.Value; } else // recurse object MergeInto(leftObject, rightChildProperty.Value, options); } } } }
/// <summary> /// <para>Merge the right token into the left</para> /// </summary> /// <param name="left">Token to be merged into</param> /// <param name="right">Token to merge, overwriting the left</param> /// <param name="options">Options for merge</param> public static void MergeInto( this JContainer left, JToken right, MergeOptions options) { foreach (var rightChild in right.Children<JProperty>()) { var rightChildProperty = rightChild; var leftPropertyValue = left.SelectToken(rightChildProperty.Name); if (leftPropertyValue == null) { // no matching property, just add left.Add(rightChild); } else { var leftProperty = (JProperty) leftPropertyValue.Parent; var leftArray = leftPropertyValue as JArray; var rightArray = rightChildProperty.Value as JArray; if (leftArray != null && rightArray != null) { switch (options.ArrayHandling) { case MergeOptionArrayHandling.Concat: foreach (var rightValue in rightArray) { leftArray.Add(rightValue); } break; case MergeOptionArrayHandling.Overwrite: leftProperty.Value = rightChildProperty.Value; break; } } else { var leftObject = leftPropertyValue as JObject; if (leftObject == null) { // replace value leftProperty.Value = rightChildProperty.Value; } else // recurse object MergeInto(leftObject, rightChildProperty.Value, options); } } } }
/// <summary> /// <para>Creates a new token which is the merge of the passed tokens</para> /// </summary> /// <param name="left">Token</param> /// <param name="right">Token to merge, overwriting the left</param> /// <param name="options">Options for merge</param> /// <returns>A new merged token</returns> public static JToken Merge( this JToken left, JToken right, MergeOptions options) { if (left.Type != JTokenType.Object) return right.DeepClone(); var leftClone = (JContainer) left.DeepClone(); MergeInto(leftClone, right, options); return leftClone; }
private void Init() { if (_mergeOptions != null) { RTParsingContext context = new RTParsingContext(_factory); var exprList = new RTExpressionList(); exprList.Parse(_mergeExpr, 0, context); _interpreter = exprList; _mergeOptions = null; //not needed anymore _mergeExpr = null; if (!_interpreter.CanExecute) { _parsingException = new RTParsingException(context.Errors, ErrorMessages.Post_Parsing_Error); } } if (_parsingException != null) throw _parsingException; }
/// <summary> /// Merges the given distributions into the system. /// </summary> /// <param name="distarr">the distributions to merge</param> /// <param name="mopts">merge option flags</param> public void Merge(IDistribution[] distarr, MergeOptions mopts) { if (distarr.Length == 0) return; Downloader downloader = new Downloader(_cfg.DistFilesDir); List<MergeEventArgs> scheduled = null; this.ScheduleMerges(distarr, mopts, downloader, out scheduled); if (!mopts.HasFlag(MergeOptions.Pretend)) { if (this.OnParallelFetch != null) this.OnParallelFetch.Invoke(this, new EventArgs()); downloader.FetchAsync(); } for (int i = 0; i < scheduled.Count; i++) { MergeEventArgs mea = scheduled[i]; mea.CurrentIter = i + 1; mea.TotalMerges = scheduled.Count; this.MergeOne(mea, mopts, downloader, _pkgmgr.RootDir); } if (!mopts.HasFlag(MergeOptions.Pretend)) { if (this.OnAutoClean != null) this.OnAutoClean.Invoke(this, new EventArgs()); TrashWorker.Purge(_pkgmgr); } }
public MergeResult Merge(Commit commit, Signature merger, MergeOptions options) { return(repositoryInstance.Merge(commit, merger, options)); }
public MergeResult Merge(Commit commit, Signature merger, MergeOptions options = null) { throw new NotImplementedException(); }
/// <inheritdoc /> public MergeResult Merge(Commit commit, Signature merger, MergeOptions options) => repository.Merge(commit, merger, options);
public void MergeReportsCheckoutProgress() { string repoPath = CloneMergeTestRepo(); using (var repo = new Repository(repoPath)) { Commit commitToMerge = repo.Branches["normal_merge"].Tip; bool wasCalled = false; MergeOptions options = new MergeOptions() { OnCheckoutProgress = (path, completed, total) => wasCalled = true, }; MergeResult result = repo.Merge(commitToMerge, Constants.Signature, options); Assert.True(wasCalled); } }
public MergeResult Merge(Branch branch, Signature merger, MergeOptions options) { return(repositoryInstance.Merge(branch, merger, options)); }
public RTMerger(string mergeExpr, MergeOptions options) { _mergeExpr = mergeExpr; _mergeOptions = options; }
protected abstract void Merge_Internal(string[] svgFiles, MergeOptions options, SVGDocument svgContainer);
protected override void Merge_Internal(string[] svgFiles, MergeOptions options, SVGDocument svgContainer) { double borderStrokeFloat = options.BorderStroke; double separatorStrokeFloat = options.SeparatorStroke; var gRootContainer = (SVGGElement)svgContainer.CreateElementNS("http://www.w3.org/2000/svg", "g"); var viewBoxWidth = 400f; //100f; //300f; float widthDocumentRootElement = 0; for (int i = 0; i < svgFiles.Length; i++) { using (var svgDocument = new SVGDocument(svgFiles[i])) { var currentWidth = svgDocument.RootElement.GetBBox().Width; if (widthDocumentRootElement < currentWidth) { widthDocumentRootElement = currentWidth; } } } var childWidthFloat = widthDocumentRootElement; int separatorAmount = svgFiles.Length - 1; // 1. First Step // Obtain height of single SVG block and total height // ================================ double ratio; float svgFirstDocumentHeight; using (var svgFirstDocument = new SVGDocument(svgFiles[0])) { var widthFirstDocumentRootElement = svgFirstDocument.RootElement.GetBBox().Width; ratio = childWidthFloat / widthFirstDocumentRootElement; svgFirstDocumentHeight = svgFirstDocument.RootElement.GetBBox().Height; } var currentHeightFloat = ratio * svgFirstDocumentHeight; var currentHeightString = GetCulturedString(currentHeightFloat); var totalHeightFloat = currentHeightFloat * svgFiles.Length + separatorStrokeFloat * svgFiles.Length - 1; // 2. RootElement attributes // ================================ svgContainer.RootElement.ViewBox.BaseVal.X = 0; svgContainer.RootElement.ViewBox.BaseVal.Y = 0; svgContainer.RootElement.ViewBox.BaseVal.Width = viewBoxWidth; svgContainer.RootElement.ViewBox.BaseVal.Height = (float)(totalHeightFloat + 2 * borderStrokeFloat + 2 * separatorStrokeFloat); svgContainer.RootElement.SetAttribute("width", "100%"); svgContainer.RootElement.SetAttribute("height", "100%"); // 3. Border Container // ================================ if (options.IsBordered && options.BorderStroke > 0) { var borderDescription = new BorderDescription( borderStrokeFloat, borderStrokeFloat / 2, borderStrokeFloat / 2, childWidthFloat + 2 * separatorStrokeFloat + borderStrokeFloat, totalHeightFloat + 2 * separatorStrokeFloat + borderStrokeFloat, options.BorderColor); var gBorderContainer = GetBorderContainer(svgContainer, borderDescription); gRootContainer.AppendChild(gBorderContainer); } // 4. Separator Container // ================================ if (options.IsWithSeparator && options.SeparatorStroke > 0) { var separatorDescription = new SeparatorDescription( separatorAmount, separatorStrokeFloat, borderStrokeFloat, borderStrokeFloat + separatorStrokeFloat, childWidthFloat + 2 * separatorStrokeFloat, currentHeightFloat, options.SeparatorColor); var gSeparatorContainer = GetSeparatorContainer(svgContainer, separatorDescription); gRootContainer.AppendChild(gSeparatorContainer); } // 5. Add child svg content // ================================ double currentY = borderStrokeFloat + separatorStrokeFloat; var childWidthSting = GetCulturedString(childWidthFloat); var xOffsetString = GetCulturedString(borderStrokeFloat + separatorStrokeFloat); foreach (var svgFile in svgFiles) { var svgDocument = new SVGDocument(svgFile); svgDocument.RootElement.SetAttribute("width", childWidthSting); svgDocument.RootElement.SetAttribute("height", currentHeightString); svgDocument.RootElement.SetAttribute("x", xOffsetString); svgDocument.RootElement.SetAttribute("y", GetCulturedString(currentY)); var gSampleContainer = (SVGGElement)svgContainer.CreateElementNS("http://www.w3.org/2000/svg", "g"); currentY += currentHeightFloat + separatorStrokeFloat; gSampleContainer.AppendChild(svgDocument.RootElement); gRootContainer.AppendChild(gSampleContainer); svgDocument.Dispose(); } svgContainer.RootElement.AppendChild(gRootContainer); }
public MergeResult MergeFetchedRefs(Signature merger, MergeOptions options) { throw new NotImplementedException(); }
public void FastForwardMergeReportsCheckoutProgress() { string repoPath = SandboxMergeTestRepo(); using (var repo = new Repository(repoPath)) { Commit commitToMerge = repo.Branches["fast_forward"].Tip; bool wasCalled = false; MergeOptions options = new MergeOptions() { OnCheckoutProgress = (path, completed, total) => wasCalled = true, }; repo.Merge(commitToMerge, Constants.Signature, options); Assert.True(wasCalled); } }
/// <inheritdoc /> public MergeResult MergeFetchedRefs(Signature merger, MergeOptions options) => repository.MergeFetchedRefs(merger, options);
/// <inheritdoc /> public MergeResult Merge(string committish, Signature merger, MergeOptions options) => repository.Merge(committish, merger, options);
/// <inheritdoc /> public MergeResult Merge(Branch branch, Signature merger, MergeOptions options) => repository.Merge(branch, merger, options);
/// <summary> /// Merge a single package into the system. /// </summary> /// <param name="mea">merge event arguments</param> /// <param name="mopts">merge options</param> /// <param name="downloader">the downloader</param> /// <param name="rootdir">root directory</param> private void MergeOne(MergeEventArgs mea, MergeOptions mopts, Downloader downloader, DirectoryInfo rootdir) { IDistribution dist = mea.Distribution; uint rc = 0; if (mopts.HasFlag(MergeOptions.Pretend)) { if (this.OnPretendMerge != null) this.OnPretendMerge.Invoke(this, mea); return; } if (this.OnRealMerge != null) this.OnRealMerge.Invoke(this, mea); if (mea.HardMask || mea.KeywordMask) throw new MaskedPackageException(mea.Distribution.Package.FullName); if (dist.PlatformSources.Length > 0) { if (mea.FetchHandle != Guid.Empty && !downloader.Peek(mea.FetchHandle)) { _log.Info("Fetching files in the background... please wait"); _log.InfoFormat("See {0} for fetch progress", downloader.LogFile); downloader.WaitFor(mea.FetchHandle); } _log.InfoFormat("Checking package digests"); foreach (SourceFile src in dist.PlatformSources) { FileInfo distfile = new FileInfo(_cfg.DistFilesDir + @"\" + src.LocalName); if (!Md5Sum.Check(distfile.FullName, src.Digest, Md5Sum.MD5SUMMODE.BINARY)) { _log.ErrorFormat("Digest check failed for {0}", distfile.FullName); throw new InstallException("Computed digest doesn't match expected value."); } } } if (mopts.HasFlag(MergeOptions.FetchOnly)) return; SandboxDirectory sbox = SandboxDirectory.Create(); _log.DebugFormat("Created sandbox directory: {0}", sbox.Root.FullName); IInstallProject installer = dist.GetInstallProject(sbox); if (installer == null) throw new InstallException("Encountered missing or invalid installer project."); bool runmake = installer.HasSrcUnpackTarget || installer.HasSrcCompileTarget || installer.HasSrcInstallTarget || installer.HasSrcTestTarget; if (runmake && (rc = this.SpawnSandboxHost(sbox, installer)) != 0) { _log.DebugFormat("sandbox host return code: {0}", rc); throw new InstallException("Installation failed. See previous errors."); } if (this.OnInstall != null) this.OnInstall.Invoke(this, mea); if (_cfg.CollisionDetect && this.DetectCollisions(sbox.ImageDir, dist.Atom)) throw new InstallException("File collision(s) were detected."); if (mea.Previous != null) { _log.Debug("Trashing files from previous installation"); FileTuple[] oldfiles = _pkgmgr.QueryPackageFiles(mea.Previous); foreach (FileTuple ft in oldfiles) { if (ft.Item2 != FileType.Directory || !this.IsProtected(ft.Item1)) TrashWorker.AddFile(ft.Item1, _pkgmgr); } } FileTuple[] files = null; FileTuple[] shortcuts = null; if (installer.HasPkgPreInstTarget) { _log.Info("Executing pre-install tasks..."); installer.PkgPreInst(); } IntPtr wow64oldval = IntPtr.Zero; if (Environment.Is64BitOperatingSystem && !Environment.Is64BitProcess) { if (!Wow64DisableWow64FsRedirection(out wow64oldval)) throw new InstallException("Failed to disable Wow64 file system redirection."); } try { this.InstallImage(sbox.ImageDir, rootdir, out files); } finally { if (Environment.Is64BitOperatingSystem && !Environment.Is64BitProcess) Wow64RevertWow64FsRedirection(wow64oldval); } this.InstallImage( sbox.LinkDir, new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.CommonStartMenu)), out shortcuts); FileTuple[] allfiles = files.Union(shortcuts).ToArray(); Dictionary<string, string> metadata = new Dictionary<string, string>(); metadata.Add("repository", dist.PortsTree.Repository); _pkgmgr.RecordPackage(dist, installer, allfiles, metadata.ToArray()); if (installer.HasPkgPostInstTarget) { _log.Info("Executing post-install tasks..."); installer.PkgPostInst(); } if (mea.Selected) { _log.InfoFormat("Recording {0} in world favourites", dist.Package.FullName); _pkgmgr.SelectPackage(dist.Atom); } _log.Debug("Destroying the sandbox..."); sbox.Delete(); }
public AnalyticsResponse Union(int overlayid1, int overlayid2, MergeOptions merge) { AnalyticsResponse retval = null; try { GeoComWebClient request = new GeoComWebClient(); string mergestring = Enum.GetName(typeof(MergeOptions), merge); string url = String.Format(_unionTemplate, EndpointURI, overlayid1, overlayid2, mergestring); setCredentials(request); //validateFileType(files); string response = request.Post(url, UserName, Password, "application/json", ""); DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(GeoIQ.Net.Data.AnalyticsResponse)); byte[] bytes = Encoding.ASCII.GetBytes(response); System.IO.MemoryStream stream = new System.IO.MemoryStream(bytes); stream.Position = 0; GeoIQ.Net.Data.AnalyticsResponse result = (GeoIQ.Net.Data.AnalyticsResponse)serializer.ReadObject(stream); retval = result; } catch (Exception ex) { this.LastError = ex; retval = null; } return retval; }
/// <summary> /// Determines the packages needed for merging, including dependencies if necessary. /// </summary> /// <param name="distarr">packages selected for merging</param> /// <param name="mopts">merge options</param> /// <param name="downloader">the downloader</param> /// <param name="scheduled">output list of packages scheduled for merge</param> private void ScheduleMerges(IDistribution[] distarr, MergeOptions mopts, Downloader downloader, out List<MergeEventArgs> scheduled) { scheduled = new List<MergeEventArgs>(); DependencyGraph dg = DependencyGraph.Compute(distarr); IDistribution[] distdeparr = dg.SortedNodes.ToArray(); DependencyGraph.Conflict[] conflicts = dg.FindSlotConflicts(); if (conflicts.Length > 0) throw new SlotConflictException(conflicts); for (int i = 0; i < distdeparr.Length; i++) { IDistribution dist = distdeparr[i]; Atom current = _pkgmgr .FindPackages(Atom.Parse(dist.Package.FullName, AtomParseOptions.WithoutVersion)) .Where(n => n.Slot == dist.Slot) .SingleOrDefault(); bool realselect = distarr.Contains(dist); if (!realselect && current != null && !mopts.HasFlag(MergeOptions.Deep) && dg.CheckSatisfies(current)) dist = dist.PortsTree.Lookup(current); MergeEventArgs mea = new MergeEventArgs(); mea.Previous = current; mea.Selected = realselect && !mopts.HasFlag(MergeOptions.OneShot); mea.Distribution = dist; mea.FetchOnly = mopts.HasFlag(MergeOptions.FetchOnly); mea.HardMask = dist.PortsTree.IsHardMasked(dist); mea.KeywordMask = dist.PortsTree.IsKeywordMasked(dist); mea.KeywordsNeeded = dist.Keywords .Where(kw => _cfg.AcceptKeywords.Contains(kw) || _cfg.AcceptKeywords.Contains(Distribution.GetKeywordName(kw))) .ToArray(); if (!mopts.HasFlag(MergeOptions.Pretend) && (mea.HardMask || mea.KeywordMask)) throw new MaskedPackageException(dist.Package.FullName); if (current == null) mea.Flags |= MergeFlags.New; if (!mea.Flags.HasFlag(MergeFlags.New) && current.Version == dist.Version) mea.Flags |= MergeFlags.Replacing; if (!mea.Flags.HasFlag(MergeFlags.New) && !mea.Flags.HasFlag(MergeFlags.Replacing)) mea.Flags |= MergeFlags.Updating; if (!mea.Flags.HasFlag(MergeFlags.New) && current.Version > dist.Version) mea.Flags |= MergeFlags.Downgrading; if (dist.Slot > 0) mea.Flags |= MergeFlags.Slot; if (dist.Interactive) mea.Flags |= MergeFlags.Interactive; /* TODO block */ if (mea.Flags.HasFlag(MergeFlags.Updating)) mea.Selected = _pkgmgr.IsSelected(dist.Atom); if (dist.FetchRestriction && Distribution.CheckSourcesExist(dist, _cfg.DistFilesDir)) mea.Flags |= MergeFlags.FetchExists; else if (dist.FetchRestriction) mea.Flags |= MergeFlags.FetchNeeded; if (mea.Flags.HasFlag(MergeFlags.Replacing) && (!realselect || mopts.HasFlag(MergeOptions.NoReplace)) && !mopts.HasFlag(MergeOptions.EmptyTree)) continue; if (mea.Flags.HasFlag(MergeFlags.FetchNeeded) && !mopts.HasFlag(MergeOptions.Pretend)) { throw new InstallException("Fetch restriction is enabled for " + dist.ToString() + "\nCopy the package archive into " + _cfg.DistFilesDir); } if (!(mea.Flags.HasFlag(MergeFlags.FetchExists) || mea.Flags.HasFlag(MergeFlags.FetchNeeded))) mea.FetchHandle = downloader.Enqueue(dist); scheduled.Add(mea); } }
public MergeResult Merge(string committish, Signature merger, MergeOptions options) { return(repositoryInstance.Merge(committish, merger, options)); }
public RuleOptions() { _matchOptions = new MatchOptions(); _templateOptions = new TemplateOptions(); _mergeOptions = new MergeOptions(); }
public void MergeCanSpecifyMergeFileFavorOption(MergeFileFavor fileFavorFlag) { const string conflictFile = "a.txt"; const string conflictBranchName = "conflicts"; string path = CloneMergeTestRepo(); using (var repo = InitIsolatedRepository(path)) { Branch branch = repo.Branches[conflictBranchName]; Assert.NotNull(branch); var status = repo.Index.RetrieveStatus(); MergeOptions mergeOptions = new MergeOptions() { MergeFileFavor = fileFavorFlag, }; MergeResult result = repo.Merge(branch, Constants.Signature, mergeOptions); Assert.Equal(MergeStatus.NonFastForward, result.Status); // Verify that the index and working directory are clean Assert.True(repo.Index.IsFullyMerged); Assert.False(repo.Index.RetrieveStatus().IsDirty); // Get the blob containing the expected content. Blob expectedBlob = null; switch (fileFavorFlag) { case MergeFileFavor.Theirs: expectedBlob = repo.Lookup<Blob>("3dd9738af654bbf1c363f6c3bbc323bacdefa179"); break; case MergeFileFavor.Ours: expectedBlob = repo.Lookup<Blob>("610b16886ca829cebd2767d9196f3c4378fe60b5"); break; default: throw new Exception("Unexpected MergeFileFavor"); } Assert.NotNull(expectedBlob); // Verify the index has the expected contents IndexEntry entry = repo.Index[conflictFile]; Assert.NotNull(entry); Assert.Equal(expectedBlob.Id, entry.Id); // Verify the content of the file on disk matches what is expected. string expectedContent = expectedBlob.GetContentText(new FilteringOptions(conflictFile)); Assert.Equal(expectedContent, File.ReadAllText(Path.Combine(repo.Info.WorkingDirectory, conflictFile))); } }
/// <summary> /// Merges fields specified by this FieldMask from one message to another with the /// specified merge options. /// </summary> public void Merge(IMessage source, IMessage destination, MergeOptions options) { new FieldMaskTree(this).Merge(source, destination, options); }
public static MergeResult Merge(MergeOptions options) { return(MergeCommand.Execute(options)); }
// this method is provided to facilitate calling from PowerShell public static DictionaryParameters Merge(DictionaryParameters left, DictionaryParameters right, MergeOptions mergeOption) { Contract.Requires(null != left); Contract.Requires(null != right); var mergedDictionary = Merge <string, object>(left, right, mergeOption); if (null == mergedDictionary) { return(null); } var result = new DictionaryParameters(); foreach (var kvp in mergedDictionary) { result.Add(kvp.Key, kvp.Value); } return(result); }
public static IDictionary <TKey, TValue> Merge <TKey, TValue>(IDictionary <TKey, TValue> left, IDictionary <TKey, TValue> right, MergeOptions mergeOption) { Contract.Requires(null != left); Contract.Requires(null != right); Contract.Requires(Enum.IsDefined(typeof(MergeOptions), mergeOption)); var mergedDictionary = left.ToDictionary(kvp => kvp.Key, kvp => kvp.Value); Contract.Assert(null != mergedDictionary); foreach (var kvp in right) { switch (mergeOption) { case MergeOptions.OverwriteLeft: if (mergedDictionary.ContainsKey(kvp.Key)) { mergedDictionary[kvp.Key] = kvp.Value; } else { mergedDictionary.Add(kvp.Key, kvp.Value); } break; case MergeOptions.OverwriteRight: if (!left.ContainsKey(kvp.Key)) { mergedDictionary.Add(kvp.Key, kvp.Value); } break; case MergeOptions.ThrowOnDuplicateKeys: Contract.Assert(!mergedDictionary.ContainsKey(kvp.Key), kvp.Key.ToString()); mergedDictionary.Add(kvp.Key, kvp.Value); break; case MergeOptions.NullOnDuplicateKeys: if (left.ContainsKey(kvp.Key)) { return(null); } break; case MergeOptions.Intersect: if (!mergedDictionary.ContainsKey(kvp.Key)) { mergedDictionary.Remove(kvp.Key); } break; case MergeOptions.Outersect: if (mergedDictionary.ContainsKey(kvp.Key)) { mergedDictionary.Remove(kvp.Key); } else { mergedDictionary.Add(kvp.Key, kvp.Value); } break; default: var isKnownMergeOption = false; Contract.Assert(isKnownMergeOption); break; } } if (MergeOptions.Intersect == mergeOption) { foreach (var kvp in left) { if (!right.ContainsKey(kvp.Key)) { mergedDictionary.Remove(kvp.Key); } } } Contract.Assert(null != mergedDictionary); return(mergedDictionary); }
public void CanSpecifyConflictFileStrategy(CheckoutFileConflictStrategy conflictStrategy) { const string conflictFile = "a.txt"; const string conflictBranchName = "conflicts"; string path = CloneMergeTestRepo(); using (var repo = new Repository(path)) { Branch branch = repo.Branches[conflictBranchName]; Assert.NotNull(branch); MergeOptions mergeOptions = new MergeOptions() { FileConflictStrategy = conflictStrategy, }; MergeResult result = repo.Merge(branch, Constants.Signature, mergeOptions); Assert.Equal(MergeStatus.Conflicts, result.Status); // Get the information on the conflict. Conflict conflict = repo.Index.Conflicts[conflictFile]; Assert.NotNull(conflict); Assert.NotNull(conflict.Theirs); Assert.NotNull(conflict.Ours); // Get the blob containing the expected content. Blob expectedBlob = null; switch(conflictStrategy) { case CheckoutFileConflictStrategy.Theirs: expectedBlob = repo.Lookup<Blob>(conflict.Theirs.Id); break; case CheckoutFileConflictStrategy.Ours: expectedBlob = repo.Lookup<Blob>(conflict.Ours.Id); break; default: throw new Exception("Unexpected FileConflictStrategy"); } Assert.NotNull(expectedBlob); // Check the content of the file on disk matches what is expected. string expectedContent = expectedBlob.GetContentText(new FilteringOptions(conflictFile)); Assert.Equal(expectedContent, File.ReadAllText(Path.Combine(repo.Info.WorkingDirectory, conflictFile))); } }
/// <summary> /// Prepares a release for the specified directory by creating a release branch and incrementing the version in the current branch. /// </summary> /// <exception cref="ReleasePreparationException">Thrown when the release could not be created.</exception> /// <param name="projectDirectory"> /// The path to the directory which may (or its ancestors may) define the version file. /// </param> /// <param name="releaseUnstableTag"> /// The prerelease tag to add to the version on the release branch. Pass <c>null</c> to omit/remove the prerelease tag. /// The leading hyphen may be specified or omitted. /// </param> /// <param name="nextVersion"> /// The next version to save to the version file on the current branch. Pass <c>null</c> to automatically determine the next /// version based on the current version and the <c>versionIncrement</c> setting in <c>version.json</c>. /// Parameter will be ignored if the current branch is a release branch. /// </param> /// <param name="versionIncrement"> /// The increment to apply in order to determine the next version on the current branch. /// If specified, value will be used instead of the increment specified in <c>version.json</c>. /// Parameter will be ignored if the current branch is a release branch. /// </param> /// <param name="outputMode"> /// The output format to use for writing to stdout. /// </param> public void PrepareRelease(string projectDirectory, string releaseUnstableTag = null, Version nextVersion = null, VersionOptions.ReleaseVersionIncrement?versionIncrement = null, ReleaseManagerOutputMode outputMode = default) { Requires.NotNull(projectDirectory, nameof(projectDirectory)); // open the git repository var repository = this.GetRepository(projectDirectory); if (repository.Info.IsHeadDetached) { this.stderr.WriteLine("Detached head. Check out a branch first."); throw new ReleasePreparationException(ReleasePreparationError.DetachedHead); } // get the current version var versionOptions = VersionFile.GetVersion(projectDirectory); if (versionOptions == null) { this.stderr.WriteLine($"Failed to load version file for directory '{projectDirectory}'."); throw new ReleasePreparationException(ReleasePreparationError.NoVersionFile); } var releaseBranchName = this.GetReleaseBranchName(versionOptions); var originalBranchName = repository.Head.FriendlyName; var releaseVersion = string.IsNullOrEmpty(releaseUnstableTag) ? versionOptions.Version.WithoutPrepreleaseTags() : versionOptions.Version.SetFirstPrereleaseTag(releaseUnstableTag); // check if the current branch is the release branch if (string.Equals(originalBranchName, releaseBranchName, StringComparison.OrdinalIgnoreCase)) { if (outputMode == ReleaseManagerOutputMode.Text) { this.stdout.WriteLine($"{releaseBranchName} branch advanced from {versionOptions.Version} to {releaseVersion}."); } else { var releaseInfo = new ReleaseInfo(new ReleaseBranchInfo(releaseBranchName, repository.Head.Tip.Id.ToString(), releaseVersion)); this.WriteToOutput(releaseInfo); } this.UpdateVersion(projectDirectory, repository, versionOptions.Version, releaseVersion); return; } var nextDevVersion = this.GetNextDevVersion(versionOptions, nextVersion, versionIncrement); // check if the release branch already exists if (repository.Branches[releaseBranchName] != null) { this.stderr.WriteLine($"Cannot create branch '{releaseBranchName}' because it already exists."); throw new ReleasePreparationException(ReleasePreparationError.BranchAlreadyExists); } // create release branch and update version var releaseBranch = repository.CreateBranch(releaseBranchName); Commands.Checkout(repository, releaseBranch); this.UpdateVersion(projectDirectory, repository, versionOptions.Version, releaseVersion); if (outputMode == ReleaseManagerOutputMode.Text) { this.stdout.WriteLine($"{releaseBranchName} branch now tracks v{releaseVersion} stabilization and release."); } // update version on main branch Commands.Checkout(repository, originalBranchName); this.UpdateVersion(projectDirectory, repository, versionOptions.Version, nextDevVersion); if (outputMode == ReleaseManagerOutputMode.Text) { this.stdout.WriteLine($"{originalBranchName} branch now tracks v{nextDevVersion} development."); } // Merge release branch back to main branch var mergeOptions = new MergeOptions() { CommitOnSuccess = true, MergeFileFavor = MergeFileFavor.Ours, }; repository.Merge(releaseBranch, this.GetSignature(repository), mergeOptions); if (outputMode == ReleaseManagerOutputMode.Json) { var originalBranchInfo = new ReleaseBranchInfo(originalBranchName, repository.Head.Tip.Sha, nextDevVersion); var releaseBranchInfo = new ReleaseBranchInfo(releaseBranchName, repository.Branches[releaseBranchName].Tip.Id.ToString(), releaseVersion); var releaseInfo = new ReleaseInfo(originalBranchInfo, releaseBranchInfo); this.WriteToOutput(releaseInfo); } }
public void MergeReportsCheckoutNotifications() { string repoPath = CloneMergeTestRepo(); using (var repo = new Repository(repoPath)) { Commit commitToMerge = repo.Branches["normal_merge"].Tip; bool wasCalled = false; CheckoutNotifyFlags actualNotifyFlags = CheckoutNotifyFlags.None; MergeOptions options = new MergeOptions() { OnCheckoutNotify = (path, notificationType) => { wasCalled = true; actualNotifyFlags = notificationType; return true; }, CheckoutNotifyFlags = CheckoutNotifyFlags.Updated, }; MergeResult result = repo.Merge(commitToMerge, Constants.Signature, options); Assert.True(wasCalled); Assert.Equal(CheckoutNotifyFlags.Updated, actualNotifyFlags); } }
public MergeResult Merge(Branch branch, Signature merger, MergeOptions options = null) { throw new NotImplementedException(); }
public void CanMergeFetchedRefs() { string url = "https://github.com/libgit2/TestGitRepository"; var scd = BuildSelfCleaningDirectory(); string clonedRepoPath = Repository.Clone(url, scd.DirectoryPath); using (var repo = new Repository(clonedRepoPath)) { repo.Reset(ResetMode.Hard, "HEAD~1"); Assert.False(repo.RetrieveStatus().Any()); Assert.Equal(repo.Lookup<Commit>("refs/remotes/origin/master~1"), repo.Head.Tip); Commands.Fetch(repo, repo.Head.RemoteName, new string[0], null, null); MergeOptions mergeOptions = new MergeOptions() { FastForwardStrategy = FastForwardStrategy.NoFastForward }; MergeResult mergeResult = repo.MergeFetchedRefs(Constants.Signature, mergeOptions); Assert.Equal(mergeResult.Status, MergeStatus.NonFastForward); } }
public MergeResult MergeFetchedRefs(Signature merger, MergeOptions options) { return(repositoryInstance.MergeFetchedRefs(merger, options)); }