private IEnumerable<SearchResult> Search(SearchQuery query, RepoInfo repo, bool includeRepoName = false)
        {
            var allTerms = string.Join(" --or ", query.Terms.Select(t => "-e " + GitUtilities.Q(t)));
            var commandResult = GitUtilities.Execute("grep --line-number --fixed-strings --ignore-case --context 3 --null --all-match " + allTerms + " HEAD", repo.RepoPath);

            var repoResults = commandResult.Split(new[] { "\n" }, StringSplitOptions.RemoveEmptyEntries);

            return from m in repoResults
                   where m != "--"
                   where !m.StartsWith("Binary file")
                   let parts = m.Split('\0')
                   let filePath = parts[0].Split(':')[1]
                   let searchLine = new SearchLine
                   {
                       Line = parts[2],
                       LineNumber = int.Parse(parts[1]),
                   }
                   group searchLine by filePath into g
                   select new SearchResult
                   {
                       LinkText = (includeRepoName ? repo.Name + " " : string.Empty) + "/" + g.Key,
                       ActionName = "ViewBlob",
                       ControllerName = "Browse",
                       RouteValues = new { repo = repo.Name, @object = "HEAD", path = g.Key },
                       Lines = g.ToList(),
                   };
        }
Beispiel #2
0
        private IEnumerable<SearchResult> Search(SearchQuery query, RepoInfo repo, bool includeRepoName = false)
        {
            TreeView tree;

            try
            {
                tree = GitUtilities.GetTreeInfo(repo.RepoPath, "HEAD", recurse: true);
            }
            catch (GitErrorException)
            {
                yield break;
            }

            foreach (var item in tree.Objects)
            {
                var name = item.Name.Substring(item.Name.LastIndexOf('/') + 1);

                if (query.Terms.All(t => name.IndexOf(t, StringComparison.OrdinalIgnoreCase) != -1))
                {
                    var linkText = (includeRepoName ? repo.Name + " " : string.Empty) + "/" + item.Name;

                    switch (item.ObjectType)
                    {
                        case ObjectType.Tree:
                            yield return new SearchResult
                            {
                                LinkText = linkText + "/",
                                ActionName = "ViewTree",
                                ControllerName = "Browse",
                                RouteValues = new { repo = repo.Name, @object = tree.Tree, path = tree.Path + item.Name + "/" },
                                Lines = new List<SearchLine>(),
                            };
                            break;

                        case ObjectType.Blob:
                            yield return new SearchResult
                            {
                                LinkText = linkText,
                                ActionName = "ViewBlob",
                                ControllerName = "Browse",
                                RouteValues = new { repo = repo.Name, @object = tree.Tree, path = tree.Path + item.Name },
                                Lines = new List<SearchLine>(),
                            };
                            break;

                        case ObjectType.Commit:
                            yield return new SearchResult
                            {
                                LinkText = linkText + "/",
                                ActionName = "ViewTree",
                                ControllerName = "Browse",
                                RouteValues = new { repo = repo.Name, @object = tree.Tree, path = tree.Path + item.Name + "/" },
                                Lines = new List<SearchLine>(),
                            };
                            break;
                    }
                }
            }
        }
Beispiel #3
0
 /// <summary>
 /// Constructor.
 /// </summary>
 public CmisRepo(RepoInfo repoInfo, IActivityListener activityListener)
     : base(repoInfo, activityListener)
 {
     this.synchronizedFolder = new SynchronizedFolder(repoInfo, this, activityListener);
     this.Watcher.ChangeEvent += OnFileActivity;
     this.Watcher.EnableEvent = true;
     Logger.Info(synchronizedFolder);
 }
 public Task<IList<SearchResult>> Search(SearchQuery query, FileManager fileManager, RepoInfo repository, int skip, int count)
 {
     if (repository != null)
     {
         return Task.Factory.StartNew(() => (IList<SearchResult>)Search(query, repository).Skip(skip).Take(count).ToList());
     }
     else
     {
         return Task.Factory.StartNew(() => (IList<SearchResult>)Search(query, fileManager).Skip(skip).Take(count).ToList());
     }
 }
        public ActionResult ViewRepoImpact(string repo, string branch, string since, string before)
        {
            var resourceInfo = this.FileManager.GetResourceInfo(repo);
            if (resourceInfo.Type != ResourceType.Directory)
            {
                return HttpNotFound();
            }

            if(string.IsNullOrWhiteSpace(since))
                since = DateTime.Now.Subtract(new TimeSpan(30, 0, 0, 0)).ToString("yyyy-MM-dd");

            var repoInfo = new RepoInfo(repo, branch);
            this.BreadCrumbs.Append("Browse", "Index", "Browse");
            AddRepoBreadCrumb(repoInfo);
            this.BreadCrumbs.Append("Impact", "ViewRepoImpact", "Impact", new { repo });

            var userImpacts = GitUtilities.GetUserImpacts(resourceInfo.FullPath, branch, since, before);

            var allTimeImpacts = (from g in userImpacts.GroupBy(u => u.Author, StringComparer.InvariantCultureIgnoreCase)
                                  select new UserImpact
                                  {
                                      Author = g.Key,
                                      Commits = g.Sum(ui => ui.Commits),
                                      Insertions = g.Sum(ui => ui.Insertions),
                                      Deletions = g.Sum(ui => ui.Deletions),
                                      Impact = g.Sum(ui => ui.Impact),
                                  }).OrderByDescending(i => i.Commits);

            var weeklyImpacts = (from u in userImpacts
                                 let dayOffset = CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek - u.Date.DayOfWeek
                                 let commitWeek = u.Date.Date.AddDays(dayOffset + (dayOffset > 0 ? -7 : 0))
                                 group u by commitWeek into wk
                                 select new ImpactWeek
                                 {
                                     Week = wk.Key,
                                     Impacts = (from g in wk.GroupBy(u => u.Author, StringComparer.InvariantCultureIgnoreCase)
                                                select new UserImpact
                                                {
                                                    Author = g.Key,
                                                    Commits = g.Sum(ui => ui.Commits),
                                                    Insertions = g.Sum(ui => ui.Insertions),
                                                    Deletions = g.Sum(ui => ui.Deletions),
                                                    Impact = g.Sum(ui => ui.Impact),
                                                }).OrderByDescending(i => i.Commits).ToList()
                                 }).OrderBy(wk => wk.Week);

            ViewBag.AllTime = allTimeImpacts;
            ViewBag.Weekly = weeklyImpacts;
            ViewBag.Branch = branch;
            ViewBag.Since = since;
            ViewBag.Before = before;
            return View();
        }
            /// <summary>
            /// Check for added folders and files.
            /// </summary>
            public void FindNewLocalObjects(RepoInfo repoInfo, string folder, ref List<string> addedFolders, ref List<string> addedFiles)
            {
                // Check files in this folder.
                string[] files;
                try
                {
                    files = Directory.GetFiles(folder);
                }
                catch (Exception e)
                {
                    Logger.Warn("Could not get the files list from folder: " + folder, e);
                    return;
                }

                foreach (string file in files)
                {
                    // Check whether this file is present in database.
                    string filePath = Path.Combine(folder, file);
                    if ( ! database.ContainsLocalFile(filePath) && Utils.WorthSyncing(folder,Path.GetFileName(file), repoInfo))
                    {
                        addedFiles.Add(filePath);
                    }
                }

                // Check folders and recurse.
                string[] subFolders;
                try
                {
                    subFolders = Directory.GetDirectories(folder);
                }
                catch (Exception e)
                {
                    Logger.Warn("Could not get the folders list from folder: " + folder, e);
                    return;
                }

                foreach (string subFolder in subFolders)
                {
                    // Check whether this sub-folder is present in database.
                    string folderPath = Path.Combine(folder, subFolder);
                    if (database.ContainsLocalPath(folderPath))
                    {
                        // Recurse.
                        FindNewLocalObjects(repoInfo, folderPath, ref addedFolders, ref addedFiles);
                    }
                    else
                    {
                        // New folder, add to list and don't recurse.
                        addedFolders.Add(folderPath);
                    }
                }
            }
Beispiel #7
0
        private ActionResult Search(string q, RepoInfo repoInfo)
        {
            var searchProviders = container.ResolveAll<ISearchProvider>();

            var query = new SearchQuery(q);

            var results = (from p in searchProviders
                           select p.Search(query, this.FileManager, repoInfo, 0, 100)).ToArray();

            Task.WaitAll(results);

            return View("Search", results.Select(r => r.Result).SelectMany(r => r));
        }
            /// <summary>
            /// Detect what has changed using the local database, and apply these
            /// modifications to the remote server.
            /// </summary>
            /// <param name="rootFolder">Full path of the local synchronized folder, for instance "/User Homes/nicolas.raoul/demos"</param>
            public bool ApplyLocalChanges(string rootFolder, RepoInfo repoInfo)
            {
                try
                {
                    var deletedFolders = new List<string>();
                    var deletedFiles = new List<string>();
                    var modifiedFiles = new List<string>();
                    var addedFolders = new List<string>();
                    var addedFiles = new List<string>();

                    // Check for added folders and files.
                    FindNewLocalObjects(repoInfo, rootFolder, ref addedFolders, ref addedFiles);

                    // Check for deleted and modified folders and files.
                    FindModifiedOrDeletedLocalObjects(repoInfo, rootFolder, ref deletedFolders, ref deletedFiles, ref modifiedFiles);

                    // TODO: Try to make sense of related changes, for instance renamed folders.
                    // TODO: Check local metadata modification cache.

                    int numberOfChanges = deletedFolders.Count + deletedFiles.Count + modifiedFiles.Count + addedFolders.Count + addedFiles.Count;
                    Logger.Debug(numberOfChanges + " local changes to apply.");

                    if (numberOfChanges == 0)
                    {
                        return true; // Success: Did nothing.
                    }

                    // Apply changes to the server.
                    activityListener.ActivityStarted();
                    bool success = ApplyDeletedFolders(ref deletedFolders);
                    success &= ApplyDeletedFiles(ref deletedFiles);
                    success &= ApplyModifiedFiles(ref modifiedFiles);
                    success &= ApplyAddedFolders(ref addedFolders);
                    success &= ApplyAddedFiles(ref addedFiles);

                    Logger.Debug("Finished applying local changes.");
                    return success;
                }
                finally
                {
                    activityListener.ActivityStopped();
                }
            }
        /// <summary>
        /// Remove a synchronized folder from the CmisSync configuration.
        /// This happens after the user removes the folder.
        /// </summary>
        /// <param name="folder">The synchronized folder to remove</param>
        private void RemoveRepository(RepoInfo folder) {
            foreach (Repository repo in this.repositories) {
                if (repo.LocalPath.Equals(folder.LocalPath)) {
                    repo.Dispose();
                    this.repositories.Remove(repo);
                    this.statusAggregator.Remove(repo);
                    repo.Dispose();
                    break;
                }
            }

            // Remove DBreeze DB folder
            try {
                Directory.Delete(folder.GetDatabasePath(), true);
            } catch (DirectoryNotFoundException) {
            }
        }
Beispiel #10
0
 public RepoConfigChangedEvent(RepoInfo repoInfo) {
     RepoInfo = repoInfo;
 }
Beispiel #11
0
            /// <summary>
            ///  Constructor for Repo (at every launch of CmisSync)
            /// </summary>
            public SynchronizedFolder(RepoInfo repoInfo, RepoBase repoCmis, IActivityListener activityListener)
            {
                this.activityListener = activityListener;

                if (null == repoInfo || null == repoCmis)
                {
                    throw new ArgumentNullException("repoInfo");
                }

                this.repo = repoCmis;
                this.repoinfo = repoInfo;

                suspended = this.repoinfo.IsSuspended;

                // Database is the user's AppData/Roaming
                database = new Database.Database(repoinfo.CmisDatabase);

                // Get path on remote repository.
                remoteFolderPath = repoInfo.RemotePath;

                if (Logger.IsInfoEnabled)
                {
                    foreach (string ignoredFolder in repoInfo.getIgnoredPaths())
                    {
                        Logger.Info("The folder \"" + ignoredFolder + "\" will be ignored");
                    }
                }

                syncWorker = new BackgroundWorker();
                syncWorker.WorkerSupportsCancellation = true;
                syncWorker.DoWork += new DoWorkEventHandler(
                    delegate(Object o, DoWorkEventArgs args)
                    {
                        bool syncFull = (bool)args.Argument;
                        try
                        {
                            Sync(syncFull);
                        }
                        catch (OperationCanceledException e)
                        {
                            Logger.Info(e.Message);
                        }
                        catch (CmisPermissionDeniedException e)
                        {
                            repo.OnSyncError(new PermissionDeniedException("Authentication failed.", e));
                        }
                        catch (CmisMissingSyncFolderException e) 
                        {
                            repo.OnSyncError(new MissingSyncFolderException("Missing sync folder.", e));
                        }
                        catch (Exception e)
                        {
                            repo.OnSyncError(new BaseException(e));
                        }
                        finally
                        {
                            SyncComplete(syncFull);
                        }
                    }
                );
            }
 public TestRepository(
     RepoInfo repoInfo,
     ActivityListenerAggregator activityListener,
     SingleStepEventQueue queue) : base(repoInfo, activityListener, true, queue) {
 }
            /// <summary>
            ///  Update Settings.
            /// </summary>
            public void UpdateSettings(RepoInfo repoInfo)
            {
                //Cancel sync before settings update.
                CancelSync();

                //Set the cmis session to null
                session = null;

                this.repoinfo = repoInfo;
                cmisParameters[SessionParameter.Password] = repoInfo.Password.ToString();
            }
Beispiel #14
0
        /// <summary>
        /// Guess the web address where files can be seen using a browser.
        /// Not bulletproof. It depends on the server, and on some servers there is no web UI at all.
        /// </summary>
        static public string GetBrowsableURL(RepoInfo repo)
        {
            if (null == repo)
            {
                throw new ArgumentNullException("repo");
            }

            // Case of Alfresco.
            string suffix1 = "alfresco/cmisatom";
            string suffix2 = "alfresco/service/cmis";

            if (repo.Address.AbsoluteUri.EndsWith(suffix1) || repo.Address.AbsoluteUri.EndsWith(suffix2))
            {
                // Detect suffix length.
                int suffixLength = 0;
                if (repo.Address.AbsoluteUri.EndsWith(suffix1))
                {
                    suffixLength = suffix1.Length;
                }
                if (repo.Address.AbsoluteUri.EndsWith(suffix2))
                {
                    suffixLength = suffix2.Length;
                }

                string root = repo.Address.AbsoluteUri.Substring(0, repo.Address.AbsoluteUri.Length - suffixLength);
                if (repo.RemotePath.StartsWith("/Sites"))
                {
                    // Case of Alfresco Share.

                    // Example RemotePath: /Sites/thesite
                    // Result: http://server/share/page/site/thesite/documentlibrary
                    // Example RemotePath: /Sites/thesite/documentLibrary/somefolder/anotherfolder
                    // Result: http://server/share/page/site/thesite/documentlibrary#filter=path|%2Fsomefolder%2Fanotherfolder
                    // Example RemotePath: /Sites/s1/documentLibrary/éß和ệ
                    // Result: http://server/share/page/site/s1/documentlibrary#filter=path|%2F%25E9%25DF%25u548C%25u1EC7
                    // Example RemotePath: /Sites/s1/documentLibrary/a#bc/éß和ệ
                    // Result: http://server/share/page/site/thesite/documentlibrary#filter=path%7C%2Fa%2523bc%2F%25E9%25DF%25u548C%25u1EC7%7C

                    string path = repo.RemotePath.Substring("/Sites/".Length);
                    if (path.Contains("documentLibrary"))
                    {
                        int    firstSlashPosition      = path.IndexOf('/');
                        string siteName                = path.Substring(0, firstSlashPosition);
                        string pathWithinSite          = path.Substring(firstSlashPosition + "/documentLibrary".Length);
                        string escapedPathWithinSite   = HttpUtility.UrlEncode(pathWithinSite);
                        string reescapedPathWithinSite = HttpUtility.UrlEncode(escapedPathWithinSite);
                        string sharePath               = reescapedPathWithinSite.Replace("%252f", "%2F");
                        sharePath = sharePath.Replace("%2b", "%20");
                        return(root + "share/page/site/" + siteName + "/documentlibrary#filter=path|" + sharePath);
                    }
                    else
                    {
                        // Site name only.
                        return(root + "share/page/site/" + path + "/documentlibrary");
                    }
                }
                else
                {
                    // Case of Alfresco Web Client. Difficult to build a direct URL, so return root.
                    return(root);
                }
            }
            else
            {
                // Another server was detected, try to open the thinclient url, otherwise try to open the repo path

                try
                {
                    // Connect to the CMIS repository.
                    ISession session = Auth.Auth.GetCmisSession(repo.Address.ToString(), repo.User, repo.Password.ToString(), repo.RepoID);

                    if (session.RepositoryInfo.ThinClientUri == null ||
                        String.IsNullOrEmpty(session.RepositoryInfo.ThinClientUri.ToString()))
                    {
                        Logger.Error("CmisUtils GetBrowsableURL | Repository does not implement ThinClientUri: " + repo.Address.AbsoluteUri);
                        return(repo.Address.AbsoluteUri + repo.RemotePath);
                    }
                    else
                    {
                        // Return CmisServer-provided thin URL.
                        return(session.RepositoryInfo.ThinClientUri.ToString());
                    }
                }
                catch (Exception e)
                {
                    Logger.Error("CmisUtils GetBrowsableURL | Exception " + e.Message, e);
                    // Server down or authentication problem, no way to know the right URL, so just open server.
                    return(repo.Address.AbsoluteUri + repo.RemotePath);
                }
            }
        }
        public ActionResult ViewCommits(string repo, string branch, int page = 1)
        {
            var resourceInfo = this.FileManager.GetResourceInfo(repo);
            if (resourceInfo.Type != ResourceType.Directory || page < 1)
            {
                return HttpNotFound();
            }

            const int PageSize = 20;
            int skip = PageSize * (page - 1);
            var count = GitUtilities.CountCommits(resourceInfo.FullPath);

            if (skip >= count)
            {
                return HttpNotFound();
            }

            var repoInfo = new RepoInfo(repo, branch);
            AddRepoBreadCrumb(repoInfo);
            this.BreadCrumbs.Append("Browse", "ViewCommits", "Commit Log", new { repo });

            var commits = GitUtilities.GetLogEntries(resourceInfo.FullPath, PageSize, skip, branch);

            ViewBag.Page = page;
            ViewBag.PageCount = (count / PageSize) + (count % PageSize > 0 ? 1 : 0);
            ViewBag.RepoName = resourceInfo.Name;

            return View(commits);
        }
            public InMemoryRepo(RepoInfo repoInfo, ActivityListenerAggregator listener) : base(repoInfo, listener, true, CmisSync.Lib.Cmis.Repository.CreateQueue()) {

            }
            /// <summary>
            ///  Constructor for Repo (at every launch of CmisSync)
            /// </summary>
            public SynchronizedFolder(RepoInfo repoInfo,
                IActivityListener listener, RepoBase repoCmis)
            {
                if (null == repoInfo || null == repoCmis)
                {
                    throw new ArgumentNullException("repoInfo");
                }

                this.repo = repoCmis;
                this.activityListener = listener;
                this.repoinfo = repoInfo;

                // Database is the user's AppData/Roaming
                database = new Database(repoinfo.CmisDatabase);

                // Get path on remote repository.
                remoteFolderPath = repoInfo.RemotePath;

                cmisParameters = new Dictionary<string, string>();
                cmisParameters[SessionParameter.BindingType] = BindingType.AtomPub;
                cmisParameters[SessionParameter.AtomPubUrl] = repoInfo.Address.ToString();
                cmisParameters[SessionParameter.User] = repoInfo.User;
                cmisParameters[SessionParameter.Password] = Crypto.Deobfuscate(repoInfo.Password); // Deobfuscate password.
                cmisParameters[SessionParameter.RepositoryId] = repoInfo.RepoID;
                cmisParameters[SessionParameter.ConnectTimeout] = "-1";

				foreach (string ignoredFolder in repoInfo.getIgnoredPaths())
				{
					Logger.Info("The folder \""+ignoredFolder+"\" will be ignored");
				}
            }
 public void RepositoryDetectsDisconnectionAndReconnects() {
     var repoInfo = new RepoInfo();
     var listener = new ActivityListenerAggregator(Mock.Of<IActivityListener>(), new TransmissionManager());
     var underTest = new InMemoryRepo(repoInfo, listener);
 }
 public CmisRepoMock(RepoInfo repoInfo, ActivityListenerAggregator activityListener, SingleStepEventQueue queue) : base(repoInfo, activityListener, true, queue) {
     this.SingleStepQueue = queue;
 }
        public void Init() {
            string testName = this.GetType().Name;
            object[] attributes = this.GetType().GetCustomAttributes(true);
            foreach (var attr in attributes) {
                if (attr is TestNameAttribute) {
                    testName = (attr as TestNameAttribute).Name;
                }
            }

            this.subfolder = testName + "_" + Guid.NewGuid().ToString();
            Console.WriteLine("Working on " + this.subfolder);

            // RepoInfo
            this.repoInfo = new RepoInfo {
                AuthenticationType = AuthenticationType.BASIC,
                LocalPath = Path.Combine(config[1].ToString(), this.subfolder),
                RemotePath = config[2].ToString() + "/" + this.subfolder,
                Address = new XmlUri(new Uri(config[3].ToString())),
                User = config[4].ToString(),
                RepositoryId = config[6].ToString(),
                Binding = config[7] != null ? config[7].ToString() : BindingType.AtomPub
            };
            this.repoInfo.RemotePath = this.repoInfo.RemotePath.Replace("//", "/");
            this.repoInfo.SetPassword(config[5].ToString());

            // FileSystemDir
            this.localRootDir = new DirectoryInfo(this.repoInfo.LocalPath);
            this.localRootDir.Create();
            if (!new DirectoryInfoWrapper(this.localRootDir).IsExtendedAttributeAvailable()) {
                Assert.Fail(string.Format("The local path {0} does not support extended attributes", this.localRootDir.FullName));
            }

            // Repo
            var activityListener = new Mock<IActivityListener>();
            this.transmissionManager = new TransmissionManager();
            var activityAggregator = new ActivityListenerAggregator(activityListener.Object, this.transmissionManager);
            var queue = new SingleStepEventQueue(new SyncEventManager());

            this.repo = new FullRepoTests.CmisRepoMock(this.repoInfo, activityAggregator, queue);

            // Session
            var cmisParameters = new Dictionary<string, string>();
            cmisParameters[SessionParameter.BindingType] = repoInfo.Binding;
            switch (repoInfo.Binding) {
            case BindingType.AtomPub:
                cmisParameters[SessionParameter.AtomPubUrl] = this.repoInfo.Address.ToString();
                break;
            case BindingType.Browser:
                cmisParameters[SessionParameter.BrowserUrl] = this.repoInfo.Address.ToString();
                break;
            default:
                Assert.Fail(string.Format("Unknown binding type {0}", repoInfo.Binding));
                break;
            }

            cmisParameters[SessionParameter.User] = this.repoInfo.User;
            cmisParameters[SessionParameter.Password] = this.repoInfo.GetPassword().ToString();
            cmisParameters[SessionParameter.RepositoryId] = this.repoInfo.RepositoryId;
            cmisParameters[SessionParameter.UserAgent] = Utils.CreateUserAgent();

            SessionFactory factory = SessionFactory.NewInstance();
            this.session = factory.CreateSession(cmisParameters);
            this.ContentChangesActive = this.session.AreChangeEventsSupported();
            IFolder root = (IFolder)this.session.GetObjectByPath(config[2].ToString());
            this.remoteRootDir = root.CreateFolder(this.subfolder);
        }
        // check vive input utility version on github
        private static void CheckVersionAndSettings()
        {
            if (Application.isPlaying)
            {
                EditorApplication.update -= CheckVersionAndSettings;
                return;
            }

            InitializeSettins();

            // fetch new version info from github release site
            if (!completeCheckVersionFlow && VIUSettings.autoCheckNewVIUVersion)
            {
                if (webReq == null) // web request not running
                {
                    if (EditorPrefs.HasKey(nextVersionCheckTimeKey) && DateTime.UtcNow < UtcDateTimeFromStr(EditorPrefs.GetString(nextVersionCheckTimeKey)))
                    {
                        VersionCheckLog("Skipped");
                        completeCheckVersionFlow = true;
                        return;
                    }

                    webReq = GetUnityWebRequestAndSend(lastestVersionUrl);
                }

                if (!webReq.isDone)
                {
                    return;
                }

                // On Windows, PlaterSetting is stored at \HKEY_CURRENT_USER\Software\Unity Technologies\Unity Editor 5.x
                EditorPrefs.SetString(nextVersionCheckTimeKey, UtcDateTimeToStr(DateTime.UtcNow.AddMinutes(versionCheckIntervalMinutes)));

                if (UrlSuccess(webReq))
                {
                    latestRepoInfo = JsonUtility.FromJson <RepoInfo>(GetWebText(webReq));
                    VersionCheckLog("Fetched");
                }

                // parse latestVersion and ignoreThisVersionKey
                if (!string.IsNullOrEmpty(latestRepoInfo.tag_name))
                {
                    try
                    {
                        latestVersion        = new System.Version(Regex.Replace(latestRepoInfo.tag_name, "[^0-9\\.]", string.Empty));
                        ignoreThisVersionKey = string.Format(fmtIgnoreUpdateKey, latestVersion.ToString());
                    }
                    catch
                    {
                        latestVersion        = default(System.Version);
                        ignoreThisVersionKey = string.Empty;
                    }
                }

                webReq.Dispose();
                webReq = null;

                completeCheckVersionFlow = true;
            }

            VIUSettingsEditor.PackageManagerHelper.PreparePackageList();
            if (VIUSettingsEditor.PackageManagerHelper.isPreparingList)
            {
                return;
            }

            showNewVersion = !string.IsNullOrEmpty(ignoreThisVersionKey) && !VIUProjectSettings.HasIgnoreKey(ignoreThisVersionKey) && latestVersion > VIUVersion.current;

            UpdateIgnoredNotifiedSettingsCount(false);

            if (showNewVersion || notifiedSettingsCount > 0)
            {
                TryOpenRecommendedSettingWindow();
            }

            EditorApplication.update -= CheckVersionAndSettings;
        }
        public ActionResult ViewRepo(string repo, string branch)
        {
            branch = branch == null ? WebConfigurationManager.AppSettings["DefaultBranch"] : branch;
            var repoInfo = new RepoInfo(repo, branch);

            var resourceInfo = this.FileManager.GetResourceInfo(repo);
            if (resourceInfo.Type != ResourceType.Directory)
            {
                return HttpNotFound();
            }

            AddRepoBreadCrumb(repoInfo);

            var lastCommit = GitUtilities.GetLogEntries(resourceInfo.FullPath, 1, 0, branch).FirstOrDefault();

            ViewBag.RepoName = resourceInfo.Name;
            ViewBag.LastCommit = lastCommit;
            ViewBag.CurrentTree = lastCommit != null ? GitUtilities.GetTreeInfo(resourceInfo.FullPath, branch) : null;
            ViewBag.Refs = GitUtilities.GetAllRefs(resourceInfo.FullPath);
            ViewBag.Branch = branch;

            ViewBag.CloneUri = PathUtilities.ParseCloneUrl(User, repoInfo);

            return View();
        }
            /// <summary>
            /// Check for deleted and modified folders and files.
            /// </summary>
            public void FindModifiedOrDeletedLocalObjects(RepoInfo repoInfo, String rootFolder, ref List<string> deletedFolders,
                ref List<string> deletedFiles, ref List<string> modifiedFiles)
            {
                // Crawl through all entries in the database, and record the ones that have changed on the filesystem.
                // Check for deleted folders.
                var folders = database.GetLocalFolders();
                foreach (string folder in folders)
                {
                    if (!Directory.Exists(Utils.PathCombine(rootFolder, folder)))
                    {
                        deletedFolders.Add(folder);
                    }
                }
                var files = database.GetChecksummedFiles();
                foreach (ChecksummedFile file in files)
                {
                    // Check for deleted files.
                    if (File.Exists(Path.Combine(rootFolder, file.RelativePath)))
                    {
                        // Check for modified files.
                        if (file.HasChanged(rootFolder))
                        {
                            modifiedFiles.Add(file.RelativePath);
                        }
                    }
                    else
                    {
                        deletedFiles.Add(file.RelativePath);
                    }
                }

                // Ignore deleted files and folders that are sub-items of a deleted folder.
                // Folder removal is done recursively so removing sub-items would be redundant.

                foreach (string deletedFolder in new List<string>(deletedFolders)) // Copy the list to avoid modifying it while iterating.
                {
                    // Ignore deleted files contained in the deleted folder.
                    deletedFiles.RemoveAll(deletedFile => deletedFile.StartsWith(deletedFolder));

                    // Ignore deleted folders contained in the deleted folder.
                    deletedFolders.RemoveAll(otherDeletedFolder => Utils.FirstFolderContainsSecond(deletedFolder, otherDeletedFolder));
                }
            }
            /// <summary>
            ///  Constructor for Repo (at every launch of CmisSync)
            /// </summary>
            public SynchronizedFolder(RepoInfo repoInfo, RepoBase repoCmis)
            {
                if (null == repoInfo || null == repoCmis)
                {
                    throw new ArgumentNullException("repoInfo");
                }

                this.repo = repoCmis;
                this.repoinfo = repoInfo;

                // Database is the user's AppData/Roaming
                database = new Database(repoinfo.CmisDatabase);

                // Get path on remote repository.
                remoteFolderPath = repoInfo.RemotePath;

                cmisParameters = new Dictionary<string, string>();
                cmisParameters[SessionParameter.BindingType] = BindingType.AtomPub;
                cmisParameters[SessionParameter.AtomPubUrl] = repoInfo.Address.ToString();
                cmisParameters[SessionParameter.User] = repoInfo.User;
                cmisParameters[SessionParameter.Password] = repoInfo.Password.ToString();
                cmisParameters[SessionParameter.RepositoryId] = repoInfo.RepoID;
                cmisParameters[SessionParameter.ConnectTimeout] = "-1";

                foreach (string ignoredFolder in repoInfo.getIgnoredPaths())
                {
                    Logger.Info("The folder \"" + ignoredFolder + "\" will be ignored");
                }

                syncWorker = new BackgroundWorker();
                syncWorker.WorkerSupportsCancellation = true;
                syncWorker.DoWork += new DoWorkEventHandler(
                    delegate(Object o, DoWorkEventArgs args)
                    {
                        bool syncFull = (bool)args.Argument;
                        try
                        {
                            Sync(syncFull);
                        }
                        catch (OperationCanceledException e)
                        {
                            Logger.Info(e.Message);
                        }
                        catch (CmisPermissionDeniedException e)
                        {
                            repo.OnSyncError(new PermissionDeniedException("Authentication failed.", e));
                        }
                        catch (Exception e)
                        {
                            repo.OnSyncError(new BaseException(e));
                        }
                        finally
                        {
                            SyncComplete(syncFull);
                        }
                    }
                );
            }
Beispiel #25
0
 /// <summary>
 /// Constructor.
 /// </summary>
 public CmisRepo(RepoInfo repoInfo, IActivityListener activityListener)
     : base(repoInfo, activityListener)
 {
     this.synchronizedFolder = new SynchronizedFolder(repoInfo, this);
     Logger.Info(synchronizedFolder);
 }
 private TestRepository CreateRepo() {
     var info = new RepoInfo {
         LocalPath = this.localPath,
         Address = this.remoteUrl,
         DisplayName = this.name
     };
     return new TestRepository(info);
 }
 /// <summary>
 /// This method is called, every time the config changes
 /// </summary>
 private bool RepoInfoChanged(ISyncEvent e)
 {
     if (e is RepoConfigChangedEvent)
     {
         repoinfo = (e as RepoConfigChangedEvent).RepoInfo;
         UpdateCmisParameters();
         ForceFullSyncAtNextSync();
     }
     return false;
 }
Beispiel #28
0
        /// <summary>
        /// Guess the web address where files can be seen using a browser.
        /// Not bulletproof. It depends on the server, and on some servers there is no web UI at all.
        /// </summary>
        static public string GetBrowsableURL(RepoInfo repo)
        {
            if (null == repo)
            {
                throw new ArgumentNullException("repo");
            }

            // Case of Alfresco.
            string suffix1 = "alfresco/cmisatom";
            string suffix2 = "alfresco/service/cmis";
            if (repo.Address.AbsoluteUri.EndsWith(suffix1) || repo.Address.AbsoluteUri.EndsWith(suffix2))
            {
                // Detect suffix length.
                int suffixLength = 0;
                if (repo.Address.AbsoluteUri.EndsWith(suffix1))
                    suffixLength = suffix1.Length;
                if (repo.Address.AbsoluteUri.EndsWith(suffix2))
                    suffixLength = suffix2.Length;

                string root = repo.Address.AbsoluteUri.Substring(0, repo.Address.AbsoluteUri.Length - suffixLength);
                if (repo.RemotePath.StartsWith("/Sites"))
                {
                    // Case of Alfresco Share.

                    // Example RemotePath: /Sites/thesite
                    // Result: http://server/share/page/site/thesite/documentlibrary
                    // Example RemotePath: /Sites/thesite/documentLibrary/somefolder/anotherfolder
                    // Result: http://server/share/page/site/thesite/documentlibrary#filter=path|%2Fsomefolder%2Fanotherfolder
                    // Example RemotePath: /Sites/s1/documentLibrary/éß和ệ
                    // Result: http://server/share/page/site/s1/documentlibrary#filter=path|%2F%25E9%25DF%25u548C%25u1EC7
                    // Example RemotePath: /Sites/s1/documentLibrary/a#bc/éß和ệ
                    // Result: http://server/share/page/site/thesite/documentlibrary#filter=path%7C%2Fa%2523bc%2F%25E9%25DF%25u548C%25u1EC7%7C

                    string path = repo.RemotePath.Substring("/Sites/".Length);
                    if (path.Contains("documentLibrary"))
                    {
                        int firstSlashPosition = path.IndexOf('/');
                        string siteName = path.Substring(0, firstSlashPosition);
                        string pathWithinSite = path.Substring(firstSlashPosition + "/documentLibrary".Length);
                        string escapedPathWithinSite = HttpUtility.UrlEncode(pathWithinSite);
                        string reescapedPathWithinSite = HttpUtility.UrlEncode(escapedPathWithinSite);
                        string sharePath = reescapedPathWithinSite.Replace("%252f", "%2F");
                        sharePath = sharePath.Replace("%2b", "%20");
                        return root + "share/page/site/" + siteName + "/documentlibrary#filter=path|" + sharePath;
                    }
                    else
                    {
                        // Site name only.
                        return root + "share/page/site/" + path + "/documentlibrary";
                    }
                }
                else
                {
                    // Case of Alfresco Web Client. Difficult to build a direct URL, so return root.
                    return root;
                }
            }
            else
            {
                // Another server was detected, try to open the thinclient url, otherwise try to open the repo path

                try
                {
                    // Connect to the CMIS repository.
                    ISession session = Auth.Auth.GetCmisSession(repo.Address.ToString(), repo.User, repo.Password.ToString(), repo.RepoID);

                    if (session.RepositoryInfo.ThinClientUri == null
                        || String.IsNullOrEmpty(session.RepositoryInfo.ThinClientUri.ToString()))
                    {
                        Logger.Error("CmisUtils GetBrowsableURL | Repository does not implement ThinClientUri: " + repo.Address.AbsoluteUri);
                        return repo.Address.AbsoluteUri + repo.RemotePath;
                    }
                    else
                    {
                        // Return CmisServer-provided thin URL.
                        return session.RepositoryInfo.ThinClientUri.ToString();
                    }
                }
                catch (Exception e)
                {
                    Logger.Error("CmisUtils GetBrowsableURL | Exception " + e.Message, e);
                    // Server down or authentication problem, no way to know the right URL, so just open server.
                    return repo.Address.AbsoluteUri + repo.RemotePath;
                }
            }
        }
        private void SetupMocks() {
            this.listener = new ActivityListenerAggregator(Mock.Of<IActivityListener>(), new TransmissionManager());
            var subfolder = Guid.NewGuid().ToString();
            this.queue = new SingleStepEventQueue(new SyncEventManager());
            this.queue.SwallowExceptions = true;
            this.repoInfo = new RepoInfo {
                AuthenticationType = AuthenticationType.BASIC,
                LocalPath = Path.Combine(config[1].ToString(), subfolder),
                RemotePath = config[2].ToString() + "/" + subfolder,
                Address = new XmlUri(new Uri(config[3].ToString())),
                User = config[4].ToString(),
                RepositoryId = config[6].ToString()
            };

            // FileSystemDir
            this.localPath = new DirectoryInfo(this.repoInfo.LocalPath);
            this.localPath.Create();
            if (!new DirectoryInfoWrapper(this.localPath).IsExtendedAttributeAvailable()) {
                Assert.Fail(string.Format("The local path {0} does not support extended attributes", this.localPath.FullName));
            }
        }
Beispiel #30
0
 public ProposalExampleModel(ScenarioModel parentScenario, MapProposalExampleModel source, MapModel map, RepoInfo repo)
     : base(parentScenario.Id + "-" + source.ProposalId, repo)
 {
     ParentScenario = parentScenario;
     ProposalId     = source.ProposalId;
     Info           = map.Proposals?.FirstOrDefault(i => i.Id == source.ProposalId);
 }
Beispiel #31
0
 /// <summary>
 /// Constructor.
 /// </summary>
 public CmisRepo(RepoInfo repoInfo, IActivityListener activityListener)
     : base(repoInfo)
 {
     this.synchronizedFolder = new SynchronizedFolder(repoInfo, activityListener, this);
     Logger.Info(synchronizedFolder);
 }
 public ContentService(RepoInfo repo)
 {
     Repo = repo;
 }
Beispiel #33
0
            /// <summary>
            ///  Update Settings.
            /// </summary>
            public void UpdateSettings(RepoInfo repoInfo)
            {
                //Cancel sync before settings update.
                CancelSync();

                //Set the cmis session to null
                session = null;

                this.repoinfo = repoInfo;
            }
        //  This method duplicates a lot of logic from the CLI in order to test generating deps files for tools in the SDK repo
        private CommandResult GenerateDepsAndRunTool(TestProject toolProject, [CallerMemberName] string callingMethod = "")
        {
            DeleteFolder(Path.Combine(RepoInfo.NuGetCachePath, toolProject.Name.ToLowerInvariant()));
            DeleteFolder(Path.Combine(RepoInfo.NuGetCachePath, ".tools", toolProject.Name.ToLowerInvariant()));

            var toolProjectInstance = _testAssetsManager.CreateTestProject(toolProject, callingMethod, identifier: toolProject.Name)
                                      .Restore(Log, toolProject.Name);

            var packCommand = new PackCommand(Log, Path.Combine(toolProjectInstance.TestRoot, toolProject.Name));

            packCommand.Execute()
            .Should()
            .Pass();

            string nupkgPath = Path.Combine(packCommand.ProjectRootPath, "bin", "Debug");

            TestProject toolReferencer = new TestProject()
            {
                Name             = "ToolReferencer",
                IsSdkProject     = true,
                TargetFrameworks = "netcoreapp2.0"
            };

            var toolReferencerInstance = _testAssetsManager.CreateTestProject(toolReferencer, callingMethod, identifier: toolReferencer.Name)
                                         .WithProjectChanges(project =>
            {
                var ns = project.Root.Name.Namespace;

                var itemGroup = new XElement(ns + "ItemGroup");
                project.Root.Add(itemGroup);

                itemGroup.Add(new XElement(ns + "DotNetCliToolReference",
                                           new XAttribute("Include", toolProject.Name),
                                           new XAttribute("Version", "1.0.0")));
            });

            var restoreCommand = toolReferencerInstance.GetRestoreCommand(Log, toolReferencer.Name);

            restoreCommand.AddSource(nupkgPath);
            restoreCommand.Execute().Should().Pass();

            string toolAssetsFilePath = Path.Combine(RepoInfo.NuGetCachePath, ".tools", toolProject.Name.ToLowerInvariant(), "1.0.0", toolProject.TargetFrameworks, "project.assets.json");
            var    toolAssetsFile     = new LockFileFormat().Read(toolAssetsFilePath);

            var args = new List <string>();

            string generateDepsProjectPath = Path.Combine(RepoInfo.SdksPath, "Microsoft.NET.Sdk", "build", "GenerateDeps", "GenerateDeps.proj");

            args.Add($"/p:ProjectAssetsFile=\"{toolAssetsFilePath}\"");

            args.Add($"/p:ToolName={toolProject.Name}");

            string depsFilePath = Path.Combine(Path.GetDirectoryName(toolAssetsFilePath), toolProject.Name + ".deps.json");

            args.Add($"/p:ProjectDepsFilePath={depsFilePath}");

            var toolTargetFramework = toolAssetsFile.Targets.First().TargetFramework.GetShortFolderName();

            args.Add($"/p:TargetFramework={toolProject.TargetFrameworks}");

            //  Look for the .props file in the Microsoft.NETCore.App package, until NuGet
            //  generates .props and .targets files for tool restores (https://github.com/NuGet/Home/issues/5037)
            var platformLibrary = toolAssetsFile.Targets
                                  .Single()
                                  .Libraries
                                  .FirstOrDefault(e => e.Name.Equals("Microsoft.NETCore.App", StringComparison.OrdinalIgnoreCase));

            if (platformLibrary != null)
            {
                string buildRelativePath = platformLibrary.Build.FirstOrDefault()?.Path;

                var platformLibraryPath = GetPackageDirectory(toolAssetsFile, platformLibrary);

                if (platformLibraryPath != null && buildRelativePath != null)
                {
                    //  Get rid of "_._" filename
                    buildRelativePath = Path.GetDirectoryName(buildRelativePath);

                    string platformLibraryBuildFolderPath = Path.Combine(platformLibraryPath, buildRelativePath);
                    var    platformLibraryPropsFile       = Directory.GetFiles(platformLibraryBuildFolderPath, "*.props").FirstOrDefault();

                    if (platformLibraryPropsFile != null)
                    {
                        args.Add($"/p:AdditionalImport={platformLibraryPropsFile}");
                    }
                }
            }

            var generateDepsCommand = new MSBuildCommand(Log, "BuildDepsJson", generateDepsProjectPath);

            generateDepsCommand.Execute(args.ToArray())
            .Should()
            .Pass();

            var toolLibrary = toolAssetsFile.Targets
                              .Single()
                              .Libraries.FirstOrDefault(
                l => StringComparer.OrdinalIgnoreCase.Equals(l.Name, toolProject.Name));

            var toolAssembly = toolLibrary?.RuntimeAssemblies
                               .FirstOrDefault(r => Path.GetFileNameWithoutExtension(r.Path) == toolProject.Name);

            var toolPackageDirectory = GetPackageDirectory(toolAssetsFile, toolLibrary);

            var toolAssemblyPath = Path.Combine(
                toolPackageDirectory,
                toolAssembly.Path);

            var dotnetArgs = new List <string>();

            dotnetArgs.Add("exec");

            dotnetArgs.Add("--depsfile");
            dotnetArgs.Add(depsFilePath);

            foreach (var packageFolder in GetNormalizedPackageFolders(toolAssetsFile))
            {
                dotnetArgs.Add("--additionalprobingpath");
                dotnetArgs.Add(packageFolder);
            }

            dotnetArgs.Add(Path.GetFullPath(toolAssemblyPath));

            ICommand toolCommand = Command.Create(RepoInfo.DotNetHostPath, dotnetArgs)
                                   .CaptureStdOut();

            toolCommand = RepoInfo.AddTestEnvironmentVariables(toolCommand);


            var toolResult = toolCommand.Execute();

            return(toolResult);
        }
 public TestRepository(RepoInfo info) : base(info) {
 }
        public static string GetExtractDestinationFolder(RepoInfo repo)
        {
            string answer = Environment.GetEnvironmentVariable("LocalAppData") + $"\\Repos\\{repo.UrlHash()}";

            return(answer);
        }
Beispiel #37
0
        /// <summary>
        /// Guess the web address where files can be seen using a browser.
        /// Not bulletproof. It depends on the server, and there is no web UI at all.
        /// </summary>
        static public string GetBrowsableURL(RepoInfo repo)
        {
            if (null == repo)
            {
                throw new ArgumentNullException("repo");
            }

            // Case of Alfresco.
            if (repo.Address.AbsoluteUri.EndsWith("alfresco/cmisatom"))
            {
                string root = repo.Address.AbsoluteUri.Substring(0, repo.Address.AbsoluteUri.Length - "alfresco/cmisatom".Length);
                if (repo.RemotePath.StartsWith("/Sites"))
                {
                    // Case of Alfresco Share.

                    // Example RemotePath: /Sites/thesite
                    // Result: http://server/share/page/site/thesite/documentlibrary
                    // Example RemotePath: /Sites/thesite/documentLibrary/somefolder/anotherfolder
                    // Result: http://server/share/page/site/thesite/documentlibrary#filter=path|%2Fsomefolder%2Fanotherfolder
                    // Example RemotePath: /Sites/s1/documentLibrary/éß和ệ
                    // Result: http://server/share/page/site/s1/documentlibrary#filter=path|%2F%25E9%25DF%25u548C%25u1EC7
                    // Example RemotePath: /Sites/s1/documentLibrary/a#bc/éß和ệ
                    // Result: http://server/share/page/site/thesite/documentlibrary#filter=path%7C%2Fa%2523bc%2F%25E9%25DF%25u548C%25u1EC7%7C

                    string path = repo.RemotePath.Substring("/Sites/".Length);
                    if (path.Contains("documentLibrary"))
                    {
                        int firstSlashPosition = path.IndexOf('/');
                        string siteName = path.Substring(0, firstSlashPosition);
                        string pathWithinSite = path.Substring(firstSlashPosition + "/documentLibrary".Length);
                        string escapedPathWithinSite = HttpUtility.UrlEncode(pathWithinSite);
                        string reescapedPathWithinSite = HttpUtility.UrlEncode(escapedPathWithinSite);
                        string sharePath = reescapedPathWithinSite.Replace("%252f", "%2F");
                        return root + "share/page/site/" + siteName + "/documentlibrary#filter=path|" + sharePath;
                    }
                    else
                    {
                        // Site name only.
                        return root + "share/page/site/" + path + "/documentlibrary";
                    }
                }
                else
                {
                    // Case of Alfresco Web Client.
                    return root;
                }
            }
            else
            {
                // If no particular server was detected, concatenate and hope it will hit close, maybe to a page that allows to access the folder with a few clicks.
                return repo.Address.AbsoluteUri + repo.RemotePath;
            }
        }
Beispiel #38
0
 private static string GetProductRepoName(RepoInfo repo)
 {
     return(repo.Name.Substring(0, repo.Name.LastIndexOf('/')));
 }