Example #1
0
 public Shell(HgRepository repository, BrowseForRepositoryEvent browseForRepositoryEvent)
 {
     _browseForRepositoryEvent = browseForRepositoryEvent;
     InitializeComponent();
     Text = Application.ProductName + " "+Application.ProductVersion +" - "+ repository.PathToRepo;
     _tabControl.TabPages.Clear();
 }
Example #2
0
 public Revision(HgRepository repository, string name, string localRevisionNumber, string hash, string comment)
     : this(repository)
 {
     UserId = name;
     Number = new RevisionNumber(localRevisionNumber, hash);
     Summary = comment;
 }
Example #3
0
        //TODO: get rid of this, or somehow combine it with the other Clone() options out there
        /// <returns>path to clone, or empty if it failed</returns>
        public static string MakeCloneFromLocalToLocal(string sourcePath, string targetDirectory, bool alsoDoCheckout, IProgress progress)
        {
            RequireThat.Directory(sourcePath).Exists();
            //Handled by GetUniqueFolderPath call now down in CloneLocal call. RequireThat.Directory(targetDirectory).DoesNotExist();
            RequireThat.Directory(targetDirectory).Parent().Exists();

            HgRepository local = new HgRepository(sourcePath, progress);

            if (!local.RemoveOldLocks())
            {
                progress.WriteError("Chorus could not create the clone at this time.  Try again after restarting the computer.");
                return string.Empty;
            }

            using (new ConsoleProgress("Trying to Create repository clone at {0}", targetDirectory))
            {
                targetDirectory = local.CloneLocalWithoutUpdate(targetDirectory);
                File.WriteAllText(Path.Combine(targetDirectory, "~~Folder has an invisible repository.txt"), "In this folder, there is a (possibly hidden) folder named '.hg' that contains the actual data of this Chorus repository. Depending on your Operating System settings, that leading '.' might make the folder invisible to you. But Chorus clients (WeSay, FLEx, OneStory, etc.) can see it and can use this folder to perform Send/Receive operations.");

                if (alsoDoCheckout)
                {
                    // string userIdForCLone = string.Empty; /* don't assume it's this user... a repo on a usb key probably shouldn't have a user default */
                    var clone = new HgRepository(targetDirectory, progress);
                    clone.Update();
                }
                return targetDirectory;
            }
        }
Example #4
0
 public CommitCop(HgRepository repository, ChorusFileTypeHandlerCollection handlers, IProgress progress)
 {
     _repository = repository;
     _handlerCollection = handlers;
     _progress = progress;
     ValidateModifiedFiles();
 }
Example #5
0
        //TODO: get rid of this, or somehow combine it with the other Clone() options out there
        /// <returns>path to clone, or empty if it failed</returns>
        private static string MakeCloneFromLocalToLocal(string sourcePath, string targetDirectory, bool cloningFromUsb, IProgress progress)
        {
            RequireThat.Directory(sourcePath).Exists();
            //Handled by GetUniqueFolderPath call now down in CloneLocal call. RequireThat.Directory(targetDirectory).DoesNotExist();
            RequireThat.Directory(targetDirectory).Parent().Exists();

            HgRepository local = new HgRepository(sourcePath, progress);

            if (!local.RemoveOldLocks())
            {
                progress.WriteError("Chorus could not create the clone at this time.  Try again after restarting the computer.");
                return string.Empty;
            }

            using (new ConsoleProgress("Trying to Create repository clone at {0}", targetDirectory))
            {
                // Make a backward compatibile clone if cloning to USB (http://mercurial.selenic.com/wiki/UpgradingMercurial)
                targetDirectory = local.CloneLocalWithoutUpdate(targetDirectory, cloningFromUsb ? null : "--config format.dotencode=false --pull");
                File.WriteAllText(Path.Combine(targetDirectory, "~~Folder has an invisible repository.txt"), "In this folder, there is a (possibly hidden) folder named '.hg' that contains the actual data of this Chorus repository. Depending on your Operating System settings, that leading '.' might make the folder invisible to you. But Chorus clients (WeSay, FLEx, OneStory, etc.) can see it and can use this folder to perform Send/Receive operations.");

                if (cloningFromUsb)
                {
                    var clone = new HgRepository(targetDirectory, progress);
                    clone.Update();
                }
                return targetDirectory;
            }
        }
		public IEnumerable<IChangeReport> Find2WayDifferences(FileInRevision parent, FileInRevision child, HgRepository repository)
		{
			var diffReports = new List<IChangeReport>(1);

			// The only relevant change to report is the version number.
			var childData = child.GetFileContents(repository);
			var splitData = SplitData(childData);
			var childModelNumber = Int32.Parse(splitData[1]);
			if (parent == null)
			{
				diffReports.Add(new FieldWorksModelVersionAdditionChangeReport(child, childModelNumber));
			}
			else
			{
				var parentData = parent.GetFileContents(repository);
				splitData = SplitData(parentData);
				var parentModelNumber = Int32.Parse(splitData[1]);
				if (parentModelNumber != childModelNumber)
					diffReports.Add(new FieldWorksModelVersionUpdatedReport(parent, child, parentModelNumber, childModelNumber));
				else
					throw new InvalidOperationException("The version number has downgraded");
			}

			return diffReports;
		}
Example #7
0
 ///<summary>
 ///</summary>
 public HgResumeTransport(HgRepository repo, string targetLabel, IApiServer apiServer, IProgress progress)
 {
     _repo = repo;
     _targetLabel = targetLabel;
     _apiServer = apiServer;
     _progress = progress;
 }
Example #8
0
 public HgTestSetup()
 {
     _progress = new ConsoleProgress();
     Root = new TemporaryFolder("ChorusHgWrappingTest");
     HgRepository.CreateRepositoryInExistingDir(Root.Path,_progress);
     Repository = new HgRepository(Root.Path, new NullProgress());
 }
Example #9
0
 private void UpdateDisplay()
 {
     var repo = new HgRepository(ProjectFolderPath, new NullProgress());
     string message;
     var ready = repo.GetIsReadyForInternetSendReceive(out message);
     _warningImage.Visible = !ready;
     _chorusReadinessMessage.Text = message;
 }
		public IEnumerable<IChangeReport> Find2WayDifferences(FileInRevision parent, FileInRevision child, HgRepository repository)
		{
			return Xml2WayDiffService.ReportDifferences(
				repository,
				parent,
				child,
				null,
				SharedConstants.MoMorphData, SharedConstants.GuidStr);
		}
Example #11
0
 public Revision(HgRepository repository)
 {
     _repository = repository;
     Parents = new List<RevisionNumber>();
     Tag = string.Empty;
     Branch = string.Empty;
     Summary = string.Empty;
     UserId = string.Empty;
 }
Example #12
0
 /// <summary>
 /// Find out if ChorusHub can connect or not.
 /// </summary>
 public override bool CanConnect(HgRepository localRepository, string projectName, IProgress progress)
 {
     // It can connect for either of these reasons:
     //	1. 'localRepository' Identifier matches one of the ids of _sourceRepositoryInformation. (Name may not be the same as 'projectName')
     //	2. The name of one of _sourceRepositoryInformation matches or begins with 'projectName' AND the id is 'newRepo'.
     //     (A clone of this isn't useful.)
     string dummy;
     return TryGetBestRepoMatch(localRepository.Identifier, projectName, out dummy, out dummy);
 }
		public IEnumerable<IChangeReport> Find2WayDifferences(FileInRevision parent, FileInRevision child, HgRepository repository)
		{
			return Xml2WayDiffService.ReportDifferences(
				repository,
				parent,
				child,
				SharedConstants.Header,
				SharedConstants.WfiWordform, SharedConstants.GuidStr);
		}
        public GetCloneFromInternetDialog(GetCloneFromInternetModel model)
        {
            _model = model;
            //#if !MONO
            Font = SystemFonts.MessageBoxFont;
            //#endif
            InitializeComponent();

            Font = SystemFonts.MessageBoxFont;

            _backgroundWorker = new BackgroundWorker();
            _backgroundWorker.WorkerSupportsCancellation = true;
            _backgroundWorker.RunWorkerCompleted += _backgroundWorker_RunWorkerCompleted;
            _backgroundWorker.DoWork += _backgroundWorker_DoWork;

            _logBox.ShowCopyToClipboardMenuItem = true;
            _logBox.ShowDetailsMenuItem = true;
            _logBox.ShowDiagnosticsMenuItem = true;
            _logBox.ShowFontMenuItem = true;

            _model.AddProgress(_statusProgress);
            _statusProgress.Text = "";
            _statusProgress.Visible = false;
            _model.AddMessageProgress(_logBox);
            _model.ProgressIndicator = _progressBar;
            _model.UIContext = SynchronizationContext.Current;

            _serverSettingsControl = new ServerSettingsControl(){Model=_model};
            _serverSettingsControl.TabIndex = 0;
            _serverSettingsControl.Anchor = (AnchorStyles.Top | AnchorStyles.Left);
            Controls.Add(_serverSettingsControl);

            _targetFolderControl = new TargetFolderControl(_model);
            _targetFolderControl.Anchor = (AnchorStyles.Bottom | AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right);
            _targetFolderControl._downloadButton.Click+=OnDownloadClick;
            _targetFolderControl.Location = new Point(0, _serverSettingsControl.Height +10);
            MinimumSize = new Size(_targetFolderControl.MinimumSize.Width+20, _targetFolderControl.Bottom +20);
            if (_targetFolderControl.Bottom +30> Bottom)
            {
                this.Size = new Size(this.Width,_targetFolderControl.Bottom + 30);
            }
            _targetFolderControl.TabIndex = 1;
            this.Controls.Add(_targetFolderControl);
            _okButton.TabIndex = 90;
            _cancelButton.TabIndex = 91;

            _fixSettingsButton.Left = _cancelButton.Left;
             _targetFolderControl._downloadButton.Top = _okButton.Top-_targetFolderControl.Top	;
             _targetFolderControl._downloadButton.Left = _okButton.Left - 15;

            _logBox.GetDiagnosticsMethod = (progress) =>
                                           	{
                                                var hg = new HgRepository(PathToNewlyClonedFolder, progress);
                                                hg.GetDiagnosticInformationForRemoteProject(progress, ThreadSafeUrl);
                                           	};
        }
        public RevisionInRepositoryModel(HgRepository repository,
										RevisionSelectedEvent revisionSelectedEvent,
										RevisionListOptions options)
        {
            Guard.AgainstNull(repository, "repository");
            _repository = repository;
            _revisionSelectedEvent = revisionSelectedEvent;
            _options = options;
            DiscoveredRevisionsQueue =  new Queue<Revision>();
        }
		internal static IChangePresenter GetCommonChangePresenter(IChangeReport report, HgRepository repository)
		{
			var xmlChangeReport = report as IXmlChangeReport;
			if (xmlChangeReport != null)
				return new FieldWorksChangePresenter(xmlChangeReport);

			if (report is ErrorDeterminingChangeReport)
				return (IChangePresenter)report;

			return new DefaultChangePresenter(report, repository);
		}
Example #17
0
 public HgNormalTransport(HgRepository repo, string targetLabel, string targetUri, IProgress progress)
 {
     _repo = repo;
     _targetUri = targetUri;
     _targetLabel = targetLabel;
     _progress = progress;
     if (_progress.ProgressIndicator != null)
     {
         _progress.ProgressIndicator.IndicateUnknownProgress();
     }
 }
		public IChangePresenter GetChangePresenter(IChangeReport report, HgRepository repository)
		{
			var fieldWorksModelVersionChangeReport = report as FieldWorksModelVersionChangeReport;
			if (fieldWorksModelVersionChangeReport != null)
				return new FieldWorksModelVersionChangePresenter(fieldWorksModelVersionChangeReport);

			if (report is ErrorDeterminingChangeReport)
				return (IChangePresenter)report;

			return new DefaultChangePresenter(report, repository);
		}
Example #19
0
 public byte[] GetFileContentsAsBytes(HgRepository repository)
 {
     var path = repository.RetrieveHistoricalVersionOfFile(FullPath, _revisionNumber);
     try
     {
         return File.ReadAllBytes(path);
     }
     finally
     {
         File.Delete(path);
     }
 }
Example #20
0
        public ChangeReportView(ChorusFileTypeHandlerCollection handlers, ChangedRecordSelectedEvent changedRecordSelectedEvent, HgRepository repository, IEnumerable<IWritingSystem> writingSystems)
        {
            this.Font = SystemFonts.MessageBoxFont;
            _handlers = handlers;
            _repository = repository;
            InitializeComponent();
            _normalChangeDescriptionRenderer.Font = SystemFonts.MessageBoxFont;
            changedRecordSelectedEvent.Subscribe(r=>LoadReport(r));
            _normalChangeDescriptionRenderer.Navigated += webBrowser1_Navigated;

            _styleSheet = CreateStyleSheet(writingSystems);
        }
Example #21
0
        public void AddingRepositoryWithinAnotherRepositoryWithEmptyStringDirectoryThrows()
        {
            using (var tempParent = new TemporaryFolder("ChorusParent"))
            {
                var parentRepo = new HgRepository(tempParent.Path, new NullProgress());
                parentRepo.Init();
                var parentFile = tempParent.GetNewTempFile(true);
                File.WriteAllText(parentFile.Path, "New Content");
                parentRepo.AddAndCheckinFile(parentFile.Path);

                Assert.Throws<ArgumentNullException>(() => HgRepository.CreateOrUseExisting("", new NullProgress()));
            }
        }
Example #22
0
        public byte[] GetFileRevision(string repositoryName, string fileRelativePath, string revisionStr)
        {
            string directory = Path.Combine(ChorusHubOptions.RootDirectory, repositoryName);
            HgRepository repo = new HgRepository(directory, new NullProgress());
            Revision revision = repo.GetRevision(revisionStr);
            if (revision == null)
                return null;

            FileInRevision file = repo.GetFilesInRevision(revision).FirstOrDefault(
                f => f.FullPath.Length > directory.Length + 1 && // Make path relative by removing directory and path separator character
                    string.Equals(f.FullPath.Substring(directory.Length + 1), fileRelativePath, StringComparison.OrdinalIgnoreCase));

            return file != null ? file.GetFileContentsAsBytes(repo) : null;
        }
Example #23
0
        private Xml2WayDiffer(HgRepository repository, IMergeEventListener eventListener, FileInRevision parent, FileInRevision child,
			string firstElementMarker,
			string startTag, string identfierAttribute)
        {
            _diffingMode = DiffingMode.FromFileInRevisions;
            _repository = repository;
            _parentFileInRevision = parent;
            _childFileInRevision = child;
            if (!string.IsNullOrEmpty(firstElementMarker))
                _firstElementTag = firstElementMarker.Trim();
            _startTag = "<" + startTag.Trim();
            _identfierAttribute = identfierAttribute;
            _eventListener = eventListener;
        }
		internal static Dictionary<string, byte[]> GetDataFromRevision(FileInRevision revision, HgRepository repository)
		{
			var doc = XDocument.Parse(revision.GetFileContents(repository));
			var data = doc.Root.Elements("layout")
				.ToDictionary(layoutElement =>
							  layoutElement.Attribute("class").Value + layoutElement.Attribute("type").Value + layoutElement.Attribute("name").Value,
							  layoutElement => SharedConstants.Utf8.GetBytes(layoutElement.ToString()));

			var layoutTypeElement = doc.Root.Element("layoutType");
			if (layoutTypeElement != null)
				data.Add("layoutType", SharedConstants.Utf8.GetBytes(doc.Root.Element("layoutType").ToString()));

			return data;
		}
		/// <summary>
		/// Start doing whatever is needed for the supported type of action.
		/// </summary>
		public void StartWorking(Dictionary<string, string> commandLineArgs)
		{
			// undo_export_lift: -p <$fwroot>\foo where 'foo' is the project folder name
			// Calling Utilities.LiftOffset(commandLineArgs["-p"]) will use the folder: <$fwroot>\foo\OtherRepositories\foo_Lift
			var pathToRepository = Utilities.LiftOffset(commandLineArgs["-p"]);
			var repo = new HgRepository(pathToRepository, new NullProgress());
			repo.Update();
			// Delete any new files (except import failure notifier file).
			var newbies = repo.GetChangedFiles();
			foreach (var goner in newbies.Where(newFile => newFile.Trim() != LiftUtilties.FailureFilename))
			{
				File.Delete(Path.Combine(pathToRepository, goner.Trim()));
			}
		}
Example #26
0
        public TroubleshootingView(HgRepository repository)
        {
            _state = State.WaitingForUserToStart;
            _repository = repository;
            InitializeComponent();
            _progress = new TextBoxProgress(_outputBox);
            _statusProgress = new StatusProgress();
            _progress = new MultiProgress(new IProgress[] { new TextBoxProgress(_outputBox), _statusProgress, new LabelStatus(_statusLabel) });
            _statusLabel.Text = string.Empty;

            _backgroundWorker = new BackgroundWorker();
            _backgroundWorker.WorkerSupportsCancellation = true;
            _backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(_backgroundWorker_RunWorkerCompleted);
            _backgroundWorker.DoWork += new DoWorkEventHandler(_backgroundWorker_DoWork);
        }
Example #27
0
        public void AddingRepositoryWithinAnotherRepositoryWithNonexistantDirectoryThrows()
        {
            using (var tempParent = new TemporaryFolder("ChorusParent"))
            {
                var parentRepo = new HgRepository(tempParent.Path, new NullProgress());
                parentRepo.Init();
                var parentFile = tempParent.GetNewTempFile(true);
                File.WriteAllText(parentFile.Path, "New Content");
                parentRepo.AddAndCheckinFile(parentFile.Path);

                var parentFolder = tempParent.Path;
                var nonexistantDirectory = Path.Combine(parentFolder, "Child");
                Assert.Throws<InvalidOperationException>(() => HgRepository.CreateOrUseExisting(nonexistantDirectory, new NullProgress()));
            }
        }
Example #28
0
        public void AddingRepositoryWithinAnotherRepositoryFromDirectoryNameIsDifferentRepository()
        {
            using (var tempParent = new TemporaryFolder("ChorusParent"))
            {
                var parentRepo = new HgRepository(tempParent.Path, new NullProgress());
                parentRepo.Init();
                var parentFile = tempParent.GetNewTempFile(true);
                File.WriteAllText(parentFile.Path, "New Content");
                parentRepo.AddAndCheckinFile(parentFile.Path);

                var parentFolder = tempParent.Path;
                var dirInfo = Directory.CreateDirectory(Path.Combine(parentFolder, "Child"));
                var childRepo = HgRepository.CreateOrUseExisting(dirInfo.FullName, new NullProgress());
                Assert.AreNotEqual(parentFolder, childRepo.PathToRepo);
            }
        }
        public void HasExtantRepositories()
        {
            using (var parentFolder = new TemporaryFolder("parentFolder"))
            using (var childFolder = new TemporaryFolder(parentFolder, "childFolder"))
            {
                var newFile = Path.Combine(childFolder.Path, "test.txt");
                File.WriteAllText(newFile, "some stuff");
                var repo = new HgRepository(childFolder.Path, new NullProgress());
                repo.Init();
                repo.AddAndCheckinFile(newFile);

                var extantRepoIdentifiers = GetSharedProjectModel.ExtantRepoIdentifiers(parentFolder.Path, null);
                Assert.AreEqual(1, extantRepoIdentifiers.Count);
                Assert.IsTrue(extantRepoIdentifiers.ContainsKey(repo.Identifier));
                Assert.That(extantRepoIdentifiers[repo.Identifier], Is.EqualTo("childFolder"));
            }
        }
Example #30
0
        ///<summary>
        /// Filter the files, before the commit. Files that are too large are added to the exclude section of the configuration.
        ///</summary>
        ///<returns>An empty string or a string with a listing of files that were not added/modified.</returns>
        public static string FilterFiles(HgRepository repository, ProjectFolderConfiguration configuration, ChorusFileTypeHandlerCollection handlerCollection)
        {
            var messageBuilder = new StringBuilder();
            Dictionary<string, Dictionary<string, List<string>>> fileStatusDictionary = GetStatusOfFilesOfInterest(repository, configuration);
            Dictionary<string, uint> extensionToMaximumSize = CacheMaxSizesOfExtension(handlerCollection);

            foreach (KeyValuePair<string, Dictionary<string, List<string>>> filesOfOneStatus in fileStatusDictionary)
            {
                var userNotificationMessageBase = "File '{0}' is too large to include in the Send/Receive system. It is {1}, but the maximum allowed is {2}. The file is at {3}.";
                var forgetItIfTooLarge = false;

                switch (filesOfOneStatus.Key)
                {
                    case "M": // modified
                        // May have grown too large.
                        // Untrack it (forget), if is too large and keep out.
                        forgetItIfTooLarge = true;
                        userNotificationMessageBase = "File '{0}' has grown too large to include in the Send/Receive system.  It is {1}, but the maximum allowed is {2}. The file is at {3}.";
                        //FilterModifiedFiles(repository, configuration, extensionToMaximumSize, messageBuilder, PathToRepository(repository), statusCheckResultKvp.Value);
                        break;
                    case "A": // marked for 'add' with; hg add
                        // Untrack it (forget), if is too large and keep out.
                        forgetItIfTooLarge = true;
                        //FilterAddedFiles(repository, configuration, extensionToMaximumSize, messageBuilder, PathToRepository(repository), statusCheckResultKvp.Value);
                        break;
                    case "?": // untracked, but going to be added.
                        // Keep out, if too large.
                        //FilterUntrackedFiles(configuration, extensionToMaximumSize, messageBuilder, PathToRepository(repository), statusCheckResultKvp.Value);
                        break;

                    //case "!": // tracked but deleted. Fall through
                    //case "R": // tracked, and marked for removal with: hg rm
                        // No need to mess with these ones.
                    //	break;
                    // If there are other keys, we don't really care about them.
                }
                Dictionary<string, List<string>> extensionToFilesDictionary = filesOfOneStatus.Value;
                FilterFiles(repository, configuration, extensionToMaximumSize, messageBuilder, PathToRepository(repository),
                            extensionToFilesDictionary, userNotificationMessageBase, forgetItIfTooLarge);
            }

            var result = messageBuilder.ToString();
            return string.IsNullOrEmpty(result) ? null : result;
        }
Example #31
0
        public void Utf8ExtensionPresent_CloneDoesNotHaveBogusFiles()
        {
            using (var setup = new RepositorySetup("Dan"))
            {
                const string utf8FilePath = "açesbsun.wav";
                setup.ChangeFile(utf8FilePath, "hello1");
                setup.ProjectFolderConfig.IncludePatterns.Add("*.wav");
                setup.AddAndCheckIn();

                using (var other = new RepositorySetup("Bob", false))
                {
                    //var uri = new Uri(String.Format("file:///{0}", setup.ProjectFolder.Path));
                    HgRepository.Clone(new HttpRepositoryPath("utf test repo", setup.ProjectFolder.Path, false), other.ProjectFolder.Path, other.Progress);
                    other.Repository.Update();

                    other.AssertFileExists(utf8FilePath);
                    string[] fileNames = Directory.GetFiles(other.ProjectFolder.Path, "*.wav");
                    Assert.AreEqual(1, fileNames.Length);

                    //Assert.IsTrue(setup.GetProgressString().Contains());
                }
            }
        }
Example #32
0
        public static Dictionary <string, Revision> CollectAllBranchHeads(string repoPath)
        {
            var retval = new Dictionary <string, Revision>();

            var repo = new HgRepository(repoPath, new NullProgress());

            foreach (var head in repo.GetHeads())
            {
                var branch = head.Branch;
                if (branch == String.Empty)
                {
                    branch = "default";
                }
                if (retval.ContainsKey(branch))
                {
                    // Use the higher rev number since it has more than one head of the same branch.
                    var extantRevNumber  = Int32.Parse(retval[branch].Number.LocalRevisionNumber);
                    var currentRevNumber = Int32.Parse(head.Number.LocalRevisionNumber);
                    if (currentRevNumber > extantRevNumber)
                    {
                        // Use the newer head of a branch.
                        retval[branch] = head;
                    }
                    //else
                    //{
                    //    // 'else' case: The one we already have is newer, so keep it.
                    //}
                }
                else
                {
                    // New branch, so add it.
                    retval.Add(branch, head);
                }
            }

            return(retval);
        }
Example #33
0
 public void MakeListItem_MakesNormalItem()
 {
     using (var usb = new TemporaryFolder("clonetestUsb"))
     {
         var path = usb.Combine("test1");
         Directory.CreateDirectory(path);
         var testFile = Path.Combine(path, "test.file");
         File.WriteAllText(testFile, @"exist");
         var repo = HgRepository.CreateRepositoryInExistingDir(path, new NullProgress());
         repo.AddAndCheckinFile(testFile);
         var model = new CloneFromUsb();
         var item  = model.CreateListItemFor(path);
         Assert.That(item, Is.Not.Null, "model should have made a list item");
         Assert.That(item.Text, Is.EqualTo("test1"));
         Assert.That(item.Tag, Is.EqualTo(path));
         var    last            = File.GetLastWriteTime(path);
         string expectedSubitem = last.ToShortDateString() + " " + last.ToShortTimeString();                 // Not a great test, basically duplicates the impl
         Assert.That(item.SubItems[1].Text, Is.EqualTo(expectedSubitem));
         Assert.That(item.ToolTipText, Is.EqualTo(path));
         Assert.That(item.ImageIndex, Is.EqualTo(0));
         Assert.That(item.BackColor, Is.EqualTo(Color.FromKnownColor(KnownColor.Window)));
         Assert.That(item.ForeColor, Is.EqualTo(Color.FromKnownColor(KnownColor.WindowText)));
     }
 }
Example #34
0
        /// <summary>
        /// used for local sources (usb, sd media, etc)
        /// </summary>
        /// <returns>the uri of a successful clone</returns>
        private string TryToMakeCloneForSource(RepositoryAddress repoDescriptor)
        {
            List <string> possibleRepoCloneUris = repoDescriptor.GetPossibleCloneUris(Repository.Identifier, RepoProjectName, _progress);

            if (possibleRepoCloneUris == null)
            {
                _progress.WriteMessage("No Uris available for cloning to {0}",
                                       repoDescriptor.Name);
                return(null);
            }
            else
            {
                foreach (string uri in possibleRepoCloneUris)
                {
                    // target may be uri, or some other folder.
                    var target = HgRepository.GetUniqueFolderPath(
                        _progress,
                        //"Folder at {0} already exists, so it can't be used. Creating clone in {1}, instead.",
                        RepositoryAddress.DuplicateWarningMessage.Replace(RepositoryAddress.MediumVariable, "USB flash drive"),
                        uri);
                    try
                    {
                        _progress.WriteMessage("Copying repository to {0}...", repoDescriptor.GetFullName(target));
                        _progress.WriteVerbose("({0})", target);
                        return(HgHighLevel.MakeCloneFromLocalToUsb(_localRepositoryPath, target, _progress));
                    }
                    catch (Exception error)
                    {
                        _progress.WriteError("Could not create repository on {0}. Error follow:", target);
                        _progress.WriteException(error);
                        // keep looping
                    }
                }
            }
            return(null);
        }
Example #35
0
        public void GetFilesInRevision_MultipleRevisionsInRepo_GivesCorrectFiles()
        {
            using (var testRoot = new TemporaryFolder("ChorusRetrieveTest"))
            {
                var temp = testRoot.Combine("filename with spaces");
                File.WriteAllText(temp, "one");
                using (var f = TempFile.TrackExisting(temp))
                {
                    HgRepository.CreateRepositoryInExistingDir(testRoot.Path, _progress);
                    var repo = new HgRepository(testRoot.Path, _progress);

                    repo.AddAndCheckinFile(f.Path);
                    repo.Commit(true, "initial");
                    File.WriteAllText(f.Path, "one two");
                    repo.Commit(true, "second");

                    var revisions = repo.GetAllRevisions();
                    Assert.AreEqual(2, revisions.Count);
                    var files = repo.GetFilesInRevision(revisions[0]);
                    Assert.AreEqual(1, files.Count());
                    Assert.AreEqual(f.Path, files.First().FullPath);
                }
            }
        }
Example #36
0
        public void GetRepostoryNames_TwoItemsInHubFolder_GetTwoItems()
        {
            using (var testRoot = new TemporaryFolder("ChorusHubCloneTest_" + Guid.NewGuid()))
                using (var chorusHubSourceFolder = new TemporaryFolder(testRoot, "ChorusHub"))
                    using (var repo1 = new TemporaryFolder(chorusHubSourceFolder, "repo1"))
                        using (var tempFile1 = TempFile.WithExtension("ext1"))
                            using (var repo2 = new TemporaryFolder(chorusHubSourceFolder, "repo2"))
                                using (var tempFile2 = TempFile.WithExtension("ext2"))
                                {
                                    tempFile1.MoveTo(Path.Combine(repo1.Path, Path.GetFileName(tempFile1.Path)));
                                    tempFile2.MoveTo(Path.Combine(repo2.Path, Path.GetFileName(tempFile2.Path)));
                                    RepositorySetup.MakeRepositoryForTest(repo1.Path, "bob", new ConsoleProgress());
                                    RepositorySetup.MakeRepositoryForTest(repo2.Path, "bob", new ConsoleProgress());

                                    var r1 = HgRepository.CreateOrUseExisting(repo1.Path, new ConsoleProgress());
                                    r1.AddAndCheckinFile(tempFile1.Path); // need this to create store/data/files
                                    var r2 = HgRepository.CreateOrUseExisting(repo2.Path, new ConsoleProgress());
                                    r2.AddAndCheckinFile(tempFile2.Path); // need this to create store/data/files

                                    ChorusHubOptions.RootDirectory = chorusHubSourceFolder.Path;
                                    using (var service = new ChorusHubServer())
                                    {
                                        // hg server side is now involved in deciding what repos are available
                                        Assert.IsTrue(service.Start(true));
                                        var chorusHubServerInfo = ChorusHubServerInfo.FindServerInformation();
                                        Assert.NotNull(chorusHubServerInfo);
                                        var client   = new ChorusHubClient(chorusHubServerInfo);
                                        var repoInfo = client.GetRepositoryInformation(string.Empty);
                                        Assert.AreEqual(2, repoInfo.Count());
                                        var info1 = repoInfo.First();
                                        var info2 = repoInfo.Last();
                                        Assert.IsTrue(info1.RepoName == "repo1");
                                        Assert.IsTrue(info2.RepoName == "repo2");
                                    }
                                }
        }
Example #37
0
        public void TipUpdatedPostMerge()
        {
            ConsoleProgress progress        = new ConsoleProgress();
            BobSetup        bobSetup        = new BobSetup(progress, _pathToTestRoot);
            var             bobSynchronizer = bobSetup.GetSynchronizer();

            //set up two branches to trigger issue
            SetAdjunctModelVersion(bobSynchronizer, "notdefault");             // Bob is on 'default' branch
            bobSetup.ChangeTextFile(bobSynchronizer);

            //Ok, this is unrealistic, but we just clone Bob onto Sally
            var hubRoot          = Path.Combine(_pathToTestRoot, "Hub");
            var sallyMachineRoot = Path.Combine(_pathToTestRoot, "sally");

            Directory.CreateDirectory(sallyMachineRoot);
            Directory.CreateDirectory(hubRoot);
            var sallyProjectRoot = bobSetup.SetupClone(sallyMachineRoot);
            var hubProjectRoot   = bobSetup.SetupClone(hubRoot);
            var sallyProject     = BobSetup.CreateFolderConfig(sallyProjectRoot);
            var hubProject       = BobSetup.CreateFolderConfig(hubProjectRoot);

            var repository = HgRepository.CreateOrUseExisting(sallyProject.FolderPath, progress);

            repository.SetUserNameInIni("sally", progress);

            // bob makes a change and syncs
            File.WriteAllText(bobSetup._pathToLift, LiftFileStrings.lift12Dog);
            var bobOptions = new SyncOptions
            {
                CheckinDescription = "added 'dog'",
                DoMergeWithOthers  = true,
                DoSendToOthers     = true,
                DoPullFromOthers   = true
            };

            bobOptions.RepositorySourcesToTry.Add(RepositoryAddress.Create("Hub", hubProject.FolderPath, false));

            //now Sally modifies the original file, not having seen Bob's changes yet
            var sallyPathToLift = Path.Combine(sallyProject.FolderPath, Path.Combine("lexicon", "foo.lift"));

            File.WriteAllText(sallyPathToLift, LiftFileStrings.lift12Cat);

            //Sally syncs, pulling in Bob's change, and encountering a need to merge (no conflicts)
            var sallyOptions = new SyncOptions
            {
                CheckinDescription = "adding cat",
                DoPullFromOthers   = true,
                DoSendToOthers     = true,
                DoMergeWithOthers  = true
            };

            sallyOptions.RepositorySourcesToTry.Add(RepositoryAddress.Create("Hub", hubProject.FolderPath, false));

            var sallySyncer = Synchronizer.FromProjectConfiguration(sallyProject, progress);

            SetAdjunctModelVersion(sallySyncer, "notdefault");
            sallySyncer.SyncNow(sallyOptions);
            bobSynchronizer.SyncNow(bobOptions);
            // bob makes a change and syncs
            File.WriteAllText(bobSetup._pathToLift, LiftFileStrings.lift12DogAnt);
            bobSynchronizer.SyncNow(bobOptions);
            sallyOptions.DoSendToOthers = false;
            sallySyncer.SyncNow(sallyOptions);
            //Debug.WriteLine("bob's: " + File.ReadAllText(bobSetup._pathToLift));
            var contents = File.ReadAllText(sallyPathToLift);

            //Debug.WriteLine("sally's: " + contents);
            Assert.That(contents, Does.Contain("ant"));
            Assert.That(contents, Does.Contain("dog"));
        }
Example #38
0
        public void TestNewVersion_SallyAndBobUpgradeButFredDelays()
        {
            ConsoleProgress progress = new ConsoleProgress();
            BobSetup        bobSetup = new BobSetup(progress, _pathToTestRoot);

            // clone Bob onto Sally
            string sallyMachineRoot = Path.Combine(_pathToTestRoot, "sally");

            Directory.CreateDirectory(sallyMachineRoot);
            string sallyProjectRoot = bobSetup.SetupClone(sallyMachineRoot);
            ProjectFolderConfiguration sallyProject = new ProjectFolderConfiguration(sallyProjectRoot);

            sallyProject.IncludePatterns.Add("**.abc");
            sallyProject.IncludePatterns.Add("**.lift");

            // clone Bob onto Fred
            string fredMachineRoot = Path.Combine(_pathToTestRoot, "fred");

            Directory.CreateDirectory(fredMachineRoot);
            string fredProjectRoot = bobSetup.SetupClone(fredMachineRoot);
            ProjectFolderConfiguration fredProject = new ProjectFolderConfiguration(fredProjectRoot);

            fredProject.IncludePatterns.Add("**.abc");
            fredProject.IncludePatterns.Add("**.lift");

            // Setup Sally and Fred repositories
            var sallyRepository = HgRepository.CreateOrUseExisting(sallyProject.FolderPath, progress);

            sallyRepository.SetUserNameInIni("sally", progress);
            var fredRepository = HgRepository.CreateOrUseExisting(fredProject.FolderPath, progress);

            fredRepository.SetUserNameInIni("fred", progress);
            var sallyRepoAddress = RepositoryAddress.Create("sally's machine", sallyProjectRoot, false);
            var fredRepoAddress  = RepositoryAddress.Create("fred's machine", fredProjectRoot, false);
            var bobRepoAddress   = RepositoryAddress.Create("bob's machine", bobSetup.BobProjectPath, false);

            // bob makes a change and syncs to everybody
            File.WriteAllText(bobSetup._pathToLift, LiftFileStrings.lift12Dog);
            var bobOptions = GetFullSyncOptions("added 'dog'");

            bobOptions.RepositorySourcesToTry.Add(sallyRepoAddress);
            bobOptions.RepositorySourcesToTry.Add(fredRepoAddress);

            var bobSyncer = bobSetup.GetSynchronizer();

            bobSyncer.SyncNow(bobOptions);             // Bob syncs with everybody on 'default' branch

            // Verification Step 1
            var sallyPathToLift = Path.Combine(sallyProject.FolderPath, "lexicon/foo.lift");
            var fredPathToLift  = Path.Combine(fredProject.FolderPath, "lexicon/foo.lift");
            var sallyContents   = File.ReadAllText(sallyPathToLift);

            Assert.That(sallyContents, Does.Contain("dog"), "'dog' should be in Sally repo.");
            var fredContents = File.ReadAllText(fredPathToLift);

            Assert.That(fredContents, Does.Contain("dog"), "'dog' should be in Fred repo.");

            // bob makes another change and syncs to new version
            File.WriteAllText(bobSetup._pathToLift, LiftFileStrings.lift13DogCat);
            var newBobOptions = GetFullSyncOptions("added 'cat'");

            newBobOptions.DoMergeWithOthers = false;          // just want a fast checkin
            newBobOptions.DoPullFromOthers  = false;          // just want a fast checkin
            newBobOptions.DoSendToOthers    = false;          // just want a fast checkin
            const string lift13version = "LIFT0.13";

            SetAdjunctModelVersion(bobSyncer, lift13version);             // Bob is now on the new version of LIFT
            bobSyncer.SyncNow(newBobOptions);

            // now Fred modifies default branch to add 'ant'
            File.WriteAllText(fredPathToLift, LiftFileStrings.lift12DogAnt);
            var fredOptions = GetFullSyncOptions("added 'ant'");

            fredOptions.RepositorySourcesToTry.Add(bobRepoAddress);
            fredOptions.RepositorySourcesToTry.Add(sallyRepoAddress);
            var fredSyncer = Synchronizer.FromProjectConfiguration(fredProject, progress);

            fredSyncer.SyncNow(fredOptions);

            // Verification Step 2
            fredContents = File.ReadAllText(fredPathToLift);
            Assert.That(fredContents, Does.Not.Contain("cat"), "'cat' should only be on Bob's branch.");
            Assert.That(fredContents, Does.Contain("ant"));
            sallyContents = File.ReadAllText(sallyPathToLift);
            Assert.That(sallyContents, Does.Contain("ant"), "'ant' was propogated to Sally's branch.");
            Assert.That(sallyContents, Does.Not.Contain("cat"), "'cat' should only be on Bob's branch.");
            var bobContents = File.ReadAllText(bobSetup._pathToLift);

            Assert.That(bobContents, Does.Not.Contain("ant"), "'ant' is only on 'default' branch.");
            // Verify Bob is on the latest branch
            string dummy;
            var    result = bobSyncer.Repository.BranchingHelper.IsLatestBranchDifferent(lift13version, out dummy);

            Assert.That(result, Is.False, "Bob should be on the new LIFT0.13 branch.");
            // And Fred isn't
            result = fredSyncer.Repository.BranchingHelper.IsLatestBranchDifferent(lift13version, out dummy);
            Assert.That(result, Is.True, "Fred should still be on the 'default' branch.");

            // Now Sally modifies the file, not having seen Bob's changes yet, but having seen Fred's changes.
            // She adds 'herring' and has upgraded to Bob's version of LIFT
            File.WriteAllText(sallyPathToLift, LiftFileStrings.lift13DogAntHerring);

            //Sally syncs, pulling in Bob's 1st change, and encountering a need to merge (no conflicts)
            var sallyOptions = GetFullSyncOptions("adding 'herring'");

            sallyOptions.RepositorySourcesToTry.Add(bobRepoAddress);
            sallyOptions.RepositorySourcesToTry.Add(fredRepoAddress);             // Why not? Even though he's still on 'default' branch

            var sallySyncer = Synchronizer.FromProjectConfiguration(sallyProject, progress);

            SetAdjunctModelVersion(sallySyncer, lift13version);             // Sally is now on the Bob's later version
            // Below is the line with the hg error
            sallySyncer.SyncNow(sallyOptions);

            // Verification Step 3
            bobContents = File.ReadAllText(bobSetup._pathToLift);
            Assert.That(bobContents, Does.Contain("herring"), "'herring' should be pulled in from Sally's branch.");
            Assert.That(bobContents, Does.Contain("ant"), "'ant' should be pulled in from Sally's branch.");
            sallyContents = File.ReadAllText(sallyPathToLift);
            Assert.That(sallyContents, Does.Contain("cat"), "'cat' should be pulled in from Bob's branch.");
            Assert.That(sallyContents, Does.Contain("dog"), "Everybody should have 'dog' from before.");
            fredContents = File.ReadAllText(fredPathToLift);
            Assert.That(fredContents, Does.Not.Contain("herring"), "The red herring is only in the new version for now.");
            Assert.That(fredContents, Does.Not.Contain("cat"), "'cat' is only in the new version for now.");
            // Verify Sally is now on the latest branch
            result = sallySyncer.Repository.BranchingHelper.IsLatestBranchDifferent(lift13version, out dummy);
            Assert.That(result, Is.False, "Sally should be on the new LIFT0.13 branch.");
            // And Fred still shouldn't be
            result = fredSyncer.Repository.BranchingHelper.IsLatestBranchDifferent(lift13version, out dummy);
            Assert.That(result, Is.True, "Fred should still be on the 'default' branch.");

            // Now Fred checks in 'pig' to the 'default' branch
            File.WriteAllText(fredPathToLift, LiftFileStrings.lift12DogAntPig);

            // Fred syncs, not finding anybody else's changes
            fredOptions.CheckinDescription = "adding 'pig'";
            fredSyncer.SyncNow(fredOptions);

            // Verification Step 4
            bobContents = File.ReadAllText(bobSetup._pathToLift);
            Assert.That(bobContents, Does.Not.Contain("pig"), "'pig' should only be on 'default' branch.");
            sallyContents = File.ReadAllText(sallyPathToLift);
            Assert.That(sallyContents, Does.Not.Contain("pig"), "'pig' should only be on 'default' branch.");
            fredContents = File.ReadAllText(fredPathToLift);
            Assert.That(fredContents, Does.Not.Contain("herring"), "'herring' should still only be in the new version.");
            // Just check Fred hasn't changed branches
            result = fredSyncer.Repository.BranchingHelper.IsLatestBranchDifferent(lift13version, out dummy);
            Assert.That(result, Is.True, "Fred should still be on the 'default' branch.");

            // Now Bob checks in 'deer' in the new version
            File.WriteAllText(bobSetup._pathToLift, LiftFileStrings.lift13DogCatHerringAntDeer);
            bobOptions.CheckinDescription = "adding 'deer'";
            bobSyncer.SyncNow(bobOptions);

            // Verification Step 5
            // Check that Fred hasn't changed
            fredContents = File.ReadAllText(fredPathToLift);
            Assert.That(fredContents, Does.Not.Contain("deer"), "'deer' should only be on new version.");
            result = fredSyncer.Repository.BranchingHelper.IsLatestBranchDifferent(lift13version, out dummy);
            Assert.That(result, Is.True, "Fred should still be on the 'default' branch.");
            // Check that Sally got her 'deer'
            sallyContents = File.ReadAllText(sallyPathToLift);
            Assert.That(sallyContents, Does.Contain("deer"), "'deer' should have propagated to Sally.");
            // Make sure that 'pig' hasn't migrated to the new version
            Assert.That(sallyContents, Does.Not.Contain("pig"), "'pig' should still only be on 'default' branch.");

            // Now Fred has finally upgraded and will check in 'fox' -- LAST CHECK-IN FOR THIS TEST!
            File.WriteAllText(fredPathToLift, LiftFileStrings.lift13DogAntPigFox);
            fredOptions.CheckinDescription = "adding 'fox'";
            SetAdjunctModelVersion(fredSyncer, lift13version);             // Fred finally updates to the new version (branch)
            fredSyncer.SyncNow(fredOptions);

            // Verification Step 6 (Last)
            bobContents = File.ReadAllText(bobSetup._pathToLift);
            Assert.That(bobContents, Does.Contain("cat"), "'cat' should survive the big hairy test in Bob's repo.");
            Assert.That(bobContents, Does.Contain("dog"), "'dog' should survive the big hairy test in Bob's repo.");
            Assert.That(bobContents, Does.Contain("pig"), "'pig' should survive the big hairy test in Bob's repo.");
            Assert.That(bobContents, Does.Contain("herring"), "'herring' should survive the big hairy test in Bob's repo.");
            Assert.That(bobContents, Does.Contain("deer"), "'deer' should survive the big hairy test in Bob's repo.");
            Assert.That(bobContents, Does.Contain("ant"), "'ant' should survive the big hairy test in Bob's repo.");
            Assert.That(bobContents, Does.Contain("fox"), "'fox' should survive the big hairy test in Bob's repo.");
            sallyContents = File.ReadAllText(sallyPathToLift);
            Assert.That(sallyContents, Does.Contain("cat"), "'cat' should survive the big hairy test in Sally's repo.");
            Assert.That(sallyContents, Does.Contain("dog"), "'dog' should survive the big hairy test in Sally's repo.");
            Assert.That(sallyContents, Does.Contain("herring"), "'herring' should survive the big hairy test in Sally's repo.");
            Assert.That(sallyContents, Does.Contain("pig"), "'pig' should survive the big hairy test in Sally's repo.");
            Assert.That(sallyContents, Does.Contain("deer"), "'deer' should survive the big hairy test in Sally's repo.");
            Assert.That(sallyContents, Does.Contain("ant"), "'ant' should survive the big hairy test in Sally's repo.");
            Assert.That(sallyContents, Does.Contain("fox"), "'fox' should survive the big hairy test in Sally's repo.");
            fredContents = File.ReadAllText(fredPathToLift);
            Assert.That(fredContents, Does.Contain("cat"), "'cat' should survive the big hairy test in Fred's repo.");
            Assert.That(fredContents, Does.Contain("dog"), "'dog' should survive the big hairy test in Fred's repo.");
            Assert.That(fredContents, Does.Contain("herring"), "'herring' should survive the big hairy test in Fred's repo.");
            Assert.That(fredContents, Does.Contain("pig"), "'pig' should survive the big hairy test in Fred's repo.");
            Assert.That(fredContents, Does.Contain("deer"), "'deer' should survive the big hairy test in Fred's repo.");
            Assert.That(fredContents, Does.Contain("ant"), "'ant' should survive the big hairy test in Fred's repo.");
            Assert.That(fredContents, Does.Contain("fox"), "'fox' should survive the big hairy test in Fred's repo.");

            // Verify Bob is on the latest branch
            result = bobSyncer.Repository.BranchingHelper.IsLatestBranchDifferent(lift13version, out dummy);
            Assert.That(result, Is.False, "Bob should be on the new LIFT0.13 branch.");

            // Verify Sally is on the right branch
            result = sallySyncer.Repository.BranchingHelper.IsLatestBranchDifferent(lift13version, out dummy);
            Assert.That(result, Is.False, "Sally should be on the new LIFT0.13 branch.");

            // Verify Fred is finally on the new branch
            result = fredSyncer.Repository.BranchingHelper.IsLatestBranchDifferent(lift13version, out dummy);
            Assert.That(result, Is.False, "Fred should finally be on the new LIFT0.13 branch.");
        }
Example #39
0
        [Category("KnownMonoIssue")]         // Actually, it is an unknown mono issue.
        public void TestNewVersion_SallyUpgradesToBobVersion()
        {
            ConsoleProgress progress = new ConsoleProgress();
            BobSetup        bobSetup = new BobSetup(progress, _pathToTestRoot);

            bobSetup.ChangeTextFile();

            //Ok, this is unrealistic, but we just clone Bob onto Sally
            string sallyMachineRoot = Path.Combine(_pathToTestRoot, "sally");

            Directory.CreateDirectory(sallyMachineRoot);
            string sallyProjectRoot = bobSetup.SetupClone(sallyMachineRoot);
            ProjectFolderConfiguration sallyProject = new ProjectFolderConfiguration(sallyProjectRoot);

            sallyProject.IncludePatterns.Add("**.abc");
            sallyProject.IncludePatterns.Add("**.lift");

            var repository = HgRepository.CreateOrUseExisting(sallyProject.FolderPath, progress);

            repository.SetUserNameInIni("sally", progress);

            // bob makes a change and syncs
            File.WriteAllText(bobSetup._pathToLift, LiftFileStrings.lift12Dog);
            var bobOptions = GetFullSyncOptions("added dog");

            bobOptions.DoMergeWithOthers = false;          // just want a fast checkin
            bobOptions.DoSendToOthers    = false;          // just want a fast checkin
            bobOptions.DoPullFromOthers  = false;          // just want a fast checkin

            var bobsyncer = bobSetup.GetSynchronizer();

            SetAdjunctModelVersion(bobsyncer, "LIFT0.12");             // Bob is still on an older branch
            bobsyncer.SyncNow(bobOptions);

            // bob makes another change and syncs
            File.WriteAllText(bobSetup._pathToLift, LiftFileStrings.lift13DogHerring);
            bobOptions.CheckinDescription = "added 'herring'";         // still just want a fast checkin

            SetAdjunctModelVersion(bobsyncer, "LIFT0.13");             // Bob is now on a new branch
            bobsyncer.SyncNow(bobOptions);

            //now Sally modifies the original file, not having seen Bob's changes yet
            var sallyPathToLift = Path.Combine(sallyProject.FolderPath, "lexicon/foo.lift");

            File.WriteAllText(sallyPathToLift, LiftFileStrings.lift12Cat);

            //Sally syncs, pulling in Bob's 1st change, and encountering a need to merge (no conflicts)
            var sallyOptions = GetFullSyncOptions("adding cat");

            sallyOptions.RepositorySourcesToTry.Add(RepositoryAddress.Create("bob's machine", bobSetup.BobProjectPath, false));

            var synchronizer = Synchronizer.FromProjectConfiguration(sallyProject, progress);

            SetAdjunctModelVersion(synchronizer, "LIFT0.12");             // Sally is still on the initial branch

            // SUT
            synchronizer.SyncNow(sallyOptions);

            // Verification stage 1
            var bobContents = File.ReadAllText(bobSetup._pathToLift);

            Assert.That(bobContents, Does.Not.Contain("cat"), "'cat' should only be on Sally's branch.");
            Assert.That(bobContents, Does.Contain("dog"));
            var sallyContents = File.ReadAllText(sallyPathToLift);

            Assert.That(sallyContents, Does.Contain("cat"));
            Assert.That(sallyContents, Does.Contain("dog"), "Sally should have merged in older branch to hers.");
            Assert.That(sallyContents, Does.Not.Contain("herring"), "The red herring is only in Bob's repo; 2nd branch.");

            // Now Sally upgrades her LIFT-capable program to Bob's version!
            File.WriteAllText(sallyPathToLift, LiftFileStrings.lift13PigDogCat);

            //Sally syncs, pulling in Bob's change, and encountering a need to merge (no conflicts)
            sallyOptions = GetFullSyncOptions("adding pig");

            const string lift13version = "LIFT0.13";

            SetAdjunctModelVersion(synchronizer, lift13version);             // Sally updates to the new version (branch)
            synchronizer.SyncNow(sallyOptions);
            bobOptions.DoPullFromOthers = true;
            bobOptions.RepositorySourcesToTry.Add(RepositoryAddress.Create("sally's machine", sallyProjectRoot, false));

            // SUT
            bobsyncer.SyncNow(bobOptions);

            // Verification stage 2
            bobContents = File.ReadAllText(bobSetup._pathToLift);
            //Debug.Print("Bob's: " + bobContents);
            Assert.That(bobContents, Does.Contain("cat"), "'cat' survived the upgrade to Bob's repo.");
            Assert.That(bobContents, Does.Contain("dog"));
            Assert.That(bobContents, Does.Contain("pig"), "'pig' survived the upgrade to Bob's repo.");
            sallyContents = File.ReadAllText(sallyPathToLift);
            //Debug.Print("Sally's: " + sallyContents);
            Assert.That(sallyContents, Does.Contain("cat"));
            Assert.That(sallyContents, Does.Contain("dog"), "'dog' should be from Bob's older repo.");
            Assert.That(sallyContents, Does.Contain("herring"), "Now we should have everything from Bob's repo.");
            Assert.That(sallyContents, Does.Contain("pig"), "'pig' should have survived the upgrade.");

            // Verify Bob is on the latest branch
            string dummy;
            var    result = bobsyncer.Repository.BranchingHelper.IsLatestBranchDifferent(lift13version, out dummy);

            Assert.That(result, Is.False, "Bob should be on the latest LIFT0.13 branch.");

            // Verify Sally is on the right branch
            result = synchronizer.Repository.BranchingHelper.IsLatestBranchDifferent(lift13version, out dummy);
            Assert.That(result, Is.False, "Sally should be on the latest LIFT0.13 branch.");
        }
Example #40
0
        public void TestNewVersion_SallyUpgrades_BobNotYet()
        {
            ConsoleProgress progress = new ConsoleProgress();
            BobSetup        bobSetup = new BobSetup(progress, _pathToTestRoot);

            bobSetup.ChangeTextFile();

            //Ok, this is unrealistic, but we just clone Bob onto Sally
            string sallyMachineRoot = Path.Combine(_pathToTestRoot, "sally");

            Directory.CreateDirectory(sallyMachineRoot);
            string sallyProjectRoot = bobSetup.SetupClone(sallyMachineRoot);
            ProjectFolderConfiguration sallyProject = new ProjectFolderConfiguration(sallyProjectRoot);

            sallyProject.IncludePatterns.Add("**.abc");
            sallyProject.IncludePatterns.Add("**.lift");

            var repository = HgRepository.CreateOrUseExisting(sallyProject.FolderPath, progress);

            repository.SetUserNameInIni("sally", progress);

            // bob makes a change and syncs
            File.WriteAllText(bobSetup._pathToLift, LiftFileStrings.lift12Dog);

            var bobOptions = GetFullSyncOptions("added dog");

            bobOptions.DoMergeWithOthers = false;          // just want a fast checkin
            bobOptions.DoSendToOthers    = false;          // just want a fast checkin
            bobOptions.DoPullFromOthers  = false;          // just want a fast checkin

            var bobSyncer = bobSetup.GetSynchronizer();

            SetAdjunctModelVersion(bobSyncer, "");             // Bob is on 'default' branch
            bobSyncer.SyncNow(bobOptions);

            //now Sally modifies the original file, not having seen Bob's changes yet
            var sallyPathToLift = Path.Combine(sallyProject.FolderPath, "lexicon/foo.lift");

            File.WriteAllText(sallyPathToLift, LiftFileStrings.lift12Cat);

            //Sally syncs, pulling in Bob's change, and encountering a need to merge (no conflicts)
            var sallyOptions = GetFullSyncOptions("adding cat");
            var bobAddress   = RepositoryAddress.Create("bob's machine", bobSetup.BobProjectPath, false);

            sallyOptions.RepositorySourcesToTry.Add(bobAddress);

            var          synchronizer    = Synchronizer.FromProjectConfiguration(sallyProject, progress);
            const string sallyNewVersion = "LIFT0.13";

            SetAdjunctModelVersion(synchronizer, sallyNewVersion);
            synchronizer.SyncNow(sallyOptions);

            // Verification
            var bobContents = File.ReadAllText(bobSetup._pathToLift);

            Assert.That(bobContents, Does.Not.Contain("cat"), "'cat' should only be on Sally's branch.");
            Assert.That(bobContents, Does.Contain("dog"));
            var sallyContents = File.ReadAllText(sallyPathToLift);

            //Debug.WriteLine("sally's: " + sallyContents);
            Assert.That(sallyContents, Does.Contain("cat"));
            Assert.That(sallyContents, Does.Not.Contain("dog"), "'dog' should only be in Bob's repo.");

            // Verify Bob is still on the default branch (empty string)
            string dummy;
            var    result = bobSyncer.Repository.BranchingHelper.IsLatestBranchDifferent("", out dummy);

            Assert.That(result, Is.False, "Bob should be on default branch.");

            // Verify Sally is on the right branch
            result = synchronizer.Repository.BranchingHelper.IsLatestBranchDifferent(sallyNewVersion, out dummy);
            Assert.That(result, Is.False, "Sally should be on LIFT0.13 branch.");
        }
Example #41
0
 public IEnumerable <IChangeReport> Find2WayDifferences(FileInRevision parent, FileInRevision child, HgRepository repository)
 {
     return(Xml2WayDiffService.ReportDifferences(repository, parent, child,
                                                 null,
                                                 SharedConstants.LangProject, SharedConstants.GuidStr));
 }
Example #42
0
 /// <summary>
 /// For use when updating a model version for the repository,
 /// sets the current branch on the repo and the ClientVersion property to the given branch name
 /// </summary>
 /// <param name="progress"></param>
 /// <param name="branchName"></param>
 public void Branch(IProgress progress, string branchName)
 {
     progress.WriteVerbose("{0} changing working dir to branch: {1}", UserId, branchName);
     _repo.Execute(_repo.SecondsBeforeTimeoutOnLocalOperation, "branch -f ", HgRepository.SurroundWithQuotes(branchName));
     ClientVersion = branchName;
 }
Example #43
0
 public IEnumerable <IChangeReport> Find2WayDifferences(FileInRevision parent, FileInRevision child, HgRepository repository)
 {
     throw new ApplicationException(string.Format("Chorus could not find a handler to diff files like '{0}'", child.FullPath));
 }
Example #44
0
        public void GetEnvironmentReadinessMessageIsNull()
        {
            var s = HgRepository.GetEnvironmentReadinessMessage("en");

            Assert.IsNullOrEmpty(s);
        }
Example #45
0
 public IEnumerable <IChangeReport> Find2WayDifferences(FileInRevision parent, FileInRevision child, HgRepository repository)
 {
     //this is never called because we said we don't do diffs yet; review is handled some other way
     throw new NotImplementedException();
 }
Example #46
0
 public IEnumerable <IChangeReport> Find2WayDifferences(FileInRevision parent, FileInRevision child, HgRepository repository)
 {
     yield return(new TextEditChangeReport(parent, child, parent.GetFileContents(repository), child.GetFileContents(repository)));
 }
Example #47
0
        public SyncResults SyncNow(SyncOptions options)
        {
            SyncResults results = new SyncResults();
            List <RepositoryAddress> sourcesToTry = options.RepositorySourcesToTry;
            //this just saves us from trying to connect twice to the same repo that is, for example, no there.
            Dictionary <RepositoryAddress, bool> connectionAttempts = new Dictionary <RepositoryAddress, bool>();

            try
            {
                if (_progress.ProgressIndicator != null)
                {
                    _progress.ProgressIndicator.IndicateUnknownProgress();
                }
                var repo = new HgRepository(_localRepositoryPath, _progress);

                RemoveLocks(repo);
                repo.RecoverFromInterruptedTransactionIfNeeded();
                repo.FixUnicodeAudio();
                string branchName = _sychronizerAdjunct.BranchName;
                ChangeBranchIfNecessary(branchName);
                Commit(options);

                var workingRevBeforeSync = repo.GetRevisionWorkingSetIsBasedOn();

                if (options.DoPullFromOthers)
                {
                    results.DidGetChangesFromOthers = PullFromOthers(repo, sourcesToTry, connectionAttempts);
                }

                if (options.DoMergeWithOthers)
                {
                    MergeHeadsOrRollbackAndThrow(repo, workingRevBeforeSync);
                }

                if (options.DoSendToOthers)
                {
                    SendToOthers(repo, sourcesToTry, connectionAttempts);
                }

                //If we did pull any data or a trivial merge succeeded we should call UpdateToTheDescendantRevision
                if (results.DidGetChangesFromOthers ||                                                             //we pulled something
                    (workingRevBeforeSync != null &&                //will be null if this is the 1st checkin ever, but no files were added so there was no actual rev created
                     !repo.GetRevisionWorkingSetIsBasedOn().Number.Hash.Equals(workingRevBeforeSync.Number.Hash))) //a merge happened
                {
                    UpdateToTheDescendantRevision(repo, workingRevBeforeSync);
                }
                _sychronizerAdjunct.CheckRepositoryBranches(repo.BranchingHelper.GetBranches(), _progress);

                results.Succeeded = true;
                _progress.WriteMessage("Done");
            }
            catch (SynchronizationException error)
            {
                error.DoNotifications(Repository, _progress);
                results.Succeeded        = false;
                results.ErrorEncountered = error;
            }
            catch (UserCancelledException error)
            {
                results.Succeeded        = false;
                results.Cancelled        = true;
                results.ErrorEncountered = null;
            }
            catch (Exception error)
            {
                if (error.InnerException != null)
                {
                    _progress.WriteVerbose("inner exception:");
                    _progress.WriteError(error.InnerException.Message);
                    _progress.WriteVerbose(error.InnerException.StackTrace);
                }

                _progress.WriteException(error);                //this preserves the whole exception for later retrieval by the client
                _progress.WriteError(error.Message);            //review still needed if we have this new WriteException?
                _progress.WriteVerbose(error.StackTrace);       //review still needed if we have this new WriteException?

                results.Succeeded        = false;
                results.ErrorEncountered = error;
            }
            return(results);
        }
Example #48
0
        private void SendToOneOther(RepositoryAddress address, Dictionary <RepositoryAddress, bool> connectionAttempt, HgRepository repo)
        {
            try
            {
                string resolvedUri = address.GetPotentialRepoUri(Repository.Identifier, RepoProjectName, _progress);

                bool canConnect;
                if (connectionAttempt.ContainsKey(address))
                {
                    canConnect = connectionAttempt[address];
                }
                else
                {
                    canConnect = address.CanConnect(repo, RepoProjectName, _progress);
                    connectionAttempt.Add(address, canConnect);
                }
                if (canConnect)
                {
                    if (s_testingDoNotPush)
                    {
                        _progress.WriteWarning("**Skipping push because s_testingDoNotPush is true");
                    }
                    else
                    {
                        repo.Push(address, resolvedUri);
                    }

                    // For USB, we do not wish to do an update, since it can cause problems if the working
                    // files are available to the user.
                    // The update is only done for tests, since only tests now use "DirectoryRepositorySource".
                    if (address is DirectoryRepositorySource && ((DirectoryRepositorySource)address).LooksLikeLocalDirectory)
                    {
                        // passes false to avoid updating the hgrc on a send to preserve backward compatibility
                        var otherRepo = new HgRepository(resolvedUri, false, _progress);
                        otherRepo.Update();
                    }
                }
                else if (address is UsbKeyRepositorySource || address is DirectoryRepositorySource)
                {
                    // If we cannot connect to a USB or Directory source (the repository doesn't exist),
                    // try to clone our repository onto the source
                    TryToMakeCloneForSource(address);
                    //nb: no need to push if we just made a clone
                }
            }
            catch (UserCancelledException)
            {
                throw;
            }
            catch (Exception error)
            {
                ExplainAndThrow(error, "Failed to send to {0} ({1}).", address.Name, address.URI);
            }
        }
Example #49
0
        static void Main(string[] args)
        {
            //MessageBox.Show(@"Get ready to debug FB exe.");
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            if (args.Length == 0)
            {
                MessageBox.Show(CommonResources.kNoCommandLineOptions, CommonResources.kFLExBridge, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            using (var hotspot = new HotSpotProvider())
            {
                // This is a kludge to make sure we have a real reference to PalasoUIWindowsForms.
                // Without this call, although PalasoUIWindowsForms is listed in the References of this project,
                // since we don't actually use it directly, it does not show up when calling GetReferencedAssemblies on this assembly.
                // But we need it to show up in that list so that ExceptionHandler.Init can install the intended PalasoUIWindowsForms
                // exception handler.
            }

            if (Settings.Default.CallUpgrade)
            {
                Settings.Default.Upgrade();
                Settings.Default.CallUpgrade = false;
            }

            SetUpErrorHandling();

            var commandLineArgs = CommandLineProcessor.ParseCommandLineArgs(args);

#if MONO
            // Set up Xpcom for geckofx (used by some Chorus dialogs that we may invoke).
            Xpcom.Initialize(XULRunnerLocator.GetXULRunnerLocation());
            GeckoPreferences.User["gfx.font_rendering.graphite.enabled"] = true;
            Application.ApplicationExit += (sender, e) => { Xpcom.Shutdown(); };
#endif

            // An aggregate catalog that combines multiple catalogs
            using (var catalog = new AggregateCatalog())
            {
                catalog.Catalogs.Add(new DirectoryCatalog(
                                         Path.GetDirectoryName(Utilities.StripFilePrefix(typeof(ActionTypeHandlerRepository).Assembly.CodeBase)),
                                         "*-ChorusPlugin.dll"));

                // Create the CompositionContainer with the parts in the catalog
                using (var container = new CompositionContainer(catalog))
                {
                    var connHelper = container.GetExportedValue <FLExConnectionHelper>();
                    if (!connHelper.Init(commandLineArgs))
                    {
                        return;
                    }

                    // Is mercurial set up?
                    var readinessMessage = HgRepository.GetEnvironmentReadinessMessage("en");
                    if (!string.IsNullOrEmpty(readinessMessage))
                    {
                        MessageBox.Show(readinessMessage, CommonResources.kFLExBridge, MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                        return;
                    }

                    var l10Managers = Utilities.SetupLocalization(commandLineArgs);

                    try
                    {
                        var handlerRepository = container.GetExportedValue <ActionTypeHandlerRepository>();
                        var currentHandler    = handlerRepository.GetHandler(commandLineArgs);
                        currentHandler.StartWorking(commandLineArgs);
                        var bridgeActionTypeHandlerShowWindow = currentHandler as IBridgeActionTypeHandlerShowWindow;
                        if (bridgeActionTypeHandlerShowWindow != null)
                        {
                            Application.Run(bridgeActionTypeHandlerShowWindow.MainForm);
                        }
                        var bridgeActionTypeHandlerCallEndWork = currentHandler as IBridgeActionTypeHandlerCallEndWork;
                        if (bridgeActionTypeHandlerCallEndWork != null)
                        {
                            bridgeActionTypeHandlerCallEndWork.EndWork();
                        }
                    }
                    catch
                    {
                        connHelper.SignalBridgeWorkComplete(false);
                        throw;                         // Re-throw the original exception, so the crash dlg has something to display.
                    }
                    finally
                    {
                        foreach (var manager in l10Managers.Values)
                        {
                            manager.Dispose();
                        }
                    }
                }
            }
            Settings.Default.Save();
        }
Example #50
0
        /// <summary>
        /// Make sure to dispose of this
        /// </summary>
        /// <returns>An IDisposable TempFile</returns>
        public TempFile CreateTempFile(HgRepository repository)
        {
            var path = repository.RetrieveHistoricalVersionOfFile(FullPath, _revisionNumber);

            return(TempFile.TrackExisting(path));
        }
Example #51
0
        // e.g. http://bobeaton:[email protected]/snwmtn-test
        // or \\Bob-StudioXPS\Backup\Storying\snwmtn-test
        public static void SyncWithRepository(string strProjectFolder, bool bIsOpening)
        {
            // the project folder name has come here bogus at times...
            if (!Directory.Exists(strProjectFolder))
            {
                return;
            }

            string strProjectName = Path.GetFileNameWithoutExtension(strProjectFolder);

            // if there's no repo yet, then create one (even if we aren't going
            //  to ultimately push with an internet repo, we still want one locally)
            var projectConfig = new Chorus.sync.ProjectFolderConfiguration(strProjectFolder);

            projectConfig.IncludePatterns.Add("*.onestory");
            projectConfig.IncludePatterns.Add("*.xml");             // the P7 key terms list
            projectConfig.IncludePatterns.Add("*.bad");             // if we write a bad file, commit that as well
            projectConfig.IncludePatterns.Add("*.conflict");        // include the conflicts file as well so we can fix them
            projectConfig.IncludePatterns.Add("*.ChorusNotes");     // the new conflict file

            string strHgUsername, strRepoUrl, strSharedNetworkUrl;

            if (GetHgRepoParameters(strProjectName, out strHgUsername, out strRepoUrl, out strSharedNetworkUrl))
            {
                if (!String.IsNullOrEmpty(strRepoUrl))
                {
                    var nullProgress = new NullProgress();
                    var repo         = new HgRepository(strProjectFolder, nullProgress);
                    if (!repo.GetCanConnectToRemote(strRepoUrl, nullProgress))
                    {
                        if (MessageBox.Show(Properties.Resources.IDS_ConnectToInternet,
                                            Properties.Resources.IDS_Caption,
                                            MessageBoxButtons.OKCancel) ==
                            DialogResult.Cancel)
                        {
                            strRepoUrl = null;
                            if (String.IsNullOrEmpty(strSharedNetworkUrl))
                            {
                                return;
                            }
                        }
                    }
                }

                // for when we launch the program, just do a quick & dirty send/receive,
                //  but for closing (or if we have a network drive also), then we want to
                //  be more informative
                SyncUIDialogBehaviors suidb = SyncUIDialogBehaviors.Lazy;
                SyncUIFeatures        suif  = SyncUIFeatures.NormalRecommended;

                /*
                 * if (bIsOpening && String.IsNullOrEmpty(strSharedNetworkUrl))
                 * {
                 *      suidb = SyncUIDialogBehaviors.StartImmediatelyAndCloseWhenFinished;
                 *      suif = SyncUIFeatures.Minimal;
                 * }
                 * else
                 * {
                 *      suidb = SyncUIDialogBehaviors.Lazy;
                 *      suif = SyncUIFeatures.NormalRecommended;
                 * }
                 */

                using (var dlg = new SyncDialog(projectConfig, suidb, suif))
                {
                    dlg.UseTargetsAsSpecifiedInSyncOptions = true;
                    if (!String.IsNullOrEmpty(strRepoUrl))
                    {
                        dlg.SyncOptions.RepositorySourcesToTry.Add(RepositoryAddress.Create(CstrInternetName, strRepoUrl));
                    }
                    if (!String.IsNullOrEmpty(strSharedNetworkUrl))
                    {
                        dlg.SyncOptions.RepositorySourcesToTry.Add(RepositoryAddress.Create(CstrNetworkDriveName, strSharedNetworkUrl));
                    }

                    dlg.Text = "Synchronizing OneStory Project: " + strProjectName;
                    dlg.ShowDialog();
                }
            }
            else if (!bIsOpening)
            {
                // even if the user doesn't want to go to the internet, we
                //  at least want to back up locally (when the user closes)
                using (var dlg = new SyncDialog(projectConfig,
                                                SyncUIDialogBehaviors.StartImmediatelyAndCloseWhenFinished,
                                                SyncUIFeatures.Minimal))
                {
                    dlg.Text = "OneStory Automatic Backup";
                    dlg.SyncOptions.DoMergeWithOthers = false;
                    dlg.SyncOptions.DoPullFromOthers  = false;
                    dlg.SyncOptions.DoSendToOthers    = false;
                    dlg.ShowDialog();
                }
            }
        }
Example #52
0
        public static Synchronizer FromProjectConfiguration(ProjectFolderConfiguration project, IProgress progress)
        {
            var hg = HgRepository.CreateOrUseExisting(project.FolderPath, progress);

            return(new Synchronizer(hg.PathToRepo, project, progress));
        }
Example #53
0
 public IChangePresenter GetChangePresenter(IChangeReport report, HgRepository repository)
 {
     //this is never called because we said we don't present diffs; review is handled some other way
     throw new NotImplementedException();
 }
Example #54
0
 internal HgModelVersionBranch(HgRepository repo, IProgress progress)
 {
     _repo     = repo;
     _progress = progress;
     SetCurrentClientVersion();
 }
Example #55
0
        /// <summary>
        /// Get a teammate's shared project from the specified source.
        /// </summary>
        /// <param name="parent">Window that will be parent of progress window</param>
        /// <param name="projectFilter">Function taking a directory path and telling whether it contains the right sort of repo</param>
        /// <param name="hubQuery">String on which to build a URL query to ChorusHub to accomplish the purpose of 'projectFilter'
        /// in the ChorusHub environment</param>
        /// <example>FLExBridge sends "fileExtension=.lift|._custom_properties" to get both LIFT and FLExBridge repos, but not Bloom ones,
        /// for instance. The server looks in the project's .hg/store/data folder for a file ending in .lift.i or ._custom_properties.i</example>
        /// <param name="baseProjectDirForNewClone">The base folder for the new clone, if created.</param>
        /// <param name="baseProjectDirInWhichToSearchForRepositories">The directory which contains projects we already have, and where the result should go</param>
        /// <param name="lowerLevelRepoPath">Optionally specifies another place to look for existing repos: look in this subfolder of each folder in baseProjectDirInWhichToSearchForRepositories.
        /// This is used in FLEx (passing "OtherRepositories") so existing LIFT repos linked to FW projects can be found. Pass null if not used.</param>
        /// <param name="preferredClonedFolderName"></param>
        /// <param name="howToSendReceiveMessageText">This string is appended to the message we build when we have received a repo and can't keep it, because
        /// it has the same hash as an existing project. We think it is likely the user actually intended to Send/Receive that project rather than obtaining
        /// a duplicate. This message thus typically tells him how to do so, in the particular client program. May also be empty.</param>
        /// <returns>
        /// A CloneResult that provides the clone results (e.g., success or failure) and the actual clone location (null if not created).
        /// </returns>
        public CloneResult GetSharedProjectUsing(Form parent, string baseProjectDirForNewClone, string preferredClonedFolderName,
                                                 Func <string, bool> projectFilter, string hubQuery, string baseProjectDirInWhichToSearchForRepositories, string lowerLevelRepoPath,
                                                 string howToSendReceiveMessageText)
        {
            Guard.AgainstNull(parent, "parent");
            Guard.AgainstNullOrEmptyString(baseProjectDirForNewClone, "baseProjectDirForNewClone");
            Guard.AgainstNullOrEmptyString(baseProjectDirInWhichToSearchForRepositories, "baseProjectDirInWhichToSearchForRepositories");
            if (preferredClonedFolderName == string.Empty)
            {
                preferredClonedFolderName = null;
            }

            Dictionary <string, string> existingRepositories;

            try
            {
                existingRepositories = ExtantRepoIdentifiers(baseProjectDirInWhichToSearchForRepositories, lowerLevelRepoPath);
            }
            catch (ApplicationException e)
            {
                // FLEx issue LT-14301: one reason we may throw is that we can't get the identifier of some project because we don't have
                // sufficient permissions.

                // We think this will be very rare...try to get an automatic notification if it happens.
                UsageReporter.SendEvent("UnusualProblems", "Chorus", "ExtantRepoIdentifiersFailed", null, 0);

                MessageBox.Show(
                    string.Format(LocalizationManager.GetString("Messages.CantGetInfo",
                                                                "You can't get a project from a colleague at present, because some required information about the projects you already have is unavailable. "
                                                                + "This may be because you don't have permission to access a file in one of the projects in {0}.\n\n"
                                                                + "You will probably need technical support to resolve this problem. The following information may be helpful to tech support:") + "\n\n{1}",
                                  baseProjectDirInWhichToSearchForRepositories, e.Message),
                    LocalizationManager.GetString("Messages.CantGetProject", "Cannot get project"));
                return(new CloneResult(null, CloneStatus.NotCreated));
            }
            var existingProjectNames = new HashSet <string>(from dir in Directory.GetDirectories(baseProjectDirInWhichToSearchForRepositories) select Path.GetFileName(dir));

            // "existingRepositoryIdentifiers" is currently not used, but the expectation is that the various models/views could use it how they see fit.
            // "Seeing fit' may mean to warn the user they already have some repository, or as a filter to not show ones that already exist.
            // What to do with the list of extant repos is left up to a view+model pair.

            // Select basic source type.
            using (var getSharedProjectDlg = new GetSharedProjectDlg())
            {
                getSharedProjectDlg.InitFromModel(this);
                getSharedProjectDlg.ShowDialog(parent);
                if (getSharedProjectDlg.DialogResult != DialogResult.OK)
                {
                    return(new CloneResult(null, CloneStatus.NotCreated));
                }
            }

            // Make clone from some source.
            string actualCloneLocation = null;
            var    cloneStatus         = CloneStatus.NotCreated;

            switch (RepositorySource)
            {
            case ExtantRepoSource.Internet:
                var cloneFromInternetModel = new GetCloneFromInternetModel(baseProjectDirForNewClone)
                {
                    LocalFolderName = preferredClonedFolderName
                };
                using (var cloneFromInternetDialog = new GetCloneFromInternetDialog(cloneFromInternetModel))
                {
                    switch (cloneFromInternetDialog.ShowDialog(parent))
                    {
                    default:
                        cloneStatus = CloneStatus.NotCreated;
                        break;

                    case DialogResult.Cancel:
                        cloneStatus = CloneStatus.Cancelled;
                        break;

                    case DialogResult.OK:
                        actualCloneLocation = cloneFromInternetDialog.PathToNewlyClonedFolder;
                        cloneStatus         = CloneStatus.Created;
                        break;
                    }
                }
                break;

            case ExtantRepoSource.ChorusHub:
                var getCloneFromChorusHubModel = new GetCloneFromChorusHubModel(baseProjectDirForNewClone)
                {
                    ProjectFilter    = hubQuery,
                    ExistingProjects = existingProjectNames,
                    ExistingRepositoryIdentifiers = existingRepositories
                };

                using (var getCloneFromChorusHubDialog = new GetCloneFromChorusHubDialog(getCloneFromChorusHubModel))
                {
                    switch (getCloneFromChorusHubDialog.ShowDialog(parent))
                    {
                    default:
                        cloneStatus = CloneStatus.NotCreated;
                        break;

                    case DialogResult.Cancel:
                        cloneStatus = CloneStatus.Cancelled;
                        break;

                    case DialogResult.OK:
                        if (getCloneFromChorusHubModel.CloneSucceeded)
                        {
                            actualCloneLocation = getCloneFromChorusHubDialog.PathToNewlyClonedFolder;
                            cloneStatus         = CloneStatus.Created;
                        }
                        else
                        {
                            cloneStatus = CloneStatus.NotCreated;
                        }
                        break;
                    }
                }
                break;

            case ExtantRepoSource.Usb:
                using (var cloneFromUsbDialog = new GetCloneFromUsbDialog(baseProjectDirForNewClone))
                {
                    cloneFromUsbDialog.Model.ProjectFilter    = projectFilter ?? DefaultProjectFilter;
                    cloneFromUsbDialog.Model.ReposInUse       = existingRepositories;
                    cloneFromUsbDialog.Model.ExistingProjects = existingProjectNames;
                    switch (cloneFromUsbDialog.ShowDialog(parent))
                    {
                    default:
                        cloneStatus = CloneStatus.NotCreated;
                        break;

                    case DialogResult.Cancel:
                        cloneStatus = CloneStatus.Cancelled;
                        break;

                    case DialogResult.OK:
                        actualCloneLocation = cloneFromUsbDialog.PathToNewlyClonedFolder;
                        cloneStatus         = CloneStatus.Created;
                        break;
                    }
                }
                break;
            }
            // Warn the user if they already have this by another name.
            // Not currently needed for USB, since those have already been checked.
            if (RepositorySource != ExtantRepoSource.Usb && cloneStatus == CloneStatus.Created)
            {
                var    repo = new HgRepository(actualCloneLocation, new NullProgress());
                string projectWithExistingRepo;
                if (repo.Identifier != null && existingRepositories.TryGetValue(repo.Identifier, out projectWithExistingRepo))
                {
                    using (var warningDlg = new DuplicateProjectWarningDialog())
                        warningDlg.Run(projectWithExistingRepo, howToSendReceiveMessageText);
                    Directory.Delete(actualCloneLocation, true);
                    actualCloneLocation = null;
                    cloneStatus         = CloneStatus.Cancelled;
                }
            }
            return(new CloneResult(actualCloneLocation, cloneStatus));
        }
Example #56
0
 public void GetAliasFromPath_HasColon_GivesSafeAlias()
 {
     Assert.AreEqual("Z_TokPisinDictionary", HgRepository.GetAliasFromPath(@"Z:TokPisinDictionary"));
 }
Example #57
0
        /// <returns>true if there was a successful pull</returns>
        private bool PullFromOneSource(HgRepository repo, RepositoryAddress source, Dictionary <RepositoryAddress, bool> connectionAttempt)
        {
            string resolvedUri = source.GetPotentialRepoUri(repo.Identifier, RepoProjectName, _progress);

            if (source is UsbKeyRepositorySource)
            {
                _progress.WriteMessage("Looking for USB flash drives...");
                var potential = source.GetPotentialRepoUri(repo.Identifier, RepoProjectName, _progress);
                if (null == potential)
                {
                    _progress.WriteWarning("No USB flash drive found");
                }
                else if (string.Empty == potential)
                {
                    _progress.WriteMessage("Did not find this project on any USB flash drive.");
                }
            }
            else
            {
                _progress.WriteMessage("Connecting to {0}...", source.Name);
            }
            var canConnect = source.CanConnect(repo, RepoProjectName, _progress);

            if (!connectionAttempt.ContainsKey(source))
            {
                connectionAttempt.Add(source, canConnect);
            }
            if (canConnect)
            {
                try
                {
                    ThrowIfCancelPending();
                }
                catch (Exception error)
                {
                    throw new SynchronizationException(error, WhatToDo.CheckSettings, "Error while pulling {0} at {1}", source.Name, resolvedUri);
                }
                //NB: this returns false if there was nothing to get.
                try
                {
                    return(repo.Pull(source, resolvedUri));
                }
                catch (HgCommonException err)
                {
                    // These kinds of errors are worth an immediate dialog, to make sure we get the user's attention.
                    ErrorReport.NotifyUserOfProblem(err.Message);
                    // The main sync routine will catch the exception, abort any other parts of the Send/Receive,
                    // and log the problem.
                    throw;
                }
                // Any other kind of exception will be caught and logged at a higher level.
            }
            else
            {
                if (source is UsbKeyRepositorySource)
                {
                    //already informed them, above
                    return(false);
                }
                else
                {
                    _progress.WriteError("Could not connect to {0} at {1}", source.Name, resolvedUri);
                    return(false);
                }
            }
        }
Example #58
0
 public IChangePresenter GetChangePresenter(IChangeReport report, HgRepository repository)
 {
     return(FieldWorksChangePresenter.GetCommonChangePresenter(report, repository));
 }
Example #59
0
 public IChangePresenter GetChangePresenter(IChangeReport report, HgRepository repository)
 {
     return(new DefaultChangePresenter(report, repository));
 }
Example #60
0
 private string GetMergeCommitSummary(string personMergedWith, HgRepository repository)
 {
     return("Merged with " + personMergedWith);
 }