protected override async Task <Action <AsyncCodeActivityContext> > ExecuteAsync(AsyncCodeActivityContext context, CancellationToken cancellationToken) { // Object Container: Use objectContainer.Get<T>() to retrieve objects from the scope var objectContainer = context.GetFromContext <IObjectContainer>(BitbucketAPIScope.ParentContainerPropertyTag); var client = objectContainer.Get <FluentClient>(); // Inputs var repositoryLocation = RepositoryLocation.Get(context); var fileToUpload = FileToUpload.Get(context); var commitMessage = CommitMessage.Get(context); var repositoryUUIDOrSlug = RepositoryUUIDOrSlug.Get(context); var workspaceUUIDOrSlug = WorkspaceUUIDOrSlug.Get(context); var branchName = BranchName.Get(context); // Validate whether Workspace UUID or Name provided (assume name will never be a GUID format) if (Validation.IsUUID(workspaceUUIDOrSlug)) { HttpUtility.UrlEncode(workspaceUUIDOrSlug); } // Validate whether Repository UUID or Slug provided (assume slug will never be a GUID format) if (Validation.IsUUID(repositoryUUIDOrSlug)) { HttpUtility.UrlEncode(repositoryUUIDOrSlug); } // Create standard request URI var uri = "repositories/" + workspaceUUIDOrSlug + "/" + repositoryUUIDOrSlug + "/src"; // Initialise and populate multipart content var multipartContent = new MultipartFormDataContent(); multipartContent.Add(new ByteArrayContent(File.ReadAllBytes(fileToUpload)), repositoryLocation, Path.GetFileName(fileToUpload)); multipartContent.Add(new StringContent(commitMessage), "message"); // Check if optional branch name parameter provided. Add to request if not null. if (branchName != null) { multipartContent.Add(new StringContent(branchName), "branch"); } // Execution Logic var response = new JObject(); var exceptionHandler = new ApiExceptionHandler(); try { response = await AsyncRequests.PostRequest_WithBody(client, uri, cancellationToken, multipartContent); } catch (ApiException ex) // Catches any API exception and returns the message { await exceptionHandler.ParseExceptionAsync(ex); } // Outputs - API response as JObject return((ctx) => { JsonResult.Set(ctx, response); }); }
public override IEnumerable <string> CollectArguments() { if (LocalChanges == LocalChangesAction.Merge) { yield return("--merge"); } else if (LocalChanges == LocalChangesAction.Reset) { yield return("--force"); } if (Remote) { if (NewBranchAction == NewBranch.Create) { yield return("-b " + NewBranchName.Quote()); } else if (NewBranchAction == NewBranch.Reset) { yield return("-B " + NewBranchName.Quote()); } } yield return(BranchName.QuoteNE()); }
private MCommit TryFindFirstAncestorWithSameName(MCommit startCommit, BranchName branchName) { foreach (MCommit commit in startCommit.CommitAndFirstAncestors()) { BranchName commitBranchName = GetBranchName(commit); if (commitBranchName != null) { if (commitBranchName == branchName) { // Found an ancestor, which has branch name we are searching fore return(commit); } else { // Fond an ancestor with another different name break; } } if (commit != startCommit && commit.BranchTipBranches.Count == 1 && commit.BranchTipBranches[0].Name == branchName) { // Found a commit with a branch tip of a branch with same name, // this can happen for local/remote pairs. Lets assume the commit is the on that branch return(commit); } } // Could not find an ancestor with the branch name we a searching for return(null); }
public async Task CheckAsync(Repository repository) { Log.Debug("Checking branch tips ..."); var branches = await gitBranchService.GetBranchesAsync(CancellationToken.None); if (branches.IsFaulted) { return; } IReadOnlyDictionary <CommitSha, string> commitIds = GetSingleBranchTipCommits(repository, branches.Value); foreach (var pair in commitIds) { BranchName branchName = pair.Value; if (branchName.StartsWith(Origin)) { branchName = branchName.Substring(Origin.Length); } await gitCommitBranchNameService.SetCommitBranchNameAsync(pair.Key, branchName); } if (gitSettings.IsRemoteDisabled) { Log.Info("IsRemoteDisabled = true"); return; } await gitCommitBranchNameService.PushNotesAsync(repository.RootCommit.RealCommitSha); }
private async Task <R> SwitchToBranchAsync(BranchName branchName, CommitSha tipSha) { Log.Debug($"Switch to branch {branchName} ..."); R <bool> checkoutResult = await gitCheckoutService.TryCheckoutAsync(branchName, CancellationToken.None); if (checkoutResult.IsFaulted) { return(R.Error("Failed to switch branch", checkoutResult.Exception)); } if (!checkoutResult.Value) { Log.Debug($"Branch {branchName} does not exist, lets try to create it"); var branchResult = await gitBranchService.BranchFromCommitAsync(branchName, tipSha.Sha, true, CancellationToken.None); if (branchResult.IsFaulted) { return(R.Error("Failed to switch branch", branchResult.Exception)); } } return(R.Ok); }
internal CommitDialog( WindowOwner owner, Func < CommitDialog, BranchName, IEnumerable <CommitFile>, string, bool, CommitDialogViewModel> CommitDialogViewModelProvider, BranchName branchName, IEnumerable <CommitFile> files, string commitMessage, bool isMerging) { Owner = owner; InitializeComponent(); viewModel = CommitDialogViewModelProvider( this, branchName, files, commitMessage, isMerging); DataContext = viewModel; if (string.IsNullOrWhiteSpace(viewModel.Subject)) { SubjectText.Focus(); } else { DescriptionText.Focus(); } }
private List <CommitBranchName> ParseBranchNames(string text) { List <CommitBranchName> branchNames = new List <CommitBranchName>(); try { if (string.IsNullOrWhiteSpace(text)) { return(branchNames); } string[] lines = text.Split("\n".ToCharArray()); foreach (string line in lines) { string[] parts = line.Split(" ".ToCharArray()); if (parts.Length == 2) { string id = parts[0]; id = TryGetCommitId(id); BranchName branchName = parts[1].Trim(); branchNames.Add(new CommitBranchName(id, branchName)); } } } catch (Exception e) { Log.Exception(e, "Failed to parse notes text"); } return(branchNames); }
public async Task SwitchToBranchCommitAsync(Commit commit) { if (commit.IsRemoteAhead) { message.ShowInfo("Commit is remote, you must first update before switching to this commit."); return; } using (statusService.PauseStatusNotifications(Refresh.Repo)) using (progress.ShowDialog("Switching to commit ...")) { BranchName branchName = commit == commit.Branch.TipCommit ? commit.Branch.Name : null; R <BranchName> switchedNamed = await SwitchToCommitAsync(commit.RealCommitSha, branchName); if (switchedNamed.IsOk) { repositoryCommands.ShowBranch(switchedNamed.Value); } else { // Show current branch message.ShowWarning($"Failed to switch to the branch {branchName}.\n{switchedNamed.Message}"); repositoryCommands.ShowBranch((BranchName)null); } } }
private bool mCurSaveBinary; //是否保存二进制文件 private void OnEnable() { if (VFS_Platform != null) { flag_platform_from_param = true; platform_from_param = VFS_Platform.Value; //如果参数给的是平台,那么要倒推出,当前该平台可用的分支 string[] main_package_branches = VFSManagerEditor.VersionManager.GetBranchNamesByMainPackage(platform_from_param); if (main_package_branches != null && main_package_branches.Length > 0) { match_branches_from_param.AddRange(main_package_branches); } string platform_name = XPlatformUtil.GetNameText(platform_from_param); string source_packages_folder_path = Path.Combine(VFSEditorConst.PROJECT_VFS_SOURCE_PACKAGES_ROOT_PATH, platform_name); string[] extension_groups_in_source_package_folder = VFSUtil.GetValidExtensionGroupNames(VFSUtil.GetExtensionPackageRootFolderInPackages(source_packages_folder_path)); foreach (var groupName in extension_groups_in_source_package_folder) { string[] group_branches = VFSManagerEditor.VersionManager.GetBranchNamesByExtensionGroup(platform_from_param, groupName); if (group_branches != null && group_branches.Length > 0) { match_branches_from_param.AddRange(group_branches); } } match_branches_from_param_arr = match_branches_from_param.ToArray(); } if (!BranchName.IsNullOrEmpty()) { flag_branchName_from_param = true; branchName_from_param = BranchName; isBrancNameFromParamValid = VFSManagerEditor.VersionManager.TryGetVersionBranch(branchName_from_param, out mCurBranch); mCurSelectBranchName = BranchName; } }
public async Task <BuildTestTime> GetBuildTestTimeAsync(Build build) { if (build.Result != BuildResult.Succeeded) { throw new InvalidOperationException(); } var branchName = BranchName.Parse(build.SourceBranch); var timeline = await DevOpsServer.GetTimelineAsync(ProjectName, build.Id); var jobs = new List <JobTestTime>(); foreach (var record in timeline.Records.Where(x => x.Name == "Build and Test")) { var parentRecord = timeline.Records.FirstOrDefault(x => x.Id == record.ParentId); if (parentRecord is null) { continue; } var jobTestTime = await TryGetJobTestTime(record, parentRecord); if (jobTestTime is object) { jobs.Add(jobTestTime); } } if (jobs.Count < 4) { throw new Exception("Could not parse the log"); } return(new BuildTestTime(build.Id, branchName, jobs)); }
protected override void CacheMetadata(CodeActivityMetadata metadata) { if (RepositoryLocation == null) { metadata.AddValidationError(string.Format(Resources.ValidationValue_Error, nameof(RepositoryLocation))); } if (FileToUpload == null) { metadata.AddValidationError(string.Format(Resources.ValidationValue_Error, nameof(FileToUpload))); } if (CommitMessage == null) { metadata.AddValidationError(string.Format(Resources.ValidationValue_Error, nameof(CommitMessage))); } if (WorkspaceUUIDOrSlug == null) { metadata.AddValidationError(string.Format(Resources.ValidationValue_Error, nameof(WorkspaceUUIDOrSlug))); } if (RepositoryUUIDOrSlug == null) { metadata.AddValidationError(string.Format(Resources.ValidationValue_Error, nameof(RepositoryUUIDOrSlug))); } // Check for valid branch name value if (BranchName.GetArgumentLiteralValue() == "") { metadata.AddValidationError(Resources.ValidationValue_Error_CommitFile_BranchName); } base.CacheMetadata(metadata); }
public async Task EditCommitBranchNameAsync( CommitSha commitSha, CommitSha rootSha, BranchName branchName) { Log.Debug($"Set manual branch name {branchName} for commit {commitSha} ..."); SetNoteBranches(ManualBranchNoteNameSpace, commitSha, branchName); await PushNotesAsync(ManualBranchNoteNameSpace, rootSha); }
public bool Equals(VersionData versionData) => RepositoryName.Equals(versionData.RepositoryName) && BranchName.Equals(versionData.BranchName) && ParentBranchName.Equals(versionData.BranchName) && NewBranch.Equals(versionData.NewBranch) && DeltaContent.Equals(versionData.DeltaContent) && FileHierarchy.All(versionData.FileHierarchy.Contains) && FileHierarchy.Count.Equals(versionData.FileHierarchy.Count) && EventId.Equals(versionData.EventId);
public void CreateBranch(BranchName branchName, string commitSha) { var newReference = new NewReference(branchName.GitRef, commitSha); _logger.LogDebug("Creating branch {branchName}", branchName); var client = CreateGitHubClient(); client.Git.Reference.Create(_repositoryOwner, _repositoryName, newReference).Wait(); }
protected override ArgumentString BuildArguments() { return(new GitArgumentBuilder("checkout") { { LocalChanges == LocalChangesAction.Merge, "--merge" }, { LocalChanges == LocalChangesAction.Reset, "--force" }, { Remote&& NewBranchMode == CheckoutNewBranchMode.Create, $"-b {NewBranchName.Quote()}" }, { Remote&& NewBranchMode == CheckoutNewBranchMode.Reset, $"-B {NewBranchName.Quote()}" }, BranchName.QuoteNE() }); }
public Commit( Repository repository, CommitId id, CommitId realCommitId, CommitSha realCommitSha, string subject, string message, string author, DateTime authorDate, DateTime commitDate, string tags, string tickets, string branchTips, IReadOnlyList <CommitId> parentIds, IReadOnlyList <CommitId> childIds, string branchId, BranchName specifiedBranchName, BranchName commitBranchName, bool isLocalAhead, bool isRemoteAhead, bool isCommon, bool isUncommitted, bool isVirtual, bool hasConflicts, bool isMerging, bool hasFirstChild) { this.Repository = repository; this.parentIds = parentIds; this.childIds = childIds; this.branchId = branchId; Id = id; RealCommitId = realCommitId; RealCommitSha = realCommitSha; Subject = subject; Message = message; Author = author; AuthorDate = authorDate; AuthorDateText = authorDate.ToShortDateString() + " " + authorDate.ToShortTimeString(); CommitDate = commitDate; Tags = tags; Tickets = tickets; BranchTips = branchTips; SpecifiedBranchName = specifiedBranchName; CommitBranchName = commitBranchName; IsLocalAhead = isLocalAhead; IsRemoteAhead = isRemoteAhead; IsCommon = isCommon; IsUncommitted = isUncommitted; IsVirtual = isVirtual; HasConflicts = hasConflicts; IsMerging = isMerging; HasFirstChild = hasFirstChild; }
public GitBasedFileSystemHistoryTest() { RepositoryInitHelper.InitializeRepository(m_TempDirectory.Location); m_Repository = new Repository(m_TempDirectory.Location); var branchName = new BranchName("", "branch1"); m_Repository.CreateBranch(branchName, m_Repository.GetAllCommits().Single()); m_Instance = new GitBasedFileSystemHistory(m_Repository, branchName); }
private BranchName CreateBranchNameForPush( BranchName sourceBranch, string sourceBranchCommitSha, BranchName destinationBranchName) { var prefix = _cfg.CreatedBranchesPrefix; var sourceCommitShaShort = sourceBranchCommitSha.Substring(0, 8); var sanitizedName = BranchName.Sanitize($"{sourceBranch}_{sourceCommitShaShort}_to_{destinationBranchName}"); return(new BranchName($"{prefix}{sanitizedName}")); }
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { lblHeads.Text = ExpenseHead; lblrptType.Text = rptType; lblBranchName.Text = BranchName.ToString(); rptExpenseDetails.DataSource = GetExpenseDetails; rptExpenseDetails.DataBind(); } }
/// <summary>Snippet for CreateProduct</summary> public void CreateProductResourceNames() { // Snippet: CreateProduct(BranchName, Product, string, CallSettings) // Create client ProductServiceClient productServiceClient = ProductServiceClient.Create(); // Initialize request argument(s) BranchName parent = BranchName.FromProjectLocationCatalogBranch("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]"); Product product = new Product(); string productId = ""; // Make the request Product response = productServiceClient.CreateProduct(parent, product, productId); // End snippet }
/// <returns>Unique name of this report, can be used as name of file.</returns> public string GetReportNameAsFilename() { string EngineVersion = string.Format ( "{0}-{1}+{2}", !string.IsNullOrEmpty(EngineBuildVersion) ? EngineBuildVersion : "NO_BUILD_VERSION", !string.IsNullOrEmpty(BuiltFromCL) ? BuiltFromCL : "NO_BUILT_FROM_CL", !string.IsNullOrEmpty(BranchName) ? BranchName.Replace('/', '+') : "NO_BRANCH" ); string Directory = string.Format("{0}_{1}__{2}", EngineVersion, !string.IsNullOrEmpty(GameName) ? GameName : "NO_GAMENAME", Ticks); return(Directory); }
public void AddActiveBranches(IReadOnlyList <GitBranch> branches, MRepository repository) { GitStatus status = repository.Status; //GitBranch2 currentBranch = branches.GetCurrent(); foreach (GitBranch gitBranch in branches) { BranchName branchName = gitBranch.Name; if (branchName == BranchName.OriginHead || branchName == BranchName.Head) { continue; } MSubBranch subBranch = ToBranch(gitBranch, repository); repository.SubBranches[subBranch.SubBranchId] = subBranch; if (!status.OK && gitBranch.IsCurrent && !gitBranch.IsRemote) { // Setting virtual uncommitted commit as tip of the current branch subBranch.TipCommitId = repository.Uncommitted.Id; subBranch.TipCommit.SubBranchId = subBranch.SubBranchId; } } if (!branches.Any()) { MSubBranch subBranch = ToEmptyMasterBranch(repository); repository.SubBranches[subBranch.SubBranchId] = subBranch; if (!status.OK) { // Setting virtual uncommitted commit as tip of the current branch subBranch.TipCommitId = repository.Uncommitted.Id; subBranch.TipCommit.SubBranchId = subBranch.SubBranchId; } } if (branches.TryGetCurrent(out GitBranch currentBranch) && currentBranch.IsDetached) { MSubBranch subBranch = ToBranch(currentBranch, repository); repository.SubBranches[subBranch.SubBranchId] = subBranch; if (!status.OK) { // Setting virtual uncommitted commit as tip of the detached branch subBranch.TipCommitId = repository.Uncommitted.Id; subBranch.TipCommit.SubBranchId = subBranch.SubBranchId; } } }
private void SetNoteBranches( string nameSpace, CommitSha commitSha, BranchName branchName) { try { string file = Path.Combine(workingFolder, ".git", nameSpace); CommitId id = new CommitId(commitSha); File.AppendAllText(file, $"{id} {branchName}\n"); } catch (Exception e) { Log.Exception(e, $"Failed to add commit name for {commitSha} {branchName}"); } }
private bool TryGetMergeDestinationBranches(BranchName branchName, out BranchName[] destinationBranchNames) { destinationBranchNames = _mergeDirectionsProvider.Get().GetMergeDestinationBranchNames(branchName.Name) .Select(x => new BranchName(x)) .ToArray(); if (destinationBranchNames.Any()) { return(true); } _logger.LogInformation("Processing dismissed. There is no configured merge directions for {branchName} branch", branchName); return(false); }
public void CreateHistory(string name) { var branchName = new BranchName(GitBasedFileSystemHistory.BranchNamePrefix, name); if (GitGroup.Repository.LocalBranchExists(branchName)) { throw new DuplicateFileSystemHistoryException(name); } var parentCommitId = GitGroup.Repository.Tags[RepositoryInitHelper.InitialCommitTagName].Target.Sha; var parentCommit = GitGroup.Repository.Lookup<Commit>(parentCommitId); GitGroup.Repository.CreateBranch(branchName, parentCommit); }
public async stt::Task CreateProductRequestObjectAsync() { moq::Mock <ProductService.ProductServiceClient> mockGrpcClient = new moq::Mock <ProductService.ProductServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock <lro::Operations.OperationsClient>().Object); CreateProductRequest request = new CreateProductRequest { ParentAsBranchName = BranchName.FromProjectLocationCatalogBranch("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]"), Product = new Product(), ProductId = "product_idde82ea9b", }; Product expectedResponse = new Product { ProductName = ProductName.FromProjectLocationCatalogBranchProduct("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]", "[PRODUCT]"), Id = "id74b70bb8", Type = Product.Types.Type.Collection, PrimaryProductId = "primary_product_id96202300", Categories = { "categoriesb4ccb5b0", }, Title = "title17dbd3d5", Description = "description2cf9da67", Attributes = { { "key8a0b6e3c", new CustomAttribute() }, }, Tags = { "tags52c47ad5", }, PriceInfo = new PriceInfo(), AvailableTime = new wkt::Timestamp(), Availability = Product.Types.Availability.InStock, AvailableQuantity = 719656040, Uri = "uri3db70593", Images = { new Image(), }, }; mockGrpcClient.Setup(x => x.CreateProductAsync(request, moq::It.IsAny <grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall <Product>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ProductServiceClient client = new ProductServiceClientImpl(mockGrpcClient.Object, null); Product responseCallSettings = await client.CreateProductAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Product responseCancellationToken = await client.CreateProductAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); }
public void AddMultiBranches(MRepository repository) { bool isFound; do { isFound = false; foreach (var commit in repository.Commits.Values) { if (commit.BranchId == null && !commit.HasBranchName) { isFound = true; BranchName branchName = AnonyousBranchPrefix + commit.ShortId; if (commit.FirstChildren.Count() > 1) { branchName = MultibranchPrefix + commit.ShortId; } else { BranchName commitBranchName = commitBranchNameService.GetBranchName(commit); if (commitBranchName != null) { branchName = commitBranchName; } } MSubBranch subBranch = new MSubBranch { Repository = repository, SubBranchId = Guid.NewGuid().ToString(), Name = branchName, TipCommitId = commit.Id, IsActive = false, }; subBranch.IsAnonymous = IsBranchNameAnonyous(branchName); subBranch.IsMultiBranch = IsBranchNameMultiBranch(branchName); repository.SubBranches[subBranch.SubBranchId] = subBranch; commit.SetBranchName(branchName); commit.SubBranchId = subBranch.SubBranchId; SetSubBranchCommits(subBranch); } } } while (isFound); }
private void RemoveBranch(BranchName headBranchName) { using (var repoContext = _repositoryConnectionProvider.GetRepositoryConnection()) { _logger.LogDebug("Removing temporary {branchName} branch from repository", headBranchName); try { repoContext.RemoveBranch(headBranchName); } catch (Exception e) { _logger.LogWarning(e, "Error when removing branch '{branchName}'. It could be deleted by human", headBranchName); } } }
public Branch( Repository repository, string id, BranchName name, CommitId tipCommitId, CommitId firstCommitId, CommitId parentCommitId, CommitId localTipCommitId, CommitId remoteTipCommitId, IReadOnlyList <CommitId> commitIds, string parentBranchId, IReadOnlyList <BranchName> childBranchNames, string mainBranchId, string localSubBranchId, bool isActive, bool isLocal, bool isRemote, bool isMainPart, bool isLocalPart, bool isMultiBranch, bool isDetached, int localAheadCount, int remoteAheadCount) { this.Repository = repository; this.tipCommitId = tipCommitId; this.firstCommitId = firstCommitId; this.parentCommitId = parentCommitId; this.localTipCommitId = localTipCommitId; this.remoteTipCommitId = remoteTipCommitId; this.commitIds = commitIds; this.parentBranchId = parentBranchId; Id = id; Name = name; ChildBranchNames = childBranchNames; MainBranchId = mainBranchId; LocalSubBranchId = localSubBranchId; IsActive = isActive; IsLocal = isLocal; IsRemote = isRemote; IsMainPart = isMainPart; IsLocalPart = isLocalPart; IsMultiBranch = isMultiBranch; LocalAheadCount = localAheadCount; RemoteAheadCount = remoteAheadCount; IsDetached = isDetached; }
/// <summary>Snippet for CreateProduct</summary> public void CreateProductRequestObject() { // Snippet: CreateProduct(CreateProductRequest, CallSettings) // Create client ProductServiceClient productServiceClient = ProductServiceClient.Create(); // Initialize request argument(s) CreateProductRequest request = new CreateProductRequest { ParentAsBranchName = BranchName.FromProjectLocationCatalogBranch("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]"), Product = new Product(), ProductId = "", }; // Make the request Product response = productServiceClient.CreateProduct(request); // End snippet }
/// <summary>Snippet for CreateProductAsync</summary> public async Task CreateProductResourceNamesAsync() { // Snippet: CreateProductAsync(BranchName, Product, string, CallSettings) // Additional: CreateProductAsync(BranchName, Product, string, CancellationToken) // Create client ProductServiceClient productServiceClient = await ProductServiceClient.CreateAsync(); // Initialize request argument(s) BranchName parent = BranchName.FromProjectLocationCatalogBranch("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]"); Product product = new Product(); string productId = ""; // Make the request Product response = await productServiceClient.CreateProductAsync(parent, product, productId); // End snippet }
public GitBasedFileSystemHistory(Repository repository, BranchName branchName) { if (branchName == null) { throw new ArgumentNullException(nameof(branchName)); } if (repository == null) { throw new ArgumentNullException(nameof(repository)); } m_Repository = repository; var branch = repository.GetBranch(branchName); m_BranchName = BranchName.Parse(branch.FriendlyName); m_Snapshots = new Lazy<IDictionary<string, GitBasedFileSystemSnapshot>>(LoadSnapshots); }
public async Task PushCurrentBranchAsync() { BranchName branchName = Repository.CurrentBranch.Name; using (statusService.PauseStatusNotifications()) using (progress.ShowDialog($"Pushing current branch {branchName} ...")) { await PushNotesAsync(Repository.RootCommit.RealCommitSha); R result = await gitPushService.PushAsync(CancellationToken.None); if (!result.IsOk) { message.ShowWarning($"Failed to push current branch {branchName}.\n{result.AllMessages}"); } } }
public static GitBasedMultiFileSystemSnapshot Create(Repository repository, BranchName branchName, IHistoryService historyService) { var directoryCreator = new LocalItemCreator(); var branch = repository.GetBranch(branchName); string commitId; using (var workingRepository = new TemporaryWorkingDirectory(repository.Info.Path, branch.FriendlyName)) { var snapshotDirectory = new Directory(null, s_SnapshotDirectoryName); foreach (var fileSystemHistory in historyService.Items) { var fileName = fileSystemHistory.Name + s_FileNameSuffix; var content = fileSystemHistory.LatestFileSystemSnapshot?.Id ?? ""; snapshotDirectory.Add(d => new TextFile(d, fileName, content)); } var snapshotDirectoryPath = Path.Combine(workingRepository.Location, s_SnapshotDirectoryName); directoryCreator.CreateDirectoryInPlace(snapshotDirectory, snapshotDirectoryPath, true); if (workingRepository.HasChanges) { try { commitId = workingRepository.Commit("Created multi-filesystem snapshot"); workingRepository.Push(); } catch (EmptyCommitException) { // no changes after all (HasChanges does not seem to be a 100% accurate) commitId = repository.GetBranch(branchName).Tip.Sha; } } else { commitId = repository.GetBranch(branchName).Tip.Sha; } } var commit = repository.Lookup<Commit>(commitId); return IsSnapshot(commit) ? new GitBasedMultiFileSystemSnapshot(commit, historyService) : null; }
public IFileSystemHistory this[string name] { get { if (String.IsNullOrWhiteSpace(name)) { throw new ArgumentNullException(nameof(name)); } var branchName = new BranchName(GitBasedFileSystemHistory.BranchNamePrefix, name); if (!GitGroup.Repository.LocalBranchExists(branchName)) { throw new ItemNotFoundException($"An item named '{name}' was not found"); } return new GitBasedFileSystemHistory(GitGroup.Repository, name); } }
public static Branch GetLocalBranch(this Repository repository, BranchName branchName) { return repository.GetLocalBranches().FirstOrDefault(b => b.FriendlyName.Equals(branchName.ToString(), StringComparison.InvariantCultureIgnoreCase)); }
public static bool LocalBranchExists(this Repository repository, BranchName branchName) => repository.LocalBranchExists(branchName.ToString());
public static Branch CreateBranch(this Repository repository, BranchName branchName, Commit commit) => repository.CreateBranch(branchName.ToString(), commit);
public static Branch GetBranch(this Repository repository, BranchName branchName) => repository.Branches.FirstOrDefault(b => BranchName.Parse(b.FriendlyName).Equals(branchName));
public void ToString_returns_expected_result(string expectedResult, string prefix, string name) { var branchName = new BranchName(prefix, name); Assert.Equal(expectedResult, branchName.ToString()); }