From 26fa50ca66af0d882b45ee41fc45f691e655907b Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Mon, 11 Sep 2017 19:53:32 -0400 Subject: [PATCH 001/241] Functionality to swith to authentication view on api failure --- src/GitHub.Api/Application/ApiClient.cs | 30 ++++++++++++------- src/GitHub.Api/Application/IApiClient.cs | 2 +- .../Editor/GitHub.Unity/UI/PublishView.cs | 4 +++ 3 files changed, 24 insertions(+), 12 deletions(-) diff --git a/src/GitHub.Api/Application/ApiClient.cs b/src/GitHub.Api/Application/ApiClient.cs index c4ae1782d..c8a8db630 100644 --- a/src/GitHub.Api/Application/ApiClient.cs +++ b/src/GitHub.Api/Application/ApiClient.cs @@ -27,7 +27,6 @@ public static IApiClient Create(UriString repositoryUrl, IKeychain keychain) private readonly IKeychain keychain; private readonly IGitHubClient githubClient; private readonly ILoginManager loginManager; - private static readonly SemaphoreSlim sem = new SemaphoreSlim(1); IList organizationsCache; Octokit.User userCache; @@ -72,11 +71,10 @@ public async Task CreateRepository(NewRepository newRepository, Action> callback) + public async Task GetOrganizations(Action> onSuccess, Action onNeedsAuth = null, Action onError = null) { - Guard.ArgumentNotNull(callback, "callback"); - var organizations = await GetOrganizationInternal(); - callback(organizations); + Guard.ArgumentNotNull(onSuccess, "callback"); + await GetOrganizationInternal(onSuccess, onNeedsAuth, onError); } public async Task LoadKeychain(Action callback) @@ -224,7 +222,7 @@ public async Task ContinueLoginAsync(LoginResult loginResult, Func> GetOrganizationInternal() + private async Task GetOrganizationInternal(Action> onSuccess, Action onNeedsAuth = null, Action onError = null) { try { @@ -232,7 +230,8 @@ private async Task> GetOrganizationInternal() if (!await LoadKeychainInternal()) { - return new List(); + onSuccess(new List()); + return; } var organizations = await githubClient.Organization.GetAllForCurrent(); @@ -244,13 +243,22 @@ private async Task> GetOrganizationInternal() organizationsCache = organizations.ToArray(); } } - catch(Exception ex) + catch (LoginAttemptsExceededException) { - logger.Error(ex, "Error Getting Organizations"); - throw; + logger.Warning("Authentication Failed; Clearing Keychain"); + + var uriString = keychain.Hosts.First(); + await keychain.Clear(uriString, false); + + onNeedsAuth?.Invoke(); + } + catch (Exception ex) + { + logger.Error(ex, "Error Getting Organizations: {0}", ex.GetType().Name); + onError?.Invoke(ex); } - return organizationsCache; + onSuccess(organizationsCache); } private async Task GetCurrentUserInternal() diff --git a/src/GitHub.Api/Application/IApiClient.cs b/src/GitHub.Api/Application/IApiClient.cs index 1ebbcd414..7d897c61f 100644 --- a/src/GitHub.Api/Application/IApiClient.cs +++ b/src/GitHub.Api/Application/IApiClient.cs @@ -10,7 +10,7 @@ interface IApiClient HostAddress HostAddress { get; } UriString OriginalUrl { get; } Task CreateRepository(NewRepository newRepository, Action callback, string organization = null); - Task GetOrganizations(Action> callback); + Task GetOrganizations(Action> onSuccess, Action onNeedsAuth = null, Action onError = null); Task Login(string username, string password, Action need2faCode, Action result); Task ContinueLogin(LoginResult loginResult, string code); Task LoginAsync(string username, string password, Func need2faCode); diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs index addb84e63..0d644d333 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs @@ -122,6 +122,10 @@ private void LoadOrganizations() owners = new[] { OwnersDefaultText, username }.Union(organizationLogins).ToArray(); isBusy = false; + }, () => { + PopupWindow.Open(PopupWindow.PopupViewType.AuthenticationView); + }, exception => { + }); }); } From 90d1f0c52ad17e6b220876f4c5c4b269a7893b71 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Mon, 11 Sep 2017 19:59:59 -0400 Subject: [PATCH 002/241] Adding an additional exception --- src/GitHub.Api/Application/ApiClient.cs | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/src/GitHub.Api/Application/ApiClient.cs b/src/GitHub.Api/Application/ApiClient.cs index c8a8db630..a32a41aef 100644 --- a/src/GitHub.Api/Application/ApiClient.cs +++ b/src/GitHub.Api/Application/ApiClient.cs @@ -243,9 +243,18 @@ private async Task GetOrganizationInternal(Action> onSuccess organizationsCache = organizations.ToArray(); } } - catch (LoginAttemptsExceededException) + catch (AuthorizationException ex) { - logger.Warning("Authentication Failed; Clearing Keychain"); + logger.Warning("Authentication Failed; {0}; Clearing Keychain", ex.GetType().Name); + + var uriString = keychain.Hosts.First(); + await keychain.Clear(uriString, false); + + onNeedsAuth?.Invoke(); + } + catch (LoginAttemptsExceededException ex) + { + logger.Warning("Authentication Failed; {0}; Clearing Keychain", ex.GetType().Name); var uriString = keychain.Hosts.First(); await keychain.Clear(uriString, false); From abd832f21dae8cf1118fd531d2f4c7187dccaf82 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Mon, 18 Sep 2017 14:37:10 -0400 Subject: [PATCH 003/241] Fix needed after merge --- .../Assets/Editor/GitHub.Unity/UI/Window.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs index 3f6fc0518..14c212e36 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs @@ -462,11 +462,11 @@ private Subview ToView(SubTab tab) default: throw new ArgumentOutOfRangeException(); } + } - public override bool IsBusy - { - get { return false; } - } + public override bool IsBusy + { + get { return false; } } private enum SubTab From 6168309dc244f9c521fb19fd5f6e1afb20b0736c Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 7 Sep 2017 10:17:20 -0400 Subject: [PATCH 004/241] Adding configurations to init project view --- .../Editor/GitHub.Unity/UI/InitProjectView.cs | 62 +++++++++++++++++-- 1 file changed, 57 insertions(+), 5 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs index 38c186839..168b18f8d 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs @@ -1,5 +1,3 @@ -#pragma warning disable 649 - using System; using System.Collections.Generic; using System.Linq; @@ -14,7 +12,9 @@ class InitProjectView : Subview { private const string NoRepoTitle = "No Git repository found for this project"; private const string NoRepoDescription = "Initialize a Git repository to track changes and collaborate with others."; - + + [SerializeField] private UserSettingsView userSettingsView = new UserSettingsView(); + [SerializeField] private GitPathView gitPathView = new GitPathView(); [SerializeField] private bool isBusy; [SerializeField] private bool isPublished; @@ -24,15 +24,63 @@ public override void OnDataUpdate() MaybeUpdateData(); } + public override void InitializeView(IView parent) + { + base.InitializeView(parent); + userSettingsView.InitializeView(this); + gitPathView.InitializeView(this); + } + + public override void OnEnable() + { + base.OnEnable(); + userSettingsView.OnEnable(); + gitPathView.OnEnable(); + } + + public override void OnDisable() + { + base.OnDisable(); + userSettingsView.OnDisable(); + gitPathView.OnDisable(); + } + + public override void OnDataUpdate() + { + base.OnDataUpdate(); + + if (userSettingsView != null) + { + userSettingsView.OnDataUpdate(); + } + + if (gitPathView != null) + { + gitPathView.OnDataUpdate(); + } + } + public override void OnRepositoryChanged(IRepository oldRepository) { base.OnRepositoryChanged(oldRepository); + + userSettingsView.OnRepositoryChanged(oldRepository); + gitPathView.OnRepositoryChanged(oldRepository); + Refresh(); } public override bool IsBusy { - get { return isBusy; } + get { return isBusy || userSettingsView.IsBusy || gitPathView.IsBusy; } + } + + public override void Refresh() + { + base.Refresh(); + + userSettingsView.Refresh(); + gitPathView.Refresh(); } public override void OnGUI() @@ -66,6 +114,10 @@ public override void OnGUI() } EditorGUILayout.EndHorizontal(); + gitPathView.OnGUI(); + + userSettingsView.OnGUI(); + GUILayout.BeginVertical(Styles.GenericBoxStyle); { GUILayout.FlexibleSpace(); @@ -75,7 +127,7 @@ public override void OnGUI() GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); - EditorGUI.BeginDisabledGroup(isBusy); + EditorGUI.BeginDisabledGroup(IsBusy); { if (GUILayout.Button(Localization.InitializeRepositoryButtonText, "Button")) { From 80539f90247ee430c20dee3ec3d2584eb4ebccfa Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 14 Sep 2017 15:38:14 -0400 Subject: [PATCH 005/241] Fixes to support initliazing the user before the project --- .../Editor/GitHub.Unity/UI/InitProjectView.cs | 83 +++++++++++++++++-- .../Editor/GitHub.Unity/UI/PopupWindow.cs | 8 +- .../GitHub.Unity/UI/UserSettingsView.cs | 44 ++++++---- 3 files changed, 111 insertions(+), 24 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs index 38c186839..32a8cec0e 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs @@ -1,11 +1,6 @@ -#pragma warning disable 649 - using System; -using System.Collections.Generic; -using System.Linq; using UnityEditor; using UnityEngine; -using Object = UnityEngine.Object; namespace GitHub.Unity { @@ -16,7 +11,25 @@ class InitProjectView : Subview private const string NoRepoDescription = "Initialize a Git repository to track changes and collaborate with others."; [SerializeField] private bool isBusy; - [SerializeField] private bool isPublished; + [SerializeField] private bool isUserDataPresent = true; + + [NonSerialized] private bool userDataHasChanged; + + public override void InitializeView(IView parent) + { + base.InitializeView(parent); + + if (!string.IsNullOrEmpty(Environment.GitExecutablePath)) + { + CheckForUser(); + } + } + + public override void OnEnable() + { + base.OnEnable(); + userDataHasChanged = Environment.GitExecutablePath != null; + } public override void OnDataUpdate() { @@ -68,6 +81,25 @@ public override void OnGUI() GUILayout.BeginVertical(Styles.GenericBoxStyle); { + if (!isUserDataPresent) + { + GUILayout.FlexibleSpace(); + + EditorGUI.BeginDisabledGroup(isBusy); + { + if (GUILayout.Button("Finish Git Configuration", "Button")) + { + PopupWindow.Open(PopupWindow.PopupViewType.UserSettingsView, completed => { + if (completed) + { + userDataHasChanged = true; + } + }); + } + } + EditorGUI.EndDisabledGroup(); + } + GUILayout.FlexibleSpace(); GUILayout.Label(NoRepoDescription, Styles.CenteredLabel); @@ -75,7 +107,7 @@ public override void OnGUI() GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); - EditorGUI.BeginDisabledGroup(isBusy); + EditorGUI.BeginDisabledGroup(isBusy || !isUserDataPresent); { if (GUILayout.Button(Localization.InitializeRepositoryButtonText, "Button")) { @@ -97,7 +129,42 @@ public override void OnGUI() private void MaybeUpdateData() { - isPublished = Repository != null && Repository.CurrentRemote.HasValue; + if (userDataHasChanged) + { + userDataHasChanged = false; + CheckForUser(); + } + } + + private void CheckForUser() + { + isBusy = true; + + string username = null; + string email = null; + + GitClient.GetConfig("user.name", GitConfigSource.User).Then((success, value) => { + Logger.Trace("Return success:{0} user.name", success, value); + if (success) + { + username = value; + } + }).Then(GitClient.GetConfig("user.email", GitConfigSource.User).Then((success, value) => { + Logger.Trace("Return success:{0} user.email", success, value); + if (success) + { + email = value; + } + })).FinallyInUI((success, ex) => { + Logger.Trace("Return success:{0} name:{1} email:{2}", success, username, email); + + isBusy = false; + isUserDataPresent = success && !String.IsNullOrEmpty(username) && !String.IsNullOrEmpty(email); + + Logger.Trace("Finally: {0}", isUserDataPresent); + + Redraw(); + }).Start(); } } } diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PopupWindow.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PopupWindow.cs index 9ee629ca9..c11ef5373 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PopupWindow.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PopupWindow.cs @@ -11,12 +11,14 @@ public enum PopupViewType { None, PublishView, - AuthenticationView + AuthenticationView, + UserSettingsView } [SerializeField] private PopupViewType activeViewType; [SerializeField] private AuthenticationView authenticationView; + [SerializeField] private UserSettingsView userSettingsView; [SerializeField] private PublishView publishView; [SerializeField] private LoadingView loadingView; @@ -52,10 +54,12 @@ public override void Initialize(IApplicationManager applicationManager) { base.Initialize(applicationManager); + userSettingsView = userSettingsView ?? new UserSettingsView(); publishView = publishView ?? new PublishView(); authenticationView = authenticationView ?? new AuthenticationView(); loadingView = loadingView ?? new LoadingView(); + userSettingsView.InitializeView(this); publishView.InitializeView(this); authenticationView.InitializeView(this); loadingView.InitializeView(this); @@ -123,6 +127,8 @@ private Subview ActiveView return publishView; case PopupViewType.AuthenticationView: return authenticationView; + case PopupViewType.UserSettingsView: + return userSettingsView; default: return loadingView; } diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/UserSettingsView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/UserSettingsView.cs index 8d50a9cdc..0044e78fe 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/UserSettingsView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/UserSettingsView.cs @@ -11,6 +11,9 @@ namespace GitHub.Unity [Serializable] class UserSettingsView : Subview { + private static readonly Vector2 viewSize = new Vector2(325, 125); + private const string WindowTitle = "User Settings"; + private const string GitConfigTitle = "Git Configuration"; private const string GitConfigNameLabel = "Name"; private const string GitConfigEmailLabel = "Email"; @@ -26,6 +29,13 @@ class UserSettingsView : Subview [SerializeField] private string newGitEmail; [SerializeField] private User cachedUser; + public override void InitializeView(IView parent) + { + base.InitializeView(parent); + Title = WindowTitle; + Size = viewSize; + } + public override void OnDataUpdate() { base.OnDataUpdate(); @@ -99,6 +109,7 @@ public override void OnGUI() { isBusy = false; Redraw(); + Finish(true); }) .Start(); } @@ -117,23 +128,26 @@ private void MaybeUpdateData() { if (Repository == null) { - if ((cachedUser == null || String.IsNullOrEmpty(cachedUser.Name)) && GitClient != null) + if (!String.IsNullOrEmpty(EntryPoint.Environment.GitExecutablePath)) { - var user = new User(); - GitClient.GetConfig("user.name", GitConfigSource.User) - .Then((success, value) => user.Name = value).Then( - GitClient.GetConfig("user.email", GitConfigSource.User) - .Then((success, value) => user.Email = value)) - .FinallyInUI((success, ex) => + if ((cachedUser == null || String.IsNullOrEmpty(cachedUser.Name)) && GitClient != null) { - if (success && !String.IsNullOrEmpty(user.Name)) - { - cachedUser = user; - userDataHasChanged = true; - Redraw(); - } - }) - .Start(); + var user = new User(); + GitClient.GetConfig("user.name", GitConfigSource.User) + .Then((success, value) => user.Name = value).Then( + GitClient.GetConfig("user.email", GitConfigSource.User) + .Then((success, value) => user.Email = value)) + .FinallyInUI((success, ex) => + { + if (success && !String.IsNullOrEmpty(user.Name)) + { + cachedUser = user; + userDataHasChanged = true; + Redraw(); + } + }) + .Start(); + } } if (userDataHasChanged) From e09d1cd20a92503f8c9afd754474da6dd936ddda Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Mon, 18 Sep 2017 15:14:00 -0400 Subject: [PATCH 006/241] Fixes needed after merge --- .../Assets/Editor/GitHub.Unity/UI/Window.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs index 3f6fc0518..14c212e36 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs @@ -462,11 +462,11 @@ private Subview ToView(SubTab tab) default: throw new ArgumentOutOfRangeException(); } + } - public override bool IsBusy - { - get { return false; } - } + public override bool IsBusy + { + get { return false; } } private enum SubTab From fd1165f9c33a850c49997e2c4a110b0ba1c80d19 Mon Sep 17 00:00:00 2001 From: Andreia Gaita Date: Tue, 19 Sep 2017 14:16:47 +0200 Subject: [PATCH 007/241] A cache manager --- .../Application/ApplicationManagerBase.cs | 8 ++++ .../Application/IApplicationManager.cs | 1 + src/GitHub.Api/Cache/CacheManager.cs | 46 +++++++++++++++++++ src/GitHub.Api/GitHub.Api.csproj | 1 + 4 files changed, 56 insertions(+) create mode 100644 src/GitHub.Api/Cache/CacheManager.cs diff --git a/src/GitHub.Api/Application/ApplicationManagerBase.cs b/src/GitHub.Api/Application/ApplicationManagerBase.cs index d48a008d9..be2643197 100644 --- a/src/GitHub.Api/Application/ApplicationManagerBase.cs +++ b/src/GitHub.Api/Application/ApplicationManagerBase.cs @@ -12,6 +12,7 @@ abstract class ApplicationManagerBase : IApplicationManager protected static ILogging Logger { get; } = Logging.GetLogger(); private RepositoryManager repositoryManager; + private IBranchCache branchCache; public ApplicationManagerBase(SynchronizationContext synchronizationContext) { @@ -21,6 +22,7 @@ public ApplicationManagerBase(SynchronizationContext synchronizationContext) UIScheduler = TaskScheduler.FromCurrentSynchronizationContext(); ThreadingHelper.MainThreadScheduler = UIScheduler; TaskManager = new TaskManager(UIScheduler); + CacheManager = new CacheManager(); } protected void Initialize() @@ -80,6 +82,11 @@ private async Task SetupGit() } + public void SetupCache(IBranchCache bcache) + { + branchCache = bcache; + } + public ITask InitializeRepository() { Logger.Trace("Running Repository Initialize"); @@ -214,6 +221,7 @@ public void Dispose() public ISettings LocalSettings { get; protected set; } public ISettings SystemSettings { get; protected set; } public ISettings UserSettings { get; protected set; } + public CacheManager CacheManager { get; private set; } public IUsageTracker UsageTracker { get; protected set; } protected TaskScheduler UIScheduler { get; private set; } diff --git a/src/GitHub.Api/Application/IApplicationManager.cs b/src/GitHub.Api/Application/IApplicationManager.cs index fd59878a8..7ae10272f 100644 --- a/src/GitHub.Api/Application/IApplicationManager.cs +++ b/src/GitHub.Api/Application/IApplicationManager.cs @@ -15,6 +15,7 @@ public interface IApplicationManager : IDisposable ISettings LocalSettings { get; } ISettings UserSettings { get; } ITaskManager TaskManager { get; } + CacheManager CacheManager { get; } IGitClient GitClient { get; } IUsageTracker UsageTracker { get; } diff --git a/src/GitHub.Api/Cache/CacheManager.cs b/src/GitHub.Api/Cache/CacheManager.cs new file mode 100644 index 000000000..11e038756 --- /dev/null +++ b/src/GitHub.Api/Cache/CacheManager.cs @@ -0,0 +1,46 @@ +using System; +using System.Linq; + +namespace GitHub.Unity +{ + class CacheManager + { + private IBranchCache branchCache; + public IBranchCache BranchCache + { + get { return branchCache; } + set + { + if (branchCache == null) + branchCache = value; + } + } + + private Action onLocalBranchListChanged; + + public void SetupCache(IBranchCache branchCache, IRepository repository) + { + if (repository == null) + return; + + BranchCache = branchCache; + UpdateCache(repository); + if (onLocalBranchListChanged != null) + repository.OnLocalBranchListChanged -= onLocalBranchListChanged; + onLocalBranchListChanged = () => + { + if (!ThreadingHelper.InUIThread) + new ActionTask(TaskManager.Instance.Token, () => UpdateCache(repository)) { Affinity = TaskAffinity.UI }.Start(); + else + UpdateCache(repository); + }; + repository.OnLocalBranchListChanged += onLocalBranchListChanged; + } + + private void UpdateCache(IRepository repository) + { + BranchCache.LocalBranches = repository.LocalBranches.ToList(); + BranchCache.RemoteBranches = repository.RemoteBranches.ToList(); + } + } +} \ No newline at end of file diff --git a/src/GitHub.Api/GitHub.Api.csproj b/src/GitHub.Api/GitHub.Api.csproj index a87766cee..8539e9725 100644 --- a/src/GitHub.Api/GitHub.Api.csproj +++ b/src/GitHub.Api/GitHub.Api.csproj @@ -110,6 +110,7 @@ + From 9775a0e02c9bf9cca8723e203993d377bfe5819c Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Tue, 19 Sep 2017 15:59:31 -0400 Subject: [PATCH 008/241] Changing popup button functionality to display an error label instead --- .../Assets/Editor/GitHub.Unity/Misc/Styles.cs | 17 +++++++++ .../Editor/GitHub.Unity/UI/InitProjectView.cs | 37 +++++++++---------- .../Editor/GitHub.Unity/UI/PopupWindow.cs | 6 --- 3 files changed, 35 insertions(+), 25 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/Misc/Styles.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/Misc/Styles.cs index a4c57790a..6df7855b9 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/Misc/Styles.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/Misc/Styles.cs @@ -53,6 +53,7 @@ class Styles private static GUIStyle label, boldLabel, + centeredErrorLabel, errorLabel, deletedFileLabel, longMessageStyle, @@ -337,6 +338,22 @@ public static GUIStyle ErrorLabel } } + public static GUIStyle CenteredErrorLabel + { + get + { + if (centeredErrorLabel == null) + { + centeredErrorLabel = new GUIStyle(EditorStyles.label); + centeredErrorLabel.alignment = TextAnchor.MiddleCenter; + centeredErrorLabel.name = "CenteredErrorLabel"; + centeredErrorLabel.wordWrap = true; + centeredErrorLabel.normal.textColor = Color.red; + } + return centeredErrorLabel; + } + } + public static GUIStyle LongMessageStyle { get diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs index 32a8cec0e..0cecf0b87 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs @@ -9,10 +9,12 @@ class InitProjectView : Subview { private const string NoRepoTitle = "No Git repository found for this project"; private const string NoRepoDescription = "Initialize a Git repository to track changes and collaborate with others."; + private const string NoUserOrEmailError = "Name and Email must be configured in Settings"; [SerializeField] private bool isBusy; [SerializeField] private bool isUserDataPresent = true; + [NonSerialized] private string errorMessage; [NonSerialized] private bool userDataHasChanged; public override void InitializeView(IView parent) @@ -81,25 +83,6 @@ public override void OnGUI() GUILayout.BeginVertical(Styles.GenericBoxStyle); { - if (!isUserDataPresent) - { - GUILayout.FlexibleSpace(); - - EditorGUI.BeginDisabledGroup(isBusy); - { - if (GUILayout.Button("Finish Git Configuration", "Button")) - { - PopupWindow.Open(PopupWindow.PopupViewType.UserSettingsView, completed => { - if (completed) - { - userDataHasChanged = true; - } - }); - } - } - EditorGUI.EndDisabledGroup(); - } - GUILayout.FlexibleSpace(); GUILayout.Label(NoRepoDescription, Styles.CenteredLabel); @@ -122,11 +105,26 @@ public override void OnGUI() GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); + ShowErrorMessage(); + GUILayout.FlexibleSpace(); } GUILayout.EndVertical(); } + private void ShowErrorMessage() + { + if (errorMessage != null) + { + GUILayout.Space(Styles.BaseSpacing); + GUILayout.BeginHorizontal(); + { + GUILayout.Label(errorMessage, Styles.CenteredErrorLabel); + } + GUILayout.EndHorizontal(); + } + } + private void MaybeUpdateData() { if (userDataHasChanged) @@ -160,6 +158,7 @@ private void CheckForUser() isBusy = false; isUserDataPresent = success && !String.IsNullOrEmpty(username) && !String.IsNullOrEmpty(email); + errorMessage = isUserDataPresent ? null : NoUserOrEmailError; Logger.Trace("Finally: {0}", isUserDataPresent); diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PopupWindow.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PopupWindow.cs index c11ef5373..c7cd2dc44 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PopupWindow.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PopupWindow.cs @@ -12,13 +12,11 @@ public enum PopupViewType None, PublishView, AuthenticationView, - UserSettingsView } [SerializeField] private PopupViewType activeViewType; [SerializeField] private AuthenticationView authenticationView; - [SerializeField] private UserSettingsView userSettingsView; [SerializeField] private PublishView publishView; [SerializeField] private LoadingView loadingView; @@ -54,12 +52,10 @@ public override void Initialize(IApplicationManager applicationManager) { base.Initialize(applicationManager); - userSettingsView = userSettingsView ?? new UserSettingsView(); publishView = publishView ?? new PublishView(); authenticationView = authenticationView ?? new AuthenticationView(); loadingView = loadingView ?? new LoadingView(); - userSettingsView.InitializeView(this); publishView.InitializeView(this); authenticationView.InitializeView(this); loadingView.InitializeView(this); @@ -127,8 +123,6 @@ private Subview ActiveView return publishView; case PopupViewType.AuthenticationView: return authenticationView; - case PopupViewType.UserSettingsView: - return userSettingsView; default: return loadingView; } From 02b2b9ea0ee063cf3c1ed529e2d8c2695f349241 Mon Sep 17 00:00:00 2001 From: Andreia Gaita Date: Wed, 20 Sep 2017 17:07:48 +0200 Subject: [PATCH 009/241] Throw if the manager isn't ready so that windows use their cached data instead --- src/GitHub.Api/Git/Repository.cs | 2 +- src/GitHub.Api/Helpers/TaskHelpers.cs | 12 ++++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/src/GitHub.Api/Git/Repository.cs b/src/GitHub.Api/Git/Repository.cs index 6da63347b..7ea6fc19b 100644 --- a/src/GitHub.Api/Git/Repository.cs +++ b/src/GitHub.Api/Git/Repository.cs @@ -82,7 +82,7 @@ public ITask SetupRemote(string remote, string remoteUrl) public ITask> Log() { if (repositoryManager == null) - return new FuncListTask(TaskHelpers.GetCompletedTask(new List())); + return new FuncListTask(new NotReadyException().ToTask>()); return repositoryManager.Log(); } diff --git a/src/GitHub.Api/Helpers/TaskHelpers.cs b/src/GitHub.Api/Helpers/TaskHelpers.cs index e1c6e301e..1698b92ab 100644 --- a/src/GitHub.Api/Helpers/TaskHelpers.cs +++ b/src/GitHub.Api/Helpers/TaskHelpers.cs @@ -1,3 +1,4 @@ +using System; using System.Threading.Tasks; namespace GitHub.Unity @@ -8,5 +9,16 @@ public static Task GetCompletedTask(T result) { return TaskEx.FromResult(result); } + + public static Task ToTask(this Exception exception) + { + TaskCompletionSource completionSource = new TaskCompletionSource(); + completionSource.TrySetException(exception); + return completionSource.Task; + } + } + + public class NotReadyException : Exception + { } } \ No newline at end of file From dd21f7118d2daf4e412f8d6ab9ca67c0a8116015 Mon Sep 17 00:00:00 2001 From: Andreia Gaita Date: Wed, 20 Sep 2017 17:53:56 +0200 Subject: [PATCH 010/241] We probably want to fail listing locks too --- src/GitHub.Api/Git/Repository.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/GitHub.Api/Git/Repository.cs b/src/GitHub.Api/Git/Repository.cs index 7ea6fc19b..e26cf1833 100644 --- a/src/GitHub.Api/Git/Repository.cs +++ b/src/GitHub.Api/Git/Repository.cs @@ -120,7 +120,7 @@ public ITask Revert(string changeset) public ITask ListLocks() { if (repositoryManager == null) - return new ActionTask(TaskExtensions.CompletedTask); + return new ActionTask(new NotReadyException().ToTask()); return repositoryManager.ListLocks(false); } From 8e9fee64f96dda92c245a629666e395131ac855f Mon Sep 17 00:00:00 2001 From: Don Okuda Date: Fri, 22 Sep 2017 13:38:21 -0700 Subject: [PATCH 011/241] Add spinner sprites --- .../Editor/GitHub.Unity/IconsAndLogos/spinner-sprite.png | 3 +++ .../Editor/GitHub.Unity/IconsAndLogos/spinner-sprite@2x.png | 3 +++ 2 files changed, 6 insertions(+) create mode 100644 src/UnityExtension/Assets/Editor/GitHub.Unity/IconsAndLogos/spinner-sprite.png create mode 100644 src/UnityExtension/Assets/Editor/GitHub.Unity/IconsAndLogos/spinner-sprite@2x.png diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/IconsAndLogos/spinner-sprite.png b/src/UnityExtension/Assets/Editor/GitHub.Unity/IconsAndLogos/spinner-sprite.png new file mode 100644 index 000000000..d0304b8e2 --- /dev/null +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/IconsAndLogos/spinner-sprite.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2ba2ab3d60e75772eb280cde78ae8f02dae8b79d9780c5a5261c86346bf88467 +size 5053 diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/IconsAndLogos/spinner-sprite@2x.png b/src/UnityExtension/Assets/Editor/GitHub.Unity/IconsAndLogos/spinner-sprite@2x.png new file mode 100644 index 000000000..2ee461a04 --- /dev/null +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/IconsAndLogos/spinner-sprite@2x.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:64897c2c664faec7d5d0a83c85073d2a2c08ab788c1b4bdb7d29e0fabefef9a8 +size 11078 From 395843c8ccffd74e0b6694a862f36106b5047d2d Mon Sep 17 00:00:00 2001 From: Mauro Palumbo Date: Tue, 3 Oct 2017 10:37:34 +0200 Subject: [PATCH 012/241] Added Unity DLLs path relative to Unity installation directory --- docs/contributing/how-to-build.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/contributing/how-to-build.md b/docs/contributing/how-to-build.md index 597a624aa..77c4fec8a 100644 --- a/docs/contributing/how-to-build.md +++ b/docs/contributing/how-to-build.md @@ -40,11 +40,11 @@ To be able to authenticate in GitHub for Unity, you'll need to: - [Register a new developer application](https://github.com/settings/developers) in your profile. - Copy [common/ApplicationInfo_Local.cs-example](../../common/ApplicationInfo_Local.cs-example) to `common/ApplicationInfo_Local.cs` and fill out the clientId/clientSecret fields for your application. -The build needs to reference `UnityEngine.dll` and `UnityEditor.dll`. These DLLs are included with Unity. If you've installed Unity in the default location, the build will be able to find them automatically. If not, copy these DLLs from your Unity installation into the `lib` directory in order for the build to work. +The build needs to reference `UnityEngine.dll` and `UnityEditor.dll`. These DLLs are included with Unity. If you've installed Unity in the default location, the build will be able to find them automatically. If not, copy these DLLs from `Unity/Editor/Data/Managed` into the `lib` directory in order for the build to work. ### Visual Studio -To build with Visual Studio 2015 open the solution file `GitHub.Unity.sln`. Select `Build Solution` in the `Build` menu. +To build with Visual Studio 2015+ open the solution file `GitHub.Unity.sln`. Select `Build Solution` in the `Build` menu. ### Mono and Bash (windows and mac) From 580c6adc767426f7958bcd3599c19a05b27ee61f Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Tue, 10 Oct 2017 15:02:08 -0400 Subject: [PATCH 013/241] Disabling focusing action in HistoryView --- .../Editor/GitHub.Unity/UI/HistoryView.cs | 25 ++----------------- 1 file changed, 2 insertions(+), 23 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/HistoryView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/HistoryView.cs index f2cfcf278..ff01b301a 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/HistoryView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/HistoryView.cs @@ -12,8 +12,6 @@ namespace GitHub.Unity [Serializable] class HistoryView : Subview { - private const string HistoryFocusAll = "(All)"; - private const string HistoryFocusSingle = "Focus: {0}"; private const string PullButton = "Pull"; private const string PullButtonCount = "Pull ({0})"; private const string PushButton = "Push"; @@ -48,7 +46,6 @@ class HistoryView : Subview [NonSerialized] private bool isBusy; [SerializeField] private Vector2 detailsScroll; - [SerializeField] private Object historyTarget; [SerializeField] private Vector2 scroll; [SerializeField] private string selectionID; [SerializeField] private int statusAhead; @@ -105,11 +102,7 @@ public override void Refresh() public override void OnSelectionChange() { - if (!string.IsNullOrEmpty(AssetDatabase.GetAssetPath(Selection.activeObject))) - { - historyTarget = Selection.activeObject; - Refresh(); - } + } public override void OnGUI() @@ -220,20 +213,6 @@ public void OnEmbeddedGUI() // History toolbar GUILayout.BeginHorizontal(EditorStyles.toolbar); { - // Target indicator / clear button - EditorGUI.BeginDisabledGroup(historyTarget == null); - { - if (GUILayout.Button( - historyTarget == null ? HistoryFocusAll : String.Format(HistoryFocusSingle, historyTarget.name), - Styles.HistoryToolbarButtonStyle) - ) - { - historyTarget = null; - Refresh(); - } - } - EditorGUI.EndDisabledGroup(); - GUILayout.FlexibleSpace(); if (isPublished) @@ -436,7 +415,7 @@ private void ScrollTo(int index, float offset = 0f) private LogEntryState GetEntryState(int index) { - return historyTarget == null ? (index < statusAhead ? LogEntryState.Local : LogEntryState.Normal) : LogEntryState.Normal; + return index < statusAhead ? LogEntryState.Local : LogEntryState.Normal; } /// From c59a7d28dc49ac1e6307f57fd12439c6f0fdd7e3 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Tue, 10 Oct 2017 15:08:54 -0400 Subject: [PATCH 014/241] Adding an update that resharper wants to make --- GitHub.Unity.sln.DotSettings | 1 + 1 file changed, 1 insertion(+) diff --git a/GitHub.Unity.sln.DotSettings b/GitHub.Unity.sln.DotSettings index ded507d07..d4374a413 100644 --- a/GitHub.Unity.sln.DotSettings +++ b/GitHub.Unity.sln.DotSettings @@ -342,6 +342,7 @@ True True True + True False x64 \ No newline at end of file From 553977c16c491274723decc54a5b2fb5bb72256a Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Wed, 11 Oct 2017 17:07:14 -0400 Subject: [PATCH 015/241] Throwing an exception when the cached username does not match the one we get from the api --- src/GitHub.Api/Application/ApiClient.cs | 60 +++++++++++++---------- src/GitHub.Api/Application/IApiClient.cs | 1 - src/GitHub.Api/Authentication/Keychain.cs | 2 +- 3 files changed, 35 insertions(+), 28 deletions(-) diff --git a/src/GitHub.Api/Application/ApiClient.cs b/src/GitHub.Api/Application/ApiClient.cs index c4ae1782d..d5bad7799 100644 --- a/src/GitHub.Api/Application/ApiClient.cs +++ b/src/GitHub.Api/Application/ApiClient.cs @@ -195,10 +195,8 @@ public async Task ContinueLoginAsync(LoginResult loginResult, Func> GetOrganizationInternal() { logger.Trace("Getting Organizations"); - if (!await LoadKeychainInternal()) - { - return new List(); - } + await ValidateKeychain(); + await ValidateCurrentUserInternal(); var organizations = await githubClient.Organization.GetAllForCurrent(); @@ -257,16 +253,16 @@ private async Task> GetOrganizationInternal() { try { - logger.Trace("Getting Organizations"); + logger.Trace("Getting Current User"); if (!await LoadKeychainInternal()) { - return null; + throw new ApplicationException("Error Loading Keychain"); } userCache = await githubClient.User.Current(); } - catch(Exception ex) + catch (Exception ex) { logger.Error(ex, "Error Getting Current User"); throw; @@ -275,6 +271,29 @@ private async Task> GetOrganizationInternal() return userCache; } + private async Task ValidateCurrentUserInternal() + { + Octokit.User apiUsername; + string cachedUsername; + + try + { + logger.Trace("Validating User"); + apiUsername = await GetCurrentUserInternal(); + cachedUsername = keychain.Connections.First().Username; + } + catch (Exception ex) + { + logger.Error(ex, "Error Validating User"); + throw; + } + + if (apiUsername.Name != cachedUsername) + { + throw new ApplicationException("Credentialed user does not match API"); + } + } + private async Task LoadKeychainInternal() { logger.Trace("LoadKeychainInternal"); @@ -283,7 +302,7 @@ private async Task LoadKeychainInternal() { if (!keychain.NeedsLoad) { - logger.Trace("LoadKeychainInternal: Has keys does not need load"); + logger.Trace("LoadKeychainInternal: Previously Loaded"); return true; } @@ -301,23 +320,12 @@ private async Task LoadKeychainInternal() return false; } - public async Task ValidateCredentials() + private async Task ValidateKeychain() { - try + if (!await LoadKeychainInternal()) { - var store = keychain.Connect(OriginalUrl); - - if (store.OctokitCredentials != Credentials.Anonymous) - { - var credential = store.Credential; - await githubClient.Authorization.CheckApplicationAuthentication(ApplicationInfo.ClientId, credential.Token); - } - } - catch - { - return false; + throw new ApplicationException("Error Loading Keychain"); } - return true; } } } diff --git a/src/GitHub.Api/Application/IApiClient.cs b/src/GitHub.Api/Application/IApiClient.cs index 1ebbcd414..78b72e280 100644 --- a/src/GitHub.Api/Application/IApiClient.cs +++ b/src/GitHub.Api/Application/IApiClient.cs @@ -14,7 +14,6 @@ interface IApiClient Task Login(string username, string password, Action need2faCode, Action result); Task ContinueLogin(LoginResult loginResult, string code); Task LoginAsync(string username, string password, Func need2faCode); - Task ValidateCredentials(); Task Logout(UriString host); Task GetCurrentUser(Action callback); Task LoadKeychain(Action callback); diff --git a/src/GitHub.Api/Authentication/Keychain.cs b/src/GitHub.Api/Authentication/Keychain.cs index b531735f9..bab311239 100644 --- a/src/GitHub.Api/Authentication/Keychain.cs +++ b/src/GitHub.Api/Authentication/Keychain.cs @@ -68,7 +68,7 @@ public async Task Load(UriString host) { if (keychainItem.Username != cachedConnection.Username) { - logger.Warning("Keychain Username: {0} does not match; Hopefully it works", keychainItem.Username); + logger.Warning("Keychain Username:\"{0}\" does not match cached Username:\"{1}\"; Hopefully it works", keychainItem.Username, cachedConnection.Username); } logger.Trace("Loaded from Credential Manager Host:\"{0}\" Username:\"{1}\"", keychainItem.Host, keychainItem.Username); From 490f92bbf0bfc7742991d70dfd9330a8c76f9aa9 Mon Sep 17 00:00:00 2001 From: Don Okuda Date: Wed, 11 Oct 2017 15:45:18 -0700 Subject: [PATCH 016/241] Remove header in Initialize Repository view --- .../Editor/GitHub.Unity/UI/InitProjectView.cs | 30 ------------------- 1 file changed, 30 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs index c8ee372a3..1d244d660 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs @@ -12,7 +12,6 @@ namespace GitHub.Unity [Serializable] class InitProjectView : Subview { - private const string NoRepoTitle = "No Git repository found for this project"; private const string NoRepoDescription = "Initialize a Git repository to track changes and collaborate with others."; [SerializeField] private bool isBusy; @@ -32,35 +31,6 @@ public override void OnRepositoryChanged(IRepository oldRepository) public override void OnGUI() { - var headerRect = EditorGUILayout.BeginHorizontal(Styles.HeaderBoxStyle); - { - GUILayout.Space(5); - GUILayout.BeginVertical(GUILayout.Width(16)); - { - GUILayout.Space(5); - - var iconRect = GUILayoutUtility.GetRect(new GUIContent(Styles.BigLogo), GUIStyle.none, GUILayout.Height(20), GUILayout.Width(20)); - iconRect.y = headerRect.center.y - (iconRect.height / 2); - GUI.DrawTexture(iconRect, Styles.BigLogo, ScaleMode.ScaleToFit); - - GUILayout.Space(5); - } - GUILayout.EndVertical(); - - GUILayout.Space(5); - - GUILayout.BeginVertical(); - { - var headerContent = new GUIContent(NoRepoTitle); - var headerTitleRect = GUILayoutUtility.GetRect(headerContent, Styles.HeaderTitleStyle); - headerTitleRect.y = headerRect.center.y - (headerTitleRect.height / 2); - - GUI.Label(headerTitleRect, headerContent, Styles.HeaderTitleStyle); - } - GUILayout.EndVertical(); - } - EditorGUILayout.EndHorizontal(); - GUILayout.BeginVertical(Styles.GenericBoxStyle); { GUILayout.FlexibleSpace(); From 7568a55cc677f9c74aa2977a57a3f4b23a61fb10 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 12 Oct 2017 10:47:56 -0400 Subject: [PATCH 017/241] Validating the user and throwing custom exceptions --- src/GitHub.Api/Application/ApiClient.cs | 92 +++++++++++-------- src/GitHub.Api/Application/IApiClient.cs | 2 +- .../Editor/GitHub.Unity/UI/PublishView.cs | 18 ++++ 3 files changed, 71 insertions(+), 41 deletions(-) diff --git a/src/GitHub.Api/Application/ApiClient.cs b/src/GitHub.Api/Application/ApiClient.cs index d5bad7799..d039d228f 100644 --- a/src/GitHub.Api/Application/ApiClient.cs +++ b/src/GitHub.Api/Application/ApiClient.cs @@ -20,17 +20,13 @@ public static IApiClient Create(UriString repositoryUrl, IKeychain keychain) new GitHubClient(AppConfiguration.ProductHeader, credentialStore, hostAddress.ApiUri)); } - private static readonly Unity.ILogging logger = Unity.Logging.GetLogger(); + private static readonly ILogging logger = Logging.GetLogger(); public HostAddress HostAddress { get; } public UriString OriginalUrl { get; } private readonly IKeychain keychain; private readonly IGitHubClient githubClient; private readonly ILoginManager loginManager; - private static readonly SemaphoreSlim sem = new SemaphoreSlim(1); - - IList organizationsCache; - Octokit.User userCache; string owner; bool? isEnterprise; @@ -72,11 +68,10 @@ public async Task CreateRepository(NewRepository newRepository, Action> callback) + public async Task GetOrganizations(Action> onSuccess, Action onError = null) { - Guard.ArgumentNotNull(callback, "callback"); - var organizations = await GetOrganizationInternal(); - callback(organizations); + Guard.ArgumentNotNull(onSuccess, nameof(onSuccess)); + await GetOrganizationInternal(onSuccess, onError); } public async Task LoadKeychain(Action callback) @@ -222,7 +217,7 @@ public async Task ContinueLoginAsync(LoginResult loginResult, Func> GetOrganizationInternal() + private async Task GetOrganizationInternal(Action> onSuccess, Action onError = null) { try { @@ -237,16 +232,14 @@ private async Task> GetOrganizationInternal() if (organizations != null) { - organizationsCache = organizations.ToArray(); + onSuccess(organizations.ToArray()); } } catch(Exception ex) { logger.Error(ex, "Error Getting Organizations"); - throw; + onError?.Invoke(ex); } - - return organizationsCache; } private async Task GetCurrentUserInternal() @@ -254,50 +247,31 @@ private async Task> GetOrganizationInternal() try { logger.Trace("Getting Current User"); + await ValidateKeychain(); - if (!await LoadKeychainInternal()) - { - throw new ApplicationException("Error Loading Keychain"); - } - - userCache = await githubClient.User.Current(); + return await githubClient.User.Current(); } catch (Exception ex) { logger.Error(ex, "Error Getting Current User"); throw; } - - return userCache; } private async Task ValidateCurrentUserInternal() { - Octokit.User apiUsername; - string cachedUsername; - - try - { - logger.Trace("Validating User"); - apiUsername = await GetCurrentUserInternal(); - cachedUsername = keychain.Connections.First().Username; - } - catch (Exception ex) - { - logger.Error(ex, "Error Validating User"); - throw; - } + logger.Trace("Validating User"); + var apiUsername = await GetCurrentUserInternal(); + var cachedUsername = keychain.Connections.First().Username; if (apiUsername.Name != cachedUsername) { - throw new ApplicationException("Credentialed user does not match API"); + throw new TokenUsernameMismatchException(); } } private async Task LoadKeychainInternal() { - logger.Trace("LoadKeychainInternal"); - if (keychain.HasKeys) { if (!keychain.NeedsLoad) @@ -312,6 +286,8 @@ private async Task LoadKeychainInternal() var uriString = keychain.Connections.First().Host; var keychainAdapter = await keychain.Load(uriString); + logger.Trace("LoadKeychainInternal: Loaded"); + return keychainAdapter.OctokitCredentials != Credentials.Anonymous; } @@ -324,8 +300,44 @@ private async Task ValidateKeychain() { if (!await LoadKeychainInternal()) { - throw new ApplicationException("Error Loading Keychain"); + throw new KeychainEmptyException(); } } } + + class ApiClientException : Exception + { + public ApiClientException() + { } + + public ApiClientException(string message) : base(message) + { } + + public ApiClientException(string message, Exception innerException) : base(message, innerException) + { } + } + + class TokenUsernameMismatchException : ApiClientException + { + public TokenUsernameMismatchException() + { } + + public TokenUsernameMismatchException(string message) : base(message) + { } + + public TokenUsernameMismatchException(string message, Exception innerException) : base(message, innerException) + { } + } + + class KeychainEmptyException : ApiClientException + { + public KeychainEmptyException() + { } + + public KeychainEmptyException(string message) : base(message) + { } + + public KeychainEmptyException(string message, Exception innerException) : base(message, innerException) + { } + } } diff --git a/src/GitHub.Api/Application/IApiClient.cs b/src/GitHub.Api/Application/IApiClient.cs index 78b72e280..95c5623ce 100644 --- a/src/GitHub.Api/Application/IApiClient.cs +++ b/src/GitHub.Api/Application/IApiClient.cs @@ -10,7 +10,7 @@ interface IApiClient HostAddress HostAddress { get; } UriString OriginalUrl { get; } Task CreateRepository(NewRepository newRepository, Action callback, string organization = null); - Task GetOrganizations(Action> callback); + Task GetOrganizations(Action> onSuccess, Action onError = null); Task Login(string username, string password, Action need2faCode, Action result); Task ContinueLogin(LoginResult loginResult, string code); Task LoginAsync(string username, string password, Func need2faCode); diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs index addb84e63..f84a66858 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs @@ -122,6 +122,24 @@ private void LoadOrganizations() owners = new[] { OwnersDefaultText, username }.Union(organizationLogins).ToArray(); isBusy = false; + }, exception => { + var tokenUsernameMismatchException = exception as TokenUsernameMismatchException; + if (tokenUsernameMismatchException != null) + { + //This is a specific case + + Logger.Error(exception, "Token Username Mismatch"); + return; + } + + var keychainEmptyException = exception as KeychainEmptyException; + if (keychainEmptyException != null) + { + Logger.Error(exception, "Keychain empty"); + return; + } + + Logger.Error(exception, "Unhandled Exception Type"); }); }); } From 682fb99b903a0b447d44c9fa300e6caac542f6a3 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 12 Oct 2017 11:32:02 -0400 Subject: [PATCH 018/241] Using custom exceptions and popping up dialog to proceed or switch accounts --- src/GitHub.Api/Application/ApiClient.cs | 36 +++--- src/GitHub.Api/Application/IApiClient.cs | 1 - .../Editor/GitHub.Unity/UI/HistoryView.cs | 10 +- .../Editor/GitHub.Unity/UI/PublishView.cs | 108 +++++++++--------- 4 files changed, 68 insertions(+), 87 deletions(-) diff --git a/src/GitHub.Api/Application/ApiClient.cs b/src/GitHub.Api/Application/ApiClient.cs index d039d228f..2667ffa8e 100644 --- a/src/GitHub.Api/Application/ApiClient.cs +++ b/src/GitHub.Api/Application/ApiClient.cs @@ -74,13 +74,6 @@ public async Task GetOrganizations(Action> onSuccess, Action await GetOrganizationInternal(onSuccess, onError); } - public async Task LoadKeychain(Action callback) - { - Guard.ArgumentNotNull(callback, "callback"); - var hasLoadedKeys = await LoadKeychainInternal(); - callback(hasLoadedKeys); - } - public async Task GetCurrentUser(Action callback) { Guard.ArgumentNotNull(callback, "callback"); @@ -261,12 +254,15 @@ private async Task GetOrganizationInternal(Action> onSuccess private async Task ValidateCurrentUserInternal() { logger.Trace("Validating User"); - var apiUsername = await GetCurrentUserInternal(); + + var apiUser = await GetCurrentUserInternal(); + var apiUsername = apiUser.Login; + var cachedUsername = keychain.Connections.First().Username; - if (apiUsername.Name != cachedUsername) + if (apiUsername != cachedUsername) { - throw new TokenUsernameMismatchException(); + throw new TokenUsernameMismatchException(cachedUsername, apiUsername); } } @@ -319,25 +315,19 @@ public ApiClientException(string message, Exception innerException) : base(messa class TokenUsernameMismatchException : ApiClientException { - public TokenUsernameMismatchException() - { } - - public TokenUsernameMismatchException(string message) : base(message) - { } + public string CachedUsername { get; } + public string CurrentUsername { get; } - public TokenUsernameMismatchException(string message, Exception innerException) : base(message, innerException) - { } + public TokenUsernameMismatchException(string cachedUsername, string currentUsername) + { + CachedUsername = cachedUsername; + CurrentUsername = currentUsername; + } } class KeychainEmptyException : ApiClientException { public KeychainEmptyException() { } - - public KeychainEmptyException(string message) : base(message) - { } - - public KeychainEmptyException(string message, Exception innerException) : base(message, innerException) - { } } } diff --git a/src/GitHub.Api/Application/IApiClient.cs b/src/GitHub.Api/Application/IApiClient.cs index 95c5623ce..2714275f4 100644 --- a/src/GitHub.Api/Application/IApiClient.cs +++ b/src/GitHub.Api/Application/IApiClient.cs @@ -16,6 +16,5 @@ interface IApiClient Task LoginAsync(string username, string password, Func need2faCode); Task Logout(UriString host); Task GetCurrentUser(Action callback); - Task LoadKeychain(Action callback); } } diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/HistoryView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/HistoryView.cs index f2cfcf278..d2a526d6b 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/HistoryView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/HistoryView.cs @@ -284,15 +284,11 @@ public void OnEmbeddedGUI() else { // Publishing a repo - EditorGUI.BeginDisabledGroup(!Platform.Keychain.Connections.Any()); + var publishedClicked = GUILayout.Button(PublishButton, Styles.HistoryToolbarButtonStyle); + if (publishedClicked) { - var publishedClicked = GUILayout.Button(PublishButton, Styles.HistoryToolbarButtonStyle); - if (publishedClicked) - { - PopupWindow.Open(PopupWindow.PopupViewType.PublishView); - } + PopupWindow.Open(PopupWindow.PopupViewType.PublishView); } - EditorGUI.EndDisabledGroup(); } } GUILayout.EndHorizontal(); diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs index f4424c6a3..ab5c11353 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs @@ -21,6 +21,10 @@ class PublishView : Subview private const string RepositoryNameLabel = "Repository Name"; private const string DescriptionLabel = "Description"; private const string CreatePrivateRepositoryLabel = "Create as a private repository"; + private const string AuthenticationChangedMessageFormat = "You were authenticated as \"{0}\", but you are now authenticated as \"{1}\". Would you like to proceed or logout?"; + private const string AuthenticationChangedTitle = "Authentication Changed"; + private const string AuthenticationChangedProceed = "Proceed"; + private const string AuthenticationChangedLogout = "Logout"; [SerializeField] private string username; [SerializeField] private string[] owners = { OwnersDefaultText }; @@ -33,7 +37,7 @@ class PublishView : Subview [NonSerialized] private IApiClient client; [NonSerialized] private bool isBusy; [NonSerialized] private string error; - [NonSerialized] private bool organizationsNeedLoading; + [NonSerialized] private bool ownersNeedLoading; public IApiClient Client { @@ -62,7 +66,7 @@ public IApiClient Client public override void OnEnable() { base.OnEnable(); - organizationsNeedLoading = organizations == null && !isBusy; + ownersNeedLoading = organizations == null && !isBusy; } public override void OnDataUpdate() @@ -73,10 +77,10 @@ public override void OnDataUpdate() private void MaybeUpdateData() { - if (organizationsNeedLoading) + if (ownersNeedLoading) { - organizationsNeedLoading = false; - LoadOrganizations(); + ownersNeedLoading = false; + LoadOwners(); } } @@ -87,75 +91,67 @@ public override void InitializeView(IView parent) Size = viewSize; } - private void LoadOrganizations() + private void LoadOwners() { var keychainConnections = Platform.Keychain.Connections; //TODO: ONE_USER_LOGIN This assumes only ever one user can login - if (keychainConnections.Any()) - { - try - { - Logger.Trace("Loading Keychain"); - - isBusy = true; - Client.LoadKeychain(hasKeys => { - if (!hasKeys) - { - Logger.Warning("Unable to get current user"); - isBusy = false; - return; - } + isBusy = true; - //TODO: ONE_USER_LOGIN This assumes only ever one user can login - username = keychainConnections.First().Username; + //TODO: ONE_USER_LOGIN This assumes only ever one user can login + username = keychainConnections.First().Username; - Logger.Trace("Loading Organizations"); + Logger.Trace("Loading Owners"); - Client.GetOrganizations(orgs => { - organizations = orgs; - Logger.Trace("Loaded {0} organizations", organizations.Count); + Client.GetOrganizations(orgs => + { + organizations = orgs; + Logger.Trace("Loaded {0} Owners", organizations.Count); - var organizationLogins = organizations - .OrderBy(organization => organization.Login).Select(organization => organization.Login); + var organizationLogins = organizations + .OrderBy(organization => organization.Login) + .Select(organization => organization.Login); - owners = new[] { OwnersDefaultText, username }.Union(organizationLogins).ToArray(); + owners = new[] { OwnersDefaultText, username }.Union(organizationLogins).ToArray(); - isBusy = false; - }, exception => { + isBusy = false; + }, exception => + { + isBusy = false; - //PopupWindow.Open(PopupWindow.PopupViewType.AuthenticationView); + var tokenUsernameMismatchException = exception as TokenUsernameMismatchException; + if (tokenUsernameMismatchException != null) + { + Logger.Trace("Token Username Mismatch"); - var tokenUsernameMismatchException = exception as TokenUsernameMismatchException; - if (tokenUsernameMismatchException != null) - { - //This is a specific case + var shouldProceed = EditorUtility.DisplayDialog(AuthenticationChangedTitle, + string.Format(AuthenticationChangedMessageFormat, + tokenUsernameMismatchException.CachedUsername, + tokenUsernameMismatchException.CurrentUsername), AuthenticationChangedProceed, AuthenticationChangedLogout); - Logger.Error(exception, "Token Username Mismatch"); - return; - } + if (shouldProceed) + { + //Proceed as current user - var keychainEmptyException = exception as KeychainEmptyException; - if (keychainEmptyException != null) - { - Logger.Error(exception, "Keychain empty"); - return; - } + } + else + { + //Logout current user and try again - Logger.Error(exception, "Unhandled Exception Type"); - }); - }); + } + return; } - catch (Exception e) + + var keychainEmptyException = exception as KeychainEmptyException; + if (keychainEmptyException != null) { - Logger.Error(e, "Error PopulateView & GetOrganizations"); - isBusy = false; + Logger.Trace("Keychain empty"); + PopupWindow.Open(PopupWindow.PopupViewType.AuthenticationView); + return; } - } - else - { - Logger.Warning("No Keychain connections to use"); - } + + Logger.Error(exception, "Unhandled Exception"); + }); } public override void OnGUI() From b0cc6969ad5529399c0ade9d9a38023fe80fc068 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 12 Oct 2017 16:12:42 -0400 Subject: [PATCH 019/241] Initial routine in PopupWindow to handle authentication before presenting specific views --- src/GitHub.Api/Application/ApiClient.cs | 14 +++ src/GitHub.Api/Application/IApiClient.cs | 1 + .../Editor/GitHub.Unity/UI/HistoryView.cs | 2 +- .../Editor/GitHub.Unity/UI/PopupWindow.cs | 90 ++++++++++++++++--- .../Editor/GitHub.Unity/UI/PublishView.cs | 2 +- .../Assets/Editor/GitHub.Unity/UI/Window.cs | 2 +- 6 files changed, 98 insertions(+), 13 deletions(-) diff --git a/src/GitHub.Api/Application/ApiClient.cs b/src/GitHub.Api/Application/ApiClient.cs index 2667ffa8e..25b744cf2 100644 --- a/src/GitHub.Api/Application/ApiClient.cs +++ b/src/GitHub.Api/Application/ApiClient.cs @@ -74,6 +74,20 @@ public async Task GetOrganizations(Action> onSuccess, Action await GetOrganizationInternal(onSuccess, onError); } + public async Task ValidateCurrentUser(Action onSuccess, Action onError = null) + { + Guard.ArgumentNotNull(onSuccess, nameof(onSuccess)); + try + { + await ValidateCurrentUserInternal(); + onSuccess(); + } + catch (Exception e) + { + onError?.Invoke(e); + } + } + public async Task GetCurrentUser(Action callback) { Guard.ArgumentNotNull(callback, "callback"); diff --git a/src/GitHub.Api/Application/IApiClient.cs b/src/GitHub.Api/Application/IApiClient.cs index 2714275f4..77819e3f5 100644 --- a/src/GitHub.Api/Application/IApiClient.cs +++ b/src/GitHub.Api/Application/IApiClient.cs @@ -16,5 +16,6 @@ interface IApiClient Task LoginAsync(string username, string password, Func need2faCode); Task Logout(UriString host); Task GetCurrentUser(Action callback); + Task ValidateCurrentUser(Action onSuccess, Action onError = null); } } diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/HistoryView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/HistoryView.cs index d2a526d6b..d9bdf4c4e 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/HistoryView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/HistoryView.cs @@ -287,7 +287,7 @@ public void OnEmbeddedGUI() var publishedClicked = GUILayout.Button(PublishButton, Styles.HistoryToolbarButtonStyle); if (publishedClicked) { - PopupWindow.Open(PopupWindow.PopupViewType.PublishView); + PopupWindow.OpenWindow(PopupWindow.PopupViewType.PublishView); } } } diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PopupWindow.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PopupWindow.cs index 9ee629ca9..d66ea6a08 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PopupWindow.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PopupWindow.cs @@ -20,32 +20,100 @@ public enum PopupViewType [SerializeField] private PublishView publishView; [SerializeField] private LoadingView loadingView; + [NonSerialized] private IApiClient client; + public event Action OnClose; [MenuItem("GitHub/Authenticate")] public static void Launch() { - Open(PopupViewType.AuthenticationView); + OpenWindow(PopupViewType.AuthenticationView); } - public static PopupWindow Open(PopupViewType popupViewType, Action onClose = null) + public static PopupWindow OpenWindow(PopupViewType popupViewType, Action onClose = null) { var popupWindow = GetWindow(true); - popupWindow.OnClose.SafeInvoke(false); + popupWindow.Open(popupViewType, onClose); + + return popupWindow; + } + + private void Open(PopupViewType popupViewType, Action onClose) + { + OnClose.SafeInvoke(false); + OnClose = null; + + Logger.Trace("OpenView: {0}", popupViewType.ToString()); + + var viewNeedsAuthentication = popupViewType == PopupViewType.PublishView; + if (viewNeedsAuthentication) + { + Logger.Trace("Validating to open view"); + + Client.ValidateCurrentUser(() => { + + Logger.Trace("User validated opening view"); + + OpenInternal(popupViewType, onClose); + + }, exception => { + + Logger.Trace("User required validation opening AuthenticationView"); + + Open(PopupViewType.AuthenticationView, completedAuthentication => { + if (completedAuthentication) + { + Logger.Trace("User completed validation opening view: {0}", popupViewType.ToString()); + + Open(popupViewType, onClose); + } + }); + }); + } + else + { + OpenInternal(popupViewType, onClose); + } + } + + private void OpenInternal(PopupViewType popupViewType, Action onClose) + { if (onClose != null) { - popupWindow.OnClose += onClose; + OnClose += onClose; } - popupWindow.ActiveViewType = popupViewType; - popupWindow.titleContent = new GUIContent(popupWindow.ActiveView.Title, Styles.SmallLogo); - popupWindow.OnEnable(); - popupWindow.Show(); - popupWindow.Refresh(); + ActiveViewType = popupViewType; + titleContent = new GUIContent(ActiveView.Title, Styles.SmallLogo); + OnEnable(); + Show(); + Refresh(); + } - return popupWindow; + public IApiClient Client + { + get + { + if (client == null) + { + var repository = Environment.Repository; + UriString host; + if (repository != null && !string.IsNullOrEmpty(repository.CloneUrl)) + { + host = repository.CloneUrl.ToRepositoryUrl(); + } + else + { + host = UriString.ToUriString(HostAddress.GitHubDotComHostAddress.WebUri); + } + + client = ApiClient.Create(host, Platform.Keychain); + } + + return client; + } } public override void Initialize(IApplicationManager applicationManager) @@ -59,6 +127,8 @@ public override void Initialize(IApplicationManager applicationManager) publishView.InitializeView(this); authenticationView.InitializeView(this); loadingView.InitializeView(this); + + titleContent = new GUIContent(ActiveView.Title, Styles.SmallLogo); } public override void OnEnable() diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs index ab5c11353..e0a799e77 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs @@ -146,7 +146,7 @@ private void LoadOwners() if (keychainEmptyException != null) { Logger.Trace("Keychain empty"); - PopupWindow.Open(PopupWindow.PopupViewType.AuthenticationView); + PopupWindow.OpenWindow(PopupWindow.PopupViewType.AuthenticationView); return; } diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs index cf9da47f6..325ca22cc 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs @@ -351,7 +351,7 @@ private void DoAccountDropdown() private void SignIn(object obj) { - PopupWindow.Open(PopupWindow.PopupViewType.AuthenticationView); + PopupWindow.OpenWindow(PopupWindow.PopupViewType.AuthenticationView); } private void GoToProfile(object obj) From 49ef1b1921414ff92c78c746f664da371e40cea3 Mon Sep 17 00:00:00 2001 From: Don Okuda Date: Thu, 12 Oct 2017 13:34:47 -0700 Subject: [PATCH 020/241] Update text for initialize repo view --- src/GitHub.Api/Localization.resx | 58 +++++++++---------- .../Assets/Editor/GitHub.Unity/Misc/Styles.cs | 16 +++++ .../Editor/GitHub.Unity/UI/InitProjectView.cs | 5 +- 3 files changed, 47 insertions(+), 32 deletions(-) diff --git a/src/GitHub.Api/Localization.resx b/src/GitHub.Api/Localization.resx index 6768713f9..ba8fc9667 100644 --- a/src/GitHub.Api/Localization.resx +++ b/src/GitHub.Api/Localization.resx @@ -1,17 +1,17 @@  - @@ -286,7 +286,7 @@ Branch pushed - Initialize repository + Initialize a git repository for this project Switch branch @@ -294,4 +294,4 @@ Could not switch to branch {0} - \ No newline at end of file + diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/Misc/Styles.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/Misc/Styles.cs index a4c57790a..c3d1c1013 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/Misc/Styles.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/Misc/Styles.cs @@ -70,6 +70,7 @@ class Styles commitFileAreaStyle, commitButtonStyle, textFieldStyle, + boldCenteredLabel, centeredLabel, commitDescriptionFieldStyle, toggleMixedStyle, @@ -543,6 +544,21 @@ public static GUIStyle CenteredLabel } } + public static GUIStyle BoldCenteredLabel + { + get + { + if (boldCenteredLabel == null) + { + boldCenteredLabel = new GUIStyle(EditorStyles.boldLabel); + boldCenteredLabel.name = "BoldCenteredLabelStyle"; + boldCenteredLabel.alignment = TextAnchor.MiddleCenter; + } + return boldCenteredLabel; + } + } + + public static GUIStyle CommitDescriptionFieldStyle { get diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs index 1d244d660..0a784756a 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs @@ -12,7 +12,7 @@ namespace GitHub.Unity [Serializable] class InitProjectView : Subview { - private const string NoRepoDescription = "Initialize a Git repository to track changes and collaborate with others."; + private const string NoRepoTitle = "To begin using GitHub, initialize a git repository"; [SerializeField] private bool isBusy; [SerializeField] private bool isPublished; @@ -35,7 +35,7 @@ public override void OnGUI() { GUILayout.FlexibleSpace(); - GUILayout.Label(NoRepoDescription, Styles.CenteredLabel); + GUILayout.Label(NoRepoTitle, Styles.BoldCenteredLabel); GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); @@ -51,7 +51,6 @@ public override void OnGUI() } } EditorGUI.EndDisabledGroup(); - GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); From 88b767e7ffaf38a2276a09573f89c1b364bb2436 Mon Sep 17 00:00:00 2001 From: Don Okuda Date: Thu, 12 Oct 2017 13:34:57 -0700 Subject: [PATCH 021/241] Add a place for errors --- .../Assets/Editor/GitHub.Unity/UI/InitProjectView.cs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs index 0a784756a..a0e865077 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs @@ -54,6 +54,12 @@ public override void OnGUI() GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); + GUILayout.BeginHorizontal(); + GUILayout.FlexibleSpace(); + GUILayout.Label("There was an error initializing a repository.", Styles.ErrorLabel); + GUILayout.FlexibleSpace(); + GUILayout.EndHorizontal(); + GUILayout.FlexibleSpace(); } GUILayout.EndVertical(); From b0845413304ed5d853dc978e3f8b48b7aac4576f Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 12 Oct 2017 16:35:31 -0400 Subject: [PATCH 022/241] Attempting to fix the close operation --- .../Assets/Editor/GitHub.Unity/UI/PopupWindow.cs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PopupWindow.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PopupWindow.cs index d66ea6a08..ac2fb4d6f 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PopupWindow.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PopupWindow.cs @@ -44,6 +44,11 @@ private void Open(PopupViewType popupViewType, Action onClose) OnClose.SafeInvoke(false); OnClose = null; + onClose = onClose ?? (b => { + Logger.Trace("Closing Window"); + //Close(); + }); + Logger.Trace("OpenView: {0}", popupViewType.ToString()); var viewNeedsAuthentication = popupViewType == PopupViewType.PublishView; @@ -172,7 +177,6 @@ public override void Finish(bool result) { OnClose.SafeInvoke(result); OnClose = null; - Close(); base.Finish(result); } From e9f7f09ed60522fa5821ef0f260fd17d2401a74b Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 12 Oct 2017 16:42:59 -0400 Subject: [PATCH 023/241] Attempting to close properly after publish --- src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PopupWindow.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PopupWindow.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PopupWindow.cs index ac2fb4d6f..642eeb023 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PopupWindow.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PopupWindow.cs @@ -46,7 +46,7 @@ private void Open(PopupViewType popupViewType, Action onClose) onClose = onClose ?? (b => { Logger.Trace("Closing Window"); - //Close(); + Close(); }); Logger.Trace("OpenView: {0}", popupViewType.ToString()); From 79507a3b1d2d09afe52c11246740ae233c8f07e4 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Fri, 13 Oct 2017 10:02:00 -0400 Subject: [PATCH 024/241] Controlling the close action with a flag --- .../Editor/GitHub.Unity/UI/PopupWindow.cs | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PopupWindow.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PopupWindow.cs index 642eeb023..36a9ac7b6 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PopupWindow.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PopupWindow.cs @@ -14,8 +14,8 @@ public enum PopupViewType AuthenticationView } + [SerializeField] private bool shouldCloseOnFinish; [SerializeField] private PopupViewType activeViewType; - [SerializeField] private AuthenticationView authenticationView; [SerializeField] private PublishView publishView; [SerializeField] private LoadingView loadingView; @@ -44,11 +44,6 @@ private void Open(PopupViewType popupViewType, Action onClose) OnClose.SafeInvoke(false); OnClose = null; - onClose = onClose ?? (b => { - Logger.Trace("Closing Window"); - Close(); - }); - Logger.Trace("OpenView: {0}", popupViewType.ToString()); var viewNeedsAuthentication = popupViewType == PopupViewType.PublishView; @@ -61,12 +56,13 @@ private void Open(PopupViewType popupViewType, Action onClose) Logger.Trace("User validated opening view"); OpenInternal(popupViewType, onClose); + shouldCloseOnFinish = true; }, exception => { Logger.Trace("User required validation opening AuthenticationView"); - Open(PopupViewType.AuthenticationView, completedAuthentication => { + OpenInternal(PopupViewType.AuthenticationView, completedAuthentication => { if (completedAuthentication) { @@ -75,11 +71,13 @@ private void Open(PopupViewType popupViewType, Action onClose) Open(popupViewType, onClose); } }); + shouldCloseOnFinish = false; }); } else { OpenInternal(popupViewType, onClose); + shouldCloseOnFinish = true; } } @@ -177,6 +175,13 @@ public override void Finish(bool result) { OnClose.SafeInvoke(result); OnClose = null; + + if (shouldCloseOnFinish) + { + shouldCloseOnFinish = false; + Close(); + } + base.Finish(result); } From 380ede928dd1bde5cb2819cd838c6a4bb768c211 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Fri, 13 Oct 2017 10:44:19 -0400 Subject: [PATCH 025/241] Displaying a message on the Authentication window and setting the cached username --- .../GitHub.Unity/UI/AuthenticationView.cs | 23 +++++++++++++++ .../Editor/GitHub.Unity/UI/PopupWindow.cs | 29 +++++++++++++++++-- 2 files changed, 50 insertions(+), 2 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/AuthenticationView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/AuthenticationView.cs index d20ab8fa7..3917a905e 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/AuthenticationView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/AuthenticationView.cs @@ -23,6 +23,7 @@ class AuthenticationView : Subview [SerializeField] private Vector2 scroll; [SerializeField] private string username = ""; [SerializeField] private string two2fa = ""; + [SerializeField] private string message; [NonSerialized] private bool need2fa; [NonSerialized] private bool isBusy; @@ -98,6 +99,16 @@ public override void OnGUI() GUILayout.EndScrollView(); } + public void SetMessage(string value) + { + message = value; + } + + public void SetUsername(string value) + { + username = value; + } + private void HandleEnterPressed() { if (Event.current.type != EventType.KeyDown) @@ -112,6 +123,8 @@ private void OnGUILogin() { EditorGUI.BeginDisabledGroup(isBusy); { + ShowMessage(); + GUILayout.Space(3); GUILayout.BeginHorizontal(); { @@ -217,6 +230,16 @@ private void DoResult(bool success, string msg) } } + private void ShowMessage() + { + if (message != null) + { + GUILayout.Space(Styles.BaseSpacing + 3); + GUILayout.Label(message, Styles.CenteredLabel); + GUILayout.Space(Styles.BaseSpacing + 3); + } + } + private void ShowErrorMessage() { if (errorMessage != null) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PopupWindow.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PopupWindow.cs index 36a9ac7b6..e0fa8581f 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PopupWindow.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PopupWindow.cs @@ -59,11 +59,30 @@ private void Open(PopupViewType popupViewType, Action onClose) shouldCloseOnFinish = true; }, exception => { - Logger.Trace("User required validation opening AuthenticationView"); - OpenInternal(PopupViewType.AuthenticationView, completedAuthentication => { + string message = null; + string username = null; + + var usernameMismatchException = exception as TokenUsernameMismatchException; + if (usernameMismatchException != null) + { + message = "Your credentials need to be refreshed"; + username = usernameMismatchException.CachedUsername; + } + + var keychainEmptyException = exception as KeychainEmptyException; + if (keychainEmptyException != null) + { + message = "We need you to authenticate first"; + } + if (usernameMismatchException == null && keychainEmptyException == null) + { + message = "There was an error validating your account"; + } + + OpenInternal(PopupViewType.AuthenticationView, completedAuthentication => { if (completedAuthentication) { Logger.Trace("User completed validation opening view: {0}", popupViewType.ToString()); @@ -71,7 +90,13 @@ private void Open(PopupViewType popupViewType, Action onClose) Open(popupViewType, onClose); } }); + shouldCloseOnFinish = false; + authenticationView.SetMessage(message); + if (username != null) + { + authenticationView.SetUsername(username); + } }); } else From fa9cc6f585126fede455d9904bb8a291ebd43bd5 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Fri, 13 Oct 2017 11:06:59 -0400 Subject: [PATCH 026/241] Shortening the error message for 'too many private repos' --- .../Editor/GitHub.Unity/UI/PublishView.cs | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs index addb84e63..0d0529d69 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs @@ -21,6 +21,7 @@ class PublishView : Subview private const string RepositoryNameLabel = "Repository Name"; private const string DescriptionLabel = "Description"; private const string CreatePrivateRepositoryLabel = "Create as a private repository"; + private const string PublishLimtPrivateRepositoriesError = "You are currently at your limt of private repositories"; [SerializeField] private string username; [SerializeField] private string[] owners = { OwnersDefaultText }; @@ -235,11 +236,11 @@ public override void OnGUI() Description = cleanRepoDescription }, (repository, ex) => { - Logger.Trace("Create Repository Callback"); - if (ex != null) { - error = ex.Message; + Logger.Error(ex, "Repository Create Error Type:{0}", ex.GetType().ToString()); + + error = GetPublishErrorMessage(ex); isBusy = false; return; } @@ -251,6 +252,8 @@ public override void OnGUI() return; } + Logger.Trace("Repository Created"); + GitClient.RemoteAdd("origin", repository.CloneUrl) .Then(GitClient.Push("origin", Repository.CurrentBranch.Value.Name)) .ThenInUI(Finish) @@ -265,6 +268,16 @@ public override void OnGUI() EditorGUI.EndDisabledGroup(); } + private string GetPublishErrorMessage(Exception ex) + { + if (ex.Message.StartsWith(PublishLimtPrivateRepositoriesError)) + { + return PublishLimtPrivateRepositoriesError; + } + + return ex.Message; + } + public override bool IsBusy { get { return isBusy; } From 9af0497e8b9d43d371fd92ac761b1dedd75c7651 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Fri, 13 Oct 2017 11:29:58 -0400 Subject: [PATCH 027/241] Changing the size of the PublishView and displaying the error after the button --- .../Editor/GitHub.Unity/UI/PublishView.cs | 24 ++++++------------- 1 file changed, 7 insertions(+), 17 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs index 0d0529d69..a2cb54df6 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs @@ -9,7 +9,7 @@ namespace GitHub.Unity { class PublishView : Subview { - private static readonly Vector2 viewSize = new Vector2(300, 250); + private static readonly Vector2 viewSize = new Vector2(400, 350); private const string WindowTitle = "Publish"; private const string Header = "Publish this repository to GitHub"; @@ -211,11 +211,6 @@ public override void OnGUI() GUILayout.Space(Styles.PublishViewSpacingHeight); - if (error != null) - GUILayout.Label(error, Styles.ErrorLabel); - - GUILayout.FlexibleSpace(); - GUILayout.BeginHorizontal(); { GUILayout.FlexibleSpace(); @@ -240,7 +235,7 @@ public override void OnGUI() { Logger.Error(ex, "Repository Create Error Type:{0}", ex.GetType().ToString()); - error = GetPublishErrorMessage(ex); + error = ex.Message; isBusy = false; return; } @@ -264,18 +259,13 @@ public override void OnGUI() } GUILayout.EndHorizontal(); GUILayout.Space(10); - } - EditorGUI.EndDisabledGroup(); - } - private string GetPublishErrorMessage(Exception ex) - { - if (ex.Message.StartsWith(PublishLimtPrivateRepositoriesError)) - { - return PublishLimtPrivateRepositoriesError; - } + if (error != null) + GUILayout.Label(error, Styles.ErrorLabel); - return ex.Message; + GUILayout.FlexibleSpace(); + } + EditorGUI.EndDisabledGroup(); } public override bool IsBusy From 6cd68a7720491f14a2a9146c4f05af3b5338f522 Mon Sep 17 00:00:00 2001 From: Don Okuda Date: Fri, 13 Oct 2017 10:26:56 -0700 Subject: [PATCH 028/241] :fire: Header --- .../Editor/GitHub.Unity/UI/PublishView.cs | 20 ------------------- 1 file changed, 20 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs index a2cb54df6..13c24e7f5 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs @@ -140,26 +140,6 @@ private void LoadOrganizations() public override void OnGUI() { - GUILayout.BeginHorizontal(Styles.AuthHeaderBoxStyle); - { - GUILayout.BeginVertical(GUILayout.Width(16)); - { - GUILayout.Space(9); - GUILayout.Label(Styles.BigLogo, GUILayout.Height(20), GUILayout.Width(20)); - } - GUILayout.EndVertical(); - - GUILayout.BeginVertical(); - { - GUILayout.Space(11); - GUILayout.Label(Title, EditorStyles.boldLabel); - } - GUILayout.EndVertical(); - } - GUILayout.EndHorizontal(); - - GUILayout.Space(Styles.PublishViewSpacingHeight); - EditorGUI.BeginDisabledGroup(isBusy); { GUILayout.BeginHorizontal(); From c673100d731ce9843f0fce8bd351520c7c2012a7 Mon Sep 17 00:00:00 2001 From: Don Okuda Date: Fri, 13 Oct 2017 10:38:21 -0700 Subject: [PATCH 029/241] :fire: Fancy layout --- .../Editor/GitHub.Unity/UI/PublishView.cs | 29 ++----------------- 1 file changed, 3 insertions(+), 26 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs index 13c24e7f5..770918e29 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs @@ -142,33 +142,10 @@ public override void OnGUI() { EditorGUI.BeginDisabledGroup(isBusy); { - GUILayout.BeginHorizontal(); - { - GUILayout.BeginVertical(); - { - GUILayout.Label(SelectedOwnerLabel); - selectedOwner = EditorGUILayout.Popup(selectedOwner, owners); - } - GUILayout.EndVertical(); - - GUILayout.BeginVertical(GUILayout.Width(8)); - { - GUILayout.Space(20); - GUILayout.Label("/"); - } - GUILayout.EndVertical(); - - GUILayout.BeginVertical(); - { - GUILayout.Label(RepositoryNameLabel); - repoName = EditorGUILayout.TextField(repoName); - } - GUILayout.EndVertical(); - } - GUILayout.EndHorizontal(); + selectedOwner = EditorGUILayout.Popup(SelectedOwnerLabel, selectedOwner, owners); + repoName = EditorGUILayout.TextField(RepositoryNameLabel, repoName); + repoDescription = EditorGUILayout.TextField(DescriptionLabel, repoDescription); - GUILayout.Label(DescriptionLabel); - repoDescription = EditorGUILayout.TextField(repoDescription); GUILayout.Space(Styles.PublishViewSpacingHeight); GUILayout.BeginVertical(); From 5aa80925d6fc7b421ed67bc6c9c92ca756b0679c Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Fri, 13 Oct 2017 13:42:26 -0400 Subject: [PATCH 030/241] Clearing the message at the right time --- .../Editor/GitHub.Unity/UI/AuthenticationView.cs | 16 +++++++++++++--- .../Assets/Editor/GitHub.Unity/UI/PopupWindow.cs | 3 +++ 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/AuthenticationView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/AuthenticationView.cs index 3917a905e..d9de5a8bc 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/AuthenticationView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/AuthenticationView.cs @@ -21,15 +21,15 @@ class AuthenticationView : Subview private const string TwofaButton = "Verify"; [SerializeField] private Vector2 scroll; - [SerializeField] private string username = ""; - [SerializeField] private string two2fa = ""; + [SerializeField] private string username = string.Empty; + [SerializeField] private string two2fa = string.Empty; [SerializeField] private string message; [NonSerialized] private bool need2fa; [NonSerialized] private bool isBusy; [NonSerialized] private string errorMessage; [NonSerialized] private bool enterPressed; - [NonSerialized] private string password = ""; + [NonSerialized] private string password = string.Empty; [NonSerialized] private AuthenticationService authenticationService; @@ -104,11 +104,21 @@ public void SetMessage(string value) message = value; } + public void ClearMessage() + { + message = null; + } + public void SetUsername(string value) { username = value; } + public void ClearUsername() + { + username = string.Empty; + } + private void HandleEnterPressed() { if (Event.current.type != EventType.KeyDown) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PopupWindow.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PopupWindow.cs index e0fa8581f..a3731aec6 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PopupWindow.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PopupWindow.cs @@ -83,6 +83,9 @@ private void Open(PopupViewType popupViewType, Action onClose) } OpenInternal(PopupViewType.AuthenticationView, completedAuthentication => { + authenticationView.ClearMessage(); + authenticationView.ClearUsername(); + if (completedAuthentication) { Logger.Trace("User completed validation opening view: {0}", popupViewType.ToString()); From 8312a720a7960a6990d396c82c732f4b496a58db Mon Sep 17 00:00:00 2001 From: Don Okuda Date: Fri, 13 Oct 2017 10:51:44 -0700 Subject: [PATCH 031/241] :fire: Toggle layout --- .../Editor/GitHub.Unity/UI/PublishView.cs | 23 ++----------------- 1 file changed, 2 insertions(+), 21 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs index 770918e29..c06285d06 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs @@ -146,27 +146,8 @@ public override void OnGUI() repoName = EditorGUILayout.TextField(RepositoryNameLabel, repoName); repoDescription = EditorGUILayout.TextField(DescriptionLabel, repoDescription); - GUILayout.Space(Styles.PublishViewSpacingHeight); - - GUILayout.BeginVertical(); - { - GUILayout.BeginHorizontal(); - { - togglePrivate = GUILayout.Toggle(togglePrivate, CreatePrivateRepositoryLabel); - } - GUILayout.EndHorizontal(); - - GUILayout.BeginHorizontal(); - { - GUILayout.Space(Styles.PublishViewSpacingHeight); - var repoPrivacyExplanation = togglePrivate ? PrivateRepoMessage : PublicRepoMessage; - GUILayout.Label(repoPrivacyExplanation, Styles.LongMessageStyle); - } - GUILayout.EndHorizontal(); - } - GUILayout.EndVertical(); - - GUILayout.Space(Styles.PublishViewSpacingHeight); + togglePrivate = EditorGUILayout.Toggle(CreatePrivateRepositoryLabel, togglePrivate); + var repoPrivacyExplanation = togglePrivate ? PrivateRepoMessage : PublicRepoMessage; GUILayout.BeginHorizontal(); { From ffffb9a71bc1242fec1960d4fe9c2b9c7c88e656 Mon Sep 17 00:00:00 2001 From: Don Okuda Date: Fri, 13 Oct 2017 10:55:17 -0700 Subject: [PATCH 032/241] Update create private repo label --- src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs index c06285d06..3327c9c8b 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs @@ -20,7 +20,7 @@ class PublishView : Subview private const string SelectedOwnerLabel = "Owner"; private const string RepositoryNameLabel = "Repository Name"; private const string DescriptionLabel = "Description"; - private const string CreatePrivateRepositoryLabel = "Create as a private repository"; + private const string CreatePrivateRepositoryLabel = "Make repository private"; private const string PublishLimtPrivateRepositoriesError = "You are currently at your limt of private repositories"; [SerializeField] private string username; From 6cdbe9db1471346a11ef9523901057524c3dc287 Mon Sep 17 00:00:00 2001 From: Don Okuda Date: Fri, 13 Oct 2017 11:10:02 -0700 Subject: [PATCH 033/241] Add title --- src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs index 3327c9c8b..31de223a7 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs @@ -140,6 +140,8 @@ private void LoadOrganizations() public override void OnGUI() { + GUILayout.Label("Publish to GitHub", EditorStyles.boldLabel); + EditorGUI.BeginDisabledGroup(isBusy); { selectedOwner = EditorGUILayout.Popup(SelectedOwnerLabel, selectedOwner, owners); From fb6b1d9bc7715c7c8c7f382bdd0da7f3b9d5760a Mon Sep 17 00:00:00 2001 From: Don Okuda Date: Fri, 13 Oct 2017 11:45:47 -0700 Subject: [PATCH 034/241] Halp --- src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs index 31de223a7..326efc849 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs @@ -201,7 +201,7 @@ public override void OnGUI() GUILayout.Space(10); if (error != null) - GUILayout.Label(error, Styles.ErrorLabel); + EditorGUILayout.HelpBox(error, MessageType.Error); GUILayout.FlexibleSpace(); } From 45a08b36c0fa2e8eee106e663d0807364645f40d Mon Sep 17 00:00:00 2001 From: Don Okuda Date: Fri, 13 Oct 2017 13:50:02 -0700 Subject: [PATCH 035/241] More halp --- src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs index 326efc849..37db9c2fb 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs @@ -149,7 +149,9 @@ public override void OnGUI() repoDescription = EditorGUILayout.TextField(DescriptionLabel, repoDescription); togglePrivate = EditorGUILayout.Toggle(CreatePrivateRepositoryLabel, togglePrivate); + var repoPrivacyExplanation = togglePrivate ? PrivateRepoMessage : PublicRepoMessage; + EditorGUILayout.HelpBox(repoPrivacyExplanation, MessageType.None); GUILayout.BeginHorizontal(); { From ac8bd7b1bf09e19c97b85d8e9b06a6fc13c20b97 Mon Sep 17 00:00:00 2001 From: Don Okuda Date: Fri, 13 Oct 2017 15:47:06 -0700 Subject: [PATCH 036/241] yay an image! --- .../Assets/Editor/GitHub.Unity/GitHub.Unity.csproj | 6 ++++-- .../IconsAndLogos/empty-state-init.png | 3 +++ .../IconsAndLogos/empty-state-init@2x.png | 3 +++ .../Assets/Editor/GitHub.Unity/Misc/Styles.cs | 14 ++++++++++++++ .../Editor/GitHub.Unity/UI/InitProjectView.cs | 2 ++ .../Assets/Editor/GitHub.Unity/UI/Window.cs | 2 +- 6 files changed, 27 insertions(+), 3 deletions(-) create mode 100644 src/UnityExtension/Assets/Editor/GitHub.Unity/IconsAndLogos/empty-state-init.png create mode 100644 src/UnityExtension/Assets/Editor/GitHub.Unity/IconsAndLogos/empty-state-init@2x.png diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/GitHub.Unity.csproj b/src/UnityExtension/Assets/Editor/GitHub.Unity/GitHub.Unity.csproj index d2ecc2a53..8eae0402c 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/GitHub.Unity.csproj +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/GitHub.Unity.csproj @@ -149,6 +149,8 @@ + + @@ -203,7 +205,7 @@ - - \ No newline at end of file + diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/IconsAndLogos/empty-state-init.png b/src/UnityExtension/Assets/Editor/GitHub.Unity/IconsAndLogos/empty-state-init.png new file mode 100644 index 000000000..09389a7dc --- /dev/null +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/IconsAndLogos/empty-state-init.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ee3c66f73cbb96d92aef34f0ef7eb9e615db83fa83b810cbc2c4eea825bd1e4c +size 5571 diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/IconsAndLogos/empty-state-init@2x.png b/src/UnityExtension/Assets/Editor/GitHub.Unity/IconsAndLogos/empty-state-init@2x.png new file mode 100644 index 000000000..c73d5222f --- /dev/null +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/IconsAndLogos/empty-state-init@2x.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ea0086690444613755947b3bc2b25390f860a362126c4a92d222da9c65ed4790 +size 14242 diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/Misc/Styles.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/Misc/Styles.cs index c3d1c1013..66fbf1fef 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/Misc/Styles.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/Misc/Styles.cs @@ -96,6 +96,7 @@ class Styles localCommitIcon, repoIcon, lockIcon, + emptyStateInit, dropdownListIcon; private static Color timelineBarColor; @@ -803,6 +804,19 @@ public static Texture2D LockIcon } } + public static Texture2D EmptyStateInit + { + get + { + if (emptyStateInit == null) + { + emptyStateInit = Utility.GetIcon("empty-state-init.png", "empty-state-init@2x.png"); + } + return emptyStateInit; + } + + } + public static Texture2D DropdownListIcon { get diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs index a0e865077..6acba776a 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs @@ -35,6 +35,8 @@ public override void OnGUI() { GUILayout.FlexibleSpace(); + GUILayout.Label(Styles.EmptyStateInit); + GUILayout.Label(NoRepoTitle, Styles.BoldCenteredLabel); GUILayout.BeginHorizontal(); diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs index cf9da47f6..f0e5b4c51 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs @@ -284,7 +284,7 @@ private void DoToolbarGUI() changeTab = activeTab; EditorGUI.BeginChangeCheck(); { - if (HasRepository) + if (!HasRepository) { changeTab = TabButton(SubTab.Changes, ChangesTitle, changeTab); changeTab = TabButton(SubTab.History, HistoryTitle, changeTab); From ae1ccde71337f5b0b3fc484a5dd6b10b02debd9f Mon Sep 17 00:00:00 2001 From: Don Okuda Date: Fri, 13 Oct 2017 16:07:45 -0700 Subject: [PATCH 037/241] Set a max height as well --- .../Assets/Editor/GitHub.Unity/UI/InitProjectView.cs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs index 6acba776a..95611b7e9 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs @@ -35,7 +35,13 @@ public override void OnGUI() { GUILayout.FlexibleSpace(); - GUILayout.Label(Styles.EmptyStateInit); + GUILayout.BeginHorizontal(); + { + GUILayout.FlexibleSpace(); + GUILayout.Label(Styles.EmptyStateInit, GUILayout.MaxWidth(265), GUILayout.MaxHeight(136)); + GUILayout.FlexibleSpace(); + } + GUILayout.EndHorizontal(); GUILayout.Label(NoRepoTitle, Styles.BoldCenteredLabel); From a4e965b2bef4cc7532d5c3140b2f47c4e6377855 Mon Sep 17 00:00:00 2001 From: Don Okuda Date: Fri, 13 Oct 2017 16:16:01 -0700 Subject: [PATCH 038/241] halp --- .../Assets/Editor/GitHub.Unity/UI/InitProjectView.cs | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs index 95611b7e9..0e96f3803 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs @@ -62,11 +62,7 @@ public override void OnGUI() GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); - GUILayout.BeginHorizontal(); - GUILayout.FlexibleSpace(); - GUILayout.Label("There was an error initializing a repository.", Styles.ErrorLabel); - GUILayout.FlexibleSpace(); - GUILayout.EndHorizontal(); + EditorGUILayout.HelpBox("There was an error initializing a repository.", MessageType.Error); GUILayout.FlexibleSpace(); } From d18ae814a37bb39f8abfb0f0feda16c4bf07a7e4 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Mon, 16 Oct 2017 17:31:24 -0400 Subject: [PATCH 039/241] IsBusy should be NonSerialized --- .../Assets/Editor/GitHub.Unity/UI/InitProjectView.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs index c8ee372a3..9f5bf67d2 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs @@ -15,7 +15,7 @@ class InitProjectView : Subview private const string NoRepoTitle = "No Git repository found for this project"; private const string NoRepoDescription = "Initialize a Git repository to track changes and collaborate with others."; - [SerializeField] private bool isBusy; + [NonSerialized] private bool isBusy; [SerializeField] private bool isPublished; public override void OnDataUpdate() From c9d20157beda249e279c6c2f3b93ef06c371df75 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Mon, 16 Oct 2017 17:47:53 -0400 Subject: [PATCH 040/241] Undoing change made for ui testing --- src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs index f0e5b4c51..cf9da47f6 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs @@ -284,7 +284,7 @@ private void DoToolbarGUI() changeTab = activeTab; EditorGUI.BeginChangeCheck(); { - if (!HasRepository) + if (HasRepository) { changeTab = TabButton(SubTab.Changes, ChangesTitle, changeTab); changeTab = TabButton(SubTab.History, HistoryTitle, changeTab); From 494f552b6b6b05edcb8e58bb07bf4c075997b136 Mon Sep 17 00:00:00 2001 From: Don Okuda Date: Tue, 17 Oct 2017 14:55:50 -0700 Subject: [PATCH 041/241] Bring back auth header styles Use default padding settings --- .../Assets/Editor/GitHub.Unity/Misc/Styles.cs | 1 - .../Assets/Editor/GitHub.Unity/UI/PublishView.cs | 6 +++++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/Misc/Styles.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/Misc/Styles.cs index a4c57790a..aac5f334f 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/Misc/Styles.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/Misc/Styles.cs @@ -578,7 +578,6 @@ public static GUIStyle AuthHeaderBoxStyle { authHeaderBoxStyle = new GUIStyle(HeaderBoxStyle); authHeaderBoxStyle.name = "AuthHeaderBoxStyle"; - authHeaderBoxStyle.padding = new RectOffset(10, 10, 0, 5); } return authHeaderBoxStyle; } diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs index 1940b728c..27f933f05 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs @@ -157,7 +157,11 @@ private void LoadOwners() public override void OnGUI() { - GUILayout.Label("Publish to GitHub", EditorStyles.boldLabel); + GUILayout.BeginHorizontal(Styles.AuthHeaderBoxStyle); + { + GUILayout.Label("Publish to GitHub", EditorStyles.boldLabel); + } + GUILayout.EndHorizontal(); EditorGUI.BeginDisabledGroup(isBusy); { From e344577c9e3c66acf49a31cd65cad72fa4434945 Mon Sep 17 00:00:00 2001 From: Andreia Gaita Date: Thu, 19 Oct 2017 15:48:57 +0200 Subject: [PATCH 042/241] Fix merge --- .../Assets/Editor/GitHub.Unity/UI/InitProjectView.cs | 7 +------ src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs | 1 - 2 files changed, 1 insertion(+), 7 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs index 4a4a4e961..f7924a89e 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs @@ -18,12 +18,6 @@ class InitProjectView : Subview [SerializeField] private bool isBusy; [SerializeField] private bool isPublished; - public override void OnDataUpdate() - { - base.OnDataUpdate(); - MaybeUpdateData(); - } - public override void InitializeView(IView parent) { base.InitializeView(parent); @@ -77,6 +71,7 @@ public override void Refresh() userSettingsView.Refresh(); gitPathView.Refresh(); } + public override void OnGUI() { var headerRect = EditorGUILayout.BeginHorizontal(Styles.HeaderBoxStyle); diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs index 576a2763e..a9bbaca1b 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs @@ -469,7 +469,6 @@ private Subview ActiveView get { return ToView(activeTab); } } - } public override bool IsBusy { get { return false; } From e13e4b5cef2662d397a239806ffcaa1fc27ead29 Mon Sep 17 00:00:00 2001 From: Andreia Gaita Date: Thu, 19 Oct 2017 15:57:31 +0200 Subject: [PATCH 043/241] Remove unused code --- .../Editor/GitHub.Unity/UI/GitPathView.cs | 1 - .../Editor/GitHub.Unity/UI/InitProjectView.cs | 49 +------------------ .../GitHub.Unity/UI/UserSettingsView.cs | 18 ++----- 3 files changed, 7 insertions(+), 61 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/GitPathView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/GitPathView.cs index bd8e60c68..c8037d152 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/GitPathView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/GitPathView.cs @@ -38,7 +38,6 @@ class GitPathView : Subview public override void OnEnable() { base.OnEnable(); - gitExecHasChanged = true; } diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs index f7924a89e..00360f0fe 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs @@ -16,7 +16,6 @@ class InitProjectView : Subview [SerializeField] private UserSettingsView userSettingsView = new UserSettingsView(); [SerializeField] private GitPathView gitPathView = new GitPathView(); [SerializeField] private bool isBusy; - [SerializeField] private bool isPublished; public override void InitializeView(IView parent) { @@ -25,51 +24,12 @@ public override void InitializeView(IView parent) gitPathView.InitializeView(this); } - public override void OnEnable() - { - base.OnEnable(); - userSettingsView.OnEnable(); - gitPathView.OnEnable(); - } - - public override void OnDisable() - { - base.OnDisable(); - userSettingsView.OnDisable(); - gitPathView.OnDisable(); - } - public override void OnDataUpdate() { base.OnDataUpdate(); - if (userSettingsView != null) - { - userSettingsView.OnDataUpdate(); - } - - if (gitPathView != null) - { - gitPathView.OnDataUpdate(); - } - } - - public override void OnRepositoryChanged(IRepository oldRepository) - { - base.OnRepositoryChanged(oldRepository); - - userSettingsView.OnRepositoryChanged(oldRepository); - gitPathView.OnRepositoryChanged(oldRepository); - - Refresh(); - } - - public override void Refresh() - { - base.Refresh(); - - userSettingsView.Refresh(); - gitPathView.Refresh(); + userSettingsView.OnDataUpdate(); + gitPathView.OnDataUpdate(); } public override void OnGUI() @@ -136,11 +96,6 @@ public override void OnGUI() GUILayout.EndVertical(); } - private void MaybeUpdateData() - { - isPublished = Repository != null && Repository.CurrentRemote.HasValue; - } - public override bool IsBusy { get { return isBusy || userSettingsView.IsBusy || gitPathView.IsBusy; } diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/UserSettingsView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/UserSettingsView.cs index 8d50a9cdc..674231aef 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/UserSettingsView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/UserSettingsView.cs @@ -21,7 +21,6 @@ class UserSettingsView : Subview [SerializeField] private string gitName; [SerializeField] private string gitEmail; - [SerializeField] private string newGitName; [SerializeField] private string newGitEmail; [SerializeField] private User cachedUser; @@ -32,13 +31,6 @@ public override void OnDataUpdate() MaybeUpdateData(); } - public override void OnRepositoryChanged(IRepository oldRepository) - { - base.OnRepositoryChanged(oldRepository); - - Refresh(); - } - public override void OnGUI() { GUILayout.Label(GitConfigTitle, EditorStyles.boldLabel); @@ -108,11 +100,6 @@ public override void OnGUI() EditorGUI.EndDisabledGroup(); } - public override bool IsBusy - { - get { return isBusy; } - } - private void MaybeUpdateData() { if (Repository == null) @@ -154,5 +141,10 @@ private void MaybeUpdateData() newGitName = gitName = Repository.User.Name; newGitEmail = gitEmail = Repository.User.Email; } + + public override bool IsBusy + { + get { return isBusy; } + } } } From 493906047e03873e0336dbdebe91bd4f77f655d4 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 19 Oct 2017 10:03:09 -0400 Subject: [PATCH 044/241] Removing unused success variable in GitConfig --- src/GitHub.Api/Git/GitConfig.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/GitHub.Api/Git/GitConfig.cs b/src/GitHub.Api/Git/GitConfig.cs index c80d59662..05ce1bb10 100644 --- a/src/GitHub.Api/Git/GitConfig.cs +++ b/src/GitHub.Api/Git/GitConfig.cs @@ -216,16 +216,16 @@ public string GetString(string key) public int GetInt(string key) { var value = this[key]; - var result = 0; - var success = int.TryParse(value, out result); + int result = 0; + int.TryParse(value, out result); return result; } public float GetFloat(string key) { var value = this[key]; - var result = 0F; - var success = float.TryParse(value, out result); + float result = 0F; + float.TryParse(value, out result); return result; } From 722363ad1db5979085e1e5fc1ad145c4e77f7f1f Mon Sep 17 00:00:00 2001 From: Andreia Gaita Date: Thu, 19 Oct 2017 16:04:42 +0200 Subject: [PATCH 045/241] La de da kill the usings la la --- .../Assets/Editor/GitHub.Unity/UI/GitPathView.cs | 4 ---- .../Assets/Editor/GitHub.Unity/UI/InitProjectView.cs | 3 --- .../Assets/Editor/GitHub.Unity/UI/UserSettingsView.cs | 4 ---- 3 files changed, 11 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/GitPathView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/GitPathView.cs index c8037d152..37db8aa24 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/GitPathView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/GitPathView.cs @@ -1,9 +1,5 @@ using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; using System.Text; -using System.Threading.Tasks; using UnityEditor; using UnityEngine; diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs index 00360f0fe..ec20862dd 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs @@ -1,9 +1,6 @@ using System; -using System.Collections.Generic; -using System.Linq; using UnityEditor; using UnityEngine; -using Object = UnityEngine.Object; namespace GitHub.Unity { diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/UserSettingsView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/UserSettingsView.cs index 674231aef..d754bb60d 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/UserSettingsView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/UserSettingsView.cs @@ -1,8 +1,4 @@ using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Threading.Tasks; using UnityEditor; using UnityEngine; From e4de8445d8bcc4ae1353042e2c57890363d0e62d Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 19 Oct 2017 10:04:49 -0400 Subject: [PATCH 046/241] Removing unused functionality to disable the native interface in RepositoryWatcher --- src/GitHub.Api/Events/RepositoryWatcher.cs | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/src/GitHub.Api/Events/RepositoryWatcher.cs b/src/GitHub.Api/Events/RepositoryWatcher.cs index b72d6bd3c..da1a07043 100644 --- a/src/GitHub.Api/Events/RepositoryWatcher.cs +++ b/src/GitHub.Api/Events/RepositoryWatcher.cs @@ -30,7 +30,6 @@ class RepositoryWatcher : IRepositoryWatcher private readonly CancellationToken cancellationToken; private readonly NPath[] ignoredPaths; private readonly ManualResetEventSlim pauseEvent; - private readonly bool disableNative; private NativeInterface nativeInterface; private bool running; private Task task; @@ -68,8 +67,7 @@ public void Initialize() try { - if (!disableNative) - nativeInterface = new NativeInterface(pathsRepositoryPath); + nativeInterface = new NativeInterface(pathsRepositoryPath); } catch (Exception ex) { @@ -79,12 +77,6 @@ public void Initialize() public void Start() { - if (disableNative) - { - Logger.Trace("Native interface is disabled"); - return; - } - if (nativeInterface == null) { Logger.Warning("NativeInterface is null"); From 7bdd974e81156dcd79d4a0866fde0460c562097e Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 19 Oct 2017 10:05:49 -0400 Subject: [PATCH 047/241] Removing unused string builder --- src/GitHub.Api/NewTaskSystem/BaseOutputProcessor.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/GitHub.Api/NewTaskSystem/BaseOutputProcessor.cs b/src/GitHub.Api/NewTaskSystem/BaseOutputProcessor.cs index 9456c7c43..1c2f2ea0d 100644 --- a/src/GitHub.Api/NewTaskSystem/BaseOutputProcessor.cs +++ b/src/GitHub.Api/NewTaskSystem/BaseOutputProcessor.cs @@ -84,7 +84,6 @@ public override void LineReceived(string line) abstract class FirstResultOutputProcessor : BaseOutputProcessor { - private readonly StringBuilder sb = new StringBuilder(); private bool isSet = false; public override void LineReceived(string line) { From de70b7f9dbf91c2b131fb47e8629024a9df94f22 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 19 Oct 2017 10:09:47 -0400 Subject: [PATCH 048/241] Removing UsageTracker from RepositoryManager --- src/GitHub.Api/Application/ApplicationManagerBase.cs | 2 +- src/GitHub.Api/Git/RepositoryManager.cs | 8 +++----- src/tests/IntegrationTests/BaseGitEnvironmentTest.cs | 2 +- 3 files changed, 5 insertions(+), 7 deletions(-) diff --git a/src/GitHub.Api/Application/ApplicationManagerBase.cs b/src/GitHub.Api/Application/ApplicationManagerBase.cs index d0eb0bc3e..fb791bcae 100644 --- a/src/GitHub.Api/Application/ApplicationManagerBase.cs +++ b/src/GitHub.Api/Application/ApplicationManagerBase.cs @@ -127,7 +127,7 @@ public void RestartRepository() { if (Environment.RepositoryPath != null) { - repositoryManager = Unity.RepositoryManager.CreateInstance(Platform, TaskManager, UsageTracker, GitClient, Environment.RepositoryPath); + repositoryManager = Unity.RepositoryManager.CreateInstance(Platform, TaskManager, GitClient, Environment.RepositoryPath); repositoryManager.Initialize(); Environment.Repository.Initialize(repositoryManager); repositoryManager.Start(); diff --git a/src/GitHub.Api/Git/RepositoryManager.cs b/src/GitHub.Api/Git/RepositoryManager.cs index e3892806a..90f9c7b32 100644 --- a/src/GitHub.Api/Git/RepositoryManager.cs +++ b/src/GitHub.Api/Git/RepositoryManager.cs @@ -100,7 +100,6 @@ class RepositoryManager : IRepositoryManager private readonly IPlatform platform; private readonly IRepositoryPathConfiguration repositoryPaths; private readonly ITaskManager taskManager; - private readonly IUsageTracker usageTracker; private readonly IRepositoryWatcher watcher; private bool isBusy; @@ -119,14 +118,13 @@ class RepositoryManager : IRepositoryManager public event Action OnRemoteBranchRemoved; public event Action OnStatusUpdated; - public RepositoryManager(IPlatform platform, ITaskManager taskManager, IUsageTracker usageTracker, IGitConfig gitConfig, + public RepositoryManager(IPlatform platform, ITaskManager taskManager, IGitConfig gitConfig, IRepositoryWatcher repositoryWatcher, IGitClient gitClient, IRepositoryPathConfiguration repositoryPaths, CancellationToken cancellationToken) { this.repositoryPaths = repositoryPaths; this.platform = platform; this.taskManager = taskManager; - this.usageTracker = usageTracker; this.cancellationToken = cancellationToken; this.gitClient = gitClient; this.watcher = repositoryWatcher; @@ -135,7 +133,7 @@ public RepositoryManager(IPlatform platform, ITaskManager taskManager, IUsageTra SetupWatcher(); } - public static RepositoryManager CreateInstance(IPlatform platform, ITaskManager taskManager, IUsageTracker usageTracker, + public static RepositoryManager CreateInstance(IPlatform platform, ITaskManager taskManager, IGitClient gitClient, NPath repositoryRoot) { var repositoryPathConfiguration = new RepositoryPathConfiguration(repositoryRoot); @@ -144,7 +142,7 @@ public static RepositoryManager CreateInstance(IPlatform platform, ITaskManager var repositoryWatcher = new RepositoryWatcher(platform, repositoryPathConfiguration, taskManager.Token); - return new RepositoryManager(platform, taskManager, usageTracker, gitConfig, repositoryWatcher, + return new RepositoryManager(platform, taskManager, gitConfig, repositoryWatcher, gitClient, repositoryPathConfiguration, taskManager.Token); } diff --git a/src/tests/IntegrationTests/BaseGitEnvironmentTest.cs b/src/tests/IntegrationTests/BaseGitEnvironmentTest.cs index e65489359..4e59da75b 100644 --- a/src/tests/IntegrationTests/BaseGitEnvironmentTest.cs +++ b/src/tests/IntegrationTests/BaseGitEnvironmentTest.cs @@ -30,7 +30,7 @@ protected async Task Initialize(NPath repoPath, NPath environmentP var usageTracker = new NullUsageTracker(); - RepositoryManager = GitHub.Unity.RepositoryManager.CreateInstance(Platform, TaskManager, usageTracker, GitClient, repoPath); + RepositoryManager = GitHub.Unity.RepositoryManager.CreateInstance(Platform, TaskManager, GitClient, repoPath); RepositoryManager.Initialize(); Environment.Repository = new Repository("TestRepo", repoPath); From e5c3ee8d6e4e90f63b0c0f500b69b1fa592223d9 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 19 Oct 2017 10:16:44 -0400 Subject: [PATCH 049/241] Removing the cancellationToken from RepositoryManager --- src/GitHub.Api/Git/RepositoryManager.cs | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/src/GitHub.Api/Git/RepositoryManager.cs b/src/GitHub.Api/Git/RepositoryManager.cs index 90f9c7b32..d36633f28 100644 --- a/src/GitHub.Api/Git/RepositoryManager.cs +++ b/src/GitHub.Api/Git/RepositoryManager.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Threading; using System.Threading.Tasks; namespace GitHub.Unity @@ -94,7 +93,6 @@ public RepositoryPathConfiguration(NPath repositoryPath) class RepositoryManager : IRepositoryManager { - private readonly CancellationToken cancellationToken; private readonly IGitConfig config; private readonly IGitClient gitClient; private readonly IPlatform platform; @@ -120,12 +118,11 @@ class RepositoryManager : IRepositoryManager public RepositoryManager(IPlatform platform, ITaskManager taskManager, IGitConfig gitConfig, IRepositoryWatcher repositoryWatcher, IGitClient gitClient, - IRepositoryPathConfiguration repositoryPaths, CancellationToken cancellationToken) + IRepositoryPathConfiguration repositoryPaths) { this.repositoryPaths = repositoryPaths; this.platform = platform; this.taskManager = taskManager; - this.cancellationToken = cancellationToken; this.gitClient = gitClient; this.watcher = repositoryWatcher; this.config = gitConfig; @@ -143,7 +140,7 @@ public static RepositoryManager CreateInstance(IPlatform platform, ITaskManager var repositoryWatcher = new RepositoryWatcher(platform, repositoryPathConfiguration, taskManager.Token); return new RepositoryManager(platform, taskManager, gitConfig, repositoryWatcher, - gitClient, repositoryPathConfiguration, taskManager.Token); + gitClient, repositoryPathConfiguration); } public void Initialize() From 0bd09d65aa8cc9bdf17040ea660209d0b0ca6927 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 19 Oct 2017 10:17:38 -0400 Subject: [PATCH 050/241] Removing unused task from RepositoryWatcher --- src/GitHub.Api/Events/RepositoryWatcher.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/GitHub.Api/Events/RepositoryWatcher.cs b/src/GitHub.Api/Events/RepositoryWatcher.cs index da1a07043..6528b0d3a 100644 --- a/src/GitHub.Api/Events/RepositoryWatcher.cs +++ b/src/GitHub.Api/Events/RepositoryWatcher.cs @@ -32,7 +32,6 @@ class RepositoryWatcher : IRepositoryWatcher private readonly ManualResetEventSlim pauseEvent; private NativeInterface nativeInterface; private bool running; - private Task task; private int lastCountOfProcessedEvents = 0; private bool processingEvents; private readonly ManualResetEventSlim signalProcessingEventsDone = new ManualResetEventSlim(false); @@ -87,7 +86,7 @@ public void Start() running = true; pauseEvent.Reset(); - task = Task.Factory.StartNew(WatcherLoop, cancellationToken, TaskCreationOptions.None, TaskScheduler.Default); + Task.Factory.StartNew(WatcherLoop, cancellationToken, TaskCreationOptions.None, TaskScheduler.Default); } public void Stop() From 5d2582fd64b33130a4135f83de81316b8926d83e Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 19 Oct 2017 10:18:37 -0400 Subject: [PATCH 051/241] Removing unused credential manager from GitClient --- src/GitHub.Api/Application/ApplicationManagerBase.cs | 2 +- src/GitHub.Api/Git/GitClient.cs | 5 +---- src/tests/IntegrationTests/BaseGitEnvironmentTest.cs | 2 +- 3 files changed, 3 insertions(+), 6 deletions(-) diff --git a/src/GitHub.Api/Application/ApplicationManagerBase.cs b/src/GitHub.Api/Application/ApplicationManagerBase.cs index fb791bcae..2622ec60c 100644 --- a/src/GitHub.Api/Application/ApplicationManagerBase.cs +++ b/src/GitHub.Api/Application/ApplicationManagerBase.cs @@ -39,7 +39,7 @@ protected void Initialize() Logging.TracingEnabled = UserSettings.Get(Constants.TraceLoggingKey, false); ProcessManager = new ProcessManager(Environment, Platform.GitEnvironment, CancellationToken); Platform.Initialize(ProcessManager, TaskManager); - GitClient = new GitClient(Environment, ProcessManager, Platform.CredentialManager, TaskManager); + GitClient = new GitClient(Environment, ProcessManager, TaskManager); SetupMetrics(); } diff --git a/src/GitHub.Api/Git/GitClient.cs b/src/GitHub.Api/Git/GitClient.cs index 0b7978338..63e9a4656 100644 --- a/src/GitHub.Api/Git/GitClient.cs +++ b/src/GitHub.Api/Git/GitClient.cs @@ -87,16 +87,13 @@ class GitClient : IGitClient { private readonly IEnvironment environment; private readonly IProcessManager processManager; - private readonly ICredentialManager credentialManager; private readonly ITaskManager taskManager; private readonly CancellationToken cancellationToken; - public GitClient(IEnvironment environment, IProcessManager processManager, - ICredentialManager credentialManager, ITaskManager taskManager) + public GitClient(IEnvironment environment, IProcessManager processManager, ITaskManager taskManager) { this.environment = environment; this.processManager = processManager; - this.credentialManager = credentialManager; this.taskManager = taskManager; this.cancellationToken = taskManager.Token; } diff --git a/src/tests/IntegrationTests/BaseGitEnvironmentTest.cs b/src/tests/IntegrationTests/BaseGitEnvironmentTest.cs index 4e59da75b..d0bd107f6 100644 --- a/src/tests/IntegrationTests/BaseGitEnvironmentTest.cs +++ b/src/tests/IntegrationTests/BaseGitEnvironmentTest.cs @@ -26,7 +26,7 @@ protected async Task Initialize(NPath repoPath, NPath environmentP Platform.Initialize(ProcessManager, TaskManager); - GitClient = new GitClient(Environment, ProcessManager, Platform.CredentialManager, TaskManager); + GitClient = new GitClient(Environment, ProcessManager, TaskManager); var usageTracker = new NullUsageTracker(); From 29cf4b96b66c5f9c79252060fd005aeec0e14414 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 19 Oct 2017 10:19:34 -0400 Subject: [PATCH 052/241] Removing unused fields from ApiClient --- src/GitHub.Api/Application/ApiClient.cs | 5 ----- 1 file changed, 5 deletions(-) diff --git a/src/GitHub.Api/Application/ApiClient.cs b/src/GitHub.Api/Application/ApiClient.cs index c4ae1782d..9783078d4 100644 --- a/src/GitHub.Api/Application/ApiClient.cs +++ b/src/GitHub.Api/Application/ApiClient.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Threading; using System.Threading.Tasks; using Octokit; @@ -27,14 +26,10 @@ public static IApiClient Create(UriString repositoryUrl, IKeychain keychain) private readonly IKeychain keychain; private readonly IGitHubClient githubClient; private readonly ILoginManager loginManager; - private static readonly SemaphoreSlim sem = new SemaphoreSlim(1); IList organizationsCache; Octokit.User userCache; - string owner; - bool? isEnterprise; - public ApiClient(UriString hostUrl, IKeychain keychain, IGitHubClient githubClient) { Guard.ArgumentNotNull(hostUrl, nameof(hostUrl)); From f9e7948084b06df2ac1fb29fe40ff26d844e0395 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 19 Oct 2017 10:20:29 -0400 Subject: [PATCH 053/241] Removing unused variables from HistoryView --- .../Assets/Editor/GitHub.Unity/UI/HistoryView.cs | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/HistoryView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/HistoryView.cs index f5b5f2fc9..62b0f8ad5 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/HistoryView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/HistoryView.cs @@ -473,7 +473,6 @@ private void RevertCommit() private bool HistoryEntry(GitLogEntry entry, LogEntryState state, bool selected) { var entryRect = GUILayoutUtility.GetRect(Styles.HistoryEntryHeight, Styles.HistoryEntryHeight); - var timelineBarRect = new Rect(entryRect.x + Styles.BaseSpacing, 0, 2, Styles.HistoryDetailsHeight); if (Event.current.type == EventType.Repaint) { @@ -481,7 +480,6 @@ private bool HistoryEntry(GitLogEntry entry, LogEntryState state, bool selected) var summaryRect = new Rect(entryRect.x, entryRect.y + (Styles.BaseSpacing / 2), entryRect.width, Styles.HistorySummaryHeight + Styles.BaseSpacing); var timestampRect = new Rect(entryRect.x, entryRect.yMax - Styles.HistoryDetailsHeight - (Styles.BaseSpacing / 2), entryRect.width, Styles.HistoryDetailsHeight); - var authorRect = new Rect(timestampRect.xMax, timestampRect.y, timestampRect.width, timestampRect.height); var contentOffset = new Vector2(Styles.BaseSpacing * 2, 0); @@ -630,7 +628,6 @@ private void Push() private void Fetch() { - var remote = Repository.CurrentRemote.HasValue ? Repository.CurrentRemote.Value.Name : String.Empty; Repository .Fetch() .FinallyInUI((success, e) => { From 46ca301913e2c2ac22e5e0013d5d2686e5aff1de Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 19 Oct 2017 10:21:17 -0400 Subject: [PATCH 054/241] Removing unused fields from SettingsView --- .../Assets/Editor/GitHub.Unity/UI/SettingsView.cs | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/SettingsView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/SettingsView.cs index 6bec1cb99..8d212ca9e 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/SettingsView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/SettingsView.cs @@ -11,7 +11,6 @@ namespace GitHub.Unity [Serializable] class SettingsView : Subview { - private const string GitInstallTitle = "Git installation"; private const string GitRepositoryTitle = "Repository Configuration"; private const string GitRepositoryRemoteLabel = "Remote"; private const string GitRepositorySave = "Save Repository"; @@ -20,9 +19,6 @@ class SettingsView : Subview private const string EnableTraceLoggingLabel = "Enable Trace Logging"; private const string MetricsOptInLabel = "Help us improve by sending anonymous usage data"; private const string DefaultRepositoryRemoteName = "origin"; - private const string BrowseButton = "..."; - private const string PathToGit = "Path to Git"; - private const string GitPathSaveButton = "Save Path"; [NonSerialized] private int newGitIgnoreRulesSelection = -1; [NonSerialized] private bool isBusy; From 4b73234e98c65b7fa6f0d6d09b9ccba1247942e1 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 19 Oct 2017 10:22:02 -0400 Subject: [PATCH 055/241] Removing unused fields from SettingsView --- .../Assets/Editor/GitHub.Unity/UI/SettingsView.cs | 7 ------- 1 file changed, 7 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/SettingsView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/SettingsView.cs index 8d212ca9e..731fe401b 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/SettingsView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/SettingsView.cs @@ -20,11 +20,8 @@ class SettingsView : Subview private const string MetricsOptInLabel = "Help us improve by sending anonymous usage data"; private const string DefaultRepositoryRemoteName = "origin"; - [NonSerialized] private int newGitIgnoreRulesSelection = -1; [NonSerialized] private bool isBusy; - [SerializeField] private int gitIgnoreRulesSelection = 0; - [SerializeField] private string initDirectory; [SerializeField] private List lockedFiles = new List(); [SerializeField] private Vector2 lockScrollPos; [SerializeField] private string repositoryRemoteName; @@ -35,16 +32,12 @@ class SettingsView : Subview [NonSerialized] private bool remoteHasChanged; [NonSerialized] private bool locksHaveChanged; - [SerializeField] private string newGitName; - [SerializeField] private string newGitEmail; [SerializeField] private string newRepositoryRemoteUrl; - [SerializeField] private User cachedUser; [SerializeField] private bool metricsEnabled; [NonSerialized] private bool metricsHasChanged; [SerializeField] private GitPathView gitPathView = new GitPathView(); - [SerializeField] private UserSettingsView userSettingsView = new UserSettingsView(); public override void InitializeView(IView parent) From e68735f29139a72640eec0ff6ec2b89933b35070 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 19 Oct 2017 10:22:47 -0400 Subject: [PATCH 056/241] Removing unused data from InitProjectView --- .../Assets/Editor/GitHub.Unity/UI/InitProjectView.cs | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs index c8ee372a3..45967dd9e 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs @@ -16,13 +16,6 @@ class InitProjectView : Subview private const string NoRepoDescription = "Initialize a Git repository to track changes and collaborate with others."; [SerializeField] private bool isBusy; - [SerializeField] private bool isPublished; - - public override void OnDataUpdate() - { - base.OnDataUpdate(); - MaybeUpdateData(); - } public override void OnRepositoryChanged(IRepository oldRepository) { @@ -90,11 +83,6 @@ public override void OnGUI() GUILayout.EndVertical(); } - private void MaybeUpdateData() - { - isPublished = Repository != null && Repository.CurrentRemote.HasValue; - } - public override bool IsBusy { get { return isBusy; } From bc15e774c8dd1a154122e6abf15c05548610703b Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 19 Oct 2017 10:24:18 -0400 Subject: [PATCH 057/241] Removing unused timelineBarColor from Styles --- .../Assets/Editor/GitHub.Unity/Misc/Styles.cs | 14 -------------- 1 file changed, 14 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/Misc/Styles.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/Misc/Styles.cs index a4c57790a..27c0e37ec 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/Misc/Styles.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/Misc/Styles.cs @@ -97,8 +97,6 @@ class Styles lockIcon, dropdownListIcon; - private static Color timelineBarColor; - public static Texture2D GetFileStatusIcon(GitFileStatus status, bool isLocked) { if (isLocked) @@ -597,18 +595,6 @@ public static GUIStyle GenericBoxStyle } } - public static Color TimelineBarColor - { - get - { - if (timelineBarColor == null) - { - timelineBarColor = new Color(0.51F, 0.51F, 0.51F, 0.2F); - } - return timelineBarColor; - } - } - public static Texture2D ActiveBranchIcon { get From 44a843f0981c0fd039de57b64d17d14c2f489b66 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 19 Oct 2017 10:27:31 -0400 Subject: [PATCH 058/241] Removing unused variable and fixing missing BeginHorizontal in Window --- src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs index a9bbaca1b..f9a32fa25 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs @@ -283,7 +283,7 @@ private void DoHeaderGUI() private void DoToolbarGUI() { // Subtabs & toolbar - Rect mainNavRect = EditorGUILayout.BeginHorizontal(EditorStyles.toolbar); + GUILayout.BeginHorizontal(EditorStyles.toolbar); { changeTab = activeTab; EditorGUI.BeginChangeCheck(); From 7b003ed43f54c63351048d6e5a111598baea7e56 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 19 Oct 2017 10:28:12 -0400 Subject: [PATCH 059/241] Removing unused field in HistoryView --- src/UnityExtension/Assets/Editor/GitHub.Unity/UI/HistoryView.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/HistoryView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/HistoryView.cs index 62b0f8ad5..cc498db17 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/HistoryView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/HistoryView.cs @@ -37,7 +37,6 @@ class HistoryView : Subview [NonSerialized] private int historyStartIndex; [NonSerialized] private int historyStopIndex; - [NonSerialized] private float lastWidth; [NonSerialized] private int listID; [NonSerialized] private int newSelectionIndex; [NonSerialized] private float scrollOffset; From 2cc492060ea250300d1210a16ba7a672b24810b5 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 19 Oct 2017 10:28:55 -0400 Subject: [PATCH 060/241] Removing unused field in ApplicationCache --- .../Assets/Editor/GitHub.Unity/ApplicationCache.cs | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs index c18c19d51..5200df7ec 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs @@ -38,7 +38,6 @@ sealed class EnvironmentCache : ScriptObjectSingleton [SerializeField] private string unityApplication; [SerializeField] private string unityAssetsPath; [SerializeField] private string extensionInstallPath; - [SerializeField] private string gitExecutablePath; [SerializeField] private string unityVersion; [NonSerialized] private IEnvironment environment; @@ -80,7 +79,6 @@ public void Flush() unityApplication = Environment.UnityApplication; unityAssetsPath = Environment.UnityAssetsPath; extensionInstallPath = Environment.ExtensionInstallPath; - gitExecutablePath = Environment.GitExecutablePath; Save(true); } } From bef2444d75686029558b15abc33c6e04924ba243 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 19 Oct 2017 10:34:04 -0400 Subject: [PATCH 061/241] Fixing build error --- src/UnityExtension/Assets/Editor/GitHub.Unity/UI/HistoryView.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/HistoryView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/HistoryView.cs index cc498db17..c93f96989 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/HistoryView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/HistoryView.cs @@ -62,7 +62,6 @@ public override void InitializeView(IView parent) { base.InitializeView(parent); - lastWidth = Position.width; selectionIndex = newSelectionIndex = -1; changesetTree.InitializeView(this); From b6daa32e1547dec25660e14596fd0c45c0b27159 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 19 Oct 2017 10:34:50 -0400 Subject: [PATCH 062/241] Removing unused field from BaseWindow --- src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BaseWindow.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BaseWindow.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BaseWindow.cs index 03ce9534c..c864652c5 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BaseWindow.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BaseWindow.cs @@ -7,7 +7,6 @@ namespace GitHub.Unity abstract class BaseWindow : EditorWindow, IView { [NonSerialized] private bool initialized = false; - [NonSerialized] private IApplicationManager cachedManager; [NonSerialized] private IRepository cachedRepository; [NonSerialized] private bool initializeWasCalled; [NonSerialized] private bool inLayout; From 161ee170048d9e015d868acfaaec8bba6304c97a Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 19 Oct 2017 10:35:34 -0400 Subject: [PATCH 063/241] Removing unused Logger --- .../Threading/SingleThreadSynchronizationContext.cs | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/Threading/SingleThreadSynchronizationContext.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/Threading/SingleThreadSynchronizationContext.cs index 5db0285d9..a4dfe6038 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/Threading/SingleThreadSynchronizationContext.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/Threading/SingleThreadSynchronizationContext.cs @@ -1,4 +1,3 @@ -using GitHub.Unity; using System; using System.Threading; using UnityEditor; @@ -7,8 +6,6 @@ namespace GitHub.Unity { class MainThreadSynchronizationContext : SynchronizationContext, IMainThreadSynchronizationContext { - private static readonly ILogging logger = Logging.GetLogger(); - public void Schedule(Action action) { Guard.ArgumentNotNull(action, "action"); From 0221b7225ebc1b5899568a7ddd6f011f21a39bd9 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 19 Oct 2017 10:36:01 -0400 Subject: [PATCH 064/241] Removing unused field from Styles --- src/UnityExtension/Assets/Editor/GitHub.Unity/Misc/Styles.cs | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/Misc/Styles.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/Misc/Styles.cs index 27c0e37ec..0e282ee88 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/Misc/Styles.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/Misc/Styles.cs @@ -49,8 +49,6 @@ class Styles private const string WarningLabel = "Warning: {0}"; - private static Color headerGreyColor = new Color(0.878f, 0.878f, 0.878f, 1.0f); - private static GUIStyle label, boldLabel, errorLabel, From 97a2ddd6380b17ebab29494fd0f8dd1762085222 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 19 Oct 2017 10:39:10 -0400 Subject: [PATCH 065/241] Removing several unused fields from TaskSystem.Tests --- src/tests/TaskSystemIntegrationTests/Tests.cs | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/src/tests/TaskSystemIntegrationTests/Tests.cs b/src/tests/TaskSystemIntegrationTests/Tests.cs index 97647db89..aef181f95 100644 --- a/src/tests/TaskSystemIntegrationTests/Tests.cs +++ b/src/tests/TaskSystemIntegrationTests/Tests.cs @@ -266,7 +266,6 @@ public async void NonUITasksAlwaysRunOnDifferentThreadFromUITasks() var output = new Dictionary(); var tasks = new List(); var seed = Randomizer.RandomSeed; - var rand = new Randomizer(seed); var uiThread = 0; await new ActionTask(Token, _ => uiThread = Thread.CurrentThread.ManagedThreadId) { Affinity = TaskAffinity.UI } @@ -290,7 +289,6 @@ public async void ChainingOnDifferentSchedulers() var output = new Dictionary>(); var tasks = new List(); var seed = Randomizer.RandomSeed; - var rand = new Randomizer(seed); var uiThread = 0; await new ActionTask(Token, _ => uiThread = Thread.CurrentThread.ManagedThreadId) { Affinity = TaskAffinity.UI } @@ -567,7 +565,6 @@ public async Task StartAndEndAreAlwaysRaised() [ExpectedException(typeof(InvalidOperationException))] public async Task ExceptionPropagatesOutIfNoFinally() { - var runOrder = new List(); var task = new ActionTask(Token, _ => { throw new InvalidOperationException(); }) .Catch(_ => { }); await task.StartAsAsync(); @@ -578,9 +575,8 @@ public async Task ExceptionPropagatesOutIfNoFinally() [ExpectedException(typeof(InvalidOperationException))] public async Task DeferExceptions() { - var runOrder = new List(); var task = new FuncTask(Token, _ => 1) - .Defer(async d => + .Defer(async d => { throw new InvalidOperationException(); return await TaskEx.FromResult(d); @@ -592,7 +588,6 @@ public async Task DeferExceptions() [Test] public async Task StartAsyncWorks() { - var runOrder = new List(); var task = new FuncTask(Token, _ => 1); var ret = await task.StartAsAsync(); Assert.AreEqual(1, ret); @@ -643,7 +638,6 @@ public async Task ContinueAfterException() [Test] public async Task StartAwaitSafelyAwaits() { - var runOrder = new List(); var task = new ActionTask(Token, _ => { throw new InvalidOperationException(); }) .Catch(_ => { }); await task.StartAwait(_ => { }); @@ -702,7 +696,6 @@ public async Task AlwaysChainAsyncBodiesWithNonAsync() }), TaskAffinity.Concurrent) .Finally((_, e, v) => v); ; - var ret = await act.StartAsAsync(); CollectionAssert.AreEqual(Enumerable.Range(1, 7), runOrder); } @@ -758,7 +751,6 @@ public async Task DoNotEndChainsWithDefer() return v; }), TaskAffinity.Concurrent); ; - var ret = await act.Start().Task; // the last one hasn't finished before await is done CollectionAssert.AreEqual(Enumerable.Range(1, 6), runOrder); } From b87d2c2324f195c677b78da0798a54d37f0d9d50 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 19 Oct 2017 10:42:34 -0400 Subject: [PATCH 066/241] Removing enivronment from GitCredentialManager --- src/GitHub.Api/Git/GitCredentialManager.cs | 4 +--- src/GitHub.Api/Platform/Platform.cs | 2 +- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/src/GitHub.Api/Git/GitCredentialManager.cs b/src/GitHub.Api/Git/GitCredentialManager.cs index 4922d7a26..fceeec221 100644 --- a/src/GitHub.Api/Git/GitCredentialManager.cs +++ b/src/GitHub.Api/Git/GitCredentialManager.cs @@ -11,14 +11,12 @@ class GitCredentialManager : ICredentialManager private ICredential credential; private string credHelper = null; - private readonly IEnvironment environment; private readonly IProcessManager processManager; private readonly ITaskManager taskManager; - public GitCredentialManager(IEnvironment environment, IProcessManager processManager, + public GitCredentialManager(IProcessManager processManager, ITaskManager taskManager) { - this.environment = environment; this.processManager = processManager; this.taskManager = taskManager; } diff --git a/src/GitHub.Api/Platform/Platform.cs b/src/GitHub.Api/Platform/Platform.cs index 6e4a20e4e..71456a5a5 100644 --- a/src/GitHub.Api/Platform/Platform.cs +++ b/src/GitHub.Api/Platform/Platform.cs @@ -26,7 +26,7 @@ public IPlatform Initialize(IProcessManager processManager, ITaskManager taskMan if (CredentialManager == null) { - CredentialManager = new GitCredentialManager(Environment, processManager, taskManager); + CredentialManager = new GitCredentialManager(processManager, taskManager); Keychain = new Keychain(Environment, CredentialManager); Keychain.Initialize(); } From 596522b989cc50de213620b546222695bacfac09 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 19 Oct 2017 10:42:44 -0400 Subject: [PATCH 067/241] Removing unused test --- src/tests/TaskSystemIntegrationTests/Tests.cs | 15 --------------- 1 file changed, 15 deletions(-) diff --git a/src/tests/TaskSystemIntegrationTests/Tests.cs b/src/tests/TaskSystemIntegrationTests/Tests.cs index aef181f95..091c87037 100644 --- a/src/tests/TaskSystemIntegrationTests/Tests.cs +++ b/src/tests/TaskSystemIntegrationTests/Tests.cs @@ -570,21 +570,6 @@ public async Task ExceptionPropagatesOutIfNoFinally() await task.StartAsAsync(); } - //[Test] - //[Ignore("borked")] - [ExpectedException(typeof(InvalidOperationException))] - public async Task DeferExceptions() - { - var task = new FuncTask(Token, _ => 1) - .Defer(async d => - { - throw new InvalidOperationException(); - return await TaskEx.FromResult(d); - }) - .Then(_ => { }); - await task.StartAsAsync(); - } - [Test] public async Task StartAsyncWorks() { From 93a3aaa413287aae02c64198282ee634e88776b2 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 19 Oct 2017 10:43:44 -0400 Subject: [PATCH 068/241] Removing unused variables --- src/tests/UnitTests/Extensions/EnvironmentExtensionTests.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/tests/UnitTests/Extensions/EnvironmentExtensionTests.cs b/src/tests/UnitTests/Extensions/EnvironmentExtensionTests.cs index d3ef863b7..bd6e4aa11 100644 --- a/src/tests/UnitTests/Extensions/EnvironmentExtensionTests.cs +++ b/src/tests/UnitTests/Extensions/EnvironmentExtensionTests.cs @@ -53,7 +53,7 @@ public void GetRepositoryPathThrowsWhenRepositoryIsChildOfProject( environment.RepositoryPath.Returns(repositoryPath.ToNPath()); environment.UnityProjectPath.Returns(projectPath.ToNPath()); - var repositoryFilePath = environment.GetRepositoryPath(path.ToNPath()); + environment.GetRepositoryPath(path.ToNPath()); } [Test, Sequential] @@ -83,7 +83,7 @@ public void GetAssetPathShouldThrowWhenRepositoryRootIsChild( environment.RepositoryPath.Returns(repositoryPath.ToNPath()); environment.UnityProjectPath.Returns(projectPath.ToNPath()); - var repositoryFilePath = environment.GetAssetPath(path.ToNPath()); + environment.GetAssetPath(path.ToNPath()); } } } \ No newline at end of file From b2829a7dac823b15b4fa3a34ff1f180ff3c09828 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 19 Oct 2017 10:44:30 -0400 Subject: [PATCH 069/241] Removing unused local variables --- src/tests/UnitTests/IO/GitStatusEntryFactoryTests.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/tests/UnitTests/IO/GitStatusEntryFactoryTests.cs b/src/tests/UnitTests/IO/GitStatusEntryFactoryTests.cs index eec8473fe..78fe0482b 100644 --- a/src/tests/UnitTests/IO/GitStatusEntryFactoryTests.cs +++ b/src/tests/UnitTests/IO/GitStatusEntryFactoryTests.cs @@ -23,7 +23,7 @@ public void CreateObjectWhenProjectRootIsChildOfGitRootAndFileInGitRoot() var repositoryPath = "/Source".ToNPath(); var unityProjectPath = repositoryPath.Combine("UnityProject"); - var gitEnvironment = SubstituteFactory.CreateProcessEnvironment(repositoryPath); + SubstituteFactory.CreateProcessEnvironment(repositoryPath); var environment = SubstituteFactory.CreateEnvironment(new CreateEnvironmentOptions { RepositoryPath = repositoryPath, UnityProjectPath = unityProjectPath @@ -54,7 +54,7 @@ public void CreateObjectWhenProjectRootIsChildOfGitRootAndFileInProjectRoot() var repositoryPath = "/Source".ToNPath(); var unityProjectPath = repositoryPath.Combine("UnityProject"); - var gitEnvironment = SubstituteFactory.CreateProcessEnvironment(repositoryPath); + SubstituteFactory.CreateProcessEnvironment(repositoryPath); var environment = SubstituteFactory.CreateEnvironment(new CreateEnvironmentOptions { RepositoryPath = repositoryPath, UnityProjectPath = unityProjectPath @@ -84,7 +84,7 @@ public void CreateObjectWhenProjectRootIsSameAsGitRootAndFileInGitRoot() var repositoryPath = "/Source".ToNPath(); var unityProjectPath = repositoryPath; - var gitEnvironment = SubstituteFactory.CreateProcessEnvironment(repositoryPath); + SubstituteFactory.CreateProcessEnvironment(repositoryPath); var environment = SubstituteFactory.CreateEnvironment(new CreateEnvironmentOptions { RepositoryPath = repositoryPath, UnityProjectPath = unityProjectPath From 23052dd276cb5e322b7726f07e13609958191833 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 19 Oct 2017 10:45:29 -0400 Subject: [PATCH 070/241] Removing unused field from SimpleJson --- src/GitHub.Api/Helpers/SimpleJson.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/GitHub.Api/Helpers/SimpleJson.cs b/src/GitHub.Api/Helpers/SimpleJson.cs index da3325c28..dd2cf8483 100644 --- a/src/GitHub.Api/Helpers/SimpleJson.cs +++ b/src/GitHub.Api/Helpers/SimpleJson.cs @@ -517,7 +517,6 @@ static class SimpleJson private static readonly char[] EscapeTable; private static readonly char[] EscapeCharacters = new char[] { '"', '\\', '\b', '\f', '\n', '\r', '\t' }; - private static readonly string EscapeCharactersString = new string(EscapeCharacters); static SimpleJson() { From 7af8e7f90c6177ac4b2c492a9f4affa067ee21db Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 19 Oct 2017 10:46:13 -0400 Subject: [PATCH 071/241] Removing more commented out tests --- src/tests/TaskSystemIntegrationTests/Tests.cs | 98 ------------------- 1 file changed, 98 deletions(-) diff --git a/src/tests/TaskSystemIntegrationTests/Tests.cs b/src/tests/TaskSystemIntegrationTests/Tests.cs index 091c87037..d916283ff 100644 --- a/src/tests/TaskSystemIntegrationTests/Tests.cs +++ b/src/tests/TaskSystemIntegrationTests/Tests.cs @@ -642,104 +642,6 @@ public async Task CanWrapATask() CollectionAssert.AreEqual(new string[] { $"ran" }, runOrder); } - /// - /// Always call Then or another non-Defer variant after calling Defer - /// - //[Test] - //[Ignore("borked")] - public async Task AlwaysChainAsyncBodiesWithNonAsync() - { - var runOrder = new List(); - var act = new FuncTask>(Token, _ => runOrder) { Name = "First" } - .Defer(GetData) - .Then((_, v) => - { - v.Add(2); - return v; - }) - .Defer(GetData2) - .Then((_, v) => - { - v.Add(4); - return v; - }) - .Defer(async v => - { - await TaskEx.Delay(10); - v.Add(5); - return v; - }) - .Then((_, v) => - { - v.Add(6); - return v; - }) - .Defer(v => new Task>(() => - { - v.Add(7); - return v; - }), TaskAffinity.Concurrent) - .Finally((_, e, v) => v); - ; - CollectionAssert.AreEqual(Enumerable.Range(1, 7), runOrder); - } - - /// - /// Always call Then or another non-Defer variant after calling Defer - /// - //[Test] - //[Ignore("borked")] - public async Task TwoDefersInARowWillNotWork() - { - var runOrder = new List(); - var act = new FuncTask>(Token, _ => runOrder) { Name = "First" } - .Defer(GetData) - .Defer(GetData2) - .Finally((_, e, v) => v); - ; - var ret = await act.StartAsAsync(); - Assert.IsNull(ret); - } - - //[Test] - //[Ignore("borked")] - public async Task DoNotEndChainsWithDefer() - { - var runOrder = new List(); - var act = new FuncTask>(Token, _ => runOrder) { Name = "First" } - .Defer(GetData) - .Then((_, v) => - { - v.Add(2); - return v; - }) - .Defer(GetData2) - .Then((_, v) => - { - v.Add(4); - return v; - }) - .Defer(async v => - { - await TaskEx.Delay(10); - v.Add(5); - return v; - }) - .Then((_, v) => - { - v.Add(6); - return v; - }) - .Defer(v => new Task>(() => - { - v.Add(7); - return v; - }), TaskAffinity.Concurrent); - ; - // the last one hasn't finished before await is done - CollectionAssert.AreEqual(Enumerable.Range(1, 6), runOrder); - } - private async Task> GetData(List v) { await TaskEx.Delay(10); From 8e2495294a83e29237fbba97db5873913bb6948d Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 19 Oct 2017 10:47:37 -0400 Subject: [PATCH 072/241] Some UnitTest cleanup --- .../IO/LinuxBasedGitEnvironmentTests.cs | 25 ------------------- .../IO/MacBasedGitEnvironmentTests.cs | 25 ------------------- .../IO/WindowsGitEnvironmentTests.cs | 17 ------------- 3 files changed, 67 deletions(-) diff --git a/src/tests/UnitTests/IO/LinuxBasedGitEnvironmentTests.cs b/src/tests/UnitTests/IO/LinuxBasedGitEnvironmentTests.cs index aaacd02c6..f7d123c24 100644 --- a/src/tests/UnitTests/IO/LinuxBasedGitEnvironmentTests.cs +++ b/src/tests/UnitTests/IO/LinuxBasedGitEnvironmentTests.cs @@ -10,29 +10,6 @@ namespace UnitTests [TestFixture] public class LinuxGitEnvironmentTests: GitEnvironmentTestsBase { - //public static IEnumerable GetDefaultGitPath_TestCases() - //{ - // var testCase = new TestCaseData(true, LinuxGitEnvironment.DefaultGitPath); - // testCase.SetName("Should be found"); - // yield return testCase; - - // testCase = new TestCaseData(false, null); - // testCase.SetName("Should be null"); - // yield return testCase; - //} - - //[TestCaseSource(nameof(GetDefaultGitPath_TestCases))] - //public void GetDefaultGitPath(bool fileFound, string filePath) - //{ - // var environment = Substitute.For(); - - // var filesystem = Substitute.For(); - // filesystem.FileExists(Args.String).Returns(fileFound); - - // var linuxBasedGitInstallationStrategy = new LinuxGitEnvironment(environment, filesystem); - // linuxBasedGitInstallationStrategy.FindGitInstallationPath(TODO).Should().Be(filePath); - //} - public static IEnumerable ValidateGitPath_TestCases() { var testCase = new TestCaseData(true, true); @@ -47,8 +24,6 @@ public static IEnumerable ValidateGitPath_TestCases() [TestCaseSource(nameof(ValidateGitPath_TestCases))] public void ValidateGitPath(bool inFileSystem, bool found) { - var environment = Substitute.For(); - var filesystem = Substitute.For(); filesystem.FileExists(Args.String).Returns(inFileSystem); diff --git a/src/tests/UnitTests/IO/MacBasedGitEnvironmentTests.cs b/src/tests/UnitTests/IO/MacBasedGitEnvironmentTests.cs index 87a8827a3..959e65e37 100644 --- a/src/tests/UnitTests/IO/MacBasedGitEnvironmentTests.cs +++ b/src/tests/UnitTests/IO/MacBasedGitEnvironmentTests.cs @@ -10,29 +10,6 @@ namespace UnitTests [TestFixture] public class MacGitEnvironmentTests { - //public static IEnumerable GetDefaultGitPath_TestCases() - //{ - // var testCase = new TestCaseData(true, MacGitEnvironment.DefaultGitPath); - // testCase.SetName("Should be found"); - // yield return testCase; - - // testCase = new TestCaseData(false, null); - // testCase.SetName("Should be null"); - // yield return testCase; - //} - - //[TestCaseSource(nameof(GetDefaultGitPath_TestCases))] - //public void GetDefaultGitPath(bool fileFound, string filePath) - //{ - // var environment = Substitute.For(); - - // var filesystem = Substitute.For(); - // filesystem.FileExists(Args.String).Returns(fileFound); - - // var linuxBasedGitInstallationStrategy = new MacGitEnvironment(environment, filesystem); - // linuxBasedGitInstallationStrategy.FindGitInstallationPath(TODO).Should().Be(filePath); - //} - public static IEnumerable ValidateGitPath_TestCases() { var testCase = new TestCaseData(true, true); @@ -47,8 +24,6 @@ public static IEnumerable ValidateGitPath_TestCases() [TestCaseSource(nameof(ValidateGitPath_TestCases))] public void ValidateGitPath(bool inFileSystem, bool found) { - var environment = Substitute.For(); - var filesystem = Substitute.For(); filesystem.FileExists(Args.String).Returns(inFileSystem); diff --git a/src/tests/UnitTests/IO/WindowsGitEnvironmentTests.cs b/src/tests/UnitTests/IO/WindowsGitEnvironmentTests.cs index 05be9b4fe..29f036638 100644 --- a/src/tests/UnitTests/IO/WindowsGitEnvironmentTests.cs +++ b/src/tests/UnitTests/IO/WindowsGitEnvironmentTests.cs @@ -48,21 +48,6 @@ public static IEnumerable GetDefaultGitPath_TestCases() yield return testCase; } - //[TestCaseSource(nameof(GetDefaultGitPath_TestCases))] - //public void GetDefaultGitPath(string localAppDataPath, string gitHubRootPath, string[] gitHubRootPathChildren, string gitExecutablePath) - //{ - // var environment = Substitute.For(); - // environment.GetSpecialFolder(Arg.Is(Environment.SpecialFolder.LocalApplicationData)) - // .Returns(localAppDataPath); - - // var filesystem = Substitute.For(); - // filesystem.GetDirectories(gitHubRootPath) - // .Returns(gitHubRootPathChildren); - - // var windowsGitInstallationStrategy = new WindowsGitEnvironment(environment, filesystem); - // windowsGitInstallationStrategy.FindGitInstallationPath(TODO).Should().Be(gitExecutablePath); - //} - public static IEnumerable ValidateGitPath_TestCases() { var testCase = new TestCaseData(true, true); @@ -77,8 +62,6 @@ public static IEnumerable ValidateGitPath_TestCases() [TestCaseSource(nameof(ValidateGitPath_TestCases))] public void ValidateGitPath(bool inFileSystem, bool found) { - var environment = Substitute.For(); - var filesystem = Substitute.For(); filesystem.FileExists(Args.String).Returns(inFileSystem); From 84b6459dc440bc655132c747e846354e31ea66c7 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 19 Oct 2017 10:48:06 -0400 Subject: [PATCH 073/241] Removing unused variable --- src/tests/IntegrationTests/BaseGitEnvironmentTest.cs | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/tests/IntegrationTests/BaseGitEnvironmentTest.cs b/src/tests/IntegrationTests/BaseGitEnvironmentTest.cs index d0bd107f6..5bbec9fd9 100644 --- a/src/tests/IntegrationTests/BaseGitEnvironmentTest.cs +++ b/src/tests/IntegrationTests/BaseGitEnvironmentTest.cs @@ -28,8 +28,6 @@ protected async Task Initialize(NPath repoPath, NPath environmentP GitClient = new GitClient(Environment, ProcessManager, TaskManager); - var usageTracker = new NullUsageTracker(); - RepositoryManager = GitHub.Unity.RepositoryManager.CreateInstance(Platform, TaskManager, GitClient, repoPath); RepositoryManager.Initialize(); From 88879b4965da8329f128ec5be30764ef2a3cf6f5 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 19 Oct 2017 10:48:23 -0400 Subject: [PATCH 074/241] Removing unused logger --- src/tests/UnitTests/UI/TreeBuilderTests.cs | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/tests/UnitTests/UI/TreeBuilderTests.cs b/src/tests/UnitTests/UI/TreeBuilderTests.cs index 6cb21977f..4a3594564 100644 --- a/src/tests/UnitTests/UI/TreeBuilderTests.cs +++ b/src/tests/UnitTests/UI/TreeBuilderTests.cs @@ -13,8 +13,6 @@ namespace UnitTests.UI [TestFixture, Isolated] public class TreeBuilderTests { - private ILogging logger = Logging.GetLogger(); - private IEnvironment environment; private GitObjectFactory gitObjectFactory; From 0c218a94519448766e7cba1376cb2be29edf858c Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 19 Oct 2017 10:50:43 -0400 Subject: [PATCH 075/241] Minor test cleanup --- .../IntegrationTests/Process/ProcessManagerIntegrationTests.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/tests/IntegrationTests/Process/ProcessManagerIntegrationTests.cs b/src/tests/IntegrationTests/Process/ProcessManagerIntegrationTests.cs index ed50875a8..8766b3798 100644 --- a/src/tests/IntegrationTests/Process/ProcessManagerIntegrationTests.cs +++ b/src/tests/IntegrationTests/Process/ProcessManagerIntegrationTests.cs @@ -175,8 +175,7 @@ public async Task CredentialHelperGetTest() { await Initialize(TestRepoMasterCleanSynchronized); - string s = null; - s = await ProcessManager + await ProcessManager .GetGitCreds(TestRepoMasterCleanSynchronized, Environment, GitEnvironment) .StartAsAsync(); } From ac50823e65dc6550af1b377566fe697ab8888c9b Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 19 Oct 2017 10:51:51 -0400 Subject: [PATCH 076/241] Removing unused variables in ThreadSynchronizationContext classes --- src/tests/IntegrationTests/ThreadSynchronizationContext.cs | 1 - .../TaskSystemIntegrationTests/ThreadSynchronizationContext.cs | 1 - 2 files changed, 2 deletions(-) diff --git a/src/tests/IntegrationTests/ThreadSynchronizationContext.cs b/src/tests/IntegrationTests/ThreadSynchronizationContext.cs index bb7e4925d..7e92bf06a 100644 --- a/src/tests/IntegrationTests/ThreadSynchronizationContext.cs +++ b/src/tests/IntegrationTests/ThreadSynchronizationContext.cs @@ -58,7 +58,6 @@ private void Start() while (!token.IsCancellationRequested) { var current = DateTime.Now.Ticks; - var elapsed = current - lastTime; count++; if (current - secondStart > TimeSpan.TicksPerMillisecond * 1000) { diff --git a/src/tests/TaskSystemIntegrationTests/ThreadSynchronizationContext.cs b/src/tests/TaskSystemIntegrationTests/ThreadSynchronizationContext.cs index 17e8d52cc..742d47c53 100644 --- a/src/tests/TaskSystemIntegrationTests/ThreadSynchronizationContext.cs +++ b/src/tests/TaskSystemIntegrationTests/ThreadSynchronizationContext.cs @@ -59,7 +59,6 @@ private void Start() while (!token.IsCancellationRequested) { var current = DateTime.Now.Ticks; - var elapsed = current - lastTime; count++; if (current - secondStart > TimeSpan.TicksPerMillisecond * 1000) { From be9c78828111b9f3df203b49991548e4a98320c7 Mon Sep 17 00:00:00 2001 From: Andreia Gaita Date: Thu, 19 Oct 2017 18:24:26 +0200 Subject: [PATCH 077/241] Add sprite sheets to the project --- .../Assets/Editor/GitHub.Unity/GitHub.Unity.csproj | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/GitHub.Unity.csproj b/src/UnityExtension/Assets/Editor/GitHub.Unity/GitHub.Unity.csproj index 1ddcf006f..b1c66b3f2 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/GitHub.Unity.csproj +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/GitHub.Unity.csproj @@ -188,6 +188,8 @@ + + From e49d090fd5b4751675cfda6c5054a848385992ba Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 19 Oct 2017 12:25:58 -0400 Subject: [PATCH 078/241] Adding missing OnEnable/OnDisable --- .../Editor/GitHub.Unity/UI/InitProjectView.cs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs index ec20862dd..9bc4db72b 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs @@ -29,6 +29,20 @@ public override void OnDataUpdate() gitPathView.OnDataUpdate(); } + public override void OnEnable() + { + base.OnEnable(); + userSettingsView.OnEnable(); + gitPathView.OnEnable(); + } + + public override void OnDisable() + { + base.OnDisable(); + userSettingsView.OnDisable(); + gitPathView.OnDisable(); + } + public override void OnGUI() { var headerRect = EditorGUILayout.BeginHorizontal(Styles.HeaderBoxStyle); From 0a7ede0a061427d049028814f0a3c83fa018be9f Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 19 Oct 2017 12:29:25 -0400 Subject: [PATCH 079/241] Code nitpick --- .../Assets/Editor/GitHub.Unity/UI/InitProjectView.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs index 9bc4db72b..b3f424534 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs @@ -24,7 +24,6 @@ public override void InitializeView(IView parent) public override void OnDataUpdate() { base.OnDataUpdate(); - userSettingsView.OnDataUpdate(); gitPathView.OnDataUpdate(); } From 1f32865d0661a57e9f7a502b020f0cda33b2b2e4 Mon Sep 17 00:00:00 2001 From: Andreia Gaita Date: Thu, 19 Oct 2017 19:00:27 +0200 Subject: [PATCH 080/241] Tweak the message to be clearer --- docs/contributing/how-to-build.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/contributing/how-to-build.md b/docs/contributing/how-to-build.md index 77c4fec8a..22d96be49 100644 --- a/docs/contributing/how-to-build.md +++ b/docs/contributing/how-to-build.md @@ -40,11 +40,11 @@ To be able to authenticate in GitHub for Unity, you'll need to: - [Register a new developer application](https://github.com/settings/developers) in your profile. - Copy [common/ApplicationInfo_Local.cs-example](../../common/ApplicationInfo_Local.cs-example) to `common/ApplicationInfo_Local.cs` and fill out the clientId/clientSecret fields for your application. -The build needs to reference `UnityEngine.dll` and `UnityEditor.dll`. These DLLs are included with Unity. If you've installed Unity in the default location, the build will be able to find them automatically. If not, copy these DLLs from `Unity/Editor/Data/Managed` into the `lib` directory in order for the build to work. +The build needs to reference `UnityEngine.dll` and `UnityEditor.dll`. These DLLs are included with Unity. If you've installed Unity in the default location, the build will be able to find them automatically. If not, copy these DLLs from `[your Unity installation path]\Unity\Editor\Data\Managed` into the `lib` directory in order for the build to work. ### Visual Studio -To build with Visual Studio 2015+ open the solution file `GitHub.Unity.sln`. Select `Build Solution` in the `Build` menu. +To build with Visual Studio 2015+, open the solution file `GitHub.Unity.sln`. Select `Build Solution` in the `Build` menu. ### Mono and Bash (windows and mac) From fffc9f02e289915339f337fe49b890cd03de0186 Mon Sep 17 00:00:00 2001 From: Andreia Gaita Date: Thu, 19 Oct 2017 19:09:04 +0200 Subject: [PATCH 081/241] Add OSX instructions --- docs/contributing/how-to-build.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/contributing/how-to-build.md b/docs/contributing/how-to-build.md index 22d96be49..3e9169196 100644 --- a/docs/contributing/how-to-build.md +++ b/docs/contributing/how-to-build.md @@ -9,14 +9,14 @@ This repository is LFS-enabled. To clone it, you should use a git client that su - Visual Studio 2015+ or Mono 4.x + bash shell (git bash). - Mono 5.x will not work - `UnityEngine.dll` and `UnityEditor.dll`. - - If you've installed Unity in the default location of `C:\Program Files\Unity` or `C:\Program Files (x86)\Unity`, the build will be able to reference these DLLs automatically. Otherwise, you'll need to copy these DLLs from your Unity installation into the `lib` directory in order for the build to work + - If you've installed Unity in the default location of `C:\Program Files\Unity` or `C:\Program Files (x86)\Unity`, the build will be able to reference these DLLs automatically. Otherwise, you'll need to copy these DLLs from `[Unity installation path]\Unity\Editor\Data\Managed` into the `lib` directory in order for the build to work ### MacOS - Mono 4.x required. - Mono 5.x will not work - `UnityEngine.dll` and `UnityEditor.dll`. - - If you've installed Unity in the default location of `/Applications/Unity`, the build will be able to reference these DLLs automatically. Otherwise, you'll need to copy these DLLs from your Unity installation into the `lib` directory in order for the build to work + - If you've installed Unity in the default location of `/Applications/Unity`, the build will be able to reference these DLLs automatically. Otherwise, you'll need to copy these DLLs from `[Unity installation path]/Unity.app/Contents/Managed` into the `lib` directory in order for the build to work ## How to Build From 229134f924054fb3fe6545cf906d5f0c459a83cd Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 19 Oct 2017 13:57:35 -0400 Subject: [PATCH 082/241] Fixes needed after merge --- .../Assets/Editor/GitHub.Unity/UI/InitProjectView.cs | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs index ef52eaba9..4e134f70e 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs @@ -14,13 +14,18 @@ class InitProjectView : Subview [SerializeField] private UserSettingsView userSettingsView = new UserSettingsView(); [SerializeField] private GitPathView gitPathView = new GitPathView(); [SerializeField] private bool isBusy; + [NonSerialized] private string errorMessage; + [NonSerialized] private bool isUserDataPresent; [NonSerialized] private bool userDataHasChanged; public override void InitializeView(IView parent) { base.InitializeView(parent); + userSettingsView.InitializeView(this); + gitPathView.InitializeView(this); + if (!string.IsNullOrEmpty(Environment.GitExecutablePath)) { CheckForUser(); @@ -33,13 +38,6 @@ public override void OnEnable() userDataHasChanged = Environment.GitExecutablePath != null; } - public override void InitializeView(IView parent) - { - base.InitializeView(parent); - userSettingsView.InitializeView(this); - gitPathView.InitializeView(this); - } - public override void OnDataUpdate() { base.OnDataUpdate(); From 23498ceda96dff73ad6ae3b3e40e564035ac46af Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 19 Oct 2017 14:01:39 -0400 Subject: [PATCH 083/241] Turning messages into constants; Changing account refresh message --- .../Assets/Editor/GitHub.Unity/UI/PopupWindow.cs | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PopupWindow.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PopupWindow.cs index a3731aec6..bda14bab9 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PopupWindow.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PopupWindow.cs @@ -7,6 +7,10 @@ namespace GitHub.Unity [Serializable] class PopupWindow : BaseWindow { + private const string CredentialsNeedRefreshMessage = "We've detected that your stored credentials are out of sync with your current user. This can happen if you have signed in to git outside of Unity. Sign in again to refresh your credentials."; + private const string NeedAuthenticationMessage = "We need you to authenticate first"; + private const string AccountValidationErrorMessage = "There was an error validating your account"; + public enum PopupViewType { None, @@ -67,19 +71,19 @@ private void Open(PopupViewType popupViewType, Action onClose) var usernameMismatchException = exception as TokenUsernameMismatchException; if (usernameMismatchException != null) { - message = "Your credentials need to be refreshed"; + message = CredentialsNeedRefreshMessage; username = usernameMismatchException.CachedUsername; } var keychainEmptyException = exception as KeychainEmptyException; if (keychainEmptyException != null) { - message = "We need you to authenticate first"; + message = NeedAuthenticationMessage; } if (usernameMismatchException == null && keychainEmptyException == null) { - message = "There was an error validating your account"; + message = AccountValidationErrorMessage; } OpenInternal(PopupViewType.AuthenticationView, completedAuthentication => { From e00c98ca1b927a3e325b67463b790365efca0249 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 19 Oct 2017 14:04:40 -0400 Subject: [PATCH 084/241] Returning the exception message --- .../Assets/Editor/GitHub.Unity/UI/PopupWindow.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PopupWindow.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PopupWindow.cs index bda14bab9..7851acd2c 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PopupWindow.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PopupWindow.cs @@ -9,7 +9,6 @@ class PopupWindow : BaseWindow { private const string CredentialsNeedRefreshMessage = "We've detected that your stored credentials are out of sync with your current user. This can happen if you have signed in to git outside of Unity. Sign in again to refresh your credentials."; private const string NeedAuthenticationMessage = "We need you to authenticate first"; - private const string AccountValidationErrorMessage = "There was an error validating your account"; public enum PopupViewType { @@ -83,7 +82,7 @@ private void Open(PopupViewType popupViewType, Action onClose) if (usernameMismatchException == null && keychainEmptyException == null) { - message = AccountValidationErrorMessage; + message = exception.Message; } OpenInternal(PopupViewType.AuthenticationView, completedAuthentication => { From 33fb66b2648eca076a692b9e8617d4b72c197c1b Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 19 Oct 2017 15:13:05 -0400 Subject: [PATCH 085/241] Removing unused overloads and calls --- .../Assets/Editor/GitHub.Unity/UI/InitProjectView.cs | 8 -------- 1 file changed, 8 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs index b3f424534..eb78b5ee0 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs @@ -31,17 +31,9 @@ public override void OnDataUpdate() public override void OnEnable() { base.OnEnable(); - userSettingsView.OnEnable(); gitPathView.OnEnable(); } - public override void OnDisable() - { - base.OnDisable(); - userSettingsView.OnDisable(); - gitPathView.OnDisable(); - } - public override void OnGUI() { var headerRect = EditorGUILayout.BeginHorizontal(Styles.HeaderBoxStyle); From 2ba066f3fd7195ed69bae1ad14ce55c3ffa501e6 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 19 Oct 2017 16:54:55 -0400 Subject: [PATCH 086/241] Combined function to retrieve git name and email --- src/GitHub.Api/Git/GitClient.cs | 23 +++++++++++++++ src/GitHub.Api/Git/RepositoryManager.cs | 24 +++++++++------- .../Editor/GitHub.Unity/UI/InitProjectView.cs | 18 ++---------- .../GitHub.Unity/UI/UserSettingsView.cs | 28 +++++++++---------- 4 files changed, 54 insertions(+), 39 deletions(-) diff --git a/src/GitHub.Api/Git/GitClient.cs b/src/GitHub.Api/Git/GitClient.cs index 0b7978338..184212191 100644 --- a/src/GitHub.Api/Git/GitClient.cs +++ b/src/GitHub.Api/Git/GitClient.cs @@ -23,6 +23,8 @@ ITask GetConfig(string key, GitConfigSource configSource, ITask SetConfig(string key, string value, GitConfigSource configSource, IOutputProcessor processor = null); + ITask GetConfigUserAndEmail(); + ITask> ListLocks(bool local, BaseOutputListProcessor processor = null); @@ -256,6 +258,27 @@ public ITask SetConfig(string key, string value, GitConfigSource configS .Configure(processManager); } + public ITask GetConfigUserAndEmail() + { + string username = null; + string email = null; + + return GetConfig("user.name", GitConfigSource.User).Then((success, value) => { + Logger.Trace("Return success:{0} user.name", success, value); + if (success) + { + username = value; + } + + }).Then(GetConfig("user.email", GitConfigSource.User).Then((success, value) => { + Logger.Trace("Return success:{0} user.email", success, value); + if (success) + { + email = value; + } + })).Then(success => new[] { username, email }); + } + public ITask> ListLocks(bool local, BaseOutputListProcessor processor = null) { Logger.Trace("ListLocks"); diff --git a/src/GitHub.Api/Git/RepositoryManager.cs b/src/GitHub.Api/Git/RepositoryManager.cs index e3892806a..6beb7dcd5 100644 --- a/src/GitHub.Api/Git/RepositoryManager.cs +++ b/src/GitHub.Api/Git/RepositoryManager.cs @@ -318,16 +318,20 @@ public ITask UnlockFile(string file, bool force) private void LoadGitUser() { - var user = new User(); - GitClient.GetConfig("user.name", GitConfigSource.User) - .Then((success, value) => user.Name = value).Then( - GitClient.GetConfig("user.email", GitConfigSource.User) - .Then((success, value) => user.Email = value)) - .Then(() => { - Logger.Trace("OnGitUserLoaded: {0}", user); - OnGitUserLoaded?.Invoke(user); - }) - .Start(); + GitClient.GetConfigUserAndEmail() + .Then((success, strings) => { + var username = strings[0]; + var email = strings[1]; + + var user = new User { + Name = username, + Email = email + }; + + Logger.Trace("OnGitUserLoaded: {0}", user); + OnGitUserLoaded?.Invoke(user); + + }).Start(); } private void SetupWatcher() diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs index 4e134f70e..a04ac7777 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs @@ -138,22 +138,10 @@ private void CheckForUser() { isBusy = true; - string username = null; - string email = null; + GitClient.GetConfigUserAndEmail().FinallyInUI((success, ex, strings) => { + var username = strings[0]; + var email = strings[1]; - GitClient.GetConfig("user.name", GitConfigSource.User).Then((success, value) => { - Logger.Trace("Return success:{0} user.name", success, value); - if (success) - { - username = value; - } - }).Then(GitClient.GetConfig("user.email", GitConfigSource.User).Then((success, value) => { - Logger.Trace("Return success:{0} user.email", success, value); - if (success) - { - email = value; - } - })).FinallyInUI((success, ex) => { Logger.Trace("Return success:{0} name:{1} email:{2}", success, username, email); isBusy = false; diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/UserSettingsView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/UserSettingsView.cs index 47d1772e2..3a984b488 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/UserSettingsView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/UserSettingsView.cs @@ -115,21 +115,21 @@ private void MaybeUpdateData() { if ((cachedUser == null || String.IsNullOrEmpty(cachedUser.Name)) && GitClient != null) { - var user = new User(); - GitClient.GetConfig("user.name", GitConfigSource.User) - .Then((success, value) => user.Name = value).Then( - GitClient.GetConfig("user.email", GitConfigSource.User) - .Then((success, value) => user.Email = value)) - .FinallyInUI((success, ex) => + GitClient.GetConfigUserAndEmail().FinallyInUI((success, ex, strings) => { + var username = strings[0]; + var email = strings[1]; + + if (success && !String.IsNullOrEmpty(username) && !String.IsNullOrEmpty(email)) { - if (success && !String.IsNullOrEmpty(user.Name)) - { - cachedUser = user; - userDataHasChanged = true; - Redraw(); - } - }) - .Start(); + cachedUser = new User { + Name = username, + Email = email + }; + + userDataHasChanged = true; + Redraw(); + } + }).Start(); } } From 3ac90e5ef61f42b773584d3aa75892c43965bab4 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 19 Oct 2017 17:05:21 -0400 Subject: [PATCH 087/241] Cleaning up log messages --- src/GitHub.Api/Git/GitClient.cs | 9 +++++---- .../Assets/Editor/GitHub.Unity/UI/InitProjectView.cs | 1 - 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/GitHub.Api/Git/GitClient.cs b/src/GitHub.Api/Git/GitClient.cs index 184212191..81ea72890 100644 --- a/src/GitHub.Api/Git/GitClient.cs +++ b/src/GitHub.Api/Git/GitClient.cs @@ -244,7 +244,7 @@ public ITask LfsVersion(IOutputProcessor processor = null) public ITask GetConfig(string key, GitConfigSource configSource, IOutputProcessor processor = null) { - Logger.Trace("GetConfig"); + Logger.Trace("GetConfig: {0}", key); return new GitConfigGetTask(key, configSource, cancellationToken, processor) .Configure(processManager); @@ -264,19 +264,20 @@ public ITask GetConfigUserAndEmail() string email = null; return GetConfig("user.name", GitConfigSource.User).Then((success, value) => { - Logger.Trace("Return success:{0} user.name", success, value); if (success) { username = value; } }).Then(GetConfig("user.email", GitConfigSource.User).Then((success, value) => { - Logger.Trace("Return success:{0} user.email", success, value); if (success) { email = value; } - })).Then(success => new[] { username, email }); + })).Then(success => { + Logger.Trace("user.name:{1} user.email:{2}", success, username, email); + return new[] { username, email }; + }); } public ITask> ListLocks(bool local, BaseOutputListProcessor processor = null) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs index a04ac7777..79cc0f427 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs @@ -142,7 +142,6 @@ private void CheckForUser() var username = strings[0]; var email = strings[1]; - Logger.Trace("Return success:{0} name:{1} email:{2}", success, username, email); isBusy = false; isUserDataPresent = success && !String.IsNullOrEmpty(username) && !String.IsNullOrEmpty(email); From 7cf80c05c62c5d3dd10b2a49fc0cc8994aa56ebf Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Fri, 20 Oct 2017 11:29:13 -0400 Subject: [PATCH 088/241] treeLocals is never null --- .../Assets/Editor/GitHub.Unity/UI/BranchesView.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs index ddccc1544..705f16137 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs @@ -80,7 +80,7 @@ public override void OnDataUpdate() private void MaybeUpdateData() { - if (treeLocals == null || !treeLocals.IsInitialized) + if (!treeLocals.IsInitialized) { BuildTree(BranchCache.Instance.LocalBranches, BranchCache.Instance.RemoteBranches); } From 99c4ed264849e7b4218558b3863ca4185a5cc155 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Fri, 20 Oct 2017 11:29:33 -0400 Subject: [PATCH 089/241] Adding branchesHasChanged flag to signal rebuild of tree --- .../Assets/Editor/GitHub.Unity/UI/BranchesView.cs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs index 705f16137..efe7c0174 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs @@ -49,6 +49,9 @@ class BranchesView : Subview [SerializeField] private Vector2 scroll; [SerializeField] private bool disableDelete; + [NonSerialized] private bool branchesHasChanged; + + public override void InitializeView(IView parent) { base.InitializeView(parent); @@ -80,7 +83,7 @@ public override void OnDataUpdate() private void MaybeUpdateData() { - if (!treeLocals.IsInitialized) + if (!treeLocals.IsInitialized || branchesHasChanged) { BuildTree(BranchCache.Instance.LocalBranches, BranchCache.Instance.RemoteBranches); } @@ -134,7 +137,10 @@ private void DetachHandlers(IRepository repository) private void HandleDataUpdated() { - new ActionTask(TaskManager.Token, Redraw) { Affinity = TaskAffinity.UI }.Start(); + new ActionTask(TaskManager.Token, () => { + branchesHasChanged = true; + Redraw(); + }) { Affinity = TaskAffinity.UI }.Start(); } private void HandleDataUpdated(string obj) From 13fcec07c4b012b20e9355ac01a461b5ef9fb649 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Fri, 20 Oct 2017 11:46:56 -0400 Subject: [PATCH 090/241] Adding missing reset of branchesHasChanged --- src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs index efe7c0174..74dbd2708 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs @@ -85,6 +85,7 @@ private void MaybeUpdateData() { if (!treeLocals.IsInitialized || branchesHasChanged) { + branchesHasChanged = false; BuildTree(BranchCache.Instance.LocalBranches, BranchCache.Instance.RemoteBranches); } From a3d978a778a35d882752ba9ca1066b3830e5ef81 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Fri, 20 Oct 2017 12:22:04 -0400 Subject: [PATCH 091/241] Updating readme to include 2017.1 as a supported version --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 6e869e011..71571e1c0 100644 --- a/README.md +++ b/README.md @@ -47,8 +47,8 @@ The GitHub for Unity extension brings [Git](https://git-scm.com/) and GitHub int ### Requirements -- Unity 5.4-5.6 - - We've only tested the extension so far on Unity 5.4 to 5.6. There's currently an blocker issue opened for 5.3 support, so we know it doesn't run there. There are some issues for 2017.x, so it may or may not run well on that version. Personal edition is fine. +- Unity 5.4-2017.1 + - We've only tested the extension so far on Unity 5.4 to 2017.1. There's currently an blocker issue opened for 5.3 support, so we know it doesn't run there. There are some issues for 2017.2, so it may or may not run well on that version. Personal edition is fine. - Git and Git LFS 2.x #### Git on macOS From 13b562c9242ab16a368d92bc527f7ffb1dab7aef Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Fri, 20 Oct 2017 13:58:41 -0400 Subject: [PATCH 092/241] Temporaily disabling integration test that incorrectly fails often --- src/tests/IntegrationTests/Events/RepositoryManagerTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tests/IntegrationTests/Events/RepositoryManagerTests.cs b/src/tests/IntegrationTests/Events/RepositoryManagerTests.cs index 3e943d875..8340ed120 100644 --- a/src/tests/IntegrationTests/Events/RepositoryManagerTests.cs +++ b/src/tests/IntegrationTests/Events/RepositoryManagerTests.cs @@ -192,7 +192,7 @@ await RepositoryManager repositoryManagerListener.DidNotReceive().OnRemoteBranchRemoved(Args.String, Args.String); } - [Test] + [Test, Ignore("Fails often")] public async Task ShouldAddAndCommitAllFiles() { await Initialize(TestRepoMasterCleanSynchronized); From e19c891e5689b5045c35cb4bbbc2afa5d657f0fe Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Fri, 20 Oct 2017 14:12:08 -0400 Subject: [PATCH 093/241] Fixing error after merge --- .../Assets/Editor/GitHub.Unity/UI/InitProjectView.cs | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs index 49f9a3b69..aae40290b 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs @@ -35,6 +35,7 @@ public override void InitializeView(IView parent) public override void OnEnable() { base.OnEnable(); + gitPathView.OnEnable(); userDataHasChanged = Environment.GitExecutablePath != null; } @@ -45,12 +46,6 @@ public override void OnDataUpdate() gitPathView.OnDataUpdate(); } - public override void OnEnable() - { - base.OnEnable(); - gitPathView.OnEnable(); - } - public override void OnGUI() { var headerRect = EditorGUILayout.BeginHorizontal(Styles.HeaderBoxStyle); From f55b9d871c2d29fb68101be86db01e7b2d3a10c8 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Fri, 20 Oct 2017 12:16:26 -0400 Subject: [PATCH 094/241] Updating branch cache on branch change --- src/GitHub.Api/Cache/CacheManager.cs | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/src/GitHub.Api/Cache/CacheManager.cs b/src/GitHub.Api/Cache/CacheManager.cs index 11e038756..18aa621ed 100644 --- a/src/GitHub.Api/Cache/CacheManager.cs +++ b/src/GitHub.Api/Cache/CacheManager.cs @@ -17,6 +17,7 @@ public IBranchCache BranchCache } private Action onLocalBranchListChanged; + private Action onStatusChanged; public void SetupCache(IBranchCache branchCache, IRepository repository) { @@ -25,8 +26,17 @@ public void SetupCache(IBranchCache branchCache, IRepository repository) BranchCache = branchCache; UpdateCache(repository); + if (onLocalBranchListChanged != null) + { repository.OnLocalBranchListChanged -= onLocalBranchListChanged; + } + + if (onStatusChanged != null) + { + repository.OnStatusChanged -= onStatusChanged; + } + onLocalBranchListChanged = () => { if (!ThreadingHelper.InUIThread) @@ -34,7 +44,17 @@ public void SetupCache(IBranchCache branchCache, IRepository repository) else UpdateCache(repository); }; + + onStatusChanged = status => + { + if (!ThreadingHelper.InUIThread) + new ActionTask(TaskManager.Instance.Token, () => UpdateCache(repository)) { Affinity = TaskAffinity.UI }.Start(); + else + UpdateCache(repository); + }; + repository.OnLocalBranchListChanged += onLocalBranchListChanged; + repository.OnStatusChanged += onStatusChanged; } private void UpdateCache(IRepository repository) From 466507f04fd1258ec91c79c1b079ddba1d3785fe Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Fri, 20 Oct 2017 12:18:12 -0400 Subject: [PATCH 095/241] Removing stray newline --- src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs index 74dbd2708..296d61a07 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs @@ -51,7 +51,6 @@ class BranchesView : Subview [NonSerialized] private bool branchesHasChanged; - public override void InitializeView(IView parent) { base.InitializeView(parent); From 289038df58329fc3ac47977649387e4784f2ed49 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Fri, 20 Oct 2017 15:58:29 -0400 Subject: [PATCH 096/241] Initializing BranchCache --- .../Assets/Editor/GitHub.Unity/ApplicationManager.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationManager.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationManager.cs index 336016729..29da1ddc3 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationManager.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationManager.cs @@ -30,6 +30,7 @@ protected override void InitializeUI() { Logger.Trace("Restarted {0}", Environment.Repository); EnvironmentCache.Instance.Flush(); + CacheManager.SetupCache(BranchCache.Instance, Environment.Repository); ProjectWindowInterface.Initialize(Environment.Repository); var window = Window.GetWindow(); if (window != null) From 4cabc1009a80a79314a3fdb8f0cd766a5662ab08 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Fri, 20 Oct 2017 15:59:09 -0400 Subject: [PATCH 097/241] Removing initialize of BranchCache from BranchView --- src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs index 296d61a07..e87d5e492 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs @@ -55,7 +55,6 @@ public override void InitializeView(IView parent) { base.InitializeView(parent); targetMode = mode; - Manager.CacheManager.SetupCache(BranchCache.Instance, Environment.Repository); } public override void OnEnable() From 91f919db4e1673080ae6493f555e62708b11e1e7 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Fri, 20 Oct 2017 17:53:39 -0400 Subject: [PATCH 098/241] Migrating GitLogCache to CacheManager --- .../Application/ApplicationManagerBase.cs | 6 -- src/GitHub.Api/Cache/CacheManager.cs | 95 ++++++++++++++++--- src/GitHub.Api/Cache/IBranchCache.cs | 2 +- src/GitHub.Api/Cache/IGitLogCache.cs | 9 ++ src/GitHub.Api/GitHub.Api.csproj | 1 + src/GitHub.Api/GitHub.Api.csproj.DotSettings | 1 + .../Editor/GitHub.Unity/ApplicationCache.cs | 47 ++++----- .../Editor/GitHub.Unity/ApplicationManager.cs | 6 +- .../Assets/Editor/GitHub.Unity/UI/Window.cs | 27 ------ 9 files changed, 124 insertions(+), 70 deletions(-) create mode 100644 src/GitHub.Api/Cache/IGitLogCache.cs diff --git a/src/GitHub.Api/Application/ApplicationManagerBase.cs b/src/GitHub.Api/Application/ApplicationManagerBase.cs index c81fad840..e2d2d7d39 100644 --- a/src/GitHub.Api/Application/ApplicationManagerBase.cs +++ b/src/GitHub.Api/Application/ApplicationManagerBase.cs @@ -12,7 +12,6 @@ abstract class ApplicationManagerBase : IApplicationManager protected static ILogging Logger { get; } = Logging.GetLogger(); private RepositoryManager repositoryManager; - private IBranchCache branchCache; public ApplicationManagerBase(SynchronizationContext synchronizationContext) { @@ -82,11 +81,6 @@ private async Task SetupGit() } - public void SetupCache(IBranchCache bcache) - { - branchCache = bcache; - } - public ITask InitializeRepository() { Logger.Trace("Running Repository Initialize"); diff --git a/src/GitHub.Api/Cache/CacheManager.cs b/src/GitHub.Api/Cache/CacheManager.cs index 18aa621ed..59969bb2b 100644 --- a/src/GitHub.Api/Cache/CacheManager.cs +++ b/src/GitHub.Api/Cache/CacheManager.cs @@ -3,8 +3,10 @@ namespace GitHub.Unity { - class CacheManager + public class CacheManager { + private static ILogging logger = Logging.GetLogger(); + private IBranchCache branchCache; public IBranchCache BranchCache { @@ -16,16 +18,40 @@ public IBranchCache BranchCache } } + private IGitLogCache gitLogCache; + public IGitLogCache GitLogCache + { + get { return gitLogCache; } + set + { + if (gitLogCache == null) + gitLogCache = value; + } + } + private Action onLocalBranchListChanged; private Action onStatusChanged; + private Action onCurrentBranchUpdated; - public void SetupCache(IBranchCache branchCache, IRepository repository) + public void SetupCache(IGitLogCache cache) + { + GitLogCache = cache; + } + + public void SetupCache(IBranchCache cache) + { + BranchCache = cache; + } + + public void SetRepository(IRepository repository) { if (repository == null) return; - BranchCache = branchCache; - UpdateCache(repository); + logger.Trace("SetRepository: {0}", repository); + + UpdateBranchCache(repository); + UpdateGitLogCache(repository); if (onLocalBranchListChanged != null) { @@ -37,30 +63,75 @@ public void SetupCache(IBranchCache branchCache, IRepository repository) repository.OnStatusChanged -= onStatusChanged; } - onLocalBranchListChanged = () => + if (onStatusChanged != null) { + repository.OnCurrentBranchUpdated -= onCurrentBranchUpdated; + } + + onCurrentBranchUpdated = () => { if (!ThreadingHelper.InUIThread) - new ActionTask(TaskManager.Instance.Token, () => UpdateCache(repository)) { Affinity = TaskAffinity.UI }.Start(); + new ActionTask(TaskManager.Instance.Token, () => OnCurrentBranchUpdated(repository)) { + Affinity = TaskAffinity.UI + }.Start(); else - UpdateCache(repository); + OnCurrentBranchUpdated(repository); }; - onStatusChanged = status => - { + onLocalBranchListChanged = () => { + if (!ThreadingHelper.InUIThread) + new ActionTask(TaskManager.Instance.Token, () => OnLocalBranchListChanged(repository)) { + Affinity = TaskAffinity.UI + }.Start(); + else + OnLocalBranchListChanged(repository); + }; + + onStatusChanged = status => { if (!ThreadingHelper.InUIThread) - new ActionTask(TaskManager.Instance.Token, () => UpdateCache(repository)) { Affinity = TaskAffinity.UI }.Start(); + new ActionTask(TaskManager.Instance.Token, () => OnStatusChanged(repository)) { + Affinity = TaskAffinity.UI + }.Start(); else - UpdateCache(repository); + OnStatusChanged(repository); }; + repository.OnCurrentBranchUpdated += onCurrentBranchUpdated; repository.OnLocalBranchListChanged += onLocalBranchListChanged; repository.OnStatusChanged += onStatusChanged; } - private void UpdateCache(IRepository repository) + private void OnCurrentBranchUpdated(IRepository repository) + { + UpdateBranchCache(repository); + UpdateGitLogCache(repository); + } + + private void OnLocalBranchListChanged(IRepository repository) + { + UpdateBranchCache(repository); + } + + private void OnStatusChanged(IRepository repository) + { + UpdateBranchCache(repository); + } + + private void UpdateBranchCache(IRepository repository) { BranchCache.LocalBranches = repository.LocalBranches.ToList(); BranchCache.RemoteBranches = repository.RemoteBranches.ToList(); } + + private void UpdateGitLogCache(IRepository repository) + { + repository + .Log() + .FinallyInUI((success, exception, log) => { + if (success) + { + GitLogCache.Log = log; + } + }).Start(); + } } } \ No newline at end of file diff --git a/src/GitHub.Api/Cache/IBranchCache.cs b/src/GitHub.Api/Cache/IBranchCache.cs index fce1b4c63..026d4f6bb 100644 --- a/src/GitHub.Api/Cache/IBranchCache.cs +++ b/src/GitHub.Api/Cache/IBranchCache.cs @@ -2,7 +2,7 @@ namespace GitHub.Unity { - interface IBranchCache + public interface IBranchCache { List LocalBranches { get; set; } List RemoteBranches { get; set; } diff --git a/src/GitHub.Api/Cache/IGitLogCache.cs b/src/GitHub.Api/Cache/IGitLogCache.cs new file mode 100644 index 000000000..07ea6a278 --- /dev/null +++ b/src/GitHub.Api/Cache/IGitLogCache.cs @@ -0,0 +1,9 @@ +using System.Collections.Generic; + +namespace GitHub.Unity +{ + public interface IGitLogCache + { + List Log { get; set; } + } +} \ No newline at end of file diff --git a/src/GitHub.Api/GitHub.Api.csproj b/src/GitHub.Api/GitHub.Api.csproj index 8539e9725..ad75ee2e9 100644 --- a/src/GitHub.Api/GitHub.Api.csproj +++ b/src/GitHub.Api/GitHub.Api.csproj @@ -99,6 +99,7 @@ + diff --git a/src/GitHub.Api/GitHub.Api.csproj.DotSettings b/src/GitHub.Api/GitHub.Api.csproj.DotSettings index 56bc11b91..83ace06a4 100644 --- a/src/GitHub.Api/GitHub.Api.csproj.DotSettings +++ b/src/GitHub.Api/GitHub.Api.csproj.DotSettings @@ -2,6 +2,7 @@ True True True + True True True True diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs index 5200df7ec..214d14518 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs @@ -123,6 +123,30 @@ public List RemoteBranches } } + [Location("cache/gitlog.yaml", LocationAttribute.Location.LibraryFolder)] + sealed class GitLogCache : ScriptObjectSingleton, IGitLogCache + { + [SerializeField] + private List log; + public GitLogCache() + { } + + public List Log + { + get + { + if (log == null) + log = new List(); + return log; + } + set + { + log = value; + Save(true); + } + } + } + [Location("views/branches.yaml", LocationAttribute.Location.LibraryFolder)] sealed class Favorites : ScriptObjectSingleton { @@ -172,27 +196,4 @@ public bool IsFavorite(string branchName) return FavoriteBranches.Contains(branchName); } } - - [Location("cache/gitlog.yaml", LocationAttribute.Location.LibraryFolder)] - sealed class GitLogCache : ScriptObjectSingleton - { - [SerializeField] private List log; - public GitLogCache() - {} - - public List Log - { - get - { - if (log == null) - log = new List(); - return log; - } - set - { - log = value; - Save(true); - } - } - } } diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationManager.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationManager.cs index 29da1ddc3..9a63f8f8f 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationManager.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationManager.cs @@ -30,7 +30,11 @@ protected override void InitializeUI() { Logger.Trace("Restarted {0}", Environment.Repository); EnvironmentCache.Instance.Flush(); - CacheManager.SetupCache(BranchCache.Instance, Environment.Repository); + + CacheManager.SetupCache(BranchCache.Instance); + CacheManager.SetupCache(GitLogCache.Instance); + CacheManager.SetRepository(Environment.Repository); + ProjectWindowInterface.Initialize(Environment.Repository); var window = Window.GetWindow(); if (window != null) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs index f9a32fa25..21fdfe63f 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs @@ -143,8 +143,6 @@ public override void OnRepositoryChanged(IRepository oldRepository) if (ActiveView != null) ActiveView.OnRepositoryChanged(oldRepository); - - UpdateLog(); } public override void OnSelectionChange() @@ -244,7 +242,6 @@ private void AttachHandlers(IRepository repository) if (repository == null) return; repository.OnRepositoryInfoChanged += RefreshOnMainThread; - repository.OnCurrentBranchUpdated += UpdateLog; } private void DetachHandlers(IRepository repository) @@ -252,7 +249,6 @@ private void DetachHandlers(IRepository repository) if (repository == null) return; repository.OnRepositoryInfoChanged -= RefreshOnMainThread; - repository.OnCurrentBranchUpdated -= UpdateLog; } private void DoHeaderGUI() @@ -397,29 +393,6 @@ private static SubTab TabButton(SubTab tab, string title, SubTab activeTab) return GUILayout.Toggle(activeTab == tab, title, EditorStyles.toolbarButton) ? tab : activeTab; } - private void UpdateLog() - { - if (Repository != null) - { - Logger.Trace("Updating Log"); - - Repository - .Log() - .FinallyInUI((success, exception, log) => { - if (success) - { - Logger.Trace("Updated Log"); - GitLogCache.Instance.Log = log; - - if (activeTab == SubTab.History) - { - HistoryView.CheckLogCache(); - } - } - }).Start(); - } - } - private Subview ToView(SubTab tab) { switch (tab) From f0083d9de6efb3e03a17a9192826a3bae32e0180 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Fri, 20 Oct 2017 18:02:18 -0400 Subject: [PATCH 099/241] Adding some logging for sanity --- src/GitHub.Api/Cache/CacheManager.cs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/GitHub.Api/Cache/CacheManager.cs b/src/GitHub.Api/Cache/CacheManager.cs index 59969bb2b..b7cf34c35 100644 --- a/src/GitHub.Api/Cache/CacheManager.cs +++ b/src/GitHub.Api/Cache/CacheManager.cs @@ -102,33 +102,39 @@ public void SetRepository(IRepository repository) private void OnCurrentBranchUpdated(IRepository repository) { + logger.Trace("OnCurrentBranchUpdated"); UpdateBranchCache(repository); UpdateGitLogCache(repository); } private void OnLocalBranchListChanged(IRepository repository) { + logger.Trace("OnLocalBranchListChanged"); UpdateBranchCache(repository); } private void OnStatusChanged(IRepository repository) { + logger.Trace("OnStatusChanged"); UpdateBranchCache(repository); } private void UpdateBranchCache(IRepository repository) { + logger.Trace("UpdateBranchCache"); BranchCache.LocalBranches = repository.LocalBranches.ToList(); BranchCache.RemoteBranches = repository.RemoteBranches.ToList(); } private void UpdateGitLogCache(IRepository repository) { + logger.Trace("Start UpdateGitLogCache"); repository .Log() .FinallyInUI((success, exception, log) => { if (success) { + logger.Trace("Completed UpdateGitLogCache"); GitLogCache.Log = log; } }).Start(); From f8c951e47226affb8191e5238003cfa6df957bc4 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Fri, 20 Oct 2017 18:04:43 -0400 Subject: [PATCH 100/241] Unintentional class move --- .../Editor/GitHub.Unity/ApplicationCache.cs | 48 +++++++++---------- 1 file changed, 24 insertions(+), 24 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs index 214d14518..097454b4d 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs @@ -123,30 +123,6 @@ public List RemoteBranches } } - [Location("cache/gitlog.yaml", LocationAttribute.Location.LibraryFolder)] - sealed class GitLogCache : ScriptObjectSingleton, IGitLogCache - { - [SerializeField] - private List log; - public GitLogCache() - { } - - public List Log - { - get - { - if (log == null) - log = new List(); - return log; - } - set - { - log = value; - Save(true); - } - } - } - [Location("views/branches.yaml", LocationAttribute.Location.LibraryFolder)] sealed class Favorites : ScriptObjectSingleton { @@ -196,4 +172,28 @@ public bool IsFavorite(string branchName) return FavoriteBranches.Contains(branchName); } } + + [Location("cache/gitlog.yaml", LocationAttribute.Location.LibraryFolder)] + sealed class GitLogCache : ScriptObjectSingleton, IGitLogCache + { + [SerializeField] + private List log; + public GitLogCache() + { } + + public List Log + { + get + { + if (log == null) + log = new List(); + return log; + } + set + { + log = value; + Save(true); + } + } + } } From fcf8667507fafc0a6038779e12730d87ea65bd70 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Fri, 20 Oct 2017 18:05:43 -0400 Subject: [PATCH 101/241] Undoing more unintentional change --- .../Assets/Editor/GitHub.Unity/ApplicationCache.cs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs index 097454b4d..fae8b70b3 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs @@ -176,10 +176,9 @@ public bool IsFavorite(string branchName) [Location("cache/gitlog.yaml", LocationAttribute.Location.LibraryFolder)] sealed class GitLogCache : ScriptObjectSingleton, IGitLogCache { - [SerializeField] - private List log; + [SerializeField] private List log; public GitLogCache() - { } + {} public List Log { From 80e392b43fa3cd3dbf471e3bb66bf9d838be6e5c Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Mon, 23 Oct 2017 10:37:45 -0400 Subject: [PATCH 102/241] Restoring code to change the error message --- .../Assets/Editor/GitHub.Unity/UI/PublishView.cs | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs index 37db9c2fb..7039ccadc 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs @@ -21,7 +21,7 @@ class PublishView : Subview private const string RepositoryNameLabel = "Repository Name"; private const string DescriptionLabel = "Description"; private const string CreatePrivateRepositoryLabel = "Make repository private"; - private const string PublishLimtPrivateRepositoriesError = "You are currently at your limt of private repositories"; + private const string PublishLimitPrivateRepositoriesError = "You are currently at your limit of private repositories"; [SerializeField] private string username; [SerializeField] private string[] owners = { OwnersDefaultText }; @@ -177,7 +177,7 @@ public override void OnGUI() { Logger.Error(ex, "Repository Create Error Type:{0}", ex.GetType().ToString()); - error = ex.Message; + error = GetPublishErrorMessage(ex); isBusy = false; return; } @@ -210,6 +210,16 @@ public override void OnGUI() EditorGUI.EndDisabledGroup(); } + private string GetPublishErrorMessage(Exception ex) + { + if (ex.Message.StartsWith(PublishLimitPrivateRepositoriesError)) + { + return PublishLimitPrivateRepositoriesError; + } + + return ex.Message; + } + public override bool IsBusy { get { return isBusy; } From 2dad14481a0ea2b0b4edd931389b36ade1ecba02 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Mon, 23 Oct 2017 10:42:19 -0400 Subject: [PATCH 103/241] Adding another constant for text --- .../Assets/Editor/GitHub.Unity/UI/PublishView.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs index 7039ccadc..14f7ed227 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs @@ -22,6 +22,7 @@ class PublishView : Subview private const string DescriptionLabel = "Description"; private const string CreatePrivateRepositoryLabel = "Make repository private"; private const string PublishLimitPrivateRepositoriesError = "You are currently at your limit of private repositories"; + private const string PublishToGithubLabel = "Publish to GitHub"; [SerializeField] private string username; [SerializeField] private string[] owners = { OwnersDefaultText }; @@ -140,7 +141,7 @@ private void LoadOrganizations() public override void OnGUI() { - GUILayout.Label("Publish to GitHub", EditorStyles.boldLabel); + GUILayout.Label(PublishToGithubLabel, EditorStyles.boldLabel); EditorGUI.BeginDisabledGroup(isBusy); { From 85969ada182024cd7bfd7e6de97481d0ba691934 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Mon, 23 Oct 2017 13:58:34 -0400 Subject: [PATCH 104/241] Preventing the exposure of Octokit objects to the codebase --- src/GitHub.Api/Application/ApiClient.cs | 38 +++++++++++++------ src/GitHub.Api/Application/IApiClient.cs | 6 +-- .../Application/OctokitExtensions.cs | 21 ++++++++++ src/GitHub.Api/Application/Organization.cs | 8 ++++ src/GitHub.Api/GitHub.Api.csproj | 2 + .../Editor/GitHub.Unity/UI/PublishView.cs | 14 +++---- 6 files changed, 68 insertions(+), 21 deletions(-) create mode 100644 src/GitHub.Api/Application/OctokitExtensions.cs create mode 100644 src/GitHub.Api/Application/Organization.cs diff --git a/src/GitHub.Api/Application/ApiClient.cs b/src/GitHub.Api/Application/ApiClient.cs index 415872b07..83b6603a1 100644 --- a/src/GitHub.Api/Application/ApiClient.cs +++ b/src/GitHub.Api/Application/ApiClient.cs @@ -50,7 +50,7 @@ private async Task LogoutInternal(UriString host) await loginManager.Logout(host); } - public async Task CreateRepository(NewRepository newRepository, Action callback, string organization = null) + public async Task CreateRepository(NewRepository newRepository, Action callback, string organization = null) { Guard.ArgumentNotNull(callback, "callback"); try @@ -64,7 +64,7 @@ public async Task CreateRepository(NewRepository newRepository, Action> onSuccess, Action onError = null) + public async Task GetOrganizations(Action onSuccess, Action onError = null) { Guard.ArgumentNotNull(onSuccess, nameof(onSuccess)); await GetOrganizationInternal(onSuccess, onError); @@ -84,7 +84,7 @@ public async Task ValidateCurrentUser(Action onSuccess, Action onErro } } - public async Task GetCurrentUser(Action callback) + public async Task GetCurrentUser(Action callback) { Guard.ArgumentNotNull(callback, "callback"); var user = await GetCurrentUserInternal(); @@ -187,7 +187,7 @@ public async Task ContinueLoginAsync(LoginResult loginResult, Func CreateRepositoryInternal(NewRepository newRepository, string organization) + private async Task CreateRepositoryInternal(NewRepository newRepository, string organization) { try { @@ -196,18 +196,18 @@ public async Task ContinueLoginAsync(LoginResult loginResult, Func ContinueLoginAsync(LoginResult loginResult, Func> onSuccess, Action onError = null) + private async Task GetOrganizationInternal(Action onSuccess, Action onError = null) { try { @@ -235,7 +235,11 @@ private async Task GetOrganizationInternal(Action> onSuccess if (organizations != null) { - onSuccess(organizations.ToArray()); + var array = organizations.Select(organization => new Organization() { + Name = organization.Name, + Login = organization.Login + }).ToArray(); + onSuccess(array); } } catch(Exception ex) @@ -245,14 +249,14 @@ private async Task GetOrganizationInternal(Action> onSuccess } } - private async Task GetCurrentUserInternal() + private async Task GetCurrentUserInternal() { try { logger.Trace("Getting Current User"); await ValidateKeychain(); - return await githubClient.User.Current(); + return (await githubClient.User.Current()).ToGitHubUser(); } catch (Exception ex) { @@ -311,6 +315,18 @@ private async Task ValidateKeychain() } } + class GitHubUser + { + public string Name { get; set; } + public string Login { get; set; } + } + + class GitHubRepository + { + public string Name { get; set; } + public string CloneUrl { get; set; } + } + class ApiClientException : Exception { public ApiClientException() diff --git a/src/GitHub.Api/Application/IApiClient.cs b/src/GitHub.Api/Application/IApiClient.cs index 77819e3f5..d4a87e3e2 100644 --- a/src/GitHub.Api/Application/IApiClient.cs +++ b/src/GitHub.Api/Application/IApiClient.cs @@ -9,13 +9,13 @@ interface IApiClient { HostAddress HostAddress { get; } UriString OriginalUrl { get; } - Task CreateRepository(NewRepository newRepository, Action callback, string organization = null); - Task GetOrganizations(Action> onSuccess, Action onError = null); + Task CreateRepository(NewRepository newRepository, Action callback, string organization = null); + Task GetOrganizations(Action onSuccess, Action onError = null); Task Login(string username, string password, Action need2faCode, Action result); Task ContinueLogin(LoginResult loginResult, string code); Task LoginAsync(string username, string password, Func need2faCode); Task Logout(UriString host); - Task GetCurrentUser(Action callback); + Task GetCurrentUser(Action callback); Task ValidateCurrentUser(Action onSuccess, Action onError = null); } } diff --git a/src/GitHub.Api/Application/OctokitExtensions.cs b/src/GitHub.Api/Application/OctokitExtensions.cs new file mode 100644 index 000000000..c53101c74 --- /dev/null +++ b/src/GitHub.Api/Application/OctokitExtensions.cs @@ -0,0 +1,21 @@ +namespace GitHub.Unity +{ + static class OctokitExtensions + { + public static GitHubUser ToGitHubUser(this Octokit.User user) + { + return new GitHubUser() { + Name = user.Name, + Login = user.Login, + }; + } + + public static GitHubRepository ToGitHubRepository(this Octokit.Repository repository) + { + return new GitHubRepository { + Name = repository.Name, + CloneUrl = repository.CloneUrl + }; + } + } +} \ No newline at end of file diff --git a/src/GitHub.Api/Application/Organization.cs b/src/GitHub.Api/Application/Organization.cs new file mode 100644 index 000000000..e78849dd6 --- /dev/null +++ b/src/GitHub.Api/Application/Organization.cs @@ -0,0 +1,8 @@ +namespace GitHub.Unity +{ + class Organization + { + public string Name { get; set; } + public string Login { get; set; } + } +} \ No newline at end of file diff --git a/src/GitHub.Api/GitHub.Api.csproj b/src/GitHub.Api/GitHub.Api.csproj index a87766cee..87f8e2c30 100644 --- a/src/GitHub.Api/GitHub.Api.csproj +++ b/src/GitHub.Api/GitHub.Api.csproj @@ -99,6 +99,8 @@ + + diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs index 27f933f05..61d19e8c8 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs @@ -29,7 +29,7 @@ class PublishView : Subview [SerializeField] private string username; [SerializeField] private string[] owners = { OwnersDefaultText }; - [SerializeField] private IList organizations; + [SerializeField] private string[] publishOwners; [SerializeField] private int selectedOwner; [SerializeField] private string repoName = String.Empty; [SerializeField] private string repoDescription = ""; @@ -67,7 +67,7 @@ public IApiClient Client public override void OnEnable() { base.OnEnable(); - ownersNeedLoading = organizations == null && !isBusy; + ownersNeedLoading = publishOwners == null && !isBusy; } public override void OnDataUpdate() @@ -106,14 +106,14 @@ private void LoadOwners() Client.GetOrganizations(orgs => { - organizations = orgs; - Logger.Trace("Loaded {0} Owners", organizations.Count); + Logger.Trace("Loaded {0} Owners", orgs.Length); - var organizationLogins = organizations + publishOwners = orgs .OrderBy(organization => organization.Login) - .Select(organization => organization.Login); + .Select(organization => organization.Login) + .ToArray(); - owners = new[] { OwnersDefaultText, username }.Union(organizationLogins).ToArray(); + owners = new[] { OwnersDefaultText, username }.Union(publishOwners).ToArray(); isBusy = false; }, exception => From 7b7b3e95c46214dcd90d8306a10c88260c883399 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Tue, 24 Oct 2017 18:16:36 -0400 Subject: [PATCH 105/241] Fix needed after merge --- .../Assets/Editor/GitHub.Unity/UI/InitProjectView.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs index 8f5e331f9..0adb17dc7 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs @@ -8,7 +8,6 @@ namespace GitHub.Unity class InitProjectView : Subview { private const string NoRepoTitle = "To begin using GitHub, initialize a git repository"; - private const string NoRepoTitle = "No Git repository found for this project"; private const string NoRepoDescription = "Initialize a Git repository to track changes and collaborate with others."; private const string NoUserOrEmailError = "Name and Email must be configured in Settings"; From b339b340d868ee2bee6bee3635911136c12cf302 Mon Sep 17 00:00:00 2001 From: Don Okuda Date: Wed, 25 Oct 2017 11:53:35 -0700 Subject: [PATCH 106/241] Adjust some spacing for empty state --- .../Assets/Editor/GitHub.Unity/UI/InitProjectView.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs index 0adb17dc7..1d6b00b2f 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs @@ -10,7 +10,7 @@ class InitProjectView : Subview private const string NoRepoTitle = "To begin using GitHub, initialize a git repository"; private const string NoRepoDescription = "Initialize a Git repository to track changes and collaborate with others."; private const string NoUserOrEmailError = "Name and Email must be configured in Settings"; - + [SerializeField] private UserSettingsView userSettingsView = new UserSettingsView(); [SerializeField] private GitPathView gitPathView = new GitPathView(); @@ -52,9 +52,7 @@ public override void OnGUI() GUILayout.BeginVertical(Styles.GenericBoxStyle); { GUILayout.FlexibleSpace(); - - gitPathView.OnGUI(); - userSettingsView.OnGUI(); + GUILayout.Space(-140); GUILayout.BeginHorizontal(); { @@ -65,6 +63,7 @@ public override void OnGUI() GUILayout.EndHorizontal(); GUILayout.Label(NoRepoTitle, Styles.BoldCenteredLabel); + EditorGUILayout.Space(); GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); @@ -84,6 +83,7 @@ public override void OnGUI() GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); + EditorGUILayout.Space(); EditorGUILayout.HelpBox("There was an error initializing a repository.", MessageType.Error); GUILayout.FlexibleSpace(); From 0fd147a0bba47c7f734929e4aa9e210c0a8a4d33 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Wed, 25 Oct 2017 16:13:17 -0400 Subject: [PATCH 107/241] Adding cache managers and making use of the RepositoryInfoCacheManager in Repository --- .../Application/ApplicationManagerBase.cs | 6 +- .../Application/IApplicationManager.cs | 2 +- src/GitHub.Api/Cache/CacheContainer.cs | 256 +++++++++ src/GitHub.Api/Cache/CacheManager.cs | 143 ----- src/GitHub.Api/Cache/IBranchCache.cs | 10 - src/GitHub.Api/Cache/IGitLogCache.cs | 9 - src/GitHub.Api/Git/IRepository.cs | 2 +- src/GitHub.Api/Git/Repository.cs | 50 +- src/GitHub.Api/GitHub.Api.csproj | 4 +- .../Editor/GitHub.Unity/ApplicationCache.cs | 538 +++++++++++++++++- .../Editor/GitHub.Unity/ApplicationManager.cs | 10 +- .../BaseGitEnvironmentTest.cs | 2 +- src/tests/UnitTests/Git/RepositoryTests.cs | 2 +- 13 files changed, 816 insertions(+), 218 deletions(-) create mode 100644 src/GitHub.Api/Cache/CacheContainer.cs delete mode 100644 src/GitHub.Api/Cache/CacheManager.cs delete mode 100644 src/GitHub.Api/Cache/IBranchCache.cs delete mode 100644 src/GitHub.Api/Cache/IGitLogCache.cs diff --git a/src/GitHub.Api/Application/ApplicationManagerBase.cs b/src/GitHub.Api/Application/ApplicationManagerBase.cs index e2d2d7d39..bfeb6fcc9 100644 --- a/src/GitHub.Api/Application/ApplicationManagerBase.cs +++ b/src/GitHub.Api/Application/ApplicationManagerBase.cs @@ -21,7 +21,7 @@ public ApplicationManagerBase(SynchronizationContext synchronizationContext) UIScheduler = TaskScheduler.FromCurrentSynchronizationContext(); ThreadingHelper.MainThreadScheduler = UIScheduler; TaskManager = new TaskManager(UIScheduler); - CacheManager = new CacheManager(); + CacheContainer = new CacheContainer(); } protected void Initialize() @@ -130,7 +130,7 @@ public void RestartRepository() { repositoryManager = Unity.RepositoryManager.CreateInstance(Platform, TaskManager, GitClient, Environment.RepositoryPath); repositoryManager.Initialize(); - Environment.Repository.Initialize(repositoryManager); + Environment.Repository.Initialize(repositoryManager, CacheContainer); repositoryManager.Start(); Logger.Trace($"Got a repository? {Environment.Repository}"); } @@ -215,7 +215,7 @@ public void Dispose() public ISettings LocalSettings { get; protected set; } public ISettings SystemSettings { get; protected set; } public ISettings UserSettings { get; protected set; } - public CacheManager CacheManager { get; private set; } + public ICacheContainer CacheContainer { get; private set; } public IUsageTracker UsageTracker { get; protected set; } protected TaskScheduler UIScheduler { get; private set; } diff --git a/src/GitHub.Api/Application/IApplicationManager.cs b/src/GitHub.Api/Application/IApplicationManager.cs index 7ae10272f..a9bfabf22 100644 --- a/src/GitHub.Api/Application/IApplicationManager.cs +++ b/src/GitHub.Api/Application/IApplicationManager.cs @@ -15,7 +15,7 @@ public interface IApplicationManager : IDisposable ISettings LocalSettings { get; } ISettings UserSettings { get; } ITaskManager TaskManager { get; } - CacheManager CacheManager { get; } + ICacheContainer CacheContainer { get; } IGitClient GitClient { get; } IUsageTracker UsageTracker { get; } diff --git a/src/GitHub.Api/Cache/CacheContainer.cs b/src/GitHub.Api/Cache/CacheContainer.cs new file mode 100644 index 000000000..529f6b7bd --- /dev/null +++ b/src/GitHub.Api/Cache/CacheContainer.cs @@ -0,0 +1,256 @@ +using System; +using System.Collections.Generic; + +namespace GitHub.Unity +{ + public class CacheContainer : ICacheContainer + { + private IBranchCache branchCache; + + private IGitLocksCache gitLocksCache; + + private IGitLogCache gitLogCache; + + private IGitStatusCache gitStatusCache; + + private IGitUserCache gitUserCache; + + private IRepositoryInfoCache repositoryInfoCache; + + public event Action CacheInvalidated; + + public event Action CacheUpdated; + + private IManagedCache GetManagedCache(CacheType cacheType) + { + switch (cacheType) + { + case CacheType.BranchCache: + return BranchCache; + + case CacheType.GitLogCache: + return GitLogCache; + + case CacheType.RepositoryInfoCache: + return RepositoryInfoCache; + + case CacheType.GitStatusCache: + return GitStatusCache; + + case CacheType.GitLocksCache: + return GitLocksCache; + + case CacheType.GitUserCache: + return GitUserCache; + + default: + throw new ArgumentOutOfRangeException(nameof(cacheType), cacheType, null); + } + } + + public void Validate(CacheType cacheType) + { + GetManagedCache(cacheType).ValidateData(); + } + + public void ValidateAll() + { + BranchCache.ValidateData(); + GitLogCache.ValidateData(); + RepositoryInfoCache.ValidateData(); + GitStatusCache.ValidateData(); + GitLocksCache.ValidateData(); + GitUserCache.ValidateData(); + } + + public void Invalidate(CacheType cacheType) + { + GetManagedCache(cacheType).InvalidateData(); + } + + public void InvalidateAll() + { + BranchCache.InvalidateData(); + GitLogCache.InvalidateData(); + RepositoryInfoCache.InvalidateData(); + GitStatusCache.InvalidateData(); + GitLocksCache.InvalidateData(); + GitUserCache.InvalidateData(); + } + + public IBranchCache BranchCache + { + get { return branchCache; } + set + { + if (branchCache == null) + { + branchCache = value; + branchCache.CacheInvalidated += () => CacheInvalidated?.Invoke(CacheType.BranchCache); + branchCache.CacheUpdated += datetime => CacheUpdated?.Invoke(CacheType.BranchCache, datetime); + } + } + } + + public IGitLogCache GitLogCache + { + get { return gitLogCache; } + set + { + if (gitLogCache == null) + { + gitLogCache = value; + gitLogCache.CacheInvalidated += () => CacheInvalidated?.Invoke(CacheType.GitLogCache); + gitLogCache.CacheUpdated += datetime => CacheUpdated?.Invoke(CacheType.GitLogCache, datetime); + } + } + } + + public IRepositoryInfoCache RepositoryInfoCache + { + get { return repositoryInfoCache; } + set + { + if (repositoryInfoCache == null) + { + repositoryInfoCache = value; + repositoryInfoCache.CacheInvalidated += () => CacheInvalidated?.Invoke(CacheType.RepositoryInfoCache); + repositoryInfoCache.CacheUpdated += datetime => CacheUpdated?.Invoke(CacheType.RepositoryInfoCache, datetime); + } + } + } + + public IGitStatusCache GitStatusCache + { + get { return gitStatusCache; } + set + { + if (gitStatusCache == null) + { + gitStatusCache = value; + gitStatusCache.CacheInvalidated += () => CacheInvalidated?.Invoke(CacheType.GitStatusCache); + gitStatusCache.CacheUpdated += datetime => CacheUpdated?.Invoke(CacheType.GitStatusCache, datetime); + } + } + } + + public IGitLocksCache GitLocksCache + { + get { return gitLocksCache; } + set + { + if (gitLocksCache == null) + { + gitLocksCache = value; + gitLocksCache.CacheInvalidated += () => CacheInvalidated?.Invoke(CacheType.GitLocksCache); + gitLocksCache.CacheUpdated += datetime => CacheUpdated?.Invoke(CacheType.GitLocksCache, datetime); + } + } + } + + public IGitUserCache GitUserCache + { + get { return gitUserCache; } + set + { + if (gitUserCache == null) + { + gitUserCache = value; + gitUserCache.CacheInvalidated += () => CacheInvalidated?.Invoke(CacheType.GitUserCache); + gitUserCache.CacheUpdated += datetime => CacheUpdated?.Invoke(CacheType.GitUserCache, datetime); + } + } + } + } + + public enum CacheType + { + BranchCache, + GitLogCache, + RepositoryInfoCache, + GitStatusCache, + GitLocksCache, + GitUserCache + } + + public interface ICacheContainer + { + event Action CacheInvalidated; + event Action CacheUpdated; + + IBranchCache BranchCache { get; } + IGitLogCache GitLogCache { get; } + IRepositoryInfoCache RepositoryInfoCache { get; } + IGitStatusCache GitStatusCache { get; } + IGitLocksCache GitLocksCache { get; } + IGitUserCache GitUserCache { get; } + void Validate(CacheType cacheType); + void ValidateAll(); + void Invalidate(CacheType cacheType); + void InvalidateAll(); + } + + public interface IManagedCache + { + event Action CacheInvalidated; + event Action CacheUpdated; + + void ValidateData(); + void InvalidateData(); + + DateTime LastUpdatedAt { get; } + DateTime LastVerifiedAt { get; } + } + + public interface IGitLocks + { + List GitLocks { get; } + } + + public interface IGitLocksCache : IManagedCache, IGitLocks + { } + + public interface IGitUser + { + User User { get; } + } + + public interface IGitUserCache : IManagedCache, IGitUser + { } + + public interface IGitStatus + { + GitStatus GitStatus { get; } + } + + public interface IGitStatusCache : IManagedCache, IGitStatus + { } + + public interface IRepositoryInfo + { + ConfigRemote? CurrentRemote { get; } + ConfigBranch? CurentBranch { get; } + } + + public interface IRepositoryInfoCache : IManagedCache, IRepositoryInfo + { + void UpdateData(ConfigRemote? gitRemoteUpdate); + void UpdateData(ConfigBranch? gitBranchUpdate); + void UpdateData(ConfigRemote? gitRemoteUpdate, ConfigBranch? gitBranchUpdate); + } + + public interface IBranch + { + void UpdateData(List localBranchUpdate, List remoteBranchUpdate); + List LocalBranches { get; } + List RemoteBranches { get; } + } + + public interface IBranchCache : IManagedCache, IBranch + { } + + public interface IGitLogCache : IManagedCache + { + List Log { get; } + } +} diff --git a/src/GitHub.Api/Cache/CacheManager.cs b/src/GitHub.Api/Cache/CacheManager.cs deleted file mode 100644 index b7cf34c35..000000000 --- a/src/GitHub.Api/Cache/CacheManager.cs +++ /dev/null @@ -1,143 +0,0 @@ -using System; -using System.Linq; - -namespace GitHub.Unity -{ - public class CacheManager - { - private static ILogging logger = Logging.GetLogger(); - - private IBranchCache branchCache; - public IBranchCache BranchCache - { - get { return branchCache; } - set - { - if (branchCache == null) - branchCache = value; - } - } - - private IGitLogCache gitLogCache; - public IGitLogCache GitLogCache - { - get { return gitLogCache; } - set - { - if (gitLogCache == null) - gitLogCache = value; - } - } - - private Action onLocalBranchListChanged; - private Action onStatusChanged; - private Action onCurrentBranchUpdated; - - public void SetupCache(IGitLogCache cache) - { - GitLogCache = cache; - } - - public void SetupCache(IBranchCache cache) - { - BranchCache = cache; - } - - public void SetRepository(IRepository repository) - { - if (repository == null) - return; - - logger.Trace("SetRepository: {0}", repository); - - UpdateBranchCache(repository); - UpdateGitLogCache(repository); - - if (onLocalBranchListChanged != null) - { - repository.OnLocalBranchListChanged -= onLocalBranchListChanged; - } - - if (onStatusChanged != null) - { - repository.OnStatusChanged -= onStatusChanged; - } - - if (onStatusChanged != null) - { - repository.OnCurrentBranchUpdated -= onCurrentBranchUpdated; - } - - onCurrentBranchUpdated = () => { - if (!ThreadingHelper.InUIThread) - new ActionTask(TaskManager.Instance.Token, () => OnCurrentBranchUpdated(repository)) { - Affinity = TaskAffinity.UI - }.Start(); - else - OnCurrentBranchUpdated(repository); - }; - - onLocalBranchListChanged = () => { - if (!ThreadingHelper.InUIThread) - new ActionTask(TaskManager.Instance.Token, () => OnLocalBranchListChanged(repository)) { - Affinity = TaskAffinity.UI - }.Start(); - else - OnLocalBranchListChanged(repository); - }; - - onStatusChanged = status => { - if (!ThreadingHelper.InUIThread) - new ActionTask(TaskManager.Instance.Token, () => OnStatusChanged(repository)) { - Affinity = TaskAffinity.UI - }.Start(); - else - OnStatusChanged(repository); - }; - - repository.OnCurrentBranchUpdated += onCurrentBranchUpdated; - repository.OnLocalBranchListChanged += onLocalBranchListChanged; - repository.OnStatusChanged += onStatusChanged; - } - - private void OnCurrentBranchUpdated(IRepository repository) - { - logger.Trace("OnCurrentBranchUpdated"); - UpdateBranchCache(repository); - UpdateGitLogCache(repository); - } - - private void OnLocalBranchListChanged(IRepository repository) - { - logger.Trace("OnLocalBranchListChanged"); - UpdateBranchCache(repository); - } - - private void OnStatusChanged(IRepository repository) - { - logger.Trace("OnStatusChanged"); - UpdateBranchCache(repository); - } - - private void UpdateBranchCache(IRepository repository) - { - logger.Trace("UpdateBranchCache"); - BranchCache.LocalBranches = repository.LocalBranches.ToList(); - BranchCache.RemoteBranches = repository.RemoteBranches.ToList(); - } - - private void UpdateGitLogCache(IRepository repository) - { - logger.Trace("Start UpdateGitLogCache"); - repository - .Log() - .FinallyInUI((success, exception, log) => { - if (success) - { - logger.Trace("Completed UpdateGitLogCache"); - GitLogCache.Log = log; - } - }).Start(); - } - } -} \ No newline at end of file diff --git a/src/GitHub.Api/Cache/IBranchCache.cs b/src/GitHub.Api/Cache/IBranchCache.cs deleted file mode 100644 index 026d4f6bb..000000000 --- a/src/GitHub.Api/Cache/IBranchCache.cs +++ /dev/null @@ -1,10 +0,0 @@ -using System.Collections.Generic; - -namespace GitHub.Unity -{ - public interface IBranchCache - { - List LocalBranches { get; set; } - List RemoteBranches { get; set; } - } -} diff --git a/src/GitHub.Api/Cache/IGitLogCache.cs b/src/GitHub.Api/Cache/IGitLogCache.cs deleted file mode 100644 index 07ea6a278..000000000 --- a/src/GitHub.Api/Cache/IGitLogCache.cs +++ /dev/null @@ -1,9 +0,0 @@ -using System.Collections.Generic; - -namespace GitHub.Unity -{ - public interface IGitLogCache - { - List Log { get; set; } - } -} \ No newline at end of file diff --git a/src/GitHub.Api/Git/IRepository.cs b/src/GitHub.Api/Git/IRepository.cs index 5818a9f52..ad616d2b8 100644 --- a/src/GitHub.Api/Git/IRepository.cs +++ b/src/GitHub.Api/Git/IRepository.cs @@ -8,7 +8,7 @@ namespace GitHub.Unity /// public interface IRepository : IEquatable { - void Initialize(IRepositoryManager repositoryManager); + void Initialize(IRepositoryManager repositoryManager, ICacheContainer cacheContainer); void Refresh(); ITask CommitAllFiles(string message, string body); ITask CommitFiles(List files, string message, string body); diff --git a/src/GitHub.Api/Git/Repository.cs b/src/GitHub.Api/Git/Repository.cs index a28a7b679..bd0f6fec5 100644 --- a/src/GitHub.Api/Git/Repository.cs +++ b/src/GitHub.Api/Git/Repository.cs @@ -10,14 +10,13 @@ namespace GitHub.Unity [DebuggerDisplay("{DebuggerDisplay,nq}")] class Repository : IEquatable, IRepository { - private ConfigBranch? currentBranch; private IList currentLocks; - private ConfigRemote? currentRemote; private GitStatus currentStatus; private Dictionary localBranches = new Dictionary(); private Dictionary> remoteBranches = new Dictionary>(); private Dictionary remotes; private IRepositoryManager repositoryManager; + private ICacheContainer cacheContainer; public event Action OnCurrentBranchChanged; public event Action OnCurrentRemoteChanged; public event Action OnCurrentBranchUpdated; @@ -43,11 +42,12 @@ public Repository(string name, NPath localPath) this.User = new User(); } - public void Initialize(IRepositoryManager repositoryManager) + public void Initialize(IRepositoryManager repositoryManager, ICacheContainer cacheContainer) { Guard.ArgumentNotNull(repositoryManager, nameof(repositoryManager)); this.repositoryManager = repositoryManager; + this.cacheContainer = cacheContainer; repositoryManager.OnCurrentBranchUpdated += RepositoryManager_OnCurrentBranchUpdated; repositoryManager.OnCurrentRemoteUpdated += RepositoryManager_OnCurrentRemoteUpdated; @@ -170,12 +170,12 @@ public bool Equals(IRepository other) private void RepositoryManager_OnCurrentRemoteUpdated(ConfigRemote? remote) { - if (!Nullable.Equals(currentRemote, remote)) + if (!Nullable.Equals(CurrentConfigRemote, remote)) { - currentRemote = remote; + CurrentConfigRemote = remote; - Logger.Trace("OnCurrentRemoteChanged: {0}", currentRemote.HasValue ? currentRemote.Value.ToString() : "[NULL]"); - OnCurrentRemoteChanged?.Invoke(currentRemote.HasValue ? currentRemote.Value.Name : null); + Logger.Trace("OnCurrentRemoteChanged: {0}", remote.HasValue ? remote.Value.ToString() : "[NULL]"); + OnCurrentRemoteChanged?.Invoke(remote.HasValue ? remote.Value.Name : null); UpdateRepositoryInfo(); } @@ -183,18 +183,18 @@ private void RepositoryManager_OnCurrentRemoteUpdated(ConfigRemote? remote) private void RepositoryManager_OnCurrentBranchUpdated(ConfigBranch? branch) { - if (!Nullable.Equals(currentBranch, branch)) + if (!Nullable.Equals(CurrentConfigBranch, branch)) { - currentBranch = branch; + CurrentConfigBranch = branch; - Logger.Trace("OnCurrentBranchChanged: {0}", currentBranch.HasValue ? currentBranch.ToString() : "[NULL]"); - OnCurrentBranchChanged?.Invoke(currentBranch.HasValue ? currentBranch.Value.Name : null); + Logger.Trace("OnCurrentBranchChanged: {0}", branch.HasValue ? branch.ToString() : "[NULL]"); + OnCurrentBranchChanged?.Invoke(branch.HasValue ? branch.Value.Name : null); } } private void RepositoryManager_OnLocalBranchUpdated(string name) { - if (name == currentBranch?.Name) + if (name == CurrentConfigBranch?.Name) { Logger.Trace("OnCurrentBranchUpdated: {0}", name); OnCurrentBranchUpdated?.Invoke(); @@ -325,7 +325,7 @@ private GitBranch GetLocalGitBranch(ConfigBranch x) { var name = x.Name; var trackingName = x.IsTracking ? x.Remote.Value.Name + "/" + name : "[None]"; - var isActive = name == currentBranch?.Name; + var isActive = name == CurrentConfigBranch?.Name; return new GitBranch(name, trackingName, isActive); } @@ -349,28 +349,40 @@ private GitRemote GetGitRemote(ConfigRemote configRemote) public IEnumerable RemoteBranches => remoteBranches.Values.SelectMany(x => x.Values).Select(GetRemoteGitBranch); + private ConfigBranch? CurrentConfigBranch + { + get { return this.cacheContainer.RepositoryInfoCache.CurentBranch; } + set { this.cacheContainer.RepositoryInfoCache.UpdateData(value); } + } + + private ConfigRemote? CurrentConfigRemote + { + get { return this.cacheContainer.RepositoryInfoCache.CurrentRemote; } + set { this.cacheContainer.RepositoryInfoCache.UpdateData(value); } + } + public GitBranch? CurrentBranch { get { - if (currentBranch != null) + if (CurrentConfigBranch != null) { - return GetLocalGitBranch(currentBranch.Value); + return GetLocalGitBranch(CurrentConfigBranch.Value); } return null; } } - public string CurrentBranchName => currentBranch?.Name; + public string CurrentBranchName => CurrentConfigBranch?.Name; public GitRemote? CurrentRemote { get { - if (currentRemote != null) + if (CurrentConfigRemote != null) { - return GetGitRemote(currentRemote.Value); + return GetGitRemote(CurrentConfigRemote.Value); } return null; @@ -432,7 +444,7 @@ public interface IUser } [Serializable] - class User : IUser + public class User : IUser { public override string ToString() { diff --git a/src/GitHub.Api/GitHub.Api.csproj b/src/GitHub.Api/GitHub.Api.csproj index ad75ee2e9..08745f6d5 100644 --- a/src/GitHub.Api/GitHub.Api.csproj +++ b/src/GitHub.Api/GitHub.Api.csproj @@ -99,7 +99,7 @@ - + @@ -111,8 +111,6 @@ - - diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs index fae8b70b3..47b845f4d 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs @@ -1,8 +1,8 @@ using System; using System.Collections.Generic; +using System.Linq; using UnityEditor; using UnityEngine; -using Debug = System.Diagnostics.Debug; namespace GitHub.Unity { @@ -86,40 +86,107 @@ public void Flush() [Location("cache/branches.yaml", LocationAttribute.Location.LibraryFolder)] sealed class BranchCache : ScriptObjectSingleton, IBranchCache { - [SerializeField] private List localBranches; - [SerializeField] private List remoteBranches; + private static ILogging Logger = Logging.GetLogger(); + private static readonly TimeSpan DataTimeout = TimeSpan.FromSeconds(0.5); + + [SerializeField] private DateTime lastUpdatedAt; + [SerializeField] private DateTime lastVerifiedAt; + [SerializeField] private List localBranches = new List(); + [SerializeField] private List remoteBranches = new List(); + + public event Action CacheInvalidated; + public event Action CacheUpdated; public BranchCache() + { } + + public void UpdateData(List localBranchUpdate, List remoteBranchUpdate) { + var now = DateTime.Now; + var isUpdated = false; + + Logger.Trace("Processing Update: {0}", now); + + var localBranchesIsNull = localBranches == null; + var localBranchUpdateIsNull = localBranchUpdate == null; + + if (localBranchesIsNull != localBranchUpdateIsNull + || !localBranchesIsNull && !localBranches.SequenceEqual(localBranchUpdate)) + { + localBranches = localBranchUpdate; + isUpdated = true; + } + + var remoteBranchesIsNull = remoteBranches == null; + var remoteBranchUpdateIsNull = remoteBranchUpdate == null; + + if (remoteBranchesIsNull != remoteBranchUpdateIsNull + || !remoteBranchesIsNull && !remoteBranches.SequenceEqual(remoteBranchUpdate)) + { + remoteBranches = remoteBranchUpdate; + isUpdated = true; + } + + if (isUpdated) + { + lastUpdatedAt = now; + } + + lastVerifiedAt = now; + Save(true); + + if (isUpdated) + { + Logger.Trace("Updated: {0}", now); + CacheUpdated.SafeInvoke(lastUpdatedAt); + } + else + { + Logger.Trace("Verified: {0}", now); + } + } + + public void ValidateData() + { + if (DateTime.Now - lastUpdatedAt > DataTimeout) + { + InvalidateData(); + } + } + + public void InvalidateData() + { + Logger.Trace("Invalidated"); + CacheInvalidated.SafeInvoke(); + UpdateData(new List(), new List()); } public List LocalBranches { get { - if (localBranches == null) - localBranches = new List(); + ValidateData(); return localBranches; } - set - { - localBranches = value; - Save(true); - } } + public List RemoteBranches { get { - if (remoteBranches == null) - remoteBranches = new List(); + ValidateData(); return remoteBranches; } - set - { - remoteBranches = value; - Save(true); - } + } + + public DateTime LastUpdatedAt + { + get { return lastUpdatedAt; } + } + + public DateTime LastVerifiedAt + { + get { return lastVerifiedAt; } } } @@ -173,26 +240,449 @@ public bool IsFavorite(string branchName) } } + [Location("cache/repoinfo.yaml", LocationAttribute.Location.LibraryFolder)] + sealed class RepositoryInfoCache : ScriptObjectSingleton, IRepositoryInfoCache + { + private static ILogging Logger = Logging.GetLogger(); + private static readonly TimeSpan DataTimeout = TimeSpan.FromSeconds(0.5); + + [SerializeField] private DateTime lastUpdatedAt; + [SerializeField] private DateTime lastVerifiedAt; + + [SerializeField] private ConfigRemote? gitRemote; + [SerializeField] private ConfigBranch? gitBranch; + + public event Action CacheInvalidated; + public event Action CacheUpdated; + + public RepositoryInfoCache() + { } + + public void UpdateData(ConfigRemote? gitRemoteUpdate) + { + UpdateData(gitRemoteUpdate, gitBranch); + } + + public void UpdateData(ConfigBranch? gitBranchUpdate) + { + UpdateData(gitRemote, gitBranchUpdate); + } + + public void UpdateData(ConfigRemote? gitRemoteUpdate, ConfigBranch? gitBranchUpdate) + { + var now = DateTime.Now; + var isUpdated = false; + + Logger.Trace("Processing Update: {0}", now); + + if (!Nullable.Equals(gitRemote, gitRemoteUpdate)) + { + gitRemote = gitRemoteUpdate; + isUpdated = true; + } + + if (!Nullable.Equals(gitBranch, gitBranchUpdate)) + { + gitBranch = gitBranchUpdate; + isUpdated = true; + } + + if (isUpdated) + { + lastUpdatedAt = now; + } + + lastVerifiedAt = now; + Save(true); + + if (isUpdated) + { + Logger.Trace("Updated: {0}", now); + CacheUpdated.SafeInvoke(lastUpdatedAt); + } + else + { + Logger.Trace("Verified: {0}", now); + } + } + + + public void ValidateData() + { + if (DateTime.Now - lastUpdatedAt > DataTimeout) + { + InvalidateData(); + } + } + + public void InvalidateData() + { + Logger.Trace("Invalidated"); + CacheInvalidated.SafeInvoke(); + UpdateData(null, null); + } + + public DateTime LastUpdatedAt + { + get { return lastUpdatedAt; } + } + + public DateTime LastVerifiedAt + { + get { return lastVerifiedAt; } + } + + public ConfigRemote? CurrentRemote + { + get + { + ValidateData(); + return gitRemote; + } + } + + public ConfigBranch? CurentBranch + { + get + { + ValidateData(); + return gitBranch; + } + } + } + [Location("cache/gitlog.yaml", LocationAttribute.Location.LibraryFolder)] sealed class GitLogCache : ScriptObjectSingleton, IGitLogCache { - [SerializeField] private List log; + private static ILogging Logger = Logging.GetLogger(); + private static readonly TimeSpan DataTimeout = TimeSpan.FromSeconds(0.5); + + [SerializeField] + private DateTime lastUpdatedAt; + [SerializeField] + private DateTime lastVerifiedAt; + [SerializeField] + private List log = new List(); + + public event Action CacheInvalidated; + public event Action CacheUpdated; + public GitLogCache() - {} + { } + + public void UpdateData(List logUpdate) + { + var now = DateTime.Now; + var isUpdated = false; + + Logger.Trace("Processing Update: {0}", now); + + var logIsNull = log == null; + var updateIsNull = logUpdate == null; + if (logIsNull != updateIsNull || + !logIsNull && !log.SequenceEqual(logUpdate)) + { + log = logUpdate; + lastUpdatedAt = now; + isUpdated = true; + } + + lastVerifiedAt = now; + Save(true); + + if (isUpdated) + { + Logger.Trace("Updated: {0}", now); + CacheUpdated.SafeInvoke(lastUpdatedAt); + } + else + { + Logger.Trace("Verified: {0}", now); + } + } public List Log { get { - if (log == null) - log = new List(); + ValidateData(); return log; } - set + } + + public void ValidateData() + { + if (DateTime.Now - lastUpdatedAt > DataTimeout) { - log = value; - Save(true); + InvalidateData(); } } + + public void InvalidateData() + { + Logger.Trace("Invalidated"); + CacheInvalidated.SafeInvoke(); + UpdateData(new List()); + } + + public DateTime LastUpdatedAt + { + get { return lastUpdatedAt; } + } + + public DateTime LastVerifiedAt + { + get { return lastVerifiedAt; } + } + } + + [Location("cache/gitstatus.yaml", LocationAttribute.Location.LibraryFolder)] + sealed class GitStatusCache : ScriptObjectSingleton, IGitStatusCache + { + private static ILogging Logger = Logging.GetLogger(); + private static readonly TimeSpan DataTimeout = TimeSpan.FromSeconds(0.5); + + [SerializeField] + private DateTime lastUpdatedAt; + [SerializeField] + private DateTime lastVerifiedAt; + [SerializeField] + private GitStatus status; + + public event Action CacheInvalidated; + public event Action CacheUpdated; + + public GitStatusCache() + { } + + public void UpdateData(GitStatus statusUpdate) + { + var now = DateTime.Now; + var isUpdated = false; + + Logger.Trace("Processing Update: {0}", now); + + if (!status.Equals(statusUpdate)) + { + status = statusUpdate; + lastUpdatedAt = now; + isUpdated = true; + } + + lastVerifiedAt = now; + Save(true); + + if (isUpdated) + { + Logger.Trace("Updated: {0}", now); + CacheUpdated.SafeInvoke(lastUpdatedAt); + } + else + { + Logger.Trace("Verified: {0}", now); + } + } + + public GitStatus GitStatus + { + get + { + ValidateData(); + return status; + } + } + + public void ValidateData() + { + if (DateTime.Now - lastUpdatedAt > DataTimeout) + { + InvalidateData(); + } + } + + public void InvalidateData() + { + Logger.Trace("Invalidated"); + CacheInvalidated.SafeInvoke(); + UpdateData(new GitStatus()); + } + + public DateTime LastUpdatedAt + { + get { return lastUpdatedAt; } + } + + public DateTime LastVerifiedAt + { + get { return lastVerifiedAt; } + } + } + + [Location("cache/gitlocks.yaml", LocationAttribute.Location.LibraryFolder)] + sealed class GitLocksCache : ScriptObjectSingleton, IGitLocksCache + { + private static ILogging Logger = Logging.GetLogger(); + private static readonly TimeSpan DataTimeout = TimeSpan.FromSeconds(0.5); + + [SerializeField] + private DateTime lastUpdatedAt; + [SerializeField] + private DateTime lastVerifiedAt; + [SerializeField] + private List locks; + + public event Action CacheInvalidated; + public event Action CacheUpdated; + + public GitLocksCache() + { } + + public void UpdateData(List locksUpdate) + { + var now = DateTime.Now; + var isUpdated = false; + + Logger.Trace("Processing Update: {0}", now); + + var locksIsNull = locks == null; + var locksUpdateIsNull = locksUpdate == null; + + if (locksIsNull != locksUpdateIsNull + || !locksIsNull && !locks.SequenceEqual(locksUpdate)) + { + locks = locksUpdate; + isUpdated = true; + lastUpdatedAt = now; + } + + lastVerifiedAt = now; + Save(true); + + if (isUpdated) + { + Logger.Trace("Updated: {0}", now); + CacheUpdated.SafeInvoke(lastUpdatedAt); + } + else + { + Logger.Trace("Verified: {0}", now); + } + } + + public List GitLocks + { + get + { + ValidateData(); + return locks; + } + } + + public void ValidateData() + { + if (DateTime.Now - lastUpdatedAt > DataTimeout) + { + InvalidateData(); + } + } + + public void InvalidateData() + { + Logger.Trace("Invalidated"); + CacheInvalidated.SafeInvoke(); + UpdateData(null); + } + + public DateTime LastUpdatedAt + { + get { return lastUpdatedAt; } + } + + public DateTime LastVerifiedAt + { + get { return lastVerifiedAt; } + } + } + + [Location("cache/gituser.yaml", LocationAttribute.Location.LibraryFolder)] + sealed class GitUserCache : ScriptObjectSingleton, IGitUserCache + { + private static ILogging Logger = Logging.GetLogger(); + private static readonly TimeSpan DataTimeout = TimeSpan.FromSeconds(0.5); + + [SerializeField] + private DateTime lastUpdatedAt; + [SerializeField] + private DateTime lastVerifiedAt; + [SerializeField] + private User user; + + public event Action CacheInvalidated; + public event Action CacheUpdated; + + public GitUserCache() + { } + + public void UpdateData(User userUpdate) + { + var now = DateTime.Now; + var isUpdated = false; + + Logger.Trace("Processing Update: {0}", now); + + if (user != userUpdate) + { + user = userUpdate; + isUpdated = true; + lastUpdatedAt = now; + } + + lastVerifiedAt = now; + Save(true); + + if (isUpdated) + { + Logger.Trace("Updated: {0}", now); + CacheUpdated.SafeInvoke(lastUpdatedAt); + } + else + { + Logger.Trace("Verified: {0}", now); + } + } + + public User User + { + get + { + ValidateData(); + return user; + } + } + + public void ValidateData() + { + if (DateTime.Now - lastUpdatedAt > DataTimeout) + { + InvalidateData(); + } + } + + public void InvalidateData() + { + Logger.Trace("Invalidated"); + CacheInvalidated.SafeInvoke(); + UpdateData(null); + } + + public DateTime LastUpdatedAt + { + get { return lastUpdatedAt; } + } + + public DateTime LastVerifiedAt + { + get { return lastVerifiedAt; } + } } } diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationManager.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationManager.cs index 9a63f8f8f..d3b0578a0 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationManager.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationManager.cs @@ -31,9 +31,13 @@ protected override void InitializeUI() Logger.Trace("Restarted {0}", Environment.Repository); EnvironmentCache.Instance.Flush(); - CacheManager.SetupCache(BranchCache.Instance); - CacheManager.SetupCache(GitLogCache.Instance); - CacheManager.SetRepository(Environment.Repository); + var cacheContainer = (CacheContainer)CacheContainer; + cacheContainer.BranchCache = BranchCache.Instance; + cacheContainer.GitLocksCache = GitLocksCache.Instance; + cacheContainer.GitLogCache = GitLogCache.Instance; + cacheContainer.GitStatusCache = GitStatusCache.Instance; + cacheContainer.GitUserCache = GitUserCache.Instance; + cacheContainer.RepositoryInfoCache = RepositoryInfoCache.Instance; ProjectWindowInterface.Initialize(Environment.Repository); var window = Window.GetWindow(); diff --git a/src/tests/IntegrationTests/BaseGitEnvironmentTest.cs b/src/tests/IntegrationTests/BaseGitEnvironmentTest.cs index 5bbec9fd9..3293a241c 100644 --- a/src/tests/IntegrationTests/BaseGitEnvironmentTest.cs +++ b/src/tests/IntegrationTests/BaseGitEnvironmentTest.cs @@ -32,7 +32,7 @@ protected async Task Initialize(NPath repoPath, NPath environmentP RepositoryManager.Initialize(); Environment.Repository = new Repository("TestRepo", repoPath); - Environment.Repository.Initialize(RepositoryManager); + Environment.Repository.Initialize(RepositoryManager, null); RepositoryManager.Start(); diff --git a/src/tests/UnitTests/Git/RepositoryTests.cs b/src/tests/UnitTests/Git/RepositoryTests.cs index 368d4a86b..175bcea9b 100644 --- a/src/tests/UnitTests/Git/RepositoryTests.cs +++ b/src/tests/UnitTests/Git/RepositoryTests.cs @@ -79,7 +79,7 @@ public void Repository() .ToDictionary(grouping => grouping.Key, grouping => grouping.ToDictionary(branch => branch.Name)); - repository.Initialize(repositoryManager); + repository.Initialize(repositoryManager, null); string expectedBranch = null; repository.OnCurrentBranchChanged += branch => { From 55038c9ad177f80400c2fe06c59e8272a960ff0c Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Wed, 25 Oct 2017 16:59:57 -0400 Subject: [PATCH 108/241] Increasing timeout --- .../Assets/Editor/GitHub.Unity/ApplicationCache.cs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs index 47b845f4d..9c5098507 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs @@ -87,7 +87,7 @@ public void Flush() sealed class BranchCache : ScriptObjectSingleton, IBranchCache { private static ILogging Logger = Logging.GetLogger(); - private static readonly TimeSpan DataTimeout = TimeSpan.FromSeconds(0.5); + private static readonly TimeSpan DataTimeout = TimeSpan.FromSeconds(30); [SerializeField] private DateTime lastUpdatedAt; [SerializeField] private DateTime lastVerifiedAt; @@ -244,7 +244,7 @@ public bool IsFavorite(string branchName) sealed class RepositoryInfoCache : ScriptObjectSingleton, IRepositoryInfoCache { private static ILogging Logger = Logging.GetLogger(); - private static readonly TimeSpan DataTimeout = TimeSpan.FromSeconds(0.5); + private static readonly TimeSpan DataTimeout = TimeSpan.FromSeconds(30); [SerializeField] private DateTime lastUpdatedAt; [SerializeField] private DateTime lastVerifiedAt; @@ -355,7 +355,7 @@ public ConfigBranch? CurentBranch sealed class GitLogCache : ScriptObjectSingleton, IGitLogCache { private static ILogging Logger = Logging.GetLogger(); - private static readonly TimeSpan DataTimeout = TimeSpan.FromSeconds(0.5); + private static readonly TimeSpan DataTimeout = TimeSpan.FromSeconds(30); [SerializeField] private DateTime lastUpdatedAt; @@ -440,7 +440,7 @@ public DateTime LastVerifiedAt sealed class GitStatusCache : ScriptObjectSingleton, IGitStatusCache { private static ILogging Logger = Logging.GetLogger(); - private static readonly TimeSpan DataTimeout = TimeSpan.FromSeconds(0.5); + private static readonly TimeSpan DataTimeout = TimeSpan.FromSeconds(30); [SerializeField] private DateTime lastUpdatedAt; @@ -522,7 +522,7 @@ public DateTime LastVerifiedAt sealed class GitLocksCache : ScriptObjectSingleton, IGitLocksCache { private static ILogging Logger = Logging.GetLogger(); - private static readonly TimeSpan DataTimeout = TimeSpan.FromSeconds(0.5); + private static readonly TimeSpan DataTimeout = TimeSpan.FromSeconds(30); [SerializeField] private DateTime lastUpdatedAt; @@ -608,7 +608,7 @@ public DateTime LastVerifiedAt sealed class GitUserCache : ScriptObjectSingleton, IGitUserCache { private static ILogging Logger = Logging.GetLogger(); - private static readonly TimeSpan DataTimeout = TimeSpan.FromSeconds(0.5); + private static readonly TimeSpan DataTimeout = TimeSpan.FromSeconds(30); [SerializeField] private DateTime lastUpdatedAt; From b3fafd8fd3aeb4a75afc3aa9d22268857ef8c766 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Wed, 25 Oct 2017 17:00:04 -0400 Subject: [PATCH 109/241] Firing events on the main thread --- src/GitHub.Api/Git/RepositoryManager.cs | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/src/GitHub.Api/Git/RepositoryManager.cs b/src/GitHub.Api/Git/RepositoryManager.cs index 7a4e20426..abc78f958 100644 --- a/src/GitHub.Api/Git/RepositoryManager.cs +++ b/src/GitHub.Api/Git/RepositoryManager.cs @@ -457,11 +457,16 @@ private void UpdateCurrentBranchAndRemote(string head) } } - Logger.Trace("OnCurrentBranchUpdated: {0}", branch.HasValue ? branch.Value.ToString() : "[NULL]"); - OnCurrentBranchUpdated?.Invoke(branch); + new ActionTask(taskManager.Token, () => { + Logger.Trace("OnCurrentBranchUpdated: {0}", branch.HasValue ? branch.Value.ToString() : "[NULL]"); + OnCurrentBranchUpdated?.Invoke(branch); - Logger.Trace("OnCurrentRemoteUpdated: {0}", remote.HasValue ? remote.Value.ToString() : "[NULL]"); - OnCurrentRemoteUpdated?.Invoke(remote); + Logger.Trace("OnCurrentRemoteUpdated: {0}", remote.HasValue ? remote.Value.ToString() : "[NULL]"); + OnCurrentRemoteUpdated?.Invoke(remote); + }) + { + Affinity = TaskAffinity.UI + }.Start(); } private void Watcher_OnIndexChanged() From 360851a8896fda7440a102fb1def946b9ec96263 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Wed, 25 Oct 2017 17:57:26 -0400 Subject: [PATCH 110/241] Figuring out a base class sytem that works for these cache objects --- src/GitHub.Api/Cache/CacheContainer.cs | 59 +++-- src/GitHub.Api/Git/GitLogEntry.cs | 4 +- .../Editor/GitHub.Unity/ApplicationCache.cs | 229 +++++++++++++----- .../Editor/GitHub.Unity/ApplicationManager.cs | 3 + 4 files changed, 218 insertions(+), 77 deletions(-) diff --git a/src/GitHub.Api/Cache/CacheContainer.cs b/src/GitHub.Api/Cache/CacheContainer.cs index 529f6b7bd..550a4c29d 100644 --- a/src/GitHub.Api/Cache/CacheContainer.cs +++ b/src/GitHub.Api/Cache/CacheContainer.cs @@ -5,6 +5,8 @@ namespace GitHub.Unity { public class CacheContainer : ICacheContainer { + private static ILogging Logger = Logging.GetLogger(); + private IBranchCache branchCache; private IGitLocksCache gitLocksCache; @@ -19,7 +21,7 @@ public class CacheContainer : ICacheContainer public event Action CacheInvalidated; - public event Action CacheUpdated; + public event Action CacheUpdated; private IManagedCache GetManagedCache(CacheType cacheType) { @@ -48,6 +50,8 @@ private IManagedCache GetManagedCache(CacheType cacheType) } } + public ITestCache TestCache { get; set; } + public void Validate(CacheType cacheType) { GetManagedCache(cacheType).ValidateData(); @@ -86,8 +90,8 @@ public IBranchCache BranchCache if (branchCache == null) { branchCache = value; - branchCache.CacheInvalidated += () => CacheInvalidated?.Invoke(CacheType.BranchCache); - branchCache.CacheUpdated += datetime => CacheUpdated?.Invoke(CacheType.BranchCache, datetime); + branchCache.CacheInvalidated += () => OnCacheInvalidated(CacheType.BranchCache); + branchCache.CacheUpdated += datetime => OnCacheUpdated(CacheType.BranchCache, datetime); } } } @@ -100,8 +104,8 @@ public IGitLogCache GitLogCache if (gitLogCache == null) { gitLogCache = value; - gitLogCache.CacheInvalidated += () => CacheInvalidated?.Invoke(CacheType.GitLogCache); - gitLogCache.CacheUpdated += datetime => CacheUpdated?.Invoke(CacheType.GitLogCache, datetime); + gitLogCache.CacheInvalidated += () => OnCacheInvalidated(CacheType.GitLogCache); + gitLogCache.CacheUpdated += datetime => OnCacheUpdated(CacheType.GitLogCache, datetime); } } } @@ -114,8 +118,8 @@ public IRepositoryInfoCache RepositoryInfoCache if (repositoryInfoCache == null) { repositoryInfoCache = value; - repositoryInfoCache.CacheInvalidated += () => CacheInvalidated?.Invoke(CacheType.RepositoryInfoCache); - repositoryInfoCache.CacheUpdated += datetime => CacheUpdated?.Invoke(CacheType.RepositoryInfoCache, datetime); + repositoryInfoCache.CacheInvalidated += () => OnCacheInvalidated(CacheType.RepositoryInfoCache); + repositoryInfoCache.CacheUpdated += datetime => OnCacheUpdated(CacheType.RepositoryInfoCache, datetime); } } } @@ -128,8 +132,8 @@ public IGitStatusCache GitStatusCache if (gitStatusCache == null) { gitStatusCache = value; - gitStatusCache.CacheInvalidated += () => CacheInvalidated?.Invoke(CacheType.GitStatusCache); - gitStatusCache.CacheUpdated += datetime => CacheUpdated?.Invoke(CacheType.GitStatusCache, datetime); + gitStatusCache.CacheInvalidated += () => OnCacheInvalidated(CacheType.GitStatusCache); + gitStatusCache.CacheUpdated += datetime => OnCacheUpdated(CacheType.GitStatusCache, datetime); } } } @@ -142,8 +146,8 @@ public IGitLocksCache GitLocksCache if (gitLocksCache == null) { gitLocksCache = value; - gitLocksCache.CacheInvalidated += () => CacheInvalidated?.Invoke(CacheType.GitLocksCache); - gitLocksCache.CacheUpdated += datetime => CacheUpdated?.Invoke(CacheType.GitLocksCache, datetime); + gitLocksCache.CacheInvalidated += () => OnCacheInvalidated(CacheType.GitLocksCache); + gitLocksCache.CacheUpdated += datetime => OnCacheUpdated(CacheType.GitLocksCache, datetime); } } } @@ -156,11 +160,23 @@ public IGitUserCache GitUserCache if (gitUserCache == null) { gitUserCache = value; - gitUserCache.CacheInvalidated += () => CacheInvalidated?.Invoke(CacheType.GitUserCache); - gitUserCache.CacheUpdated += datetime => CacheUpdated?.Invoke(CacheType.GitUserCache, datetime); + gitUserCache.CacheInvalidated += () => OnCacheInvalidated(CacheType.GitUserCache); + gitUserCache.CacheUpdated += datetime => OnCacheUpdated(CacheType.GitUserCache, datetime); } } } + + private void OnCacheUpdated(CacheType cacheType, DateTimeOffset datetime) + { + Logger.Trace("OnCacheUpdated cacheType:{0} datetime:{1}", cacheType, datetime); + CacheUpdated?.Invoke(cacheType, datetime); + } + + private void OnCacheInvalidated(CacheType cacheType) + { + Logger.Trace("OnCacheInvalidated cacheType:{0}", cacheType); + CacheInvalidated?.Invoke(cacheType); + } } public enum CacheType @@ -176,7 +192,7 @@ public enum CacheType public interface ICacheContainer { event Action CacheInvalidated; - event Action CacheUpdated; + event Action CacheUpdated; IBranchCache BranchCache { get; } IGitLogCache GitLogCache { get; } @@ -184,6 +200,7 @@ public interface ICacheContainer IGitStatusCache GitStatusCache { get; } IGitLocksCache GitLocksCache { get; } IGitUserCache GitUserCache { get; } + ITestCache TestCache { get; } void Validate(CacheType cacheType); void ValidateAll(); void Invalidate(CacheType cacheType); @@ -193,13 +210,13 @@ public interface ICacheContainer public interface IManagedCache { event Action CacheInvalidated; - event Action CacheUpdated; + event Action CacheUpdated; void ValidateData(); void InvalidateData(); - DateTime LastUpdatedAt { get; } - DateTime LastVerifiedAt { get; } + DateTimeOffset LastUpdatedAt { get; } + DateTimeOffset LastVerifiedAt { get; } } public interface IGitLocks @@ -215,6 +232,14 @@ public interface IGitUser User User { get; } } + public interface ITestCache : IManagedCache, ITestCacheItem + { + void UpdateData(); + } + + public interface ITestCacheItem + { } + public interface IGitUserCache : IManagedCache, IGitUser { } diff --git a/src/GitHub.Api/Git/GitLogEntry.cs b/src/GitHub.Api/Git/GitLogEntry.cs index 617245379..5861f4334 100644 --- a/src/GitHub.Api/Git/GitLogEntry.cs +++ b/src/GitHub.Api/Git/GitLogEntry.cs @@ -42,7 +42,7 @@ public string PrettyTimeString } } - [NonSerialized] public DateTimeOffset? timeValue; + [NonSerialized] private DateTimeOffset? timeValue; public DateTimeOffset Time { get @@ -56,7 +56,7 @@ public DateTimeOffset Time } } - [NonSerialized] public DateTimeOffset? commitTimeValue; + [NonSerialized] private DateTimeOffset? commitTimeValue; public DateTimeOffset? CommitTime { get diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs index 9c5098507..6b9b78cdf 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs @@ -83,26 +83,146 @@ public void Flush() } } + abstract class ManagedCacheBase : ScriptObjectSingleton where T : ScriptableObject, IManagedCache + { + private ILogging logger; + private static readonly TimeSpan DataTimeout = TimeSpan.FromSeconds(30); + + public event Action CacheInvalidated; + public event Action CacheUpdated; + + public abstract string LastUpdatedAtString { get; protected set; } + public abstract string LastVerifiedAtString { get; protected set; } + + [NonSerialized] private DateTimeOffset? lastUpdatedAtValue; + public DateTimeOffset LastUpdatedAt { + get + { + if (!lastUpdatedAtValue.HasValue) + { + lastUpdatedAtValue = DateTimeOffset.Parse(LastUpdatedAtString); + } + + return lastUpdatedAtValue.Value; + } + set + { + LastUpdatedAtString = value.ToString(); + lastUpdatedAtValue = null; + } + } + + [NonSerialized] private DateTimeOffset? lastVerifiedAtValue; + public DateTimeOffset LastVerifiedAt { + get + { + if (!lastVerifiedAtValue.HasValue) + { + lastVerifiedAtValue = DateTimeOffset.Parse(LastVerifiedAtString); + } + + return lastVerifiedAtValue.Value; + } + set + { + LastVerifiedAtString = value.ToString(); + lastVerifiedAtValue = null; + } + } + + protected ManagedCacheBase() + { + logger = Logging.GetLogger(GetType()); + } + + public void ValidateData() + { + if (DateTimeOffset.Now - LastUpdatedAt > DataTimeout) + { + InvalidateData(); + } + } + + public void InvalidateData() + { + logger.Trace("Invalidated"); + CacheInvalidated.SafeInvoke(); + ResetData(); + } + + protected abstract void ResetData(); + + protected void SaveData(DateTimeOffset now, bool isUpdated) + { + if (isUpdated) + { + LastUpdatedAt = now; + } + + LastVerifiedAt = now; + Save(true); + + if (isUpdated) + { + logger.Trace("Updated: {0}", now); + CacheUpdated.SafeInvoke(now); + } + else + { + logger.Trace("Verified: {0}", now); + } + } + } + + [Location("cache/testCache.yaml", LocationAttribute.Location.LibraryFolder)] + sealed class TestCache : ManagedCacheBase, ITestCache + { + [SerializeField] private string lastUpdatedAtString; + [SerializeField] private string lastVerifiedAtString; + + public override string LastUpdatedAtString + { + get { return lastUpdatedAtString; } + protected set { lastUpdatedAtString = value; } + } + + public override string LastVerifiedAtString + { + get { return lastVerifiedAtString; } + protected set { lastVerifiedAtString = value; } + } + + protected override void ResetData() + { + + } + + public void UpdateData() + { + SaveData(DateTimeOffset.Now, false); + } + } + [Location("cache/branches.yaml", LocationAttribute.Location.LibraryFolder)] sealed class BranchCache : ScriptObjectSingleton, IBranchCache { private static ILogging Logger = Logging.GetLogger(); private static readonly TimeSpan DataTimeout = TimeSpan.FromSeconds(30); - [SerializeField] private DateTime lastUpdatedAt; - [SerializeField] private DateTime lastVerifiedAt; + [SerializeField] private DateTimeOffset lastUpdatedAt; + [SerializeField] private DateTimeOffset lastVerifiedAt; [SerializeField] private List localBranches = new List(); [SerializeField] private List remoteBranches = new List(); public event Action CacheInvalidated; - public event Action CacheUpdated; + public event Action CacheUpdated; public BranchCache() { } public void UpdateData(List localBranchUpdate, List remoteBranchUpdate) { - var now = DateTime.Now; + var now = DateTimeOffset.Now; var isUpdated = false; Logger.Trace("Processing Update: {0}", now); @@ -127,6 +247,11 @@ public void UpdateData(List localBranchUpdate, List remote isUpdated = true; } + SaveData(now, isUpdated); + } + + private void SaveData(DateTimeOffset now, bool isUpdated) + { if (isUpdated) { lastUpdatedAt = now; @@ -148,7 +273,7 @@ public void UpdateData(List localBranchUpdate, List remote public void ValidateData() { - if (DateTime.Now - lastUpdatedAt > DataTimeout) + if (DateTimeOffset.Now - lastUpdatedAt > DataTimeout) { InvalidateData(); } @@ -179,12 +304,12 @@ public List RemoteBranches } } - public DateTime LastUpdatedAt + public DateTimeOffset LastUpdatedAt { get { return lastUpdatedAt; } } - public DateTime LastVerifiedAt + public DateTimeOffset LastVerifiedAt { get { return lastVerifiedAt; } } @@ -246,14 +371,14 @@ sealed class RepositoryInfoCache : ScriptObjectSingleton, I private static ILogging Logger = Logging.GetLogger(); private static readonly TimeSpan DataTimeout = TimeSpan.FromSeconds(30); - [SerializeField] private DateTime lastUpdatedAt; - [SerializeField] private DateTime lastVerifiedAt; + [SerializeField] private DateTimeOffset lastUpdatedAt; + [SerializeField] private DateTimeOffset lastVerifiedAt; [SerializeField] private ConfigRemote? gitRemote; [SerializeField] private ConfigBranch? gitBranch; public event Action CacheInvalidated; - public event Action CacheUpdated; + public event Action CacheUpdated; public RepositoryInfoCache() { } @@ -270,7 +395,7 @@ public void UpdateData(ConfigBranch? gitBranchUpdate) public void UpdateData(ConfigRemote? gitRemoteUpdate, ConfigBranch? gitBranchUpdate) { - var now = DateTime.Now; + var now = DateTimeOffset.Now; var isUpdated = false; Logger.Trace("Processing Update: {0}", now); @@ -309,7 +434,7 @@ public void UpdateData(ConfigRemote? gitRemoteUpdate, ConfigBranch? gitBranchUpd public void ValidateData() { - if (DateTime.Now - lastUpdatedAt > DataTimeout) + if (DateTimeOffset.Now - lastUpdatedAt > DataTimeout) { InvalidateData(); } @@ -322,12 +447,12 @@ public void InvalidateData() UpdateData(null, null); } - public DateTime LastUpdatedAt + public DateTimeOffset LastUpdatedAt { get { return lastUpdatedAt; } } - public DateTime LastVerifiedAt + public DateTimeOffset LastVerifiedAt { get { return lastVerifiedAt; } } @@ -357,22 +482,19 @@ sealed class GitLogCache : ScriptObjectSingleton, IGitLogCache private static ILogging Logger = Logging.GetLogger(); private static readonly TimeSpan DataTimeout = TimeSpan.FromSeconds(30); - [SerializeField] - private DateTime lastUpdatedAt; - [SerializeField] - private DateTime lastVerifiedAt; - [SerializeField] - private List log = new List(); + [SerializeField] private DateTimeOffset lastUpdatedAt; + [SerializeField] private DateTimeOffset lastVerifiedAt; + [SerializeField] private List log = new List(); public event Action CacheInvalidated; - public event Action CacheUpdated; + public event Action CacheUpdated; public GitLogCache() { } public void UpdateData(List logUpdate) { - var now = DateTime.Now; + var now = DateTimeOffset.Now; var isUpdated = false; Logger.Trace("Processing Update: {0}", now); @@ -412,7 +534,7 @@ public List Log public void ValidateData() { - if (DateTime.Now - lastUpdatedAt > DataTimeout) + if (DateTimeOffset.Now - lastUpdatedAt > DataTimeout) { InvalidateData(); } @@ -425,12 +547,12 @@ public void InvalidateData() UpdateData(new List()); } - public DateTime LastUpdatedAt + public DateTimeOffset LastUpdatedAt { get { return lastUpdatedAt; } } - public DateTime LastVerifiedAt + public DateTimeOffset LastVerifiedAt { get { return lastVerifiedAt; } } @@ -442,22 +564,19 @@ sealed class GitStatusCache : ScriptObjectSingleton, IGitStatusC private static ILogging Logger = Logging.GetLogger(); private static readonly TimeSpan DataTimeout = TimeSpan.FromSeconds(30); - [SerializeField] - private DateTime lastUpdatedAt; - [SerializeField] - private DateTime lastVerifiedAt; - [SerializeField] - private GitStatus status; + [SerializeField] private DateTimeOffset lastUpdatedAt; + [SerializeField] private DateTimeOffset lastVerifiedAt; + [SerializeField] private GitStatus status; public event Action CacheInvalidated; - public event Action CacheUpdated; + public event Action CacheUpdated; public GitStatusCache() { } public void UpdateData(GitStatus statusUpdate) { - var now = DateTime.Now; + var now = DateTimeOffset.Now; var isUpdated = false; Logger.Trace("Processing Update: {0}", now); @@ -494,7 +613,7 @@ public GitStatus GitStatus public void ValidateData() { - if (DateTime.Now - lastUpdatedAt > DataTimeout) + if (DateTimeOffset.Now - lastUpdatedAt > DataTimeout) { InvalidateData(); } @@ -507,12 +626,12 @@ public void InvalidateData() UpdateData(new GitStatus()); } - public DateTime LastUpdatedAt + public DateTimeOffset LastUpdatedAt { get { return lastUpdatedAt; } } - public DateTime LastVerifiedAt + public DateTimeOffset LastVerifiedAt { get { return lastVerifiedAt; } } @@ -524,22 +643,19 @@ sealed class GitLocksCache : ScriptObjectSingleton, IGitLocksCach private static ILogging Logger = Logging.GetLogger(); private static readonly TimeSpan DataTimeout = TimeSpan.FromSeconds(30); - [SerializeField] - private DateTime lastUpdatedAt; - [SerializeField] - private DateTime lastVerifiedAt; - [SerializeField] - private List locks; + [SerializeField] private DateTimeOffset lastUpdatedAt; + [SerializeField] private DateTimeOffset lastVerifiedAt; + [SerializeField] private List locks; public event Action CacheInvalidated; - public event Action CacheUpdated; + public event Action CacheUpdated; public GitLocksCache() { } public void UpdateData(List locksUpdate) { - var now = DateTime.Now; + var now = DateTimeOffset.Now; var isUpdated = false; Logger.Trace("Processing Update: {0}", now); @@ -580,7 +696,7 @@ public List GitLocks public void ValidateData() { - if (DateTime.Now - lastUpdatedAt > DataTimeout) + if (DateTimeOffset.Now - lastUpdatedAt > DataTimeout) { InvalidateData(); } @@ -593,12 +709,12 @@ public void InvalidateData() UpdateData(null); } - public DateTime LastUpdatedAt + public DateTimeOffset LastUpdatedAt { get { return lastUpdatedAt; } } - public DateTime LastVerifiedAt + public DateTimeOffset LastVerifiedAt { get { return lastVerifiedAt; } } @@ -610,22 +726,19 @@ sealed class GitUserCache : ScriptObjectSingleton, IGitUserCache private static ILogging Logger = Logging.GetLogger(); private static readonly TimeSpan DataTimeout = TimeSpan.FromSeconds(30); - [SerializeField] - private DateTime lastUpdatedAt; - [SerializeField] - private DateTime lastVerifiedAt; - [SerializeField] - private User user; + [SerializeField] private DateTimeOffset lastUpdatedAt; + [SerializeField] private DateTimeOffset lastVerifiedAt; + [SerializeField] private User user; public event Action CacheInvalidated; - public event Action CacheUpdated; + public event Action CacheUpdated; public GitUserCache() { } public void UpdateData(User userUpdate) { - var now = DateTime.Now; + var now = DateTimeOffset.Now; var isUpdated = false; Logger.Trace("Processing Update: {0}", now); @@ -662,7 +775,7 @@ public User User public void ValidateData() { - if (DateTime.Now - lastUpdatedAt > DataTimeout) + if (DateTimeOffset.Now - lastUpdatedAt > DataTimeout) { InvalidateData(); } @@ -675,12 +788,12 @@ public void InvalidateData() UpdateData(null); } - public DateTime LastUpdatedAt + public DateTimeOffset LastUpdatedAt { get { return lastUpdatedAt; } } - public DateTime LastVerifiedAt + public DateTimeOffset LastVerifiedAt { get { return lastVerifiedAt; } } diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationManager.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationManager.cs index d3b0578a0..2c848deb7 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationManager.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationManager.cs @@ -37,8 +37,11 @@ protected override void InitializeUI() cacheContainer.GitLogCache = GitLogCache.Instance; cacheContainer.GitStatusCache = GitStatusCache.Instance; cacheContainer.GitUserCache = GitUserCache.Instance; + cacheContainer.TestCache = TestCache.Instance; cacheContainer.RepositoryInfoCache = RepositoryInfoCache.Instance; + cacheContainer.TestCache.UpdateData(); + ProjectWindowInterface.Initialize(Environment.Repository); var window = Window.GetWindow(); if (window != null) From 41b9d4e72e0e51ab4b2e389fb74020303a90dc69 Mon Sep 17 00:00:00 2001 From: Don Okuda Date: Wed, 25 Oct 2017 15:48:29 -0700 Subject: [PATCH 111/241] More space adjustments --- .../Assets/Editor/GitHub.Unity/UI/InitProjectView.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs index 1d6b00b2f..2db87b024 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs @@ -63,7 +63,7 @@ public override void OnGUI() GUILayout.EndHorizontal(); GUILayout.Label(NoRepoTitle, Styles.BoldCenteredLabel); - EditorGUILayout.Space(); + GUILayout.Space(4); GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); From 6819d7f4100a535642d602e14bfac2f3326b3413 Mon Sep 17 00:00:00 2001 From: Don Okuda Date: Wed, 25 Oct 2017 16:51:37 -0700 Subject: [PATCH 112/241] Try out a different kind of error message --- .../Assets/Editor/GitHub.Unity/UI/InitProjectView.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs index 2db87b024..401721e72 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs @@ -84,7 +84,10 @@ public override void OnGUI() GUILayout.EndHorizontal(); EditorGUILayout.Space(); - EditorGUILayout.HelpBox("There was an error initializing a repository.", MessageType.Error); + EditorGUILayout.HelpBox( + "Name and email not set in git. Go into the settings tab and enter the missing information", + MessageType.Error + ); GUILayout.FlexibleSpace(); } From 87ec22da617f750c03470836d3486a565651ffd8 Mon Sep 17 00:00:00 2001 From: Don Okuda Date: Wed, 25 Oct 2017 20:29:25 -0700 Subject: [PATCH 113/241] Center text --- src/UnityExtension/Assets/Editor/GitHub.Unity/Misc/Styles.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/Misc/Styles.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/Misc/Styles.cs index b3af92b6e..5580f1065 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/Misc/Styles.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/Misc/Styles.cs @@ -567,6 +567,7 @@ public static GUIStyle BoldCenteredLabel boldCenteredLabel = new GUIStyle(EditorStyles.boldLabel); boldCenteredLabel.name = "BoldCenteredLabelStyle"; boldCenteredLabel.alignment = TextAnchor.MiddleCenter; + boldCenteredLabel.wordWrap = true; } return boldCenteredLabel; } From 748c126c90e66537a6803d48ccdca527426e6b9c Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 26 Oct 2017 09:10:11 -0400 Subject: [PATCH 114/241] Using this new base class --- .../Editor/GitHub.Unity/ApplicationCache.cs | 560 ++++++------------ 1 file changed, 179 insertions(+), 381 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs index 6b9b78cdf..3936be2dc 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs @@ -8,9 +8,8 @@ namespace GitHub.Unity { sealed class ApplicationCache : ScriptObjectSingleton { - [SerializeField] private bool firstRun = true; - [NonSerialized] private bool? val; + [SerializeField] private bool firstRun = true; public bool FirstRun { @@ -34,13 +33,32 @@ public bool FirstRun sealed class EnvironmentCache : ScriptObjectSingleton { + [NonSerialized] private IEnvironment environment; + [SerializeField] private string extensionInstallPath; [SerializeField] private string repositoryPath; [SerializeField] private string unityApplication; [SerializeField] private string unityAssetsPath; - [SerializeField] private string extensionInstallPath; [SerializeField] private string unityVersion; - [NonSerialized] private IEnvironment environment; + public void Flush() + { + repositoryPath = Environment.RepositoryPath; + unityApplication = Environment.UnityApplication; + unityAssetsPath = Environment.UnityAssetsPath; + extensionInstallPath = Environment.ExtensionInstallPath; + Save(true); + } + + private NPath DetermineInstallationPath() + { + // Juggling to find out where we got installed + var shim = CreateInstance(); + var script = MonoScript.FromScriptableObject(shim); + var scriptPath = AssetDatabase.GetAssetPath(script).ToNPath(); + DestroyImmediate(shim); + return scriptPath.Parent; + } + public IEnvironment Environment { get @@ -55,84 +73,32 @@ public IEnvironment Environment extensionInstallPath = DetermineInstallationPath(); unityVersion = Application.unityVersion; } - environment.Initialize(unityVersion, extensionInstallPath.ToNPath(), unityApplication.ToNPath(), unityAssetsPath.ToNPath()); - environment.InitializeRepository(!String.IsNullOrEmpty(repositoryPath) ? repositoryPath.ToNPath() : null); + environment.Initialize(unityVersion, extensionInstallPath.ToNPath(), unityApplication.ToNPath(), + unityAssetsPath.ToNPath()); + environment.InitializeRepository(!String.IsNullOrEmpty(repositoryPath) + ? repositoryPath.ToNPath() + : null); Flush(); } return environment; } } - - private NPath DetermineInstallationPath() - { - // Juggling to find out where we got installed - var shim = ScriptableObject.CreateInstance(); - var script = MonoScript.FromScriptableObject(shim); - var scriptPath = AssetDatabase.GetAssetPath(script).ToNPath(); - ScriptableObject.DestroyImmediate(shim); - return scriptPath.Parent; - } - - public void Flush() - { - repositoryPath = Environment.RepositoryPath; - unityApplication = Environment.UnityApplication; - unityAssetsPath = Environment.UnityAssetsPath; - extensionInstallPath = Environment.ExtensionInstallPath; - Save(true); - } } abstract class ManagedCacheBase : ScriptObjectSingleton where T : ScriptableObject, IManagedCache { - private ILogging logger; private static readonly TimeSpan DataTimeout = TimeSpan.FromSeconds(30); - public event Action CacheInvalidated; - public event Action CacheUpdated; - - public abstract string LastUpdatedAtString { get; protected set; } - public abstract string LastVerifiedAtString { get; protected set; } - [NonSerialized] private DateTimeOffset? lastUpdatedAtValue; - public DateTimeOffset LastUpdatedAt { - get - { - if (!lastUpdatedAtValue.HasValue) - { - lastUpdatedAtValue = DateTimeOffset.Parse(LastUpdatedAtString); - } - - return lastUpdatedAtValue.Value; - } - set - { - LastUpdatedAtString = value.ToString(); - lastUpdatedAtValue = null; - } - } [NonSerialized] private DateTimeOffset? lastVerifiedAtValue; - public DateTimeOffset LastVerifiedAt { - get - { - if (!lastVerifiedAtValue.HasValue) - { - lastVerifiedAtValue = DateTimeOffset.Parse(LastVerifiedAtString); - } - return lastVerifiedAtValue.Value; - } - set - { - LastVerifiedAtString = value.ToString(); - lastVerifiedAtValue = null; - } - } + public event Action CacheInvalidated; + public event Action CacheUpdated; protected ManagedCacheBase() { - logger = Logging.GetLogger(GetType()); + Logger = Logging.GetLogger(GetType()); } public void ValidateData() @@ -145,7 +111,7 @@ public void ValidateData() public void InvalidateData() { - logger.Trace("Invalidated"); + Logger.Trace("Invalidated"); CacheInvalidated.SafeInvoke(); ResetData(); } @@ -164,62 +130,65 @@ protected void SaveData(DateTimeOffset now, bool isUpdated) if (isUpdated) { - logger.Trace("Updated: {0}", now); + Logger.Trace("Updated: {0}", now); CacheUpdated.SafeInvoke(now); } else { - logger.Trace("Verified: {0}", now); + Logger.Trace("Verified: {0}", now); } } - } - [Location("cache/testCache.yaml", LocationAttribute.Location.LibraryFolder)] - sealed class TestCache : ManagedCacheBase, ITestCache - { - [SerializeField] private string lastUpdatedAtString; - [SerializeField] private string lastVerifiedAtString; + public abstract string LastUpdatedAtString { get; protected set; } + public abstract string LastVerifiedAtString { get; protected set; } - public override string LastUpdatedAtString + public DateTimeOffset LastUpdatedAt { - get { return lastUpdatedAtString; } - protected set { lastUpdatedAtString = value; } - } + get + { + if (!lastUpdatedAtValue.HasValue) + { + lastUpdatedAtValue = DateTimeOffset.Parse(LastUpdatedAtString); + } - public override string LastVerifiedAtString - { - get { return lastVerifiedAtString; } - protected set { lastVerifiedAtString = value; } + return lastUpdatedAtValue.Value; + } + set + { + LastUpdatedAtString = value.ToString(); + lastUpdatedAtValue = null; + } } - protected override void ResetData() + public DateTimeOffset LastVerifiedAt { - - } + get + { + if (!lastVerifiedAtValue.HasValue) + { + lastVerifiedAtValue = DateTimeOffset.Parse(LastVerifiedAtString); + } - public void UpdateData() - { - SaveData(DateTimeOffset.Now, false); + return lastVerifiedAtValue.Value; + } + set + { + LastVerifiedAtString = value.ToString(); + lastVerifiedAtValue = null; + } } + + protected ILogging Logger { get; private set; } } [Location("cache/branches.yaml", LocationAttribute.Location.LibraryFolder)] - sealed class BranchCache : ScriptObjectSingleton, IBranchCache + sealed class BranchCache : ManagedCacheBase, IBranchCache { - private static ILogging Logger = Logging.GetLogger(); - private static readonly TimeSpan DataTimeout = TimeSpan.FromSeconds(30); - - [SerializeField] private DateTimeOffset lastUpdatedAt; - [SerializeField] private DateTimeOffset lastVerifiedAt; + [SerializeField] private string lastUpdatedAtString; + [SerializeField] private string lastVerifiedAtString; [SerializeField] private List localBranches = new List(); [SerializeField] private List remoteBranches = new List(); - public event Action CacheInvalidated; - public event Action CacheUpdated; - - public BranchCache() - { } - public void UpdateData(List localBranchUpdate, List remoteBranchUpdate) { var now = DateTimeOffset.Now; @@ -230,8 +199,8 @@ public void UpdateData(List localBranchUpdate, List remote var localBranchesIsNull = localBranches == null; var localBranchUpdateIsNull = localBranchUpdate == null; - if (localBranchesIsNull != localBranchUpdateIsNull - || !localBranchesIsNull && !localBranches.SequenceEqual(localBranchUpdate)) + if (localBranchesIsNull != localBranchUpdateIsNull || + !localBranchesIsNull && !localBranches.SequenceEqual(localBranchUpdate)) { localBranches = localBranchUpdate; isUpdated = true; @@ -240,8 +209,8 @@ public void UpdateData(List localBranchUpdate, List remote var remoteBranchesIsNull = remoteBranches == null; var remoteBranchUpdateIsNull = remoteBranchUpdate == null; - if (remoteBranchesIsNull != remoteBranchUpdateIsNull - || !remoteBranchesIsNull && !remoteBranches.SequenceEqual(remoteBranchUpdate)) + if (remoteBranchesIsNull != remoteBranchUpdateIsNull || + !remoteBranchesIsNull && !remoteBranches.SequenceEqual(remoteBranchUpdate)) { remoteBranches = remoteBranchUpdate; isUpdated = true; @@ -250,68 +219,36 @@ public void UpdateData(List localBranchUpdate, List remote SaveData(now, isUpdated); } - private void SaveData(DateTimeOffset now, bool isUpdated) - { - if (isUpdated) - { - lastUpdatedAt = now; - } - - lastVerifiedAt = now; - Save(true); - - if (isUpdated) - { - Logger.Trace("Updated: {0}", now); - CacheUpdated.SafeInvoke(lastUpdatedAt); - } - else - { - Logger.Trace("Verified: {0}", now); - } - } - - public void ValidateData() - { - if (DateTimeOffset.Now - lastUpdatedAt > DataTimeout) - { - InvalidateData(); - } + public List LocalBranches { + get { return localBranches; } } - public void InvalidateData() + public List RemoteBranches { - Logger.Trace("Invalidated"); - CacheInvalidated.SafeInvoke(); - UpdateData(new List(), new List()); + get { return remoteBranches; } } - public List LocalBranches + public void UpdateData() { - get - { - ValidateData(); - return localBranches; - } + SaveData(DateTimeOffset.Now, false); } - public List RemoteBranches + protected override void ResetData() { - get - { - ValidateData(); - return remoteBranches; - } + localBranches = new List(); + remoteBranches = new List(); } - public DateTimeOffset LastUpdatedAt + public override string LastUpdatedAtString { - get { return lastUpdatedAt; } + get { return lastUpdatedAtString; } + protected set { lastUpdatedAtString = value; } } - public DateTimeOffset LastVerifiedAt + public override string LastVerifiedAtString { - get { return lastVerifiedAt; } + get { return lastVerifiedAtString; } + protected set { lastVerifiedAtString = value; } } } @@ -319,25 +256,14 @@ public DateTimeOffset LastVerifiedAt sealed class Favorites : ScriptObjectSingleton { [SerializeField] private List favoriteBranches; - public List FavoriteBranches - { - get - { - if (favoriteBranches == null) - FavoriteBranches = new List(); - return favoriteBranches; - } - set - { - favoriteBranches = value; - Save(true); - } - } public void SetFavorite(string branchName) { if (FavoriteBranches.Contains(branchName)) + { return; + } + FavoriteBranches.Add(branchName); Save(true); } @@ -345,7 +271,10 @@ public void SetFavorite(string branchName) public void UnsetFavorite(string branchName) { if (!FavoriteBranches.Contains(branchName)) + { return; + } + FavoriteBranches.Remove(branchName); Save(true); } @@ -353,9 +282,13 @@ public void UnsetFavorite(string branchName) public void ToggleFavorite(string branchName) { if (FavoriteBranches.Contains(branchName)) + { FavoriteBranches.Remove(branchName); + } else + { FavoriteBranches.Add(branchName); + } Save(true); } @@ -363,25 +296,32 @@ public bool IsFavorite(string branchName) { return FavoriteBranches.Contains(branchName); } + + public List FavoriteBranches + { + get + { + if (favoriteBranches == null) + { + FavoriteBranches = new List(); + } + return favoriteBranches; + } + set + { + favoriteBranches = value; + Save(true); + } + } } [Location("cache/repoinfo.yaml", LocationAttribute.Location.LibraryFolder)] - sealed class RepositoryInfoCache : ScriptObjectSingleton, IRepositoryInfoCache + sealed class RepositoryInfoCache : ManagedCacheBase, IRepositoryInfoCache { - private static ILogging Logger = Logging.GetLogger(); - private static readonly TimeSpan DataTimeout = TimeSpan.FromSeconds(30); - - [SerializeField] private DateTimeOffset lastUpdatedAt; - [SerializeField] private DateTimeOffset lastVerifiedAt; - - [SerializeField] private ConfigRemote? gitRemote; + [SerializeField] private string lastUpdatedAtString; + [SerializeField] private string lastVerifiedAtString; [SerializeField] private ConfigBranch? gitBranch; - - public event Action CacheInvalidated; - public event Action CacheUpdated; - - public RepositoryInfoCache() - { } + [SerializeField] private ConfigRemote? gitRemote; public void UpdateData(ConfigRemote? gitRemoteUpdate) { @@ -412,49 +352,25 @@ public void UpdateData(ConfigRemote? gitRemoteUpdate, ConfigBranch? gitBranchUpd isUpdated = true; } - if (isUpdated) - { - lastUpdatedAt = now; - } - - lastVerifiedAt = now; - Save(true); - - if (isUpdated) - { - Logger.Trace("Updated: {0}", now); - CacheUpdated.SafeInvoke(lastUpdatedAt); - } - else - { - Logger.Trace("Verified: {0}", now); - } - } - - - public void ValidateData() - { - if (DateTimeOffset.Now - lastUpdatedAt > DataTimeout) - { - InvalidateData(); - } + SaveData(now, isUpdated); } - public void InvalidateData() + protected override void ResetData() { - Logger.Trace("Invalidated"); - CacheInvalidated.SafeInvoke(); - UpdateData(null, null); + gitBranch = null; + gitRemote = null; } - public DateTimeOffset LastUpdatedAt + public override string LastUpdatedAtString { - get { return lastUpdatedAt; } + get { return lastUpdatedAtString; } + protected set { lastUpdatedAtString = value; } } - public DateTimeOffset LastVerifiedAt + public override string LastVerifiedAtString { - get { return lastVerifiedAt; } + get { return lastVerifiedAtString; } + protected set { lastVerifiedAtString = value; } } public ConfigRemote? CurrentRemote @@ -477,21 +393,12 @@ public ConfigBranch? CurentBranch } [Location("cache/gitlog.yaml", LocationAttribute.Location.LibraryFolder)] - sealed class GitLogCache : ScriptObjectSingleton, IGitLogCache + sealed class GitLogCache : ManagedCacheBase, IGitLogCache { - private static ILogging Logger = Logging.GetLogger(); - private static readonly TimeSpan DataTimeout = TimeSpan.FromSeconds(30); - - [SerializeField] private DateTimeOffset lastUpdatedAt; - [SerializeField] private DateTimeOffset lastVerifiedAt; + [SerializeField] private string lastUpdatedAtString; + [SerializeField] private string lastVerifiedAtString; [SerializeField] private List log = new List(); - public event Action CacheInvalidated; - public event Action CacheUpdated; - - public GitLogCache() - { } - public void UpdateData(List logUpdate) { var now = DateTimeOffset.Now; @@ -501,26 +408,13 @@ public void UpdateData(List logUpdate) var logIsNull = log == null; var updateIsNull = logUpdate == null; - if (logIsNull != updateIsNull || - !logIsNull && !log.SequenceEqual(logUpdate)) + if (logIsNull != updateIsNull || !logIsNull && !log.SequenceEqual(logUpdate)) { log = logUpdate; - lastUpdatedAt = now; isUpdated = true; } - lastVerifiedAt = now; - Save(true); - - if (isUpdated) - { - Logger.Trace("Updated: {0}", now); - CacheUpdated.SafeInvoke(lastUpdatedAt); - } - else - { - Logger.Trace("Verified: {0}", now); - } + SaveData(now, isUpdated); } public List Log @@ -532,48 +426,31 @@ public List Log } } - public void ValidateData() - { - if (DateTimeOffset.Now - lastUpdatedAt > DataTimeout) - { - InvalidateData(); - } - } - - public void InvalidateData() + protected override void ResetData() { - Logger.Trace("Invalidated"); - CacheInvalidated.SafeInvoke(); - UpdateData(new List()); + log = new List(); } - public DateTimeOffset LastUpdatedAt + public override string LastUpdatedAtString { - get { return lastUpdatedAt; } + get { return lastUpdatedAtString; } + protected set { lastUpdatedAtString = value; } } - public DateTimeOffset LastVerifiedAt + public override string LastVerifiedAtString { - get { return lastVerifiedAt; } + get { return lastVerifiedAtString; } + protected set { lastVerifiedAtString = value; } } } [Location("cache/gitstatus.yaml", LocationAttribute.Location.LibraryFolder)] - sealed class GitStatusCache : ScriptObjectSingleton, IGitStatusCache + sealed class GitStatusCache : ManagedCacheBase, IGitStatusCache { - private static ILogging Logger = Logging.GetLogger(); - private static readonly TimeSpan DataTimeout = TimeSpan.FromSeconds(30); - - [SerializeField] private DateTimeOffset lastUpdatedAt; - [SerializeField] private DateTimeOffset lastVerifiedAt; + [SerializeField] private string lastUpdatedAtString; + [SerializeField] private string lastVerifiedAtString; [SerializeField] private GitStatus status; - public event Action CacheInvalidated; - public event Action CacheUpdated; - - public GitStatusCache() - { } - public void UpdateData(GitStatus statusUpdate) { var now = DateTimeOffset.Now; @@ -584,22 +461,10 @@ public void UpdateData(GitStatus statusUpdate) if (!status.Equals(statusUpdate)) { status = statusUpdate; - lastUpdatedAt = now; isUpdated = true; } - lastVerifiedAt = now; - Save(true); - - if (isUpdated) - { - Logger.Trace("Updated: {0}", now); - CacheUpdated.SafeInvoke(lastUpdatedAt); - } - else - { - Logger.Trace("Verified: {0}", now); - } + SaveData(now, isUpdated); } public GitStatus GitStatus @@ -611,47 +476,30 @@ public GitStatus GitStatus } } - public void ValidateData() - { - if (DateTimeOffset.Now - lastUpdatedAt > DataTimeout) - { - InvalidateData(); - } - } - - public void InvalidateData() + protected override void ResetData() { - Logger.Trace("Invalidated"); - CacheInvalidated.SafeInvoke(); - UpdateData(new GitStatus()); + status = new GitStatus(); } - public DateTimeOffset LastUpdatedAt + public override string LastUpdatedAtString { - get { return lastUpdatedAt; } + get { return lastUpdatedAtString; } + protected set { lastUpdatedAtString = value; } } - public DateTimeOffset LastVerifiedAt + public override string LastVerifiedAtString { - get { return lastVerifiedAt; } + get { return lastVerifiedAtString; } + protected set { lastVerifiedAtString = value; } } } [Location("cache/gitlocks.yaml", LocationAttribute.Location.LibraryFolder)] - sealed class GitLocksCache : ScriptObjectSingleton, IGitLocksCache + sealed class GitLocksCache : ManagedCacheBase, IGitLocksCache { - private static ILogging Logger = Logging.GetLogger(); - private static readonly TimeSpan DataTimeout = TimeSpan.FromSeconds(30); - - [SerializeField] private DateTimeOffset lastUpdatedAt; - [SerializeField] private DateTimeOffset lastVerifiedAt; - [SerializeField] private List locks; - - public event Action CacheInvalidated; - public event Action CacheUpdated; - - public GitLocksCache() - { } + [SerializeField] private string lastUpdatedAtString; + [SerializeField] private string lastVerifiedAtString; + [SerializeField] private List locks = new List(); public void UpdateData(List locksUpdate) { @@ -663,26 +511,13 @@ public void UpdateData(List locksUpdate) var locksIsNull = locks == null; var locksUpdateIsNull = locksUpdate == null; - if (locksIsNull != locksUpdateIsNull - || !locksIsNull && !locks.SequenceEqual(locksUpdate)) + if (locksIsNull != locksUpdateIsNull || !locksIsNull && !locks.SequenceEqual(locksUpdate)) { locks = locksUpdate; isUpdated = true; - lastUpdatedAt = now; } - lastVerifiedAt = now; - Save(true); - - if (isUpdated) - { - Logger.Trace("Updated: {0}", now); - CacheUpdated.SafeInvoke(lastUpdatedAt); - } - else - { - Logger.Trace("Verified: {0}", now); - } + SaveData(now, isUpdated); } public List GitLocks @@ -694,48 +529,31 @@ public List GitLocks } } - public void ValidateData() - { - if (DateTimeOffset.Now - lastUpdatedAt > DataTimeout) - { - InvalidateData(); - } - } - - public void InvalidateData() + protected override void ResetData() { - Logger.Trace("Invalidated"); - CacheInvalidated.SafeInvoke(); - UpdateData(null); + locks = new List(); } - public DateTimeOffset LastUpdatedAt + public override string LastUpdatedAtString { - get { return lastUpdatedAt; } + get { return lastUpdatedAtString; } + protected set { lastUpdatedAtString = value; } } - public DateTimeOffset LastVerifiedAt + public override string LastVerifiedAtString { - get { return lastVerifiedAt; } + get { return lastVerifiedAtString; } + protected set { lastVerifiedAtString = value; } } } [Location("cache/gituser.yaml", LocationAttribute.Location.LibraryFolder)] - sealed class GitUserCache : ScriptObjectSingleton, IGitUserCache + sealed class GitUserCache : ManagedCacheBase, IGitUserCache { - private static ILogging Logger = Logging.GetLogger(); - private static readonly TimeSpan DataTimeout = TimeSpan.FromSeconds(30); - - [SerializeField] private DateTimeOffset lastUpdatedAt; - [SerializeField] private DateTimeOffset lastVerifiedAt; + [SerializeField] private string lastUpdatedAtString; + [SerializeField] private string lastVerifiedAtString; [SerializeField] private User user; - public event Action CacheInvalidated; - public event Action CacheUpdated; - - public GitUserCache() - { } - public void UpdateData(User userUpdate) { var now = DateTimeOffset.Now; @@ -747,21 +565,9 @@ public void UpdateData(User userUpdate) { user = userUpdate; isUpdated = true; - lastUpdatedAt = now; } - lastVerifiedAt = now; - Save(true); - - if (isUpdated) - { - Logger.Trace("Updated: {0}", now); - CacheUpdated.SafeInvoke(lastUpdatedAt); - } - else - { - Logger.Trace("Verified: {0}", now); - } + SaveData(now, isUpdated); } public User User @@ -773,29 +579,21 @@ public User User } } - public void ValidateData() - { - if (DateTimeOffset.Now - lastUpdatedAt > DataTimeout) - { - InvalidateData(); - } - } - - public void InvalidateData() + protected override void ResetData() { - Logger.Trace("Invalidated"); - CacheInvalidated.SafeInvoke(); - UpdateData(null); + user = null; } - public DateTimeOffset LastUpdatedAt + public override string LastUpdatedAtString { - get { return lastUpdatedAt; } + get { return lastUpdatedAtString; } + protected set { lastUpdatedAtString = value; } } - public DateTimeOffset LastVerifiedAt + public override string LastVerifiedAtString { - get { return lastVerifiedAt; } + get { return lastVerifiedAtString; } + protected set { lastVerifiedAtString = value; } } } } From f00b333ab6460661aaad18b84d0bbc08e418e314 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 26 Oct 2017 09:29:48 -0400 Subject: [PATCH 115/241] Removing more test cache code --- src/GitHub.Api/Cache/CacheContainer.cs | 7 ------- .../Assets/Editor/GitHub.Unity/ApplicationManager.cs | 3 --- 2 files changed, 10 deletions(-) diff --git a/src/GitHub.Api/Cache/CacheContainer.cs b/src/GitHub.Api/Cache/CacheContainer.cs index 550a4c29d..8d65ed0f9 100644 --- a/src/GitHub.Api/Cache/CacheContainer.cs +++ b/src/GitHub.Api/Cache/CacheContainer.cs @@ -50,8 +50,6 @@ private IManagedCache GetManagedCache(CacheType cacheType) } } - public ITestCache TestCache { get; set; } - public void Validate(CacheType cacheType) { GetManagedCache(cacheType).ValidateData(); @@ -232,11 +230,6 @@ public interface IGitUser User User { get; } } - public interface ITestCache : IManagedCache, ITestCacheItem - { - void UpdateData(); - } - public interface ITestCacheItem { } diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationManager.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationManager.cs index 2c848deb7..d3b0578a0 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationManager.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationManager.cs @@ -37,11 +37,8 @@ protected override void InitializeUI() cacheContainer.GitLogCache = GitLogCache.Instance; cacheContainer.GitStatusCache = GitStatusCache.Instance; cacheContainer.GitUserCache = GitUserCache.Instance; - cacheContainer.TestCache = TestCache.Instance; cacheContainer.RepositoryInfoCache = RepositoryInfoCache.Instance; - cacheContainer.TestCache.UpdateData(); - ProjectWindowInterface.Initialize(Environment.Repository); var window = Window.GetWindow(); if (window != null) From 952a1427a8b671284b97c5c3610ca0a445d3bbc7 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 26 Oct 2017 10:41:09 -0400 Subject: [PATCH 116/241] Removing last instance of that test cache object --- src/GitHub.Api/Cache/CacheContainer.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/GitHub.Api/Cache/CacheContainer.cs b/src/GitHub.Api/Cache/CacheContainer.cs index 8d65ed0f9..32a69ffe0 100644 --- a/src/GitHub.Api/Cache/CacheContainer.cs +++ b/src/GitHub.Api/Cache/CacheContainer.cs @@ -198,7 +198,6 @@ public interface ICacheContainer IGitStatusCache GitStatusCache { get; } IGitLocksCache GitLocksCache { get; } IGitUserCache GitUserCache { get; } - ITestCache TestCache { get; } void Validate(CacheType cacheType); void ValidateAll(); void Invalidate(CacheType cacheType); From 7f4428ef4f5f01a4d8ef5ca7f88954b6dd036ca1 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 26 Oct 2017 10:41:20 -0400 Subject: [PATCH 117/241] Setting default value on lastUpdated and lastVerified values --- .../Editor/GitHub.Unity/ApplicationCache.cs | 24 +++++++++---------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs index 3936be2dc..e72ee4731 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs @@ -184,8 +184,8 @@ public DateTimeOffset LastVerifiedAt [Location("cache/branches.yaml", LocationAttribute.Location.LibraryFolder)] sealed class BranchCache : ManagedCacheBase, IBranchCache { - [SerializeField] private string lastUpdatedAtString; - [SerializeField] private string lastVerifiedAtString; + [SerializeField] private string lastUpdatedAtString = DateTimeOffset.MinValue.ToString(); + [SerializeField] private string lastVerifiedAtString = DateTimeOffset.MinValue.ToString(); [SerializeField] private List localBranches = new List(); [SerializeField] private List remoteBranches = new List(); @@ -318,8 +318,8 @@ public List FavoriteBranches [Location("cache/repoinfo.yaml", LocationAttribute.Location.LibraryFolder)] sealed class RepositoryInfoCache : ManagedCacheBase, IRepositoryInfoCache { - [SerializeField] private string lastUpdatedAtString; - [SerializeField] private string lastVerifiedAtString; + [SerializeField] private string lastUpdatedAtString = DateTimeOffset.MinValue.ToString(); + [SerializeField] private string lastVerifiedAtString = DateTimeOffset.MinValue.ToString(); [SerializeField] private ConfigBranch? gitBranch; [SerializeField] private ConfigRemote? gitRemote; @@ -395,8 +395,8 @@ public ConfigBranch? CurentBranch [Location("cache/gitlog.yaml", LocationAttribute.Location.LibraryFolder)] sealed class GitLogCache : ManagedCacheBase, IGitLogCache { - [SerializeField] private string lastUpdatedAtString; - [SerializeField] private string lastVerifiedAtString; + [SerializeField] private string lastUpdatedAtString = DateTimeOffset.MinValue.ToString(); + [SerializeField] private string lastVerifiedAtString = DateTimeOffset.MinValue.ToString(); [SerializeField] private List log = new List(); public void UpdateData(List logUpdate) @@ -447,8 +447,8 @@ public override string LastVerifiedAtString [Location("cache/gitstatus.yaml", LocationAttribute.Location.LibraryFolder)] sealed class GitStatusCache : ManagedCacheBase, IGitStatusCache { - [SerializeField] private string lastUpdatedAtString; - [SerializeField] private string lastVerifiedAtString; + [SerializeField] private string lastUpdatedAtString = DateTimeOffset.MinValue.ToString(); + [SerializeField] private string lastVerifiedAtString = DateTimeOffset.MinValue.ToString(); [SerializeField] private GitStatus status; public void UpdateData(GitStatus statusUpdate) @@ -497,8 +497,8 @@ public override string LastVerifiedAtString [Location("cache/gitlocks.yaml", LocationAttribute.Location.LibraryFolder)] sealed class GitLocksCache : ManagedCacheBase, IGitLocksCache { - [SerializeField] private string lastUpdatedAtString; - [SerializeField] private string lastVerifiedAtString; + [SerializeField] private string lastUpdatedAtString = DateTimeOffset.MinValue.ToString(); + [SerializeField] private string lastVerifiedAtString = DateTimeOffset.MinValue.ToString(); [SerializeField] private List locks = new List(); public void UpdateData(List locksUpdate) @@ -550,8 +550,8 @@ public override string LastVerifiedAtString [Location("cache/gituser.yaml", LocationAttribute.Location.LibraryFolder)] sealed class GitUserCache : ManagedCacheBase, IGitUserCache { - [SerializeField] private string lastUpdatedAtString; - [SerializeField] private string lastVerifiedAtString; + [SerializeField] private string lastUpdatedAtString = DateTimeOffset.MinValue.ToString(); + [SerializeField] private string lastVerifiedAtString = DateTimeOffset.MinValue.ToString(); [SerializeField] private User user; public void UpdateData(User userUpdate) From ffd2f1b3b72afea1cad5463ffaee91c981134fdc Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 26 Oct 2017 10:49:40 -0400 Subject: [PATCH 118/241] Renaming some variables --- src/GitHub.Api/Git/Repository.cs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/GitHub.Api/Git/Repository.cs b/src/GitHub.Api/Git/Repository.cs index bd0f6fec5..c59151204 100644 --- a/src/GitHub.Api/Git/Repository.cs +++ b/src/GitHub.Api/Git/Repository.cs @@ -39,15 +39,15 @@ public Repository(string name, NPath localPath) Name = name; LocalPath = localPath; - this.User = new User(); + User = new User(); } - public void Initialize(IRepositoryManager repositoryManager, ICacheContainer cacheContainer) + public void Initialize(IRepositoryManager initRepositoryManager, ICacheContainer initCacheContainer) { - Guard.ArgumentNotNull(repositoryManager, nameof(repositoryManager)); + Guard.ArgumentNotNull(initRepositoryManager, nameof(initRepositoryManager)); - this.repositoryManager = repositoryManager; - this.cacheContainer = cacheContainer; + repositoryManager = initRepositoryManager; + cacheContainer = initCacheContainer; repositoryManager.OnCurrentBranchUpdated += RepositoryManager_OnCurrentBranchUpdated; repositoryManager.OnCurrentRemoteUpdated += RepositoryManager_OnCurrentRemoteUpdated; From 6482545048a412c80481d46d7343ce8f95a2f57d Mon Sep 17 00:00:00 2001 From: Don Okuda Date: Thu, 26 Oct 2017 08:55:34 -0700 Subject: [PATCH 119/241] :fire: extra cruft from auth view --- .../GitHub.Unity/UI/AuthenticationView.cs | 21 ++----------------- 1 file changed, 2 insertions(+), 19 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/AuthenticationView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/AuthenticationView.cs index d9de5a8bc..4c33e1b3f 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/AuthenticationView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/AuthenticationView.cs @@ -59,28 +59,11 @@ public override void OnGUI() scroll = GUILayout.BeginScrollView(scroll); { - Rect authHeader = EditorGUILayout.BeginHorizontal(Styles.AuthHeaderBoxStyle); + GUILayout.BeginHorizontal(Styles.AuthHeaderBoxStyle); { - GUILayout.BeginVertical(GUILayout.Width(16)); - { - GUILayout.Space(9); - GUILayout.Label(Styles.BigLogo, GUILayout.Height(20), GUILayout.Width(20)); - } - GUILayout.EndVertical(); - - GUILayout.BeginVertical(); - { - GUILayout.Space(11); - GUILayout.Label(AuthTitle, Styles.HeaderRepoLabelStyle); - } - GUILayout.EndVertical(); + GUILayout.Label(AuthTitle, Styles.HeaderRepoLabelStyle); } - GUILayout.EndHorizontal(); - EditorGUI.DrawRect( - new Rect(authHeader.x, authHeader.yMax, authHeader.xMax, 1), - new Color(0.455F, 0.455F, 0.455F, 1F) - ); GUILayout.BeginVertical(Styles.GenericBoxStyle); { From 58b48aa871a9fef9d5c45b474b51c7b00e18193c Mon Sep 17 00:00:00 2001 From: Don Okuda Date: Thu, 26 Oct 2017 09:00:08 -0700 Subject: [PATCH 120/241] Use a HelpBox instead --- .../Assets/Editor/GitHub.Unity/UI/AuthenticationView.cs | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/AuthenticationView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/AuthenticationView.cs index 4c33e1b3f..2da6d2209 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/AuthenticationView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/AuthenticationView.cs @@ -227,9 +227,7 @@ private void ShowMessage() { if (message != null) { - GUILayout.Space(Styles.BaseSpacing + 3); - GUILayout.Label(message, Styles.CenteredLabel); - GUILayout.Space(Styles.BaseSpacing + 3); + EditorGUILayout.HelpBox(message, MessageType.Warning); } } @@ -237,7 +235,7 @@ private void ShowErrorMessage() { if (errorMessage != null) { - GUILayout.Label(errorMessage, Styles.ErrorLabel); + EditorGUILayout.HelpBox(errorMessage, MessageType.Error); } } From 60528e7cacea700984a3a7aef900fb0fb26d8dbc Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 26 Oct 2017 12:20:15 -0400 Subject: [PATCH 121/241] Removing the extra InitializeRepository call --- src/GitHub.Api/Platform/DefaultEnvironment.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/GitHub.Api/Platform/DefaultEnvironment.cs b/src/GitHub.Api/Platform/DefaultEnvironment.cs index f4b60389a..45e9b3c0b 100644 --- a/src/GitHub.Api/Platform/DefaultEnvironment.cs +++ b/src/GitHub.Api/Platform/DefaultEnvironment.cs @@ -42,7 +42,6 @@ public void Initialize(string unityVersion, NPath extensionInstallPath, NPath un UnityAssetsPath = assetsPath; UnityProjectPath = assetsPath.Parent; UnityVersion = unityVersion; - InitializeRepository(); } public void InitializeRepository(NPath expectedRepositoryPath = null) From 144da6cbb12f1da4468fb2e016a8e6e10229893b Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 26 Oct 2017 15:07:45 -0400 Subject: [PATCH 122/241] Moving where CacheContainer is created and how it gets into Repository --- .../Application/ApplicationManagerBase.cs | 7 +- src/GitHub.Api/Cache/CacheContainer.cs | 174 ---------------- src/GitHub.Api/Git/IRepository.cs | 2 +- src/GitHub.Api/Git/Repository.cs | 9 +- src/GitHub.Api/Platform/DefaultEnvironment.cs | 4 +- src/GitHub.Api/Platform/IEnvironment.cs | 2 +- .../Editor/GitHub.Unity/ApplicationCache.cs | 2 +- .../Editor/GitHub.Unity/ApplicationManager.cs | 10 +- .../Editor/GitHub.Unity/CacheContainer.cs | 194 ++++++++++++++++++ .../Editor/GitHub.Unity/GitHub.Unity.csproj | 1 + .../BaseGitEnvironmentTest.cs | 6 +- .../Git/IntegrationTestEnvironment.cs | 8 +- src/tests/UnitTests/Git/RepositoryTests.cs | 6 +- 13 files changed, 222 insertions(+), 203 deletions(-) create mode 100644 src/UnityExtension/Assets/Editor/GitHub.Unity/CacheContainer.cs diff --git a/src/GitHub.Api/Application/ApplicationManagerBase.cs b/src/GitHub.Api/Application/ApplicationManagerBase.cs index bfeb6fcc9..0267c023c 100644 --- a/src/GitHub.Api/Application/ApplicationManagerBase.cs +++ b/src/GitHub.Api/Application/ApplicationManagerBase.cs @@ -21,7 +21,6 @@ public ApplicationManagerBase(SynchronizationContext synchronizationContext) UIScheduler = TaskScheduler.FromCurrentSynchronizationContext(); ThreadingHelper.MainThreadScheduler = UIScheduler; TaskManager = new TaskManager(UIScheduler); - CacheContainer = new CacheContainer(); } protected void Initialize() @@ -117,7 +116,7 @@ public ITask InitializeRepository() .Then(GitClient.Commit("Initial commit", null)) .Then(_ => { - Environment.InitializeRepository(); + Environment.InitializeRepository(CacheContainer); RestartRepository(); }) .ThenInUI(InitializeUI); @@ -130,7 +129,7 @@ public void RestartRepository() { repositoryManager = Unity.RepositoryManager.CreateInstance(Platform, TaskManager, GitClient, Environment.RepositoryPath); repositoryManager.Initialize(); - Environment.Repository.Initialize(repositoryManager, CacheContainer); + Environment.Repository.Initialize(repositoryManager); repositoryManager.Start(); Logger.Trace($"Got a repository? {Environment.Repository}"); } @@ -215,7 +214,7 @@ public void Dispose() public ISettings LocalSettings { get; protected set; } public ISettings SystemSettings { get; protected set; } public ISettings UserSettings { get; protected set; } - public ICacheContainer CacheContainer { get; private set; } + public ICacheContainer CacheContainer { get; protected set; } public IUsageTracker UsageTracker { get; protected set; } protected TaskScheduler UIScheduler { get; private set; } diff --git a/src/GitHub.Api/Cache/CacheContainer.cs b/src/GitHub.Api/Cache/CacheContainer.cs index 32a69ffe0..ffab80f42 100644 --- a/src/GitHub.Api/Cache/CacheContainer.cs +++ b/src/GitHub.Api/Cache/CacheContainer.cs @@ -3,180 +3,6 @@ namespace GitHub.Unity { - public class CacheContainer : ICacheContainer - { - private static ILogging Logger = Logging.GetLogger(); - - private IBranchCache branchCache; - - private IGitLocksCache gitLocksCache; - - private IGitLogCache gitLogCache; - - private IGitStatusCache gitStatusCache; - - private IGitUserCache gitUserCache; - - private IRepositoryInfoCache repositoryInfoCache; - - public event Action CacheInvalidated; - - public event Action CacheUpdated; - - private IManagedCache GetManagedCache(CacheType cacheType) - { - switch (cacheType) - { - case CacheType.BranchCache: - return BranchCache; - - case CacheType.GitLogCache: - return GitLogCache; - - case CacheType.RepositoryInfoCache: - return RepositoryInfoCache; - - case CacheType.GitStatusCache: - return GitStatusCache; - - case CacheType.GitLocksCache: - return GitLocksCache; - - case CacheType.GitUserCache: - return GitUserCache; - - default: - throw new ArgumentOutOfRangeException(nameof(cacheType), cacheType, null); - } - } - - public void Validate(CacheType cacheType) - { - GetManagedCache(cacheType).ValidateData(); - } - - public void ValidateAll() - { - BranchCache.ValidateData(); - GitLogCache.ValidateData(); - RepositoryInfoCache.ValidateData(); - GitStatusCache.ValidateData(); - GitLocksCache.ValidateData(); - GitUserCache.ValidateData(); - } - - public void Invalidate(CacheType cacheType) - { - GetManagedCache(cacheType).InvalidateData(); - } - - public void InvalidateAll() - { - BranchCache.InvalidateData(); - GitLogCache.InvalidateData(); - RepositoryInfoCache.InvalidateData(); - GitStatusCache.InvalidateData(); - GitLocksCache.InvalidateData(); - GitUserCache.InvalidateData(); - } - - public IBranchCache BranchCache - { - get { return branchCache; } - set - { - if (branchCache == null) - { - branchCache = value; - branchCache.CacheInvalidated += () => OnCacheInvalidated(CacheType.BranchCache); - branchCache.CacheUpdated += datetime => OnCacheUpdated(CacheType.BranchCache, datetime); - } - } - } - - public IGitLogCache GitLogCache - { - get { return gitLogCache; } - set - { - if (gitLogCache == null) - { - gitLogCache = value; - gitLogCache.CacheInvalidated += () => OnCacheInvalidated(CacheType.GitLogCache); - gitLogCache.CacheUpdated += datetime => OnCacheUpdated(CacheType.GitLogCache, datetime); - } - } - } - - public IRepositoryInfoCache RepositoryInfoCache - { - get { return repositoryInfoCache; } - set - { - if (repositoryInfoCache == null) - { - repositoryInfoCache = value; - repositoryInfoCache.CacheInvalidated += () => OnCacheInvalidated(CacheType.RepositoryInfoCache); - repositoryInfoCache.CacheUpdated += datetime => OnCacheUpdated(CacheType.RepositoryInfoCache, datetime); - } - } - } - - public IGitStatusCache GitStatusCache - { - get { return gitStatusCache; } - set - { - if (gitStatusCache == null) - { - gitStatusCache = value; - gitStatusCache.CacheInvalidated += () => OnCacheInvalidated(CacheType.GitStatusCache); - gitStatusCache.CacheUpdated += datetime => OnCacheUpdated(CacheType.GitStatusCache, datetime); - } - } - } - - public IGitLocksCache GitLocksCache - { - get { return gitLocksCache; } - set - { - if (gitLocksCache == null) - { - gitLocksCache = value; - gitLocksCache.CacheInvalidated += () => OnCacheInvalidated(CacheType.GitLocksCache); - gitLocksCache.CacheUpdated += datetime => OnCacheUpdated(CacheType.GitLocksCache, datetime); - } - } - } - - public IGitUserCache GitUserCache - { - get { return gitUserCache; } - set - { - if (gitUserCache == null) - { - gitUserCache = value; - gitUserCache.CacheInvalidated += () => OnCacheInvalidated(CacheType.GitUserCache); - gitUserCache.CacheUpdated += datetime => OnCacheUpdated(CacheType.GitUserCache, datetime); - } - } - } - - private void OnCacheUpdated(CacheType cacheType, DateTimeOffset datetime) - { - Logger.Trace("OnCacheUpdated cacheType:{0} datetime:{1}", cacheType, datetime); - CacheUpdated?.Invoke(cacheType, datetime); - } - - private void OnCacheInvalidated(CacheType cacheType) - { - Logger.Trace("OnCacheInvalidated cacheType:{0}", cacheType); - CacheInvalidated?.Invoke(cacheType); - } - } - public enum CacheType { BranchCache, diff --git a/src/GitHub.Api/Git/IRepository.cs b/src/GitHub.Api/Git/IRepository.cs index ad616d2b8..5818a9f52 100644 --- a/src/GitHub.Api/Git/IRepository.cs +++ b/src/GitHub.Api/Git/IRepository.cs @@ -8,7 +8,7 @@ namespace GitHub.Unity /// public interface IRepository : IEquatable { - void Initialize(IRepositoryManager repositoryManager, ICacheContainer cacheContainer); + void Initialize(IRepositoryManager repositoryManager); void Refresh(); ITask CommitAllFiles(string message, string body); ITask CommitFiles(List files, string message, string body); diff --git a/src/GitHub.Api/Git/Repository.cs b/src/GitHub.Api/Git/Repository.cs index c59151204..6f10920ff 100644 --- a/src/GitHub.Api/Git/Repository.cs +++ b/src/GitHub.Api/Git/Repository.cs @@ -32,7 +32,8 @@ class Repository : IEquatable, IRepository /// /// The repository name. /// - public Repository(string name, NPath localPath) + /// + public Repository(string name, NPath localPath, ICacheContainer container) { Guard.ArgumentNotNullOrWhiteSpace(name, nameof(name)); Guard.ArgumentNotNull(localPath, nameof(localPath)); @@ -40,15 +41,15 @@ public Repository(string name, NPath localPath) Name = name; LocalPath = localPath; User = new User(); + + cacheContainer = container; } - public void Initialize(IRepositoryManager initRepositoryManager, ICacheContainer initCacheContainer) + public void Initialize(IRepositoryManager initRepositoryManager) { Guard.ArgumentNotNull(initRepositoryManager, nameof(initRepositoryManager)); repositoryManager = initRepositoryManager; - cacheContainer = initCacheContainer; - repositoryManager.OnCurrentBranchUpdated += RepositoryManager_OnCurrentBranchUpdated; repositoryManager.OnCurrentRemoteUpdated += RepositoryManager_OnCurrentRemoteUpdated; repositoryManager.OnStatusUpdated += status => CurrentStatus = status; diff --git a/src/GitHub.Api/Platform/DefaultEnvironment.cs b/src/GitHub.Api/Platform/DefaultEnvironment.cs index 45e9b3c0b..30be45448 100644 --- a/src/GitHub.Api/Platform/DefaultEnvironment.cs +++ b/src/GitHub.Api/Platform/DefaultEnvironment.cs @@ -44,7 +44,7 @@ public void Initialize(string unityVersion, NPath extensionInstallPath, NPath un UnityVersion = unityVersion; } - public void InitializeRepository(NPath expectedRepositoryPath = null) + public void InitializeRepository(ICacheContainer cacheContainer, NPath expectedRepositoryPath = null) { Guard.NotNull(this, FileSystem, nameof(FileSystem)); @@ -79,7 +79,7 @@ public void InitializeRepository(NPath expectedRepositoryPath = null) { Logger.Trace("Determined expectedRepositoryPath:{0}", expectedRepositoryPath); RepositoryPath = expectedRepositoryPath; - Repository = new Repository(RepositoryPath.FileName, RepositoryPath); + Repository = new Repository(RepositoryPath.FileName, RepositoryPath, cacheContainer); } } diff --git a/src/GitHub.Api/Platform/IEnvironment.cs b/src/GitHub.Api/Platform/IEnvironment.cs index 1c42158ad..ddc534fe8 100644 --- a/src/GitHub.Api/Platform/IEnvironment.cs +++ b/src/GitHub.Api/Platform/IEnvironment.cs @@ -5,7 +5,7 @@ namespace GitHub.Unity public interface IEnvironment { void Initialize(string unityVersion, NPath extensionInstallPath, NPath unityPath, NPath assetsPath); - void InitializeRepository(NPath expectedRepositoryPath = null); + void InitializeRepository(ICacheContainer cacheContainer, NPath expectedRepositoryPath = null); string ExpandEnvironmentVariables(string name); string GetEnvironmentVariable(string v); string GetSpecialFolder(Environment.SpecialFolder folder); diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs index e72ee4731..c81f0f90b 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs @@ -75,7 +75,7 @@ public IEnvironment Environment } environment.Initialize(unityVersion, extensionInstallPath.ToNPath(), unityApplication.ToNPath(), unityAssetsPath.ToNPath()); - environment.InitializeRepository(!String.IsNullOrEmpty(repositoryPath) + environment.InitializeRepository(EntryPoint.ApplicationManager.CacheContainer, !String.IsNullOrEmpty(repositoryPath) ? repositoryPath.ToNPath() : null); Flush(); diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationManager.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationManager.cs index d3b0578a0..5b15205e7 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationManager.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationManager.cs @@ -19,6 +19,7 @@ public ApplicationManager(IMainThreadSynchronizationContext synchronizationConte { ListenToUnityExit(); Initialize(); + CacheContainer = new CacheContainer(); } protected override void SetupMetrics() @@ -31,14 +32,6 @@ protected override void InitializeUI() Logger.Trace("Restarted {0}", Environment.Repository); EnvironmentCache.Instance.Flush(); - var cacheContainer = (CacheContainer)CacheContainer; - cacheContainer.BranchCache = BranchCache.Instance; - cacheContainer.GitLocksCache = GitLocksCache.Instance; - cacheContainer.GitLogCache = GitLogCache.Instance; - cacheContainer.GitStatusCache = GitStatusCache.Instance; - cacheContainer.GitUserCache = GitUserCache.Instance; - cacheContainer.RepositoryInfoCache = RepositoryInfoCache.Instance; - ProjectWindowInterface.Initialize(Environment.Repository); var window = Window.GetWindow(); if (window != null) @@ -51,7 +44,6 @@ protected override void SetProjectToTextSerialization() EditorSettings.serializationMode = SerializationMode.ForceText; } - private void ListenToUnityExit() { EditorApplicationQuit = (UnityAction)Delegate.Combine(EditorApplicationQuit, new UnityAction(Dispose)); diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/CacheContainer.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/CacheContainer.cs new file mode 100644 index 000000000..c96a191b1 --- /dev/null +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/CacheContainer.cs @@ -0,0 +1,194 @@ +using System; + +namespace GitHub.Unity +{ + public class CacheContainer : ICacheContainer + { + private static ILogging Logger = Logging.GetLogger(); + + private IBranchCache branchCache; + + private IGitLocksCache gitLocksCache; + + private IGitLogCache gitLogCache; + + private IGitStatusCache gitStatusCache; + + private IGitUserCache gitUserCache; + + private IRepositoryInfoCache repositoryInfoCache; + + public event Action CacheInvalidated; + + public event Action CacheUpdated; + + public CacheContainer() + { + BranchCache = Unity.BranchCache.Instance; + GitLocksCache = Unity.GitLocksCache.Instance; + GitLogCache = Unity.GitLogCache.Instance; + GitStatusCache = Unity.GitStatusCache.Instance; + GitUserCache = Unity.GitUserCache.Instance; + RepositoryInfoCache = Unity.RepositoryInfoCache.Instance; + } + + private IManagedCache GetManagedCache(CacheType cacheType) + { + switch (cacheType) + { + case CacheType.BranchCache: + return BranchCache; + + case CacheType.GitLogCache: + return GitLogCache; + + case CacheType.RepositoryInfoCache: + return RepositoryInfoCache; + + case CacheType.GitStatusCache: + return GitStatusCache; + + case CacheType.GitLocksCache: + return GitLocksCache; + + case CacheType.GitUserCache: + return GitUserCache; + + default: + throw new ArgumentOutOfRangeException("cacheType", cacheType, null); + } + } + + public void Validate(CacheType cacheType) + { + GetManagedCache(cacheType).ValidateData(); + } + + public void ValidateAll() + { + BranchCache.ValidateData(); + GitLogCache.ValidateData(); + RepositoryInfoCache.ValidateData(); + GitStatusCache.ValidateData(); + GitLocksCache.ValidateData(); + GitUserCache.ValidateData(); + } + + public void Invalidate(CacheType cacheType) + { + GetManagedCache(cacheType).InvalidateData(); + } + + public void InvalidateAll() + { + BranchCache.InvalidateData(); + GitLogCache.InvalidateData(); + RepositoryInfoCache.InvalidateData(); + GitStatusCache.InvalidateData(); + GitLocksCache.InvalidateData(); + GitUserCache.InvalidateData(); + } + + public IBranchCache BranchCache + { + get { return branchCache; } + set + { + if (branchCache == null) + { + branchCache = value; + branchCache.CacheInvalidated += () => OnCacheInvalidated(CacheType.BranchCache); + branchCache.CacheUpdated += datetime => OnCacheUpdated(CacheType.BranchCache, datetime); + } + } + } + + public IGitLogCache GitLogCache + { + get { return gitLogCache; } + set + { + if (gitLogCache == null) + { + gitLogCache = value; + gitLogCache.CacheInvalidated += () => OnCacheInvalidated(CacheType.GitLogCache); + gitLogCache.CacheUpdated += datetime => OnCacheUpdated(CacheType.GitLogCache, datetime); + } + } + } + + public IRepositoryInfoCache RepositoryInfoCache + { + get { return repositoryInfoCache; } + set + { + if (repositoryInfoCache == null) + { + repositoryInfoCache = value; + repositoryInfoCache.CacheInvalidated += () => OnCacheInvalidated(CacheType.RepositoryInfoCache); + repositoryInfoCache.CacheUpdated += datetime => OnCacheUpdated(CacheType.RepositoryInfoCache, datetime); + } + } + } + + public IGitStatusCache GitStatusCache + { + get { return gitStatusCache; } + set + { + if (gitStatusCache == null) + { + gitStatusCache = value; + gitStatusCache.CacheInvalidated += () => OnCacheInvalidated(CacheType.GitStatusCache); + gitStatusCache.CacheUpdated += datetime => OnCacheUpdated(CacheType.GitStatusCache, datetime); + } + } + } + + public IGitLocksCache GitLocksCache + { + get { return gitLocksCache; } + set + { + if (gitLocksCache == null) + { + gitLocksCache = value; + gitLocksCache.CacheInvalidated += () => OnCacheInvalidated(CacheType.GitLocksCache); + gitLocksCache.CacheUpdated += datetime => OnCacheUpdated(CacheType.GitLocksCache, datetime); + } + } + } + + public IGitUserCache GitUserCache + { + get { return gitUserCache; } + set + { + if (gitUserCache == null) + { + gitUserCache = value; + gitUserCache.CacheInvalidated += () => OnCacheInvalidated(CacheType.GitUserCache); + gitUserCache.CacheUpdated += datetime => OnCacheUpdated(CacheType.GitUserCache, datetime); + } + } + } + + private void OnCacheUpdated(CacheType cacheType, DateTimeOffset datetime) + { + Logger.Trace("OnCacheUpdated cacheType:{0} datetime:{1}", cacheType, datetime); + if (CacheUpdated != null) + { + CacheUpdated.Invoke(cacheType, datetime); + } + } + + private void OnCacheInvalidated(CacheType cacheType) + { + Logger.Trace("OnCacheInvalidated cacheType:{0}", cacheType); + if (CacheInvalidated != null) + { + CacheInvalidated.Invoke(cacheType); + } + } + } +} \ No newline at end of file diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/GitHub.Unity.csproj b/src/UnityExtension/Assets/Editor/GitHub.Unity/GitHub.Unity.csproj index d6d7c4c0f..4dfba8277 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/GitHub.Unity.csproj +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/GitHub.Unity.csproj @@ -76,6 +76,7 @@ + diff --git a/src/tests/IntegrationTests/BaseGitEnvironmentTest.cs b/src/tests/IntegrationTests/BaseGitEnvironmentTest.cs index 3293a241c..96151f82d 100644 --- a/src/tests/IntegrationTests/BaseGitEnvironmentTest.cs +++ b/src/tests/IntegrationTests/BaseGitEnvironmentTest.cs @@ -31,8 +31,10 @@ protected async Task Initialize(NPath repoPath, NPath environmentP RepositoryManager = GitHub.Unity.RepositoryManager.CreateInstance(Platform, TaskManager, GitClient, repoPath); RepositoryManager.Initialize(); - Environment.Repository = new Repository("TestRepo", repoPath); - Environment.Repository.Initialize(RepositoryManager, null); + //TODO: Mock CacheContainer + ICacheContainer cacheContainer = null; + Environment.Repository = new Repository("TestRepo", repoPath, cacheContainer); + Environment.Repository.Initialize(RepositoryManager); RepositoryManager.Start(); diff --git a/src/tests/IntegrationTests/Git/IntegrationTestEnvironment.cs b/src/tests/IntegrationTests/Git/IntegrationTestEnvironment.cs index 10e0c8ebe..bd790f28d 100644 --- a/src/tests/IntegrationTests/Git/IntegrationTestEnvironment.cs +++ b/src/tests/IntegrationTests/Git/IntegrationTestEnvironment.cs @@ -28,8 +28,10 @@ public IntegrationTestEnvironment(NPath repoPath, NPath solutionDirectory, NPath var installPath = solutionDirectory.Parent.Parent.Combine("src", "GitHub.Api"); + //TODO: Mock CacheContainer + ICacheContainer cacheContainer = null; Initialize(UnityVersion, installPath, solutionDirectory, repoPath.Combine("Assets")); - InitializeRepository(); + InitializeRepository(cacheContainer); this.enableTrace = enableTrace; @@ -45,9 +47,9 @@ public void Initialize(string unityVersion, NPath extensionInstallPath, NPath un defaultEnvironment.Initialize(unityVersion, extensionInstallPath, unityPath, assetsPath); } - public void InitializeRepository(NPath expectedPath = null) + public void InitializeRepository(ICacheContainer cacheContainer, NPath expectedPath = null) { - defaultEnvironment.InitializeRepository(expectedPath); + defaultEnvironment.InitializeRepository(cacheContainer, expectedPath); } public string ExpandEnvironmentVariables(string name) diff --git a/src/tests/UnitTests/Git/RepositoryTests.cs b/src/tests/UnitTests/Git/RepositoryTests.cs index 175bcea9b..9be53470c 100644 --- a/src/tests/UnitTests/Git/RepositoryTests.cs +++ b/src/tests/UnitTests/Git/RepositoryTests.cs @@ -27,7 +27,9 @@ private static Repository LoadRepository() NPath.FileSystem = fileSystem; - return new Repository("TestRepo", @"C:\Repo".ToNPath()); + //TODO: Mock CacheContainer + ICacheContainer cacheContainer = null; + return new Repository("TestRepo", @"C:\Repo".ToNPath(), cacheContainer); } private RepositoryEvents repositoryEvents; @@ -79,7 +81,7 @@ public void Repository() .ToDictionary(grouping => grouping.Key, grouping => grouping.ToDictionary(branch => branch.Name)); - repository.Initialize(repositoryManager, null); + repository.Initialize(repositoryManager); string expectedBranch = null; repository.OnCurrentBranchChanged += branch => { From 20e137a3eaee4fef6d2df215fa7dabad157e680d Mon Sep 17 00:00:00 2001 From: Don Okuda Date: Thu, 26 Oct 2017 14:55:56 -0700 Subject: [PATCH 123/241] Adjust some spacing --- .../Assets/Editor/GitHub.Unity/UI/AuthenticationView.cs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/AuthenticationView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/AuthenticationView.cs index 2da6d2209..d669d738d 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/AuthenticationView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/AuthenticationView.cs @@ -118,20 +118,24 @@ private void OnGUILogin() { ShowMessage(); - GUILayout.Space(3); + EditorGUILayout.Space(); + GUILayout.BeginHorizontal(); { username = EditorGUILayout.TextField(UsernameLabel ,username, Styles.TextFieldStyle); } GUILayout.EndHorizontal(); - GUILayout.Space(Styles.BaseSpacing); + EditorGUILayout.Space(); + GUILayout.BeginHorizontal(); { password = EditorGUILayout.PasswordField(PasswordLabel, password, Styles.TextFieldStyle); } GUILayout.EndHorizontal(); + EditorGUILayout.Space(); + ShowErrorMessage(); GUILayout.Space(Styles.BaseSpacing + 3); From 9eea8a6db371e505c79d8aed21e84bee682a994e Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 26 Oct 2017 19:03:54 -0400 Subject: [PATCH 124/241] Changing how the cache items are created --- .../Editor/GitHub.Unity/CacheContainer.cs | 46 +++++++++---------- 1 file changed, 22 insertions(+), 24 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/CacheContainer.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/CacheContainer.cs index c96a191b1..083749a45 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/CacheContainer.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/CacheContainer.cs @@ -24,12 +24,8 @@ public class CacheContainer : ICacheContainer public CacheContainer() { - BranchCache = Unity.BranchCache.Instance; - GitLocksCache = Unity.GitLocksCache.Instance; - GitLogCache = Unity.GitLogCache.Instance; - GitStatusCache = Unity.GitStatusCache.Instance; - GitUserCache = Unity.GitUserCache.Instance; - RepositoryInfoCache = Unity.RepositoryInfoCache.Instance; + var t = new System.Diagnostics.StackTrace(); + Logger.Trace("Constructing: {0}", t.ToString()); } private IManagedCache GetManagedCache(CacheType cacheType) @@ -91,85 +87,87 @@ public void InvalidateAll() public IBranchCache BranchCache { - get { return branchCache; } - set + get { if (branchCache == null) { - branchCache = value; + branchCache = Unity.BranchCache.Instance; branchCache.CacheInvalidated += () => OnCacheInvalidated(CacheType.BranchCache); branchCache.CacheUpdated += datetime => OnCacheUpdated(CacheType.BranchCache, datetime); } + return branchCache; } } public IGitLogCache GitLogCache { - get { return gitLogCache; } - set + get { if (gitLogCache == null) { - gitLogCache = value; + gitLogCache = Unity.GitLogCache.Instance; gitLogCache.CacheInvalidated += () => OnCacheInvalidated(CacheType.GitLogCache); gitLogCache.CacheUpdated += datetime => OnCacheUpdated(CacheType.GitLogCache, datetime); } + return gitLogCache; } } public IRepositoryInfoCache RepositoryInfoCache { - get { return repositoryInfoCache; } - set + get { if (repositoryInfoCache == null) { - repositoryInfoCache = value; + repositoryInfoCache = Unity.RepositoryInfoCache.Instance; repositoryInfoCache.CacheInvalidated += () => OnCacheInvalidated(CacheType.RepositoryInfoCache); repositoryInfoCache.CacheUpdated += datetime => OnCacheUpdated(CacheType.RepositoryInfoCache, datetime); } + return repositoryInfoCache; } } public IGitStatusCache GitStatusCache { - get { return gitStatusCache; } - set + get { if (gitStatusCache == null) { - gitStatusCache = value; + gitStatusCache = Unity.GitStatusCache.Instance; gitStatusCache.CacheInvalidated += () => OnCacheInvalidated(CacheType.GitStatusCache); gitStatusCache.CacheUpdated += datetime => OnCacheUpdated(CacheType.GitStatusCache, datetime); } + return gitStatusCache; } } public IGitLocksCache GitLocksCache { - get { return gitLocksCache; } - set + get { if (gitLocksCache == null) { - gitLocksCache = value; + gitLocksCache = Unity.GitLocksCache.Instance; gitLocksCache.CacheInvalidated += () => OnCacheInvalidated(CacheType.GitLocksCache); gitLocksCache.CacheUpdated += datetime => OnCacheUpdated(CacheType.GitLocksCache, datetime); } + + return gitLocksCache; } } public IGitUserCache GitUserCache { - get { return gitUserCache; } - set + get { if (gitUserCache == null) { - gitUserCache = value; + gitUserCache = Unity.GitUserCache.Instance; gitUserCache.CacheInvalidated += () => OnCacheInvalidated(CacheType.GitUserCache); gitUserCache.CacheUpdated += datetime => OnCacheUpdated(CacheType.GitUserCache, datetime); } + + return gitUserCache; } } From 181ca0a446eac530a03cd1a0f4bc475d55494828 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 26 Oct 2017 19:09:48 -0400 Subject: [PATCH 125/241] Missing save in base class --- .../Assets/Editor/GitHub.Unity/ApplicationCache.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs index c81f0f90b..c3bbe13a2 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs @@ -114,6 +114,7 @@ public void InvalidateData() Logger.Trace("Invalidated"); CacheInvalidated.SafeInvoke(); ResetData(); + SaveData(DateTimeOffset.Now, true); } protected abstract void ResetData(); From 41b105f16a3c38417ee7618aab530067f0ce1116 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 26 Oct 2017 19:10:30 -0400 Subject: [PATCH 126/241] Renaming file --- src/GitHub.Api/Cache/{CacheContainer.cs => CacheInterfaces.cs} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename src/GitHub.Api/Cache/{CacheContainer.cs => CacheInterfaces.cs} (100%) diff --git a/src/GitHub.Api/Cache/CacheContainer.cs b/src/GitHub.Api/Cache/CacheInterfaces.cs similarity index 100% rename from src/GitHub.Api/Cache/CacheContainer.cs rename to src/GitHub.Api/Cache/CacheInterfaces.cs From 1b7862b5071e9a59140b70207a712e1e1ba25ac1 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Fri, 27 Oct 2017 09:44:16 -0400 Subject: [PATCH 127/241] Changing the struct GitBranch to use a default constructor and fields --- src/GitHub.Api/Git/GitBranch.cs | 26 +- src/GitHub.Api/Git/Repository.cs | 12 +- .../BranchListOutputProcessor.cs | 7 +- .../Events/RepositoryManagerTests.cs | 516 +++++++++++++++--- .../IntegrationTests/Git/GitSetupTests.cs | 12 +- .../Process/ProcessManagerIntegrationTests.cs | 12 +- .../IO/BranchListOutputProcessorTests.cs | 18 +- 7 files changed, 485 insertions(+), 118 deletions(-) diff --git a/src/GitHub.Api/Git/GitBranch.cs b/src/GitHub.Api/Git/GitBranch.cs index 9080accce..ef397344c 100644 --- a/src/GitHub.Api/Git/GitBranch.cs +++ b/src/GitHub.Api/Git/GitBranch.cs @@ -2,30 +2,12 @@ namespace GitHub.Unity { - interface ITreeData - { - string Name { get; } - bool IsActive { get; } - } - [Serializable] - public struct GitBranch : ITreeData + public struct GitBranch { - private string name; - private string tracking; - private bool active; - public string Name { get { return name; } } - public string Tracking { get { return tracking; } } - public bool IsActive { get { return active; } } - - public GitBranch(string name, string tracking, bool active) - { - Guard.ArgumentNotNullOrWhiteSpace(name, "name"); - - this.name = name; - this.tracking = tracking; - this.active = active; - } + public string Name; + public string Tracking; + public bool IsActive; public override string ToString() { diff --git a/src/GitHub.Api/Git/Repository.cs b/src/GitHub.Api/Git/Repository.cs index a28a7b679..a70f496f4 100644 --- a/src/GitHub.Api/Git/Repository.cs +++ b/src/GitHub.Api/Git/Repository.cs @@ -327,7 +327,11 @@ private GitBranch GetLocalGitBranch(ConfigBranch x) var trackingName = x.IsTracking ? x.Remote.Value.Name + "/" + name : "[None]"; var isActive = name == currentBranch?.Name; - return new GitBranch(name, trackingName, isActive); + return new GitBranch { + Name = name, + Tracking = trackingName, + IsActive = isActive + }; } private GitBranch GetRemoteGitBranch(ConfigBranch x) @@ -335,7 +339,11 @@ private GitBranch GetRemoteGitBranch(ConfigBranch x) var name = x.Remote.Value.Name + "/" + x.Name; var trackingName = "[None]"; - return new GitBranch(name, trackingName, false); + return new GitBranch { + Name = name, + Tracking = trackingName, + IsActive = false + }; } private GitRemote GetGitRemote(ConfigRemote configRemote) diff --git a/src/GitHub.Api/OutputProcessors/BranchListOutputProcessor.cs b/src/GitHub.Api/OutputProcessors/BranchListOutputProcessor.cs index cca8ed4ed..5df87e56b 100644 --- a/src/GitHub.Api/OutputProcessors/BranchListOutputProcessor.cs +++ b/src/GitHub.Api/OutputProcessors/BranchListOutputProcessor.cs @@ -36,7 +36,12 @@ public override void LineReceived(string line) trackingName = proc.ReadChunk('[', ']'); } - var branch = new GitBranch(name, trackingName, active); + var branch = new GitBranch + { + Name = name, + Tracking = trackingName, + IsActive = active + }; RaiseOnEntry(branch); } diff --git a/src/tests/IntegrationTests/Events/RepositoryManagerTests.cs b/src/tests/IntegrationTests/Events/RepositoryManagerTests.cs index 3e943d875..a8f97788a 100644 --- a/src/tests/IntegrationTests/Events/RepositoryManagerTests.cs +++ b/src/tests/IntegrationTests/Events/RepositoryManagerTests.cs @@ -47,9 +47,21 @@ public async Task ShouldDoNothingOnInitialize() Repository.CurrentRemote.Value.Name.Should().Be("origin"); Repository.CurrentRemote.Value.Url.Should().Be("https://github.com/EvilStanleyGoldman/IOTestsRepo.git"); Repository.LocalBranches.Should().BeEquivalentTo(new[] { - new GitBranch("master", "origin/master", true), - new GitBranch("feature/document", "origin/feature/document", false), - new GitBranch("feature/other-feature", "origin/feature/other-feature", false), + new GitBranch { + Name = "master", + Tracking = "origin/master", + IsActive = true + }, + new GitBranch { + Name = "feature/document", + Tracking = "origin/feature/document", + IsActive = false + }, + new GitBranch { + Name = "feature/other-feature", + Tracking = "origin/feature/other-feature", + IsActive = false + }, }); Repository.Remotes.Should().BeEquivalentTo(new GitRemote { @@ -57,9 +69,21 @@ public async Task ShouldDoNothingOnInitialize() Url = "https://github.com/EvilStanleyGoldman/IOTestsRepo.git" }); Repository.RemoteBranches.Should().BeEquivalentTo(new[] { - new GitBranch("origin/master", "[None]", false), - new GitBranch("origin/feature/document-2", "[None]", false), - new GitBranch("origin/feature/other-feature", "[None]", false), + new GitBranch { + Name = "origin/master", + Tracking = "[None]", + IsActive = false + }, + new GitBranch { + Name = "origin/feature/document-2", + Tracking = "[None]", + IsActive = false + }, + new GitBranch { + Name = "origin/feature/other-feature", + Tracking = "[None]", + IsActive = false + }, }); } @@ -323,18 +347,42 @@ public async Task ShouldDetectBranchChange() Repository.CurrentRemote.Value.Name.Should().Be("origin"); Repository.CurrentRemote.Value.Url.Should().Be("https://github.com/EvilStanleyGoldman/IOTestsRepo.git"); Repository.LocalBranches.Should().BeEquivalentTo(new[] { - new GitBranch("master", "origin/master", false), - new GitBranch("feature/document", "origin/feature/document", true), - new GitBranch("feature/other-feature", "origin/feature/other-feature", false), + new GitBranch { + Name = "master", + Tracking = "origin/master", + IsActive = false + }, + new GitBranch { + Name = "feature/document", + Tracking = "origin/feature/document", + IsActive = true + }, + new GitBranch { + Name = "feature/other-feature", + Tracking = "origin/feature/other-feature", + IsActive = false + }, }); Repository.Remotes.Should().BeEquivalentTo(new GitRemote { Name = "origin", Url = "https://github.com/EvilStanleyGoldman/IOTestsRepo.git" }); Repository.RemoteBranches.Should().BeEquivalentTo(new[] { - new GitBranch("origin/master", "[None]", false), - new GitBranch("origin/feature/document-2", "[None]", false), - new GitBranch("origin/feature/other-feature", "[None]", false), + new GitBranch { + Name = "origin/master", + Tracking = "[None]", + IsActive = false + }, + new GitBranch { + Name = "origin/feature/document-2", + Tracking = "[None]", + IsActive = false + }, + new GitBranch { + Name = "origin/feature/other-feature", + Tracking = "[None]", + IsActive = false + }, }); } @@ -377,8 +425,16 @@ public async Task ShouldDetectBranchDelete() Repository.CurrentRemote.Value.Name.Should().Be("origin"); Repository.CurrentRemote.Value.Url.Should().Be("https://github.com/EvilStanleyGoldman/IOTestsRepo.git"); Repository.LocalBranches.Should().BeEquivalentTo(new[] { - new GitBranch("master", "origin/master", true), - new GitBranch("feature/other-feature", "origin/feature/other-feature", false), + new GitBranch { + Name = "master", + Tracking = "origin/master", + IsActive = true + }, + new GitBranch { + Name = "feature/other-feature", + Tracking = "origin/feature/other-feature", + IsActive = false + }, }); Repository.Remotes.Should().BeEquivalentTo(new GitRemote { @@ -386,9 +442,21 @@ public async Task ShouldDetectBranchDelete() Url = "https://github.com/EvilStanleyGoldman/IOTestsRepo.git" }); Repository.RemoteBranches.Should().BeEquivalentTo(new[] { - new GitBranch("origin/master", "[None]", false), - new GitBranch("origin/feature/document-2", "[None]", false), - new GitBranch("origin/feature/other-feature", "[None]", false), + new GitBranch { + Name = "origin/master", + Tracking = "[None]", + IsActive = false + }, + new GitBranch { + Name = "origin/feature/document-2", + Tracking = "[None]", + IsActive = false + }, + new GitBranch { + Name = "origin/feature/other-feature", + Tracking = "[None]", + IsActive = false + }, }); } @@ -431,10 +499,26 @@ public async Task ShouldDetectBranchCreate() Repository.CurrentRemote.Value.Name.Should().Be("origin"); Repository.CurrentRemote.Value.Url.Should().Be("https://github.com/EvilStanleyGoldman/IOTestsRepo.git"); Repository.LocalBranches.Should().BeEquivalentTo(new[] { - new GitBranch("master", "origin/master", true), - new GitBranch("feature/document", "origin/feature/document", false), - new GitBranch("feature/document2", "[None]", false), - new GitBranch("feature/other-feature", "origin/feature/other-feature", false), + new GitBranch { + Name = "master", + Tracking = "origin/master", + IsActive = true + }, + new GitBranch { + Name = "feature/document", + Tracking = "origin/feature/document", + IsActive = false + }, + new GitBranch { + Name = "feature/document2", + Tracking = "[None]", + IsActive = false + }, + new GitBranch { + Name = "feature/other-feature", + Tracking = "origin/feature/other-feature", + IsActive = false + }, }); Repository.Remotes.Should().BeEquivalentTo(new GitRemote { @@ -442,9 +526,21 @@ public async Task ShouldDetectBranchCreate() Url = "https://github.com/EvilStanleyGoldman/IOTestsRepo.git" }); Repository.RemoteBranches.Should().BeEquivalentTo(new[] { - new GitBranch("origin/master", "[None]", false), - new GitBranch("origin/feature/document-2", "[None]", false), - new GitBranch("origin/feature/other-feature", "[None]", false), + new GitBranch { + Name = "origin/master", + Tracking = "[None]", + IsActive = false + }, + new GitBranch { + Name = "origin/feature/document-2", + Tracking = "[None]", + IsActive = false + }, + new GitBranch { + Name = "origin/feature/other-feature", + Tracking = "[None]", + IsActive = false + }, }); repositoryManagerListener.ClearReceivedCalls(); @@ -481,11 +577,31 @@ public async Task ShouldDetectBranchCreate() Repository.CurrentRemote.Value.Name.Should().Be("origin"); Repository.CurrentRemote.Value.Url.Should().Be("https://github.com/EvilStanleyGoldman/IOTestsRepo.git"); Repository.LocalBranches.Should().BeEquivalentTo(new[] { - new GitBranch("master", "origin/master", true), - new GitBranch("feature/document", "origin/feature/document", false), - new GitBranch("feature/document2", "[None]", false), - new GitBranch("feature2/document2", "[None]", false), - new GitBranch("feature/other-feature", "origin/feature/other-feature", false), + new GitBranch { + Name = "master", + Tracking = "origin/master", + IsActive = true + }, + new GitBranch { + Name = "feature/document", + Tracking = "origin/feature/document", + IsActive = false + }, + new GitBranch { + Name = "feature/document2", + Tracking = "[None]", + IsActive = false + }, + new GitBranch { + Name = "feature2/document2", + Tracking = "[None]", + IsActive = false + }, + new GitBranch { + Name = "feature/other-feature", + Tracking = "origin/feature/other-feature", + IsActive = false + }, }); Repository.Remotes.Should().BeEquivalentTo(new GitRemote { @@ -493,9 +609,21 @@ public async Task ShouldDetectBranchCreate() Url = "https://github.com/EvilStanleyGoldman/IOTestsRepo.git" }); Repository.RemoteBranches.Should().BeEquivalentTo(new[] { - new GitBranch("origin/master", "[None]", false), - new GitBranch("origin/feature/document-2", "[None]", false), - new GitBranch("origin/feature/other-feature", "[None]", false), + new GitBranch { + Name = "origin/master", + Tracking = "[None]", + IsActive = false + }, + new GitBranch { + Name = "origin/feature/document-2", + Tracking = "[None]", + IsActive = false + }, + new GitBranch { + Name = "origin/feature/other-feature", + Tracking = "[None]", + IsActive = false + }, }); } @@ -524,9 +652,21 @@ public async Task ShouldDetectChangesToRemotes() Repository.CurrentRemote.Value.Name.Should().Be("origin"); Repository.CurrentRemote.Value.Url.Should().Be("https://github.com/EvilStanleyGoldman/IOTestsRepo.git"); Repository.LocalBranches.Should().BeEquivalentTo(new[] { - new GitBranch("master", "origin/master", true), - new GitBranch("feature/document", "origin/feature/document", false), - new GitBranch("feature/other-feature", "origin/feature/other-feature", false), + new GitBranch { + Name = "master", + Tracking = "origin/master", + IsActive = true + }, + new GitBranch { + Name = "feature/document", + Tracking = "origin/feature/document", + IsActive = false + }, + new GitBranch { + Name = "feature/other-feature", + Tracking = "origin/feature/other-feature", + IsActive = false + }, }); Repository.Remotes.Should().BeEquivalentTo(new GitRemote { @@ -534,9 +674,21 @@ public async Task ShouldDetectChangesToRemotes() Url = "https://github.com/EvilStanleyGoldman/IOTestsRepo.git" }); Repository.RemoteBranches.Should().BeEquivalentTo(new[] { - new GitBranch("origin/master", "[None]", false), - new GitBranch("origin/feature/document-2", "[None]", false), - new GitBranch("origin/feature/other-feature", "[None]", false), + new GitBranch { + Name = "origin/master", + Tracking = "[None]", + IsActive = false + }, + new GitBranch { + Name = "origin/feature/document-2", + Tracking = "[None]", + IsActive = false + }, + new GitBranch { + Name = "origin/feature/other-feature", + Tracking = "[None]", + IsActive = false + }, }); await RepositoryManager.RemoteRemove("origin").StartAsAsync(); @@ -608,9 +760,21 @@ public async Task ShouldDetectChangesToRemotes() Repository.CurrentRemote.Value.Name.Should().Be("origin"); Repository.CurrentRemote.Value.Url.Should().Be("https://github.com/EvilShana/IOTestsRepo.git"); Repository.LocalBranches.Should().BeEquivalentTo(new[] { - new GitBranch("master", "[None]", true), - new GitBranch("feature/document", "[None]", false), - new GitBranch("feature/other-feature", "[None]", false), + new GitBranch { + Name = "master", + Tracking = "[None]", + IsActive = true + }, + new GitBranch { + Name = "feature/document", + Tracking = "[None]", + IsActive = false + }, + new GitBranch { + Name = "feature/other-feature", + Tracking = "[None]", + IsActive = false + }, }); Repository.Remotes.Should().BeEquivalentTo(new GitRemote { @@ -645,9 +809,21 @@ public async Task ShouldDetectChangesToRemotesWhenSwitchingBranches() Repository.CurrentRemote.Value.Name.Should().Be("origin"); Repository.CurrentRemote.Value.Url.Should().Be("https://github.com/EvilStanleyGoldman/IOTestsRepo.git"); Repository.LocalBranches.Should().BeEquivalentTo(new[] { - new GitBranch("master", "origin/master", true), - new GitBranch("feature/document", "origin/feature/document", false), - new GitBranch("feature/other-feature", "origin/feature/other-feature", false), + new GitBranch { + Name = "master", + Tracking = "origin/master", + IsActive = true + }, + new GitBranch { + Name = "feature/document", + Tracking = "origin/feature/document", + IsActive = false + }, + new GitBranch { + Name = "feature/other-feature", + Tracking = "origin/feature/other-feature", + IsActive = false + }, }); Repository.Remotes.Should().BeEquivalentTo(new GitRemote { @@ -659,12 +835,36 @@ public async Task ShouldDetectChangesToRemotesWhenSwitchingBranches() Url = "https://another.remote/Owner/Url.git" }); Repository.RemoteBranches.Should().BeEquivalentTo(new[] { - new GitBranch("origin/master", "[None]", false), - new GitBranch("origin/feature/document-2", "[None]", false), - new GitBranch("origin/feature/other-feature", "[None]", false), - new GitBranch("another/master", "[None]", false), - new GitBranch("another/feature/document-2", "[None]", false), - new GitBranch("another/feature/other-feature", "[None]", false), + new GitBranch { + Name = "origin/master", + Tracking = "[None]", + IsActive = false + }, + new GitBranch { + Name = "origin/feature/document-2", + Tracking = "[None]", + IsActive = false + }, + new GitBranch { + Name = "origin/feature/other-feature", + Tracking = "[None]", + IsActive = false + }, + new GitBranch { + Name = "another/master", + Tracking = "[None]", + IsActive = false + }, + new GitBranch { + Name = "another/feature/document-2", + Tracking = "[None]", + IsActive = false + }, + new GitBranch { + Name = "another/feature/other-feature", + Tracking = "[None]", + IsActive = false + }, }); await RepositoryManager.CreateBranch("branch2", "another/master") @@ -699,10 +899,26 @@ await RepositoryManager.CreateBranch("branch2", "another/master") Repository.CurrentRemote.Value.Name.Should().Be("origin"); Repository.CurrentRemote.Value.Url.Should().Be("https://github.com/EvilStanleyGoldman/IOTestsRepo.git"); Repository.LocalBranches.Should().BeEquivalentTo(new[] { - new GitBranch("master", "origin/master", true), - new GitBranch("branch2", "another/branch2", false), - new GitBranch("feature/document", "origin/feature/document", false), - new GitBranch("feature/other-feature", "origin/feature/other-feature", false), + new GitBranch { + Name = "master", + Tracking = "origin/master", + IsActive = true + }, + new GitBranch { + Name = "branch2", + Tracking = "another/branch2", + IsActive = false + }, + new GitBranch { + Name = "feature/document", + Tracking = "origin/feature/document", + IsActive = false + }, + new GitBranch { + Name = "feature/other-feature", + Tracking = "origin/feature/other-feature", + IsActive = false + }, }); Repository.Remotes.Should().BeEquivalentTo(new GitRemote { @@ -714,12 +930,36 @@ await RepositoryManager.CreateBranch("branch2", "another/master") Url = "https://another.remote/Owner/Url.git" }); Repository.RemoteBranches.Should().BeEquivalentTo(new[] { - new GitBranch("origin/master", "[None]", false), - new GitBranch("origin/feature/document-2", "[None]", false), - new GitBranch("origin/feature/other-feature", "[None]", false), - new GitBranch("another/master", "[None]", false), - new GitBranch("another/feature/document-2", "[None]", false), - new GitBranch("another/feature/other-feature", "[None]", false), + new GitBranch { + Name = "origin/master", + Tracking = "[None]", + IsActive = false + }, + new GitBranch { + Name = "origin/feature/document-2", + Tracking = "[None]", + IsActive = false + }, + new GitBranch { + Name = "origin/feature/other-feature", + Tracking = "[None]", + IsActive = false + }, + new GitBranch { + Name = "another/master", + Tracking = "[None]", + IsActive = false + }, + new GitBranch { + Name = "another/feature/document-2", + Tracking = "[None]", + IsActive = false + }, + new GitBranch { + Name = "another/feature/other-feature", + Tracking = "[None]", + IsActive = false + }, }); repositoryManagerListener.ClearReceivedCalls(); @@ -758,10 +998,26 @@ await RepositoryManager.SwitchBranch("branch2") Repository.CurrentRemote.Value.Name.Should().Be("another"); Repository.CurrentRemote.Value.Url.Should().Be("https://another.remote/Owner/Url.git"); Repository.LocalBranches.Should().BeEquivalentTo(new[] { - new GitBranch("master", "origin/master", false), - new GitBranch("branch2", "another/branch2", true), - new GitBranch("feature/document", "origin/feature/document", false), - new GitBranch("feature/other-feature", "origin/feature/other-feature", false), + new GitBranch { + Name = "master", + Tracking = "origin/master", + IsActive = false + }, + new GitBranch { + Name = "branch2", + Tracking = "another/branch2", + IsActive = true + }, + new GitBranch { + Name = "feature/document", + Tracking = "origin/feature/document", + IsActive = false + }, + new GitBranch { + Name = "feature/other-feature", + Tracking = "origin/feature/other-feature", + IsActive = false + }, }); Repository.Remotes.Should().BeEquivalentTo(new GitRemote { @@ -773,12 +1029,36 @@ await RepositoryManager.SwitchBranch("branch2") Url = "https://another.remote/Owner/Url.git" }); Repository.RemoteBranches.Should().BeEquivalentTo(new[] { - new GitBranch("origin/master", "[None]", false), - new GitBranch("origin/feature/document-2", "[None]", false), - new GitBranch("origin/feature/other-feature", "[None]", false), - new GitBranch("another/master", "[None]", false), - new GitBranch("another/feature/document-2", "[None]", false), - new GitBranch("another/feature/other-feature", "[None]", false), + new GitBranch { + Name = "origin/master", + Tracking = "[None]", + IsActive = false + }, + new GitBranch { + Name = "origin/feature/document-2", + Tracking = "[None]", + IsActive = false + }, + new GitBranch { + Name = "origin/feature/other-feature", + Tracking = "[None]", + IsActive = false + }, + new GitBranch { + Name = "another/master", + Tracking = "[None]", + IsActive = false + }, + new GitBranch { + Name = "another/feature/document-2", + Tracking = "[None]", + IsActive = false + }, + new GitBranch { + Name = "another/feature/other-feature", + Tracking = "[None]", + IsActive = false + }, }); } @@ -832,9 +1112,21 @@ public async Task ShouldDetectGitPull() Repository.CurrentRemote.Value.Name.Should().Be("origin"); Repository.CurrentRemote.Value.Url.Should().Be("https://github.com/EvilStanleyGoldman/IOTestsRepo.git"); Repository.LocalBranches.Should().BeEquivalentTo(new[] { - new GitBranch("master", "origin/master", true), - new GitBranch("feature/document", "origin/feature/document", false), - new GitBranch("feature/other-feature", "origin/feature/other-feature", false), + new GitBranch { + Name = "master", + Tracking = "origin/master", + IsActive = true + }, + new GitBranch { + Name = "feature/document", + Tracking = "origin/feature/document", + IsActive = false + }, + new GitBranch { + Name = "feature/other-feature", + Tracking = "origin/feature/other-feature", + IsActive = false + }, }); Repository.Remotes.Should().BeEquivalentTo(new GitRemote { @@ -842,9 +1134,21 @@ public async Task ShouldDetectGitPull() Url = "https://github.com/EvilStanleyGoldman/IOTestsRepo.git" }); Repository.RemoteBranches.Should().BeEquivalentTo(new[] { - new GitBranch("origin/master", "[None]", false), - new GitBranch("origin/feature/document-2", "[None]", false), - new GitBranch("origin/feature/other-feature", "[None]", false), + new GitBranch { + Name = "origin/master", + Tracking = "[None]", + IsActive = false + }, + new GitBranch { + Name = "origin/feature/document-2", + Tracking = "[None]", + IsActive = false + }, + new GitBranch { + Name = "origin/feature/other-feature", + Tracking = "[None]", + IsActive = false + }, }); repositoryManagerEvents.Reset(); @@ -876,7 +1180,11 @@ public async Task ShouldDetectGitFetch() Repository.CurrentRemote.Value.Name.Should().Be("origin"); Repository.CurrentRemote.Value.Url.Should().Be("https://github.com/EvilStanleyGoldman/IOTestsRepo.git"); Repository.LocalBranches.Should().BeEquivalentTo(new[] { - new GitBranch("feature/document", "origin/feature/document", false), + new GitBranch { + Name = "feature/document", + Tracking = "origin/feature/document", + IsActive = false + }, }); Repository.Remotes.Should().BeEquivalentTo(new GitRemote { @@ -884,9 +1192,21 @@ public async Task ShouldDetectGitFetch() Url = "https://github.com/EvilStanleyGoldman/IOTestsRepo.git" }); Repository.RemoteBranches.Should().BeEquivalentTo(new[] { - new GitBranch("origin/master", "[None]", false), - new GitBranch("origin/feature/document", "[None]", false), - new GitBranch("origin/feature/document-2", "[None]", false), + new GitBranch { + Name = "origin/master", + Tracking = "[None]", + IsActive = false + }, + new GitBranch { + Name = "origin/feature/document", + Tracking = "[None]", + IsActive = false + }, + new GitBranch { + Name = "origin/feature/document-2", + Tracking = "[None]", + IsActive = false + }, }); await RepositoryManager.Fetch("origin").StartAsAsync(); @@ -919,7 +1239,11 @@ public async Task ShouldDetectGitFetch() Repository.CurrentRemote.Value.Name.Should().Be("origin"); Repository.CurrentRemote.Value.Url.Should().Be("https://github.com/EvilStanleyGoldman/IOTestsRepo.git"); Repository.LocalBranches.Should().BeEquivalentTo(new[] { - new GitBranch("feature/document", "origin/feature/document", false), + new GitBranch { + Name = "feature/document", + Tracking = "origin/feature/document", + IsActive = false + }, }); Repository.Remotes.Should().BeEquivalentTo(new GitRemote { @@ -927,11 +1251,31 @@ public async Task ShouldDetectGitFetch() Url = "https://github.com/EvilStanleyGoldman/IOTestsRepo.git" }); Repository.RemoteBranches.Should().BeEquivalentTo(new[] { - new GitBranch("origin/master", "[None]", false), - new GitBranch("origin/feature/document", "[None]", false), - new GitBranch("origin/feature/document-2", "[None]", false), - new GitBranch("origin/feature/new-feature", "[None]", false), - new GitBranch("origin/feature/other-feature", "[None]", false), + new GitBranch { + Name = "origin/master", + Tracking = "[None]", + IsActive = false + }, + new GitBranch { + Name = "origin/feature/document", + Tracking = "[None]", + IsActive = false + }, + new GitBranch { + Name = "origin/feature/document-2", + Tracking = "[None]", + IsActive = false + }, + new GitBranch { + Name = "origin/feature/new-feature", + Tracking = "[None]", + IsActive = false + }, + new GitBranch { + Name = "origin/feature/other-feature", + Tracking = "[None]", + IsActive = false + }, }); } } diff --git a/src/tests/IntegrationTests/Git/GitSetupTests.cs b/src/tests/IntegrationTests/Git/GitSetupTests.cs index 1a18cdc8b..4e239dd94 100644 --- a/src/tests/IntegrationTests/Git/GitSetupTests.cs +++ b/src/tests/IntegrationTests/Git/GitSetupTests.cs @@ -63,8 +63,16 @@ public async Task InstallGit() .StartAsAsync(); gitBranches.Should().BeEquivalentTo( - new GitBranch("master", "origin/master: behind 1", true), - new GitBranch("feature/document", "origin/feature/document", false)); + new GitBranch { + Name = "master", + Tracking = "origin/master: behind 1", + IsActive = true + }, + new GitBranch { + Name = "feature/document", + Tracking = "origin/feature/document", + IsActive = false + }); } diff --git a/src/tests/IntegrationTests/Process/ProcessManagerIntegrationTests.cs b/src/tests/IntegrationTests/Process/ProcessManagerIntegrationTests.cs index 8766b3798..db6a90e7b 100644 --- a/src/tests/IntegrationTests/Process/ProcessManagerIntegrationTests.cs +++ b/src/tests/IntegrationTests/Process/ProcessManagerIntegrationTests.cs @@ -23,8 +23,16 @@ public async Task BranchListTest() .StartAsAsync(); gitBranches.Should().BeEquivalentTo( - new GitBranch("master", "origin/master: behind 1", true), - new GitBranch("feature/document", "origin/feature/document", false)); + new GitBranch { + Name = "master", + Tracking = "origin/master: behind 1", + IsActive = true + }, + new GitBranch { + Name = "feature/document", + Tracking = "origin/feature/document", + IsActive = false + }); } [Test] diff --git a/src/tests/UnitTests/IO/BranchListOutputProcessorTests.cs b/src/tests/UnitTests/IO/BranchListOutputProcessorTests.cs index 64d265bdf..6fb9fc7fa 100644 --- a/src/tests/UnitTests/IO/BranchListOutputProcessorTests.cs +++ b/src/tests/UnitTests/IO/BranchListOutputProcessorTests.cs @@ -20,9 +20,21 @@ public void ShouldProcessOutput() AssertProcessOutput(output, new[] { - new GitBranch("master", "origin/master", true), - new GitBranch("feature/feature-1", "", false), - new GitBranch("bugfixes/bugfix-1", "origin/bugfixes/bugfix-1", false), + new GitBranch { + Name = "master", + Tracking = "origin/master", + IsActive = true + }, + new GitBranch { + Name = "feature/feature-1", + Tracking = "", + IsActive = false + }, + new GitBranch { + Name = "bugfixes/bugfix-1", + Tracking = "origin/bugfixes/bugfix-1", + IsActive = false + }, }); } From 14a1a83af56b0ac2aedb868e7d171bdbc77491c3 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Fri, 27 Oct 2017 09:54:19 -0400 Subject: [PATCH 128/241] Using default values for structs correctly --- src/GitHub.Api/Cache/CacheInterfaces.cs | 9 +- src/GitHub.Api/Git/Repository.cs | 45 ++---- src/GitHub.Api/GitHub.Api.csproj | 2 +- .../Editor/GitHub.Unity/ApplicationCache.cs | 149 +++++++++++++----- .../Editor/GitHub.Unity/CacheContainer.cs | 4 +- 5 files changed, 130 insertions(+), 79 deletions(-) diff --git a/src/GitHub.Api/Cache/CacheInterfaces.cs b/src/GitHub.Api/Cache/CacheInterfaces.cs index ffab80f42..a900bc30e 100644 --- a/src/GitHub.Api/Cache/CacheInterfaces.cs +++ b/src/GitHub.Api/Cache/CacheInterfaces.cs @@ -71,15 +71,14 @@ public interface IGitStatusCache : IManagedCache, IGitStatus public interface IRepositoryInfo { - ConfigRemote? CurrentRemote { get; } - ConfigBranch? CurentBranch { get; } + ConfigRemote? CurrentConfigRemote { get; set; } + ConfigBranch? CurentConfigBranch { get; set; } } public interface IRepositoryInfoCache : IManagedCache, IRepositoryInfo { - void UpdateData(ConfigRemote? gitRemoteUpdate); - void UpdateData(ConfigBranch? gitBranchUpdate); - void UpdateData(ConfigRemote? gitRemoteUpdate, ConfigBranch? gitBranchUpdate); + GitRemote? CurrentGitRemote { get; set; } + GitBranch? CurentGitBranch { get; set; } } public interface IBranch diff --git a/src/GitHub.Api/Git/Repository.cs b/src/GitHub.Api/Git/Repository.cs index 8c4a36b96..89707f340 100644 --- a/src/GitHub.Api/Git/Repository.cs +++ b/src/GitHub.Api/Git/Repository.cs @@ -360,43 +360,32 @@ private GitRemote GetGitRemote(ConfigRemote configRemote) private ConfigBranch? CurrentConfigBranch { - get { return this.cacheContainer.RepositoryInfoCache.CurentBranch; } - set { this.cacheContainer.RepositoryInfoCache.UpdateData(value); } + get { return this.cacheContainer.RepositoryInfoCache.CurentConfigBranch; } + set + { + cacheContainer.RepositoryInfoCache.CurentConfigBranch = value; + cacheContainer.RepositoryInfoCache.CurentGitBranch = value != null + ? (GitBranch?)GetLocalGitBranch(value.Value) + : null; + } } private ConfigRemote? CurrentConfigRemote { - get { return this.cacheContainer.RepositoryInfoCache.CurrentRemote; } - set { this.cacheContainer.RepositoryInfoCache.UpdateData(value); } - } - - public GitBranch? CurrentBranch - { - get - { - if (CurrentConfigBranch != null) - { - return GetLocalGitBranch(CurrentConfigBranch.Value); - } - - return null; + get { return this.cacheContainer.RepositoryInfoCache.CurrentConfigRemote; } + set { + cacheContainer.RepositoryInfoCache.CurrentConfigRemote = value; + cacheContainer.RepositoryInfoCache.CurrentGitRemote = value != null + ? (GitRemote?) GetGitRemote(value.Value) + : null; } } - public string CurrentBranchName => CurrentConfigBranch?.Name; + public GitBranch? CurrentBranch => cacheContainer.RepositoryInfoCache.CurentGitBranch; - public GitRemote? CurrentRemote - { - get - { - if (CurrentConfigRemote != null) - { - return GetGitRemote(CurrentConfigRemote.Value); - } + public string CurrentBranchName => CurrentConfigBranch?.Name; - return null; - } - } + public GitRemote? CurrentRemote => cacheContainer.RepositoryInfoCache.CurrentGitRemote; public UriString CloneUrl { get; private set; } diff --git a/src/GitHub.Api/GitHub.Api.csproj b/src/GitHub.Api/GitHub.Api.csproj index 08745f6d5..9ad4bb1a8 100644 --- a/src/GitHub.Api/GitHub.Api.csproj +++ b/src/GitHub.Api/GitHub.Api.csproj @@ -99,7 +99,7 @@ - + diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs index c3bbe13a2..922501755 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs @@ -117,7 +117,13 @@ public void InvalidateData() SaveData(DateTimeOffset.Now, true); } - protected abstract void ResetData(); + private void ResetData() + { + Logger.Trace("ResetData"); + OnResetData(); + } + + protected abstract void OnResetData(); protected void SaveData(DateTimeOffset now, bool isUpdated) { @@ -234,7 +240,7 @@ public void UpdateData() SaveData(DateTimeOffset.Now, false); } - protected override void ResetData() + protected override void OnResetData() { localBranches = new List(); remoteBranches = new List(); @@ -319,76 +325,133 @@ public List FavoriteBranches [Location("cache/repoinfo.yaml", LocationAttribute.Location.LibraryFolder)] sealed class RepositoryInfoCache : ManagedCacheBase, IRepositoryInfoCache { + public static readonly ConfigBranch DefaultConfigBranch = new ConfigBranch(); + public static readonly ConfigRemote DefaultConfigRemote = new ConfigRemote(); + public static readonly GitRemote DefaultGitRemote = new GitRemote(); + public static readonly GitBranch DefaultGitBranch = new GitBranch(); + [SerializeField] private string lastUpdatedAtString = DateTimeOffset.MinValue.ToString(); [SerializeField] private string lastVerifiedAtString = DateTimeOffset.MinValue.ToString(); - [SerializeField] private ConfigBranch? gitBranch; - [SerializeField] private ConfigRemote? gitRemote; + [SerializeField] private ConfigBranch gitConfigBranch; + [SerializeField] private ConfigRemote gitConfigRemote; + [SerializeField] private GitRemote gitRemote; + [SerializeField] private GitBranch gitBranch; - public void UpdateData(ConfigRemote? gitRemoteUpdate) + protected override void OnResetData() { - UpdateData(gitRemoteUpdate, gitBranch); + gitConfigBranch = DefaultConfigBranch; + gitConfigRemote = DefaultConfigRemote; } - public void UpdateData(ConfigBranch? gitBranchUpdate) + public override string LastUpdatedAtString { - UpdateData(gitRemote, gitBranchUpdate); + get { return lastUpdatedAtString; } + protected set { lastUpdatedAtString = value; } } - public void UpdateData(ConfigRemote? gitRemoteUpdate, ConfigBranch? gitBranchUpdate) + public override string LastVerifiedAtString { - var now = DateTimeOffset.Now; - var isUpdated = false; - - Logger.Trace("Processing Update: {0}", now); + get { return lastVerifiedAtString; } + protected set { lastVerifiedAtString = value; } + } - if (!Nullable.Equals(gitRemote, gitRemoteUpdate)) + public ConfigRemote? CurrentConfigRemote + { + get { - gitRemote = gitRemoteUpdate; - isUpdated = true; + Logger.Trace("Get CurrentConfigRemote"); + ValidateData(); + return gitConfigRemote.Equals(DefaultConfigRemote) ? (ConfigRemote?) null : gitConfigRemote; } - - if (!Nullable.Equals(gitBranch, gitBranchUpdate)) + set { - gitBranch = gitBranchUpdate; - isUpdated = true; - } + var now = DateTimeOffset.Now; + var isUpdated = false; - SaveData(now, isUpdated); - } + Logger.Trace("Updating: {0} gitConfigRemote:{1}", now, value); - protected override void ResetData() - { - gitBranch = null; - gitRemote = null; - } + if (!Nullable.Equals(gitConfigRemote, value)) + { + gitConfigRemote = value ?? DefaultConfigRemote; + isUpdated = true; + } - public override string LastUpdatedAtString - { - get { return lastUpdatedAtString; } - protected set { lastUpdatedAtString = value; } + SaveData(now, isUpdated); + } } - public override string LastVerifiedAtString + public ConfigBranch? CurentConfigBranch { - get { return lastVerifiedAtString; } - protected set { lastVerifiedAtString = value; } + get + { + Logger.Trace("Get CurentConfigBranch"); + ValidateData(); + return gitConfigBranch.Equals(DefaultConfigBranch) ? (ConfigBranch?) null : gitConfigBranch; + } + set + { + var now = DateTimeOffset.Now; + var isUpdated = false; + + Logger.Trace("Updating: {0} gitConfigBranch:{1}", now, value); + + if (!Nullable.Equals(gitConfigBranch, value)) + { + gitConfigBranch = value ?? DefaultConfigBranch; + isUpdated = true; + } + + SaveData(now, isUpdated); + } } - public ConfigRemote? CurrentRemote + public GitRemote? CurrentGitRemote { get { + Logger.Trace("Get CurrentGitRemote"); ValidateData(); - return gitRemote; + return gitRemote.Equals(DefaultGitRemote) ? (GitRemote?) null : gitRemote; + } + set + { + var now = DateTimeOffset.Now; + var isUpdated = false; + + Logger.Trace("Updating: {0} gitRemote:{1}", now, value); + + if (!Nullable.Equals(gitRemote, value)) + { + gitRemote = value ?? DefaultGitRemote; + isUpdated = true; + } + + SaveData(now, isUpdated); } } - public ConfigBranch? CurentBranch + public GitBranch? CurentGitBranch { get { + Logger.Trace("Get CurentConfigBranch"); ValidateData(); - return gitBranch; + return gitBranch.Equals(DefaultGitBranch) ? (GitBranch?)null : gitBranch; + } + set + { + var now = DateTimeOffset.Now; + var isUpdated = false; + + Logger.Trace("Updating: {0} gitBranch:{1}", now, value); + + if (!Nullable.Equals(gitBranch, value)) + { + gitBranch = value ?? DefaultGitBranch; + isUpdated = true; + } + + SaveData(now, isUpdated); } } } @@ -427,7 +490,7 @@ public List Log } } - protected override void ResetData() + protected override void OnResetData() { log = new List(); } @@ -477,7 +540,7 @@ public GitStatus GitStatus } } - protected override void ResetData() + protected override void OnResetData() { status = new GitStatus(); } @@ -530,7 +593,7 @@ public List GitLocks } } - protected override void ResetData() + protected override void OnResetData() { locks = new List(); } @@ -580,7 +643,7 @@ public User User } } - protected override void ResetData() + protected override void OnResetData() { user = null; } diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/CacheContainer.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/CacheContainer.cs index 083749a45..98e89c5a1 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/CacheContainer.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/CacheContainer.cs @@ -173,7 +173,7 @@ public IGitUserCache GitUserCache private void OnCacheUpdated(CacheType cacheType, DateTimeOffset datetime) { - Logger.Trace("OnCacheUpdated cacheType:{0} datetime:{1}", cacheType, datetime); + //Logger.Trace("OnCacheUpdated cacheType:{0} datetime:{1}", cacheType, datetime); if (CacheUpdated != null) { CacheUpdated.Invoke(cacheType, datetime); @@ -182,7 +182,7 @@ private void OnCacheUpdated(CacheType cacheType, DateTimeOffset datetime) private void OnCacheInvalidated(CacheType cacheType) { - Logger.Trace("OnCacheInvalidated cacheType:{0}", cacheType); + //Logger.Trace("OnCacheInvalidated cacheType:{0}", cacheType); if (CacheInvalidated != null) { CacheInvalidated.Invoke(cacheType); From 86530acac90d729ba6bb1b5e1b73fb971f04330a Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Fri, 27 Oct 2017 10:03:21 -0400 Subject: [PATCH 129/241] Removing reset during invalidation --- .../Assets/Editor/GitHub.Unity/ApplicationCache.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs index 922501755..47ab3780f 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs @@ -113,7 +113,6 @@ public void InvalidateData() { Logger.Trace("Invalidated"); CacheInvalidated.SafeInvoke(); - ResetData(); SaveData(DateTimeOffset.Now, true); } From 5e1879a6925edd0aa4f3d34d22b1ef18a62ec92b Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Fri, 27 Oct 2017 10:03:47 -0400 Subject: [PATCH 130/241] Kneecapping data timeout --- .../Assets/Editor/GitHub.Unity/ApplicationCache.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs index 47ab3780f..22493e906 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs @@ -87,7 +87,7 @@ public IEnvironment Environment abstract class ManagedCacheBase : ScriptObjectSingleton where T : ScriptableObject, IManagedCache { - private static readonly TimeSpan DataTimeout = TimeSpan.FromSeconds(30); + private static readonly TimeSpan DataTimeout = TimeSpan.MaxValue; [NonSerialized] private DateTimeOffset? lastUpdatedAtValue; From 08c566db8238d092698e7423ed186861ca08b5ac Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Fri, 27 Oct 2017 10:45:47 -0400 Subject: [PATCH 131/241] Disabling RepositoryManagerTests --- src/tests/IntegrationTests/Events/RepositoryManagerTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tests/IntegrationTests/Events/RepositoryManagerTests.cs b/src/tests/IntegrationTests/Events/RepositoryManagerTests.cs index a8f97788a..9addb6ef6 100644 --- a/src/tests/IntegrationTests/Events/RepositoryManagerTests.cs +++ b/src/tests/IntegrationTests/Events/RepositoryManagerTests.cs @@ -11,7 +11,7 @@ namespace IntegrationTests { - [TestFixture] + [TestFixture, Ignore] class RepositoryManagerTests : BaseGitEnvironmentTest { private RepositoryManagerEvents repositoryManagerEvents; From a20de1ec347e6baa629b4a447cc8de0f317d4c03 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Fri, 27 Oct 2017 10:51:50 -0400 Subject: [PATCH 132/241] Disabling RepositoryTests as well --- src/tests/UnitTests/Git/RepositoryTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tests/UnitTests/Git/RepositoryTests.cs b/src/tests/UnitTests/Git/RepositoryTests.cs index 9be53470c..23dc4f358 100644 --- a/src/tests/UnitTests/Git/RepositoryTests.cs +++ b/src/tests/UnitTests/Git/RepositoryTests.cs @@ -12,7 +12,7 @@ namespace UnitTests { - [TestFixture, Isolated] + [TestFixture, Isolated, Ignore] public class RepositoryTests { private static readonly SubstituteFactory SubstituteFactory = new SubstituteFactory(); From 9510e893756385633f7a5a28a7ce84dfaa6f3a87 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Fri, 27 Oct 2017 11:35:53 -0400 Subject: [PATCH 133/241] Refactoring Window.MaybeUpdateData --- .../Assets/Editor/GitHub.Unity/UI/Window.cs | 33 +++++++++---------- 1 file changed, 16 insertions(+), 17 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs index f9a32fa25..7c9070d90 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs @@ -109,19 +109,7 @@ public override void OnDataUpdate() { base.OnDataUpdate(); - string repoRemote = null; - if (MaybeUpdateData(out repoRemote)) - { - repoBranchContent = new GUIContent(repoBranch, Window_RepoBranchTooltip); - if (repoUrl != null) - { - repoUrlContent = new GUIContent(repoUrl, string.Format(Window_RepoUrlTooltip, repoRemote)); - } - else - { - repoUrlContent = new GUIContent(repoUrl, Window_RepoNoUrlTooltip); - } - } + MaybeUpdateData(); if (ActiveView != null) ActiveView.OnDataUpdate(); @@ -198,10 +186,10 @@ private void RefreshOnMainThread() new ActionTask(TaskManager.Token, Refresh) { Affinity = TaskAffinity.UI }.Start(); } - private bool MaybeUpdateData(out string repoRemote) + private void MaybeUpdateData() { - repoRemote = null; - bool repoDataChanged = false; + string repoRemote = null; + var repoDataChanged = false; if (Repository != null) { var currentBranchString = (Repository.CurrentBranch.HasValue ? Repository.CurrentBranch.Value.Name : null); @@ -236,7 +224,18 @@ private bool MaybeUpdateData(out string repoRemote) } } - return repoDataChanged; + if (repoDataChanged) + { + repoBranchContent = new GUIContent(repoBranch, Window_RepoBranchTooltip); + if (repoUrl != null) + { + repoUrlContent = new GUIContent(repoUrl, string.Format(Window_RepoUrlTooltip, repoRemote)); + } + else + { + repoUrlContent = new GUIContent(repoUrl, Window_RepoNoUrlTooltip); + } + } } private void AttachHandlers(IRepository repository) From 4407481a460e45720d1ab8ad866775baa78dbd70 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Fri, 27 Oct 2017 11:38:47 -0400 Subject: [PATCH 134/241] Starting to add an event to represent cache changes from the Repository --- src/GitHub.Api/Git/IRepository.cs | 3 + src/GitHub.Api/Git/Repository.cs | 81 +++++++++++++++++++ .../Assets/Editor/GitHub.Unity/UI/Window.cs | 17 +++- 3 files changed, 97 insertions(+), 4 deletions(-) diff --git a/src/GitHub.Api/Git/IRepository.cs b/src/GitHub.Api/Git/IRepository.cs index 5818a9f52..e482dd28f 100644 --- a/src/GitHub.Api/Git/IRepository.cs +++ b/src/GitHub.Api/Git/IRepository.cs @@ -22,6 +22,8 @@ public interface IRepository : IEquatable ITask RequestLock(string file); ITask ReleaseLock(string file, bool force); + void CheckRepositoryInfoCacheEvent(UpdateDataEventData repositoryInfoCacheEvent); + /// /// Gets the name of the repository. /// @@ -66,5 +68,6 @@ public interface IRepository : IEquatable event Action> OnLocksChanged; event Action OnRepositoryInfoChanged; event Action OnRemoteBranchListChanged; + event Action OnRepositoryInfoCacheChanged; } } \ No newline at end of file diff --git a/src/GitHub.Api/Git/Repository.cs b/src/GitHub.Api/Git/Repository.cs index 89707f340..b164e7932 100644 --- a/src/GitHub.Api/Git/Repository.cs +++ b/src/GitHub.Api/Git/Repository.cs @@ -25,6 +25,8 @@ class Repository : IEquatable, IRepository public event Action OnRemoteBranchListChanged; public event Action OnRepositoryInfoChanged; + public event Action OnRepositoryInfoCacheChanged; + public event Action OnStatusChanged; /// @@ -43,6 +45,68 @@ public Repository(string name, NPath localPath, ICacheContainer container) User = new User(); cacheContainer = container; + + cacheContainer.CacheInvalidated += CacheContainer_OnCacheInvalidated; + + cacheContainer.CacheUpdated += CacheContainer_OnCacheUpdated; + } + + private void CacheContainer_OnCacheInvalidated(CacheType cacheType) + { + switch (cacheType) + { + case CacheType.BranchCache: + break; + + case CacheType.GitLogCache: + break; + + case CacheType.RepositoryInfoCache: + break; + + case CacheType.GitStatusCache: + break; + + case CacheType.GitLocksCache: + break; + + case CacheType.GitUserCache: + break; + + default: + throw new ArgumentOutOfRangeException(nameof(cacheType), cacheType, null); + } + } + + private void CacheContainer_OnCacheUpdated(CacheType cacheType, DateTimeOffset offset) + { + switch (cacheType) + { + case CacheType.BranchCache: + break; + + case CacheType.GitLogCache: + break; + + case CacheType.RepositoryInfoCache: + OnRepositoryInfoCacheChanged?.Invoke(new UpdateDataEventData + { + UpdatedTimeString = offset.ToString() + }); + break; + + case CacheType.GitStatusCache: + break; + + case CacheType.GitLocksCache: + break; + + case CacheType.GitUserCache: + break; + + default: + throw new ArgumentOutOfRangeException(nameof(cacheType), cacheType, null); + } } public void Initialize(IRepositoryManager initRepositoryManager) @@ -138,6 +202,17 @@ public ITask ReleaseLock(string file, bool force) return repositoryManager.UnlockFile(file, force); } + public void CheckRepositoryInfoCacheEvent(UpdateDataEventData repositoryInfoCacheEvent) + { + if (repositoryInfoCacheEvent.UpdatedTimeString == null) + { + if (cacheContainer.RepositoryInfoCache.LastUpdatedAt != DateTimeOffset.MinValue) + { + + } + } + } + /// /// Note: We don't consider CloneUrl a part of the hash code because it can change during the lifetime /// of a repository. Equals takes care of any hash collisions because of this @@ -452,4 +527,10 @@ public override string ToString() public string Name { get; set; } public string Email { get; set; } } + + [Serializable] + public struct UpdateDataEventData + { + public string UpdatedTimeString; + } } \ No newline at end of file diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs index 160fda4ae..6dab6c878 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs @@ -38,6 +38,9 @@ class Window : BaseWindow [SerializeField] private GUIContent repoBranchContent; [SerializeField] private GUIContent repoUrlContent; + [SerializeField] private UpdateDataEventData repositoryInfoCacheEvent; + [NonSerialized] private bool repositoryInfoCacheHasChanged; + [MenuItem(LaunchMenu)] public static void Window_GitHub() { @@ -90,10 +93,11 @@ public override void OnEnable() #if DEVELOPER_BUILD Selection.activeObject = this; #endif - // Set window title titleContent = new GUIContent(Title, Styles.SmallLogo); + Repository.CheckRepositoryInfoCacheEvent(repositoryInfoCacheEvent); + if (ActiveView != null) ActiveView.OnEnable(); } @@ -240,14 +244,19 @@ private void AttachHandlers(IRepository repository) { if (repository == null) return; - repository.OnRepositoryInfoChanged += RefreshOnMainThread; + repository.OnRepositoryInfoCacheChanged += Repository_RepositoryInfoCacheChanged; } - + + private void Repository_RepositoryInfoCacheChanged(UpdateDataEventData data) + { + repositoryInfoCacheEvent = data; + repositoryInfoCacheHasChanged = true; + } + private void DetachHandlers(IRepository repository) { if (repository == null) return; - repository.OnRepositoryInfoChanged -= RefreshOnMainThread; } private void DoHeaderGUI() From aa92bf0022e51cde680b54fa2b2da8134da1dc47 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Fri, 27 Oct 2017 11:59:30 -0400 Subject: [PATCH 135/241] Cleaning up this logic --- .../Assets/Editor/GitHub.Unity/UI/Window.cs | 49 +++++++------------ 1 file changed, 18 insertions(+), 31 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs index 7c9070d90..6664577cd 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs @@ -188,48 +188,35 @@ private void RefreshOnMainThread() private void MaybeUpdateData() { - string repoRemote = null; - var repoDataChanged = false; + string updatedRepoBranch = null; + string updatedRepoRemote = null; + string updatedRepoUrl = DefaultRepoUrl; + if (Repository != null) { - var currentBranchString = (Repository.CurrentBranch.HasValue ? Repository.CurrentBranch.Value.Name : null); - if (repoBranch != currentBranchString) - { - repoBranch = currentBranchString; - repoDataChanged = true; - } + var repositoryCurrentBranch = Repository.CurrentBranch; + updatedRepoBranch = repositoryCurrentBranch.HasValue ? repositoryCurrentBranch.Value.Name : null; - var url = Repository.CloneUrl != null ? Repository.CloneUrl.ToString() : DefaultRepoUrl; - if (repoUrl != url) - { - repoUrl = url; - repoDataChanged = true; - } + var repositoryCloneUrl = Repository.CloneUrl; + updatedRepoUrl = repositoryCloneUrl != null ? repositoryCloneUrl.ToString() : DefaultRepoUrl; - if (Repository.CurrentRemote.HasValue) - repoRemote = Repository.CurrentRemote.Value.Name; + var repositoryCurrentRemote = Repository.CurrentRemote; + if (repositoryCurrentRemote.HasValue) + updatedRepoRemote = repositoryCurrentRemote.Value.Name; } - else - { - if (repoBranch != null) - { - repoBranch = null; - repoDataChanged = true; - } - if (repoUrl != DefaultRepoUrl) - { - repoUrl = DefaultRepoUrl; - repoDataChanged = true; - } + if (repoBranch != updatedRepoBranch) + { + repoBranch = updatedRepoBranch; + repoBranchContent = new GUIContent(repoBranch, Window_RepoBranchTooltip); } - if (repoDataChanged) + if (repoUrl != updatedRepoUrl) { - repoBranchContent = new GUIContent(repoBranch, Window_RepoBranchTooltip); + repoUrl = updatedRepoUrl; if (repoUrl != null) { - repoUrlContent = new GUIContent(repoUrl, string.Format(Window_RepoUrlTooltip, repoRemote)); + repoUrlContent = new GUIContent(repoUrl, string.Format(Window_RepoUrlTooltip, updatedRepoRemote)); } else { From a97787088cb5062b60c533e47b18d29d05d289ad Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Fri, 27 Oct 2017 12:06:59 -0400 Subject: [PATCH 136/241] Logic error --- src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs index 6664577cd..82ece2823 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs @@ -214,7 +214,7 @@ private void MaybeUpdateData() if (repoUrl != updatedRepoUrl) { repoUrl = updatedRepoUrl; - if (repoUrl != null) + if (updatedRepoRemote != null) { repoUrlContent = new GUIContent(repoUrl, string.Format(Window_RepoUrlTooltip, updatedRepoRemote)); } From 8b260dd85e1d42f362ea7f7cffb19660272842f0 Mon Sep 17 00:00:00 2001 From: Don Okuda Date: Fri, 27 Oct 2017 09:26:36 -0700 Subject: [PATCH 137/241] Remove unneeded spacing --- .../GitHub.Unity/UI/AuthenticationView.cs | 18 ++++++------------ 1 file changed, 6 insertions(+), 12 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/AuthenticationView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/AuthenticationView.cs index d669d738d..0bb15fb25 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/AuthenticationView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/AuthenticationView.cs @@ -65,7 +65,7 @@ public override void OnGUI() } GUILayout.EndHorizontal(); - GUILayout.BeginVertical(Styles.GenericBoxStyle); + GUILayout.BeginVertical(); { if (!need2fa) { @@ -119,7 +119,7 @@ private void OnGUILogin() ShowMessage(); EditorGUILayout.Space(); - + GUILayout.BeginHorizontal(); { username = EditorGUILayout.TextField(UsernameLabel ,username, Styles.TextFieldStyle); @@ -163,17 +163,11 @@ private void OnGUI2FA() EditorGUI.BeginDisabledGroup(isBusy); { - GUILayout.Space(Styles.BaseSpacing); - GUILayout.BeginHorizontal(); - { - two2fa = EditorGUILayout.TextField(TwofaLabel, two2fa, Styles.TextFieldStyle); - } - GUILayout.EndHorizontal(); - - GUILayout.Space(Styles.BaseSpacing); + EditorGUILayout.Space(); + two2fa = EditorGUILayout.TextField(TwofaLabel, two2fa, Styles.TextFieldStyle); + EditorGUILayout.Space(); ShowErrorMessage(); - GUILayout.Space(Styles.BaseSpacing); GUILayout.BeginHorizontal(); { GUILayout.FlexibleSpace(); @@ -193,7 +187,7 @@ private void OnGUI2FA() } GUILayout.EndHorizontal(); - GUILayout.Space(Styles.BaseSpacing); + EditorGUILayout.Space(); } EditorGUI.EndDisabledGroup(); } From 1b9b4703844feb81abfe6fd84cee8c322bf458e0 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Fri, 27 Oct 2017 15:06:24 -0400 Subject: [PATCH 138/241] Integrating the few Window displays with the cache notification system --- src/GitHub.Api/Git/Repository.cs | 31 +++++-- .../Editor/GitHub.Unity/ApplicationCache.cs | 4 - .../Assets/Editor/GitHub.Unity/UI/Window.cs | 87 ++++++++++++++----- 3 files changed, 89 insertions(+), 33 deletions(-) diff --git a/src/GitHub.Api/Git/Repository.cs b/src/GitHub.Api/Git/Repository.cs index b164e7932..06c4e76c4 100644 --- a/src/GitHub.Api/Git/Repository.cs +++ b/src/GitHub.Api/Git/Repository.cs @@ -89,10 +89,7 @@ private void CacheContainer_OnCacheUpdated(CacheType cacheType, DateTimeOffset o break; case CacheType.RepositoryInfoCache: - OnRepositoryInfoCacheChanged?.Invoke(new UpdateDataEventData - { - UpdatedTimeString = offset.ToString() - }); + FireOnRepositoryInfoCacheChanged(offset); break; case CacheType.GitStatusCache: @@ -109,6 +106,12 @@ private void CacheContainer_OnCacheUpdated(CacheType cacheType, DateTimeOffset o } } + private void FireOnRepositoryInfoCacheChanged(DateTimeOffset dateTimeOffset) + { + Logger.Trace("OnRepositoryInfoCacheChanged {0}", dateTimeOffset); + OnRepositoryInfoCacheChanged?.Invoke(new UpdateDataEventData { UpdatedTimeString = dateTimeOffset.ToString() }); + } + public void Initialize(IRepositoryManager initRepositoryManager) { Guard.ArgumentNotNull(initRepositoryManager, nameof(initRepositoryManager)); @@ -204,12 +207,24 @@ public ITask ReleaseLock(string file, bool force) public void CheckRepositoryInfoCacheEvent(UpdateDataEventData repositoryInfoCacheEvent) { + bool raiseEvent; if (repositoryInfoCacheEvent.UpdatedTimeString == null) { - if (cacheContainer.RepositoryInfoCache.LastUpdatedAt != DateTimeOffset.MinValue) - { - - } + raiseEvent = cacheContainer.RepositoryInfoCache.LastUpdatedAt != DateTimeOffset.MinValue; + } + else + { + raiseEvent = cacheContainer.RepositoryInfoCache.LastUpdatedAt.ToString() != repositoryInfoCacheEvent.UpdatedTimeString; + } + + Logger.Trace("CheckRepositoryInfoCacheEvent Current:{0} Check:{1} Result:{2}", + cacheContainer.RepositoryInfoCache.LastUpdatedAt, + repositoryInfoCacheEvent.UpdatedTimeString ?? "[NULL]", + raiseEvent); + + if (raiseEvent) + { + FireOnRepositoryInfoCacheChanged(cacheContainer.RepositoryInfoCache.LastUpdatedAt); } } diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs index 22493e906..0a7a16049 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs @@ -358,7 +358,6 @@ public ConfigRemote? CurrentConfigRemote { get { - Logger.Trace("Get CurrentConfigRemote"); ValidateData(); return gitConfigRemote.Equals(DefaultConfigRemote) ? (ConfigRemote?) null : gitConfigRemote; } @@ -383,7 +382,6 @@ public ConfigBranch? CurentConfigBranch { get { - Logger.Trace("Get CurentConfigBranch"); ValidateData(); return gitConfigBranch.Equals(DefaultConfigBranch) ? (ConfigBranch?) null : gitConfigBranch; } @@ -408,7 +406,6 @@ public GitRemote? CurrentGitRemote { get { - Logger.Trace("Get CurrentGitRemote"); ValidateData(); return gitRemote.Equals(DefaultGitRemote) ? (GitRemote?) null : gitRemote; } @@ -433,7 +430,6 @@ public GitBranch? CurentGitBranch { get { - Logger.Trace("Get CurentConfigBranch"); ValidateData(); return gitBranch.Equals(DefaultGitBranch) ? (GitBranch?)null : gitBranch; } diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs index b0cb506b1..2220ea719 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs @@ -33,6 +33,7 @@ class Window : BaseWindow [SerializeField] private HistoryView historyView = new HistoryView(); [SerializeField] private SettingsView settingsView = new SettingsView(); + [SerializeField] private string repoRemote; [SerializeField] private string repoBranch; [SerializeField] private string repoUrl; [SerializeField] private GUIContent repoBranchContent; @@ -40,6 +41,7 @@ class Window : BaseWindow [SerializeField] private UpdateDataEventData repositoryInfoCacheEvent; [NonSerialized] private bool repositoryInfoCacheHasChanged; + [NonSerialized] private bool hasMaybeUpdateDataWithRepository; [MenuItem(LaunchMenu)] public static void Window_GitHub() @@ -96,7 +98,8 @@ public override void OnEnable() // Set window title titleContent = new GUIContent(Title, Styles.SmallLogo); - Repository.CheckRepositoryInfoCacheEvent(repositoryInfoCacheEvent); + if (Repository != null) + Repository.CheckRepositoryInfoCacheEvent(repositoryInfoCacheEvent); if (ActiveView != null) ActiveView.OnEnable(); @@ -183,39 +186,76 @@ public override void Update() } } - private void RefreshOnMainThread() - { - new ActionTask(TaskManager.Token, Refresh) { Affinity = TaskAffinity.UI }.Start(); - } - private void MaybeUpdateData() { string updatedRepoBranch = null; string updatedRepoRemote = null; string updatedRepoUrl = DefaultRepoUrl; + var shouldUpdateContentFields = false; + if (Repository != null) { - var repositoryCurrentBranch = Repository.CurrentBranch; - updatedRepoBranch = repositoryCurrentBranch.HasValue ? repositoryCurrentBranch.Value.Name : null; + if(!hasMaybeUpdateDataWithRepository || repositoryInfoCacheHasChanged) + { + hasMaybeUpdateDataWithRepository = true; - var repositoryCloneUrl = Repository.CloneUrl; - updatedRepoUrl = repositoryCloneUrl != null ? repositoryCloneUrl.ToString() : DefaultRepoUrl; + var repositoryCurrentBranch = Repository.CurrentBranch; + updatedRepoBranch = repositoryCurrentBranch.HasValue ? repositoryCurrentBranch.Value.Name : null; - var repositoryCurrentRemote = Repository.CurrentRemote; - if (repositoryCurrentRemote.HasValue) - updatedRepoRemote = repositoryCurrentRemote.Value.Name; - } + var repositoryCloneUrl = Repository.CloneUrl; + updatedRepoUrl = repositoryCloneUrl != null ? repositoryCloneUrl.ToString() : DefaultRepoUrl; - if (repoBranch != updatedRepoBranch) + var repositoryCurrentRemote = Repository.CurrentRemote; + if (repositoryCurrentRemote.HasValue) + { + updatedRepoRemote = repositoryCurrentRemote.Value.Name; + } + + if (repoRemote != updatedRepoRemote) + { + repoRemote = updatedRepoBranch; + shouldUpdateContentFields = true; + } + + if (repoBranch != updatedRepoBranch) + { + repoBranch = updatedRepoBranch; + shouldUpdateContentFields = true; + } + + if (repoUrl != updatedRepoUrl) + { + repoUrl = updatedRepoUrl; + shouldUpdateContentFields = true; + } + } + } + else { - repoBranch = updatedRepoBranch; - repoBranchContent = new GUIContent(repoBranch, Window_RepoBranchTooltip); + if (repoRemote != null) + { + repoRemote = null; + shouldUpdateContentFields = true; + } + + if (repoBranch != null) + { + repoBranch = null; + shouldUpdateContentFields = true; + } + + if (repoUrl != DefaultRepoUrl) + { + repoUrl = DefaultRepoUrl; + shouldUpdateContentFields = true; + } } - if (repoUrl != updatedRepoUrl) + if (shouldUpdateContentFields) { - repoUrl = updatedRepoUrl; + repoBranchContent = new GUIContent(repoBranch, Window_RepoBranchTooltip); + if (updatedRepoRemote != null) { repoUrlContent = new GUIContent(repoUrl, string.Format(Window_RepoUrlTooltip, updatedRepoRemote)); @@ -236,14 +276,19 @@ private void AttachHandlers(IRepository repository) private void Repository_RepositoryInfoCacheChanged(UpdateDataEventData data) { - repositoryInfoCacheEvent = data; - repositoryInfoCacheHasChanged = true; + new ActionTask(TaskManager.Token, () => { + repositoryInfoCacheEvent = data; + repositoryInfoCacheHasChanged = true; + Redraw(); + }) { Affinity = TaskAffinity.UI }.Start(); } private void DetachHandlers(IRepository repository) { if (repository == null) return; + + repository.OnRepositoryInfoCacheChanged -= Repository_RepositoryInfoCacheChanged; } private void DoHeaderGUI() From 54c55aa63027b6d1cea24195fb89f761701ccdaf Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Fri, 27 Oct 2017 16:24:01 -0400 Subject: [PATCH 139/241] Changing a nullable GitStatus operations to non nullable --- src/GitHub.Api/Git/GitClient.cs | 4 ++-- src/GitHub.Api/Git/RepositoryManager.cs | 6 +++--- src/GitHub.Api/Git/Tasks/GitStatusTask.cs | 4 ++-- src/GitHub.Api/OutputProcessors/StatusOutputProcessor.cs | 2 +- src/tests/IntegrationTests/ProcessManagerExtensions.cs | 4 ++-- .../Substitutes/CreateRepositoryProcessRunnerOptions.cs | 4 ++-- src/tests/TestUtils/Substitutes/SubstituteFactory.cs | 9 ++++----- src/tests/UnitTests/ProcessManagerExtensions.cs | 4 ++-- 8 files changed, 18 insertions(+), 19 deletions(-) diff --git a/src/GitHub.Api/Git/GitClient.cs b/src/GitHub.Api/Git/GitClient.cs index faca75d12..12d9bf78b 100644 --- a/src/GitHub.Api/Git/GitClient.cs +++ b/src/GitHub.Api/Git/GitClient.cs @@ -15,7 +15,7 @@ public interface IGitClient ITask LfsInstall(IOutputProcessor processor = null); - ITask Status(IOutputProcessor processor = null); + ITask Status(IOutputProcessor processor = null); ITask GetConfig(string key, GitConfigSource configSource, IOutputProcessor processor = null); @@ -207,7 +207,7 @@ public ITask LfsInstall(IOutputProcessor processor = null) .Configure(processManager); } - public ITask Status(IOutputProcessor processor = null) + public ITask Status(IOutputProcessor processor = null) { Logger.Trace("Status"); diff --git a/src/GitHub.Api/Git/RepositoryManager.cs b/src/GitHub.Api/Git/RepositoryManager.cs index 7a4e20426..e241459a3 100644 --- a/src/GitHub.Api/Git/RepositoryManager.cs +++ b/src/GitHub.Api/Git/RepositoryManager.cs @@ -397,10 +397,10 @@ private void UpdateGitStatus() var task = GitClient.Status() .Finally((success, ex, data) => { - Logger.Trace($"GitStatus update: {success} {(data.HasValue ? data.Value.ToString() : "[null]")}"); - if (success && data.HasValue) + Logger.Trace($"GitStatus update: {success} {data}"); + if (success) { - OnStatusUpdated?.Invoke(data.Value); + OnStatusUpdated?.Invoke(data); Logger.Trace("Updated Git Status"); } }); diff --git a/src/GitHub.Api/Git/Tasks/GitStatusTask.cs b/src/GitHub.Api/Git/Tasks/GitStatusTask.cs index e8ee0bf8f..da66e2c98 100644 --- a/src/GitHub.Api/Git/Tasks/GitStatusTask.cs +++ b/src/GitHub.Api/Git/Tasks/GitStatusTask.cs @@ -2,12 +2,12 @@ namespace GitHub.Unity { - class GitStatusTask : ProcessTask + class GitStatusTask : ProcessTask { private const string TaskName = "git status"; public GitStatusTask(IGitObjectFactory gitObjectFactory, - CancellationToken token, IOutputProcessor processor = null) + CancellationToken token, IOutputProcessor processor = null) : base(token, processor ?? new StatusOutputProcessor(gitObjectFactory)) { Name = TaskName; diff --git a/src/GitHub.Api/OutputProcessors/StatusOutputProcessor.cs b/src/GitHub.Api/OutputProcessors/StatusOutputProcessor.cs index a2629893f..1b95daca4 100644 --- a/src/GitHub.Api/OutputProcessors/StatusOutputProcessor.cs +++ b/src/GitHub.Api/OutputProcessors/StatusOutputProcessor.cs @@ -5,7 +5,7 @@ namespace GitHub.Unity { - class StatusOutputProcessor : BaseOutputProcessor + class StatusOutputProcessor : BaseOutputProcessor { private static readonly Regex branchTrackedAndDelta = new Regex(@"(.*)\.\.\.(.*)\s\[(.*)\]", RegexOptions.Compiled); diff --git a/src/tests/IntegrationTests/ProcessManagerExtensions.cs b/src/tests/IntegrationTests/ProcessManagerExtensions.cs index 0ddfc0e68..281b5002d 100644 --- a/src/tests/IntegrationTests/ProcessManagerExtensions.cs +++ b/src/tests/IntegrationTests/ProcessManagerExtensions.cs @@ -44,7 +44,7 @@ public static ITask> GetGitLogEntries(this IProcessManager pro .Configure(processManager, path, logNameStatus, workingDirectory, false); } - public static ITask GetGitStatus(this IProcessManager processManager, + public static ITask GetGitStatus(this IProcessManager processManager, NPath workingDirectory, IEnvironment environment, IProcessEnvironment gitEnvironment, NPath gitPath = null) @@ -54,7 +54,7 @@ public static ITask> GetGitLogEntries(this IProcessManager pro NPath path = gitPath ?? defaultGitPath; - return new ProcessTask(CancellationToken.None, processor) + return new ProcessTask(CancellationToken.None, processor) .Configure(processManager, path, "status -b -u --porcelain", workingDirectory, false); } diff --git a/src/tests/TestUtils/Substitutes/CreateRepositoryProcessRunnerOptions.cs b/src/tests/TestUtils/Substitutes/CreateRepositoryProcessRunnerOptions.cs index 0d60f4cd0..7b0d8e91f 100644 --- a/src/tests/TestUtils/Substitutes/CreateRepositoryProcessRunnerOptions.cs +++ b/src/tests/TestUtils/Substitutes/CreateRepositoryProcessRunnerOptions.cs @@ -7,12 +7,12 @@ class CreateRepositoryProcessRunnerOptions { public Dictionary GitConfigGetResults { get; set; } - public GitStatus? GitStatusResults { get; set; } + public GitStatus GitStatusResults { get; set; } public List GitListLocksResults { get; set; } public CreateRepositoryProcessRunnerOptions(Dictionary getConfigResults = null, - GitStatus? gitStatusResults = null, + GitStatus gitStatusResults = new GitStatus(), List gitListLocksResults = null) { GitListLocksResults = gitListLocksResults; diff --git a/src/tests/TestUtils/Substitutes/SubstituteFactory.cs b/src/tests/TestUtils/Substitutes/SubstituteFactory.cs index be5929f17..49b82fc1f 100644 --- a/src/tests/TestUtils/Substitutes/SubstituteFactory.cs +++ b/src/tests/TestUtils/Substitutes/SubstituteFactory.cs @@ -411,13 +411,12 @@ public IGitClient CreateRepositoryProcessRunner( }); gitClient.Status().Returns(info => { - GitStatus? result = options.GitStatusResults; - - var ret = new FuncTask(CancellationToken.None, _ => result); + var result = options.GitStatusResults; + var ret = new FuncTask(CancellationToken.None, _ => result); logger.Trace(@"RunGitStatus() -> {0}", - result != null ? $"Success: \"{result.Value}\"" : "Failure"); - var task = Args.GitStatusTask; + $"Success: \"{result}\""); + return ret; }); diff --git a/src/tests/UnitTests/ProcessManagerExtensions.cs b/src/tests/UnitTests/ProcessManagerExtensions.cs index 6833ec273..5a0820b8a 100644 --- a/src/tests/UnitTests/ProcessManagerExtensions.cs +++ b/src/tests/UnitTests/ProcessManagerExtensions.cs @@ -62,12 +62,12 @@ public static async Task GetGitStatus(this ProcessManager processMana NPath path = gitPath ?? defaultGitPath; - var results = await new ProcessTask(CancellationToken.None, processor) + var results = await new ProcessTask(CancellationToken.None, processor) .Configure(processManager, path, "status -b -u --porcelain", workingDirectory, false) .Start() .Task; - return results.Value; + return results; } public static async Task> GetGitRemoteEntries(this ProcessManager processManager, From 51d37b325952a9057e689334e6c002332700eb57 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Fri, 27 Oct 2017 17:00:54 -0400 Subject: [PATCH 140/241] Removing log from CacheContainer constructor --- .../Assets/Editor/GitHub.Unity/CacheContainer.cs | 6 ------ 1 file changed, 6 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/CacheContainer.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/CacheContainer.cs index 98e89c5a1..fd8bbf64f 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/CacheContainer.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/CacheContainer.cs @@ -22,12 +22,6 @@ public class CacheContainer : ICacheContainer public event Action CacheUpdated; - public CacheContainer() - { - var t = new System.Diagnostics.StackTrace(); - Logger.Trace("Constructing: {0}", t.ToString()); - } - private IManagedCache GetManagedCache(CacheType cacheType) { switch (cacheType) From fcb9481dc7379221a83c1b290835f0c578f795b8 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Fri, 27 Oct 2017 17:06:52 -0400 Subject: [PATCH 141/241] Removing unused logger --- src/UnityExtension/Assets/Editor/GitHub.Unity/CacheContainer.cs | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/CacheContainer.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/CacheContainer.cs index fd8bbf64f..ddfb111d3 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/CacheContainer.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/CacheContainer.cs @@ -4,8 +4,6 @@ namespace GitHub.Unity { public class CacheContainer : ICacheContainer { - private static ILogging Logger = Logging.GetLogger(); - private IBranchCache branchCache; private IGitLocksCache gitLocksCache; From aca36638c9775875d3f1f23180e737383bb771ee Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Fri, 27 Oct 2017 18:04:52 -0400 Subject: [PATCH 142/241] Attaching and detaching handlers at the right time --- .../Assets/Editor/GitHub.Unity/UI/BranchesView.cs | 8 -------- .../Assets/Editor/GitHub.Unity/UI/ChangesView.cs | 14 +++++++++++++- .../Assets/Editor/GitHub.Unity/UI/HistoryView.cs | 3 --- .../Assets/Editor/GitHub.Unity/UI/SettingsView.cs | 9 --------- 4 files changed, 13 insertions(+), 21 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs index 8c00a6f63..10f40ada1 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs @@ -88,18 +88,10 @@ private void MaybeUpdateData() } } - public override void OnRepositoryChanged(IRepository oldRepository) - { - base.OnRepositoryChanged(oldRepository); - DetachHandlers(oldRepository); - AttachHandlers(Repository); - } - private void AttachHandlers(IRepository repository) { if (repository == null) return; - repository.OnLocalBranchListChanged += RunUpdateBranchesOnMainThread; repository.OnCurrentBranchChanged += HandleRepositoryBranchChangeEvent; repository.OnCurrentRemoteChanged += HandleRepositoryBranchChangeEvent; diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ChangesView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ChangesView.cs index 2c560ef44..d2722d168 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ChangesView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ChangesView.cs @@ -40,13 +40,25 @@ public override void OnEnable() return; OnStatusUpdate(Repository.CurrentStatus); - Repository.OnStatusChanged += RunStatusUpdateOnMainThread; + AttachHandlers(Repository); Repository.Refresh(); } public override void OnDisable() { base.OnDisable(); + DetachHandlers(); + } + + private void AttachHandlers(IRepository repository) + { + if (repository == null) + return; + repository.OnStatusChanged += RunStatusUpdateOnMainThread; + } + + private void DetachHandlers() + { if (Repository == null) return; Repository.OnStatusChanged -= RunStatusUpdateOnMainThread; diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/HistoryView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/HistoryView.cs index 14e803c78..b5760279e 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/HistoryView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/HistoryView.cs @@ -87,9 +87,6 @@ public override void OnDataUpdate() public override void OnRepositoryChanged(IRepository oldRepository) { base.OnRepositoryChanged(oldRepository); - - DetachHandlers(oldRepository); - AttachHandlers(Repository); } public override void OnSelectionChange() diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/SettingsView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/SettingsView.cs index 731fe401b..0446adc08 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/SettingsView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/SettingsView.cs @@ -82,13 +82,6 @@ public override void OnRepositoryChanged(IRepository oldRepository) base.OnRepositoryChanged(oldRepository); gitPathView.OnRepositoryChanged(oldRepository); userSettingsView.OnRepositoryChanged(oldRepository); - - DetachHandlers(oldRepository); - AttachHandlers(Repository); - - remoteHasChanged = true; - - Refresh(); } public override void Refresh() @@ -106,7 +99,6 @@ private void AttachHandlers(IRepository repository) { if (repository == null) return; - repository.OnCurrentRemoteChanged += Repository_OnActiveRemoteChanged; repository.OnLocksChanged += RunLocksUpdateOnMainThread; } @@ -115,7 +107,6 @@ private void DetachHandlers(IRepository repository) { if (repository == null) return; - repository.OnCurrentRemoteChanged -= Repository_OnActiveRemoteChanged; repository.OnLocksChanged -= RunLocksUpdateOnMainThread; } From f99cf4634af69fe73404c88658db793f5cf54fff Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Fri, 27 Oct 2017 18:11:15 -0400 Subject: [PATCH 143/241] Making Repository a parameter for DetachHandlers --- .../Assets/Editor/GitHub.Unity/UI/ChangesView.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ChangesView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ChangesView.cs index d2722d168..082312a4c 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ChangesView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ChangesView.cs @@ -47,7 +47,7 @@ public override void OnEnable() public override void OnDisable() { base.OnDisable(); - DetachHandlers(); + DetachHandlers(Repository); } private void AttachHandlers(IRepository repository) @@ -57,11 +57,11 @@ private void AttachHandlers(IRepository repository) repository.OnStatusChanged += RunStatusUpdateOnMainThread; } - private void DetachHandlers() + private void DetachHandlers(IRepository oldRepository) { - if (Repository == null) + if (oldRepository == null) return; - Repository.OnStatusChanged -= RunStatusUpdateOnMainThread; + oldRepository.OnStatusChanged -= RunStatusUpdateOnMainThread; } private void RunStatusUpdateOnMainThread(GitStatus status) From f57da7a9cd29e101e013e71a287a633687b7ca69 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Fri, 27 Oct 2017 18:20:34 -0400 Subject: [PATCH 144/241] Populating GitStatus through cache --- src/GitHub.Api/Cache/CacheInterfaces.cs | 2 +- src/GitHub.Api/Git/IRepository.cs | 7 +- src/GitHub.Api/Git/Repository.cs | 85 ++++++++++++++----- src/GitHub.Api/Git/RepositoryManager.cs | 34 +++----- .../Editor/GitHub.Unity/ApplicationCache.cs | 15 ++++ .../Editor/GitHub.Unity/UI/ChangesView.cs | 84 ++++++++++++------ .../Editor/GitHub.Unity/UI/HistoryView.cs | 5 +- .../GitHub.Unity/UI/ProjectWindowInterface.cs | 3 +- .../Events/RepositoryManagerTests.cs | 14 +-- .../TestUtils/Events/IRepositoryListener.cs | 13 +-- .../Events/IRepositoryManagerListener.cs | 11 +-- 11 files changed, 178 insertions(+), 95 deletions(-) diff --git a/src/GitHub.Api/Cache/CacheInterfaces.cs b/src/GitHub.Api/Cache/CacheInterfaces.cs index a900bc30e..96867f879 100644 --- a/src/GitHub.Api/Cache/CacheInterfaces.cs +++ b/src/GitHub.Api/Cache/CacheInterfaces.cs @@ -63,7 +63,7 @@ public interface IGitUserCache : IManagedCache, IGitUser public interface IGitStatus { - GitStatus GitStatus { get; } + GitStatus GitStatus { get; set; } } public interface IGitStatusCache : IManagedCache, IGitStatus diff --git a/src/GitHub.Api/Git/IRepository.cs b/src/GitHub.Api/Git/IRepository.cs index e482dd28f..fe23b0ef7 100644 --- a/src/GitHub.Api/Git/IRepository.cs +++ b/src/GitHub.Api/Git/IRepository.cs @@ -22,8 +22,9 @@ public interface IRepository : IEquatable ITask RequestLock(string file); ITask ReleaseLock(string file, bool force); - void CheckRepositoryInfoCacheEvent(UpdateDataEventData repositoryInfoCacheEvent); - + void CheckRepositoryInfoCacheEvent(UpdateDataEventData updateDataEventData); + void CheckGitStatusCacheEvent(UpdateDataEventData gitStatusCacheEvent); + /// /// Gets the name of the repository. /// @@ -60,7 +61,6 @@ public interface IRepository : IEquatable IList CurrentLocks { get; } string CurrentBranchName { get; } - event Action OnStatusChanged; event Action OnCurrentBranchChanged; event Action OnCurrentRemoteChanged; event Action OnLocalBranchListChanged; @@ -69,5 +69,6 @@ public interface IRepository : IEquatable event Action OnRepositoryInfoChanged; event Action OnRemoteBranchListChanged; event Action OnRepositoryInfoCacheChanged; + event Action OnGitStatusCacheChanged; } } \ No newline at end of file diff --git a/src/GitHub.Api/Git/Repository.cs b/src/GitHub.Api/Git/Repository.cs index 06c4e76c4..9f3f08301 100644 --- a/src/GitHub.Api/Git/Repository.cs +++ b/src/GitHub.Api/Git/Repository.cs @@ -11,7 +11,6 @@ namespace GitHub.Unity class Repository : IEquatable, IRepository { private IList currentLocks; - private GitStatus currentStatus; private Dictionary localBranches = new Dictionary(); private Dictionary> remoteBranches = new Dictionary>(); private Dictionary remotes; @@ -26,8 +25,7 @@ class Repository : IEquatable, IRepository public event Action OnRepositoryInfoChanged; public event Action OnRepositoryInfoCacheChanged; - - public event Action OnStatusChanged; + public event Action OnGitStatusCacheChanged; /// /// Initializes a new instance of the class. @@ -93,6 +91,7 @@ private void CacheContainer_OnCacheUpdated(CacheType cacheType, DateTimeOffset o break; case CacheType.GitStatusCache: + FireOnGitStatusCacheChanged(offset); break; case CacheType.GitLocksCache: @@ -112,14 +111,21 @@ private void FireOnRepositoryInfoCacheChanged(DateTimeOffset dateTimeOffset) OnRepositoryInfoCacheChanged?.Invoke(new UpdateDataEventData { UpdatedTimeString = dateTimeOffset.ToString() }); } + private void FireOnGitStatusCacheChanged(DateTimeOffset dateTimeOffset) + { + Logger.Trace("OnGitStatusCacheChanged {0}", dateTimeOffset); + OnGitStatusCacheChanged?.Invoke(new UpdateDataEventData { UpdatedTimeString = dateTimeOffset.ToString() }); + } + public void Initialize(IRepositoryManager initRepositoryManager) { + Logger.Trace("Initialize"); Guard.ArgumentNotNull(initRepositoryManager, nameof(initRepositoryManager)); repositoryManager = initRepositoryManager; repositoryManager.OnCurrentBranchUpdated += RepositoryManager_OnCurrentBranchUpdated; repositoryManager.OnCurrentRemoteUpdated += RepositoryManager_OnCurrentRemoteUpdated; - repositoryManager.OnStatusUpdated += status => CurrentStatus = status; + repositoryManager.OnRepositoryUpdated += RepositoryManager_OnRepositoryUpdated; repositoryManager.OnLocksUpdated += locks => CurrentLocks = locks; repositoryManager.OnLocalBranchListUpdated += RepositoryManager_OnLocalBranchListUpdated; repositoryManager.OnRemoteBranchListUpdated += RepositoryManager_OnRemoteBranchListUpdated; @@ -129,6 +135,8 @@ public void Initialize(IRepositoryManager initRepositoryManager) repositoryManager.OnRemoteBranchAdded += RepositoryManager_OnRemoteBranchAdded; repositoryManager.OnRemoteBranchRemoved += RepositoryManager_OnRemoteBranchRemoved; repositoryManager.OnGitUserLoaded += user => User = user; + + UpdateGitStatus(); } public void Refresh() @@ -205,26 +213,53 @@ public ITask ReleaseLock(string file, bool force) return repositoryManager.UnlockFile(file, force); } - public void CheckRepositoryInfoCacheEvent(UpdateDataEventData repositoryInfoCacheEvent) + public void CheckRepositoryInfoCacheEvent(UpdateDataEventData updateDataEventData) { bool raiseEvent; - if (repositoryInfoCacheEvent.UpdatedTimeString == null) + IManagedCache managedCache = cacheContainer.RepositoryInfoCache; + + if (updateDataEventData.UpdatedTimeString == null) { - raiseEvent = cacheContainer.RepositoryInfoCache.LastUpdatedAt != DateTimeOffset.MinValue; + raiseEvent = managedCache.LastUpdatedAt != DateTimeOffset.MinValue; } else { - raiseEvent = cacheContainer.RepositoryInfoCache.LastUpdatedAt.ToString() != repositoryInfoCacheEvent.UpdatedTimeString; + raiseEvent = managedCache.LastUpdatedAt.ToString() != updateDataEventData.UpdatedTimeString; } Logger.Trace("CheckRepositoryInfoCacheEvent Current:{0} Check:{1} Result:{2}", - cacheContainer.RepositoryInfoCache.LastUpdatedAt, - repositoryInfoCacheEvent.UpdatedTimeString ?? "[NULL]", + managedCache.LastUpdatedAt, + updateDataEventData.UpdatedTimeString ?? "[NULL]", raiseEvent); if (raiseEvent) { - FireOnRepositoryInfoCacheChanged(cacheContainer.RepositoryInfoCache.LastUpdatedAt); + FireOnRepositoryInfoCacheChanged(managedCache.LastUpdatedAt); + } + } + + public void CheckGitStatusCacheEvent(UpdateDataEventData updateDataEventData) + { + bool raiseEvent; + IManagedCache managedCache = cacheContainer.GitStatusCache; + + if (updateDataEventData.UpdatedTimeString == null) + { + raiseEvent = managedCache.LastUpdatedAt != DateTimeOffset.MinValue; + } + else + { + raiseEvent = managedCache.LastUpdatedAt.ToString() != updateDataEventData.UpdatedTimeString; + } + + Logger.Trace("CheckGitStatusCacheEvent Current:{0} Check:{1} Result:{2}", + managedCache.LastUpdatedAt, + updateDataEventData.UpdatedTimeString ?? "[NULL]", + raiseEvent); + + if (raiseEvent) + { + FireOnGitStatusCacheChanged(managedCache.LastUpdatedAt); } } @@ -272,6 +307,17 @@ private void RepositoryManager_OnCurrentRemoteUpdated(ConfigRemote? remote) } } + private void RepositoryManager_OnRepositoryUpdated() + { + Logger.Trace("OnRepositoryUpdated"); + UpdateGitStatus(); + } + + private void UpdateGitStatus() + { + repositoryManager?.Status().ThenInUI((b, status) => { CurrentStatus = status; }).Start(); + } + private void RepositoryManager_OnCurrentBranchUpdated(ConfigBranch? branch) { if (!Nullable.Equals(CurrentConfigBranch, branch)) @@ -471,6 +517,12 @@ private ConfigRemote? CurrentConfigRemote } } + public GitStatus CurrentStatus + { + get { return cacheContainer.GitStatusCache.GitStatus; } + set { cacheContainer.GitStatusCache.GitStatus = value; } + } + public GitBranch? CurrentBranch => cacheContainer.RepositoryInfoCache.CurentGitBranch; public string CurrentBranchName => CurrentConfigBranch?.Name; @@ -498,17 +550,6 @@ private ConfigRemote? CurrentConfigRemote CurrentBranch, CurrentRemote); - public GitStatus CurrentStatus - { - get { return currentStatus; } - private set - { - currentStatus = value; - Logger.Trace("OnStatusChanged: {0}", value.ToString()); - OnStatusChanged?.Invoke(value); - } - } - public IUser User { get; set; } public IList CurrentLocks diff --git a/src/GitHub.Api/Git/RepositoryManager.cs b/src/GitHub.Api/Git/RepositoryManager.cs index e52ec1beb..18f74fe1c 100644 --- a/src/GitHub.Api/Git/RepositoryManager.cs +++ b/src/GitHub.Api/Git/RepositoryManager.cs @@ -19,7 +19,7 @@ public interface IRepositoryManager : IDisposable event Action OnRemoteBranchAdded; event Action, Dictionary>> OnRemoteBranchListUpdated; event Action OnRemoteBranchRemoved; - event Action OnStatusUpdated; + event Action OnRepositoryUpdated; void Initialize(); void Start(); @@ -28,6 +28,7 @@ public interface IRepositoryManager : IDisposable ITask CommitAllFiles(string message, string body); ITask CommitFiles(List files, string message, string body); ITask> Log(); + ITask Status(); ITask Fetch(string remote); ITask Pull(string remote, string branch); ITask Push(string remote, string branch); @@ -114,7 +115,7 @@ class RepositoryManager : IRepositoryManager public event Action OnRemoteBranchAdded; public event Action, Dictionary>> OnRemoteBranchListUpdated; public event Action OnRemoteBranchRemoved; - public event Action OnStatusUpdated; + public event Action OnRepositoryUpdated; public RepositoryManager(IPlatform platform, ITaskManager taskManager, IGitConfig gitConfig, IRepositoryWatcher repositoryWatcher, IGitClient gitClient, @@ -178,7 +179,6 @@ public int WaitForEvents() public void Refresh() { Logger.Trace("Refresh"); - UpdateGitStatus(); } public ITask CommitAllFiles(string message, string body) @@ -206,6 +206,13 @@ public ITask> Log() return task; } + public ITask Status() + { + var task = GitClient.Status(); + HookupHandlers(task); + return task; + } + public ITask Fetch(string remote) { var task = GitClient.Fetch(remote); @@ -387,25 +394,7 @@ private void Watcher_OnRemoteBranchCreated(string remote, string name) private void Watcher_OnRepositoryChanged() { Logger.Trace("OnRepositoryChanged"); - UpdateGitStatus(); - } - - private void UpdateGitStatus() - { - Logger.Trace("Updating Git Status"); - - var task = GitClient.Status() - .Finally((success, ex, data) => - { - Logger.Trace($"GitStatus update: {success} {data}"); - if (success) - { - OnStatusUpdated?.Invoke(data); - Logger.Trace("Updated Git Status"); - } - }); - - HookupHandlers(task).Start(); + OnRepositoryUpdated?.Invoke(); } private void Watcher_OnConfigChanged() @@ -417,7 +406,6 @@ private void Watcher_OnHeadChanged() { Logger.Trace("Watcher_OnHeadChanged"); UpdateHead(); - UpdateGitStatus(); } private void UpdateCurrentBranchAndRemote(string head) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs index 0a7a16049..e9da84ebc 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs @@ -533,6 +533,21 @@ public GitStatus GitStatus ValidateData(); return status; } + set + { + var now = DateTimeOffset.Now; + var isUpdated = false; + + Logger.Trace("Updating: {0} gitStatus:{1}", now, value); + + if (!status.Equals(value)) + { + status = value; + isUpdated = true; + } + + SaveData(now, isUpdated); + } } protected override void OnResetData() diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ChangesView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ChangesView.cs index 082312a4c..9a84c3ce0 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ChangesView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ChangesView.cs @@ -27,64 +27,94 @@ class ChangesView : Subview [SerializeField] private Vector2 horizontalScroll; [SerializeField] private ChangesetTreeView tree = new ChangesetTreeView(); + [SerializeField] private UpdateDataEventData repositoryInfoCacheEvent; + [NonSerialized] private bool repositoryInfoCacheHasChanged; + + [SerializeField] private UpdateDataEventData gitStatusCacheEvent; + [NonSerialized] private bool gitStatusCacheHasChanged; + public override void InitializeView(IView parent) { base.InitializeView(parent); tree.InitializeView(this); } - public override void OnEnable() + private void Repository_GitStatusCacheChanged(UpdateDataEventData data) { - base.OnEnable(); - if (Repository == null) - return; - - OnStatusUpdate(Repository.CurrentStatus); - AttachHandlers(Repository); - Repository.Refresh(); + new ActionTask(TaskManager.Token, () => { + gitStatusCacheEvent = data; + gitStatusCacheHasChanged = true; + Redraw(); + }) + { Affinity = TaskAffinity.UI }.Start(); } - public override void OnDisable() + private void Repository_RepositoryInfoCacheChanged(UpdateDataEventData data) { - base.OnDisable(); - DetachHandlers(Repository); + new ActionTask(TaskManager.Token, () => { + repositoryInfoCacheEvent = data; + repositoryInfoCacheHasChanged = true; + Redraw(); + }) + { Affinity = TaskAffinity.UI }.Start(); } private void AttachHandlers(IRepository repository) { if (repository == null) return; - repository.OnStatusChanged += RunStatusUpdateOnMainThread; + repository.OnRepositoryInfoCacheChanged += Repository_RepositoryInfoCacheChanged; + repository.OnGitStatusCacheChanged += Repository_GitStatusCacheChanged; } private void DetachHandlers(IRepository oldRepository) { if (oldRepository == null) return; - oldRepository.OnStatusChanged -= RunStatusUpdateOnMainThread; - } - private void RunStatusUpdateOnMainThread(GitStatus status) - { - new ActionTask(TaskManager.Token, _ => OnStatusUpdate(status)) - .ScheduleUI(TaskManager); + oldRepository.OnRepositoryInfoCacheChanged -= Repository_RepositoryInfoCacheChanged; + oldRepository.OnGitStatusCacheChanged -= Repository_GitStatusCacheChanged; } - private void OnStatusUpdate(GitStatus update) + public override void OnEnable() { - if (update.Entries == null) + base.OnEnable(); + AttachHandlers(Repository); + + if (Repository != null) { - //Refresh(); - return; + Repository.CheckRepositoryInfoCacheEvent(repositoryInfoCacheEvent); + Repository.CheckGitStatusCacheEvent(gitStatusCacheEvent); } + } + + public override void OnDisable() + { + base.OnDisable(); + DetachHandlers(Repository); + } - // Set branch state - currentBranch = update.LocalBranch; + public override void OnDataUpdate() + { + base.OnDataUpdate(); + + MaybeUpdateData(); + } - // (Re)build tree - tree.UpdateEntries(update.Entries.Where(x => x.Status != GitFileStatus.Ignored).ToList()); + private void MaybeUpdateData() + { + if (repositoryInfoCacheHasChanged) + { + repositoryInfoCacheHasChanged = false; + currentBranch = string.Format("[{0}]", Repository.CurrentBranchName); + } - isBusy = false; + if (gitStatusCacheHasChanged) + { + gitStatusCacheHasChanged = false; + var gitStatus = Repository.CurrentStatus; + tree.UpdateEntries(gitStatus.Entries.Where(x => x.Status != GitFileStatus.Ignored).ToList()); + } } public override void OnGUI() diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/HistoryView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/HistoryView.cs index b5760279e..f5e1e5bed 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/HistoryView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/HistoryView.cs @@ -127,14 +127,15 @@ private void AttachHandlers(IRepository repository) { if (repository == null) return; - repository.OnStatusChanged += UpdateStatusOnMainThread; + + //TODO: Handle this event + //repository.OnStatusChanged += UpdateStatusOnMainThread; } private void DetachHandlers(IRepository repository) { if (repository == null) return; - repository.OnStatusChanged -= UpdateStatusOnMainThread; } private void UpdateStatusOnMainThread(GitStatus status) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ProjectWindowInterface.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ProjectWindowInterface.cs index 05fc0d66c..3fe1fd2ca 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ProjectWindowInterface.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ProjectWindowInterface.cs @@ -30,7 +30,8 @@ public static void Initialize(IRepository repo) repository = repo; if (repository != null) { - repository.OnStatusChanged += RunStatusUpdateOnMainThread; + //TODO: Listen to status change event + //repository.OnStatusChanged += RunStatusUpdateOnMainThread; repository.OnLocksChanged += RunLocksUpdateOnMainThread; } } diff --git a/src/tests/IntegrationTests/Events/RepositoryManagerTests.cs b/src/tests/IntegrationTests/Events/RepositoryManagerTests.cs index 9addb6ef6..6072ada09 100644 --- a/src/tests/IntegrationTests/Events/RepositoryManagerTests.cs +++ b/src/tests/IntegrationTests/Events/RepositoryManagerTests.cs @@ -107,7 +107,8 @@ public async Task ShouldDetectFileChanges() }; var result = new GitStatus(); - Environment.Repository.OnStatusChanged += status => { result = status; }; + //TODO: Figure this out + //Environment.Repository.OnStatusChanged += status => { result = status; }; var foobarTxt = TestRepoMasterCleanSynchronized.Combine("foobar.txt"); foobarTxt.WriteAllText("foobar"); @@ -157,7 +158,7 @@ public async Task ShouldAddAndCommitFiles() }; var result = new GitStatus(); - RepositoryManager.OnStatusUpdated += status => { result = status; }; + //RepositoryManager.OnStatusUpdated += status => { result = status; }; var foobarTxt = TestRepoMasterCleanSynchronized.Combine("foobar.txt"); foobarTxt.WriteAllText("foobar"); @@ -240,7 +241,8 @@ public async Task ShouldAddAndCommitAllFiles() }; var result = new GitStatus(); - RepositoryManager.OnStatusUpdated += status => { result = status; }; + //TODO: Figure this out + //RepositoryManager.OnStatusUpdated += status => { result = status; }; var foobarTxt = TestRepoMasterCleanSynchronized.Combine("foobar.txt"); foobarTxt.WriteAllText("foobar"); @@ -309,7 +311,8 @@ public async Task ShouldDetectBranchChange() }; var result = new GitStatus(); - RepositoryManager.OnStatusUpdated += status => { result = status; }; + //TODO: Figure this out + //RepositoryManager.OnStatusUpdated += status => { result = status; }; Logger.Trace("Starting test"); @@ -1077,7 +1080,8 @@ public async Task ShouldDetectGitPull() }; var result = new GitStatus(); - RepositoryManager.OnStatusUpdated += status => { result = status; }; + //TODO: Figure this out + //RepositoryManager.OnStatusUpdated += status => { result = status; }; await RepositoryManager.Pull("origin", "master").StartAsAsync(); await TaskManager.Wait(); diff --git a/src/tests/TestUtils/Events/IRepositoryListener.cs b/src/tests/TestUtils/Events/IRepositoryListener.cs index 5a56ed4c1..37baccda0 100644 --- a/src/tests/TestUtils/Events/IRepositoryListener.cs +++ b/src/tests/TestUtils/Events/IRepositoryListener.cs @@ -49,12 +49,13 @@ public static void AttachListener(this IRepositoryListener listener, { var logger = trace ? Logging.GetLogger() : null; - repository.OnStatusChanged += gitStatus => - { - logger?.Trace("OnStatusChanged: {0}", gitStatus); - listener.OnStatusChanged(gitStatus); - repositoryEvents?.OnStatusChanged.Set(); - }; + //TODO: Figure this out + //repository.OnStatusChanged += gitStatus => + //{ + // logger?.Trace("OnStatusChanged: {0}", gitStatus); + // listener.OnStatusChanged(gitStatus); + // repositoryEvents?.OnStatusChanged.Set(); + //}; repository.OnCurrentBranchChanged += name => { diff --git a/src/tests/TestUtils/Events/IRepositoryManagerListener.cs b/src/tests/TestUtils/Events/IRepositoryManagerListener.cs index 1f7432652..bf24392a1 100644 --- a/src/tests/TestUtils/Events/IRepositoryManagerListener.cs +++ b/src/tests/TestUtils/Events/IRepositoryManagerListener.cs @@ -94,11 +94,12 @@ public static void AttachListener(this IRepositoryManagerListener listener, managerEvents?.OnIsNotBusy.Set(); }; - repositoryManager.OnStatusUpdated += status => { - logger?.Debug("OnStatusUpdated: {0}", status); - listener.OnStatusUpdated(status); - managerEvents?.OnStatusUpdated.Set(); - }; + //TODO: Figure this out + //repositoryManager.OnStatusUpdated += status => { + // logger?.Debug("OnStatusUpdated: {0}", status); + // listener.OnStatusUpdated(status); + // managerEvents?.OnStatusUpdated.Set(); + //}; repositoryManager.OnLocksUpdated += locks => { var lockArray = locks.ToArray(); From b933b5333050e03c221aa25255cb3e7ff7e839f0 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Mon, 30 Oct 2017 09:53:30 -0400 Subject: [PATCH 145/241] Removing #pragma diable of 649 --- src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ChangesView.cs | 2 -- .../Assets/Editor/GitHub.Unity/UI/ChangesetTreeView.cs | 2 -- src/UnityExtension/Assets/Editor/GitHub.Unity/UI/HistoryView.cs | 2 -- src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs | 2 -- 4 files changed, 8 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ChangesView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ChangesView.cs index 2c560ef44..71d619226 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ChangesView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ChangesView.cs @@ -1,5 +1,3 @@ -#pragma warning disable 649 - using System; using System.Linq; using UnityEditor; diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ChangesetTreeView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ChangesetTreeView.cs index 61da1ceb2..5d787da89 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ChangesetTreeView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ChangesetTreeView.cs @@ -1,5 +1,3 @@ -#pragma warning disable 649 - using System; using System.Collections.Generic; using System.IO; diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/HistoryView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/HistoryView.cs index 14e803c78..42ef90e00 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/HistoryView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/HistoryView.cs @@ -1,5 +1,3 @@ -#pragma warning disable 649 - using System; using System.Collections.Generic; using System.Linq; diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs index f9a32fa25..858873d73 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs @@ -1,5 +1,3 @@ -#pragma warning disable 649 - using System; using System.Linq; using UnityEditor; From a07d0196441a8c915be2e98d75a62c7631a052a6 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Mon, 30 Oct 2017 09:53:52 -0400 Subject: [PATCH 146/241] Inline isBusy value of false that is never assigned to --- .../Assets/Editor/GitHub.Unity/UI/HistoryView.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/HistoryView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/HistoryView.cs index 42ef90e00..ee0386a9f 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/HistoryView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/HistoryView.cs @@ -40,7 +40,6 @@ class HistoryView : Subview [NonSerialized] private int selectionIndex; [NonSerialized] private bool logHasChanged; [NonSerialized] private bool useScrollTime; - [NonSerialized] private bool isBusy; [SerializeField] private Vector2 detailsScroll; [SerializeField] private Vector2 scroll; @@ -648,7 +647,7 @@ private void DrawTimelineRectAroundIconRect(Rect parentRect, Rect iconRect) public override bool IsBusy { - get { return isBusy; } + get { return false; } } private float EntryHeight From 2b4dff4c1acc955ddd7aa8ff48d7bc29e13aad04 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Mon, 30 Oct 2017 10:10:31 -0400 Subject: [PATCH 147/241] Figuring out a naming convention --- src/GitHub.Api/Git/IRepository.cs | 8 ++--- src/GitHub.Api/Git/Repository.cs | 26 +++++++-------- .../Editor/GitHub.Unity/UI/ChangesView.cs | 32 +++++++++---------- .../Assets/Editor/GitHub.Unity/UI/Window.cs | 18 +++++------ 4 files changed, 42 insertions(+), 42 deletions(-) diff --git a/src/GitHub.Api/Git/IRepository.cs b/src/GitHub.Api/Git/IRepository.cs index fe23b0ef7..87173268e 100644 --- a/src/GitHub.Api/Git/IRepository.cs +++ b/src/GitHub.Api/Git/IRepository.cs @@ -22,8 +22,8 @@ public interface IRepository : IEquatable ITask RequestLock(string file); ITask ReleaseLock(string file, bool force); - void CheckRepositoryInfoCacheEvent(UpdateDataEventData updateDataEventData); - void CheckGitStatusCacheEvent(UpdateDataEventData gitStatusCacheEvent); + void CheckRepositoryInfoCacheEvent(CacheUpdateEvent cacheUpdateEvent); + void CheckGitStatusCacheEvent(CacheUpdateEvent gitStatusCacheEvent); /// /// Gets the name of the repository. @@ -68,7 +68,7 @@ public interface IRepository : IEquatable event Action> OnLocksChanged; event Action OnRepositoryInfoChanged; event Action OnRemoteBranchListChanged; - event Action OnRepositoryInfoCacheChanged; - event Action OnGitStatusCacheChanged; + event Action OnRepositoryInfoCacheChanged; + event Action OnGitStatusCacheChanged; } } \ No newline at end of file diff --git a/src/GitHub.Api/Git/Repository.cs b/src/GitHub.Api/Git/Repository.cs index 9f3f08301..dbcbe8464 100644 --- a/src/GitHub.Api/Git/Repository.cs +++ b/src/GitHub.Api/Git/Repository.cs @@ -24,8 +24,8 @@ class Repository : IEquatable, IRepository public event Action OnRemoteBranchListChanged; public event Action OnRepositoryInfoChanged; - public event Action OnRepositoryInfoCacheChanged; - public event Action OnGitStatusCacheChanged; + public event Action OnRepositoryInfoCacheChanged; + public event Action OnGitStatusCacheChanged; /// /// Initializes a new instance of the class. @@ -108,13 +108,13 @@ private void CacheContainer_OnCacheUpdated(CacheType cacheType, DateTimeOffset o private void FireOnRepositoryInfoCacheChanged(DateTimeOffset dateTimeOffset) { Logger.Trace("OnRepositoryInfoCacheChanged {0}", dateTimeOffset); - OnRepositoryInfoCacheChanged?.Invoke(new UpdateDataEventData { UpdatedTimeString = dateTimeOffset.ToString() }); + OnRepositoryInfoCacheChanged?.Invoke(new CacheUpdateEvent { UpdatedTimeString = dateTimeOffset.ToString() }); } private void FireOnGitStatusCacheChanged(DateTimeOffset dateTimeOffset) { Logger.Trace("OnGitStatusCacheChanged {0}", dateTimeOffset); - OnGitStatusCacheChanged?.Invoke(new UpdateDataEventData { UpdatedTimeString = dateTimeOffset.ToString() }); + OnGitStatusCacheChanged?.Invoke(new CacheUpdateEvent { UpdatedTimeString = dateTimeOffset.ToString() }); } public void Initialize(IRepositoryManager initRepositoryManager) @@ -213,23 +213,23 @@ public ITask ReleaseLock(string file, bool force) return repositoryManager.UnlockFile(file, force); } - public void CheckRepositoryInfoCacheEvent(UpdateDataEventData updateDataEventData) + public void CheckRepositoryInfoCacheEvent(CacheUpdateEvent cacheUpdateEvent) { bool raiseEvent; IManagedCache managedCache = cacheContainer.RepositoryInfoCache; - if (updateDataEventData.UpdatedTimeString == null) + if (cacheUpdateEvent.UpdatedTimeString == null) { raiseEvent = managedCache.LastUpdatedAt != DateTimeOffset.MinValue; } else { - raiseEvent = managedCache.LastUpdatedAt.ToString() != updateDataEventData.UpdatedTimeString; + raiseEvent = managedCache.LastUpdatedAt.ToString() != cacheUpdateEvent.UpdatedTimeString; } Logger.Trace("CheckRepositoryInfoCacheEvent Current:{0} Check:{1} Result:{2}", managedCache.LastUpdatedAt, - updateDataEventData.UpdatedTimeString ?? "[NULL]", + cacheUpdateEvent.UpdatedTimeString ?? "[NULL]", raiseEvent); if (raiseEvent) @@ -238,23 +238,23 @@ public void CheckRepositoryInfoCacheEvent(UpdateDataEventData updateDataEventDat } } - public void CheckGitStatusCacheEvent(UpdateDataEventData updateDataEventData) + public void CheckGitStatusCacheEvent(CacheUpdateEvent cacheUpdateEvent) { bool raiseEvent; IManagedCache managedCache = cacheContainer.GitStatusCache; - if (updateDataEventData.UpdatedTimeString == null) + if (cacheUpdateEvent.UpdatedTimeString == null) { raiseEvent = managedCache.LastUpdatedAt != DateTimeOffset.MinValue; } else { - raiseEvent = managedCache.LastUpdatedAt.ToString() != updateDataEventData.UpdatedTimeString; + raiseEvent = managedCache.LastUpdatedAt.ToString() != cacheUpdateEvent.UpdatedTimeString; } Logger.Trace("CheckGitStatusCacheEvent Current:{0} Check:{1} Result:{2}", managedCache.LastUpdatedAt, - updateDataEventData.UpdatedTimeString ?? "[NULL]", + cacheUpdateEvent.UpdatedTimeString ?? "[NULL]", raiseEvent); if (raiseEvent) @@ -585,7 +585,7 @@ public override string ToString() } [Serializable] - public struct UpdateDataEventData + public struct CacheUpdateEvent { public string UpdatedTimeString; } diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ChangesView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ChangesView.cs index 48d8ee433..f12bfeaa0 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ChangesView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ChangesView.cs @@ -25,11 +25,11 @@ class ChangesView : Subview [SerializeField] private Vector2 horizontalScroll; [SerializeField] private ChangesetTreeView tree = new ChangesetTreeView(); - [SerializeField] private UpdateDataEventData repositoryInfoCacheEvent; - [NonSerialized] private bool repositoryInfoCacheHasChanged; + [SerializeField] private CacheUpdateEvent repositoryInfoUpdateEvent; + [NonSerialized] private bool repositoryInfoCacheHasUpdate; - [SerializeField] private UpdateDataEventData gitStatusCacheEvent; - [NonSerialized] private bool gitStatusCacheHasChanged; + [SerializeField] private CacheUpdateEvent gitStatusUpdateEvent; + [NonSerialized] private bool gitStatusCacheHasUpdate; public override void InitializeView(IView parent) { @@ -37,21 +37,21 @@ public override void InitializeView(IView parent) tree.InitializeView(this); } - private void Repository_GitStatusCacheChanged(UpdateDataEventData data) + private void Repository_GitStatusCacheChanged(CacheUpdateEvent cacheUpdateEvent) { new ActionTask(TaskManager.Token, () => { - gitStatusCacheEvent = data; - gitStatusCacheHasChanged = true; + gitStatusUpdateEvent = cacheUpdateEvent; + gitStatusCacheHasUpdate = true; Redraw(); }) { Affinity = TaskAffinity.UI }.Start(); } - private void Repository_RepositoryInfoCacheChanged(UpdateDataEventData data) + private void Repository_RepositoryInfoCacheChanged(CacheUpdateEvent cacheUpdateEvent) { new ActionTask(TaskManager.Token, () => { - repositoryInfoCacheEvent = data; - repositoryInfoCacheHasChanged = true; + repositoryInfoUpdateEvent = cacheUpdateEvent; + repositoryInfoCacheHasUpdate = true; Redraw(); }) { Affinity = TaskAffinity.UI }.Start(); @@ -81,8 +81,8 @@ public override void OnEnable() if (Repository != null) { - Repository.CheckRepositoryInfoCacheEvent(repositoryInfoCacheEvent); - Repository.CheckGitStatusCacheEvent(gitStatusCacheEvent); + Repository.CheckRepositoryInfoCacheEvent(repositoryInfoUpdateEvent); + Repository.CheckGitStatusCacheEvent(gitStatusUpdateEvent); } } @@ -101,15 +101,15 @@ public override void OnDataUpdate() private void MaybeUpdateData() { - if (repositoryInfoCacheHasChanged) + if (repositoryInfoCacheHasUpdate) { - repositoryInfoCacheHasChanged = false; + repositoryInfoCacheHasUpdate = false; currentBranch = string.Format("[{0}]", Repository.CurrentBranchName); } - if (gitStatusCacheHasChanged) + if (gitStatusCacheHasUpdate) { - gitStatusCacheHasChanged = false; + gitStatusCacheHasUpdate = false; var gitStatus = Repository.CurrentStatus; tree.UpdateEntries(gitStatus.Entries.Where(x => x.Status != GitFileStatus.Ignored).ToList()); } diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs index c05be9e1d..315ea1d65 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs @@ -37,9 +37,9 @@ class Window : BaseWindow [SerializeField] private GUIContent repoBranchContent; [SerializeField] private GUIContent repoUrlContent; - [SerializeField] private UpdateDataEventData repositoryInfoCacheEvent; - [NonSerialized] private bool repositoryInfoCacheHasChanged; - [NonSerialized] private bool hasMaybeUpdateDataWithRepository; + [SerializeField] private CacheUpdateEvent repositoryInfoUpdateEvent; + [NonSerialized] private bool repositoryInfoCacheHasUpdate; + [NonSerialized] private bool hasRunMaybeUpdateDataWithRepository; [MenuItem(LaunchMenu)] public static void Window_GitHub() @@ -97,7 +97,7 @@ public override void OnEnable() titleContent = new GUIContent(Title, Styles.SmallLogo); if (Repository != null) - Repository.CheckRepositoryInfoCacheEvent(repositoryInfoCacheEvent); + Repository.CheckRepositoryInfoCacheEvent(repositoryInfoUpdateEvent); if (ActiveView != null) ActiveView.OnEnable(); @@ -194,9 +194,9 @@ private void MaybeUpdateData() if (Repository != null) { - if(!hasMaybeUpdateDataWithRepository || repositoryInfoCacheHasChanged) + if(!hasRunMaybeUpdateDataWithRepository || repositoryInfoCacheHasUpdate) { - hasMaybeUpdateDataWithRepository = true; + hasRunMaybeUpdateDataWithRepository = true; var repositoryCurrentBranch = Repository.CurrentBranch; updatedRepoBranch = repositoryCurrentBranch.HasValue ? repositoryCurrentBranch.Value.Name : null; @@ -272,11 +272,11 @@ private void AttachHandlers(IRepository repository) repository.OnRepositoryInfoCacheChanged += Repository_RepositoryInfoCacheChanged; } - private void Repository_RepositoryInfoCacheChanged(UpdateDataEventData data) + private void Repository_RepositoryInfoCacheChanged(CacheUpdateEvent cacheUpdateEvent) { new ActionTask(TaskManager.Token, () => { - repositoryInfoCacheEvent = data; - repositoryInfoCacheHasChanged = true; + repositoryInfoUpdateEvent = cacheUpdateEvent; + repositoryInfoCacheHasUpdate = true; Redraw(); }) { Affinity = TaskAffinity.UI }.Start(); } From 463d91676366952e3b1bc1b4a7c5d5dcecabfa2a Mon Sep 17 00:00:00 2001 From: Gal Horowitz Date: Mon, 30 Oct 2017 17:57:14 +0200 Subject: [PATCH 148/241] Fixing #351 Applying shiena's code fixed this issue. --- src/UnityExtension/Assets/Editor/GitHub.Unity/Misc/Utility.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/Misc/Utility.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/Misc/Utility.cs index e645e5654..0deb4c975 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/Misc/Utility.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/Misc/Utility.cs @@ -32,7 +32,7 @@ static class StreamExtensions static StreamExtensions() { - var t = typeof(Texture2D).Assembly.GetType("UnityEngine.ImageConversion", false, false); + var t = Assembly.Load("UnityEngine.dll").GetType("UnityEngine.ImageConversion", false, false); if (t != null) { // looking for ImageConversion.LoadImage(this Texture2D tex, byte[] data) From 946ef394a3ea2e04d1a72b856b9f9ee913634add Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Mon, 30 Oct 2017 14:00:47 -0400 Subject: [PATCH 149/241] A few renames and converting HistoryView --- src/GitHub.Api/Cache/CacheInterfaces.cs | 2 +- src/GitHub.Api/Git/IRepository.cs | 10 +- src/GitHub.Api/Git/Repository.cs | 104 ++++++++----- .../Editor/GitHub.Unity/ApplicationCache.cs | 15 ++ .../Editor/GitHub.Unity/CacheContainer.cs | 6 +- .../Editor/GitHub.Unity/UI/ChangesView.cs | 16 +- .../Editor/GitHub.Unity/UI/HistoryView.cs | 146 ++++++++++-------- .../Assets/Editor/GitHub.Unity/UI/Window.cs | 6 +- 8 files changed, 185 insertions(+), 120 deletions(-) diff --git a/src/GitHub.Api/Cache/CacheInterfaces.cs b/src/GitHub.Api/Cache/CacheInterfaces.cs index 96867f879..93b674360 100644 --- a/src/GitHub.Api/Cache/CacheInterfaces.cs +++ b/src/GitHub.Api/Cache/CacheInterfaces.cs @@ -93,6 +93,6 @@ public interface IBranchCache : IManagedCache, IBranch public interface IGitLogCache : IManagedCache { - List Log { get; } + List Log { get; set; } } } diff --git a/src/GitHub.Api/Git/IRepository.cs b/src/GitHub.Api/Git/IRepository.cs index 87173268e..61ce4dff3 100644 --- a/src/GitHub.Api/Git/IRepository.cs +++ b/src/GitHub.Api/Git/IRepository.cs @@ -13,7 +13,6 @@ public interface IRepository : IEquatable ITask CommitAllFiles(string message, string body); ITask CommitFiles(List files, string message, string body); ITask SetupRemote(string remoteName, string remoteUrl); - ITask> Log(); ITask Pull(); ITask Push(); ITask Fetch(); @@ -23,7 +22,8 @@ public interface IRepository : IEquatable ITask ReleaseLock(string file, bool force); void CheckRepositoryInfoCacheEvent(CacheUpdateEvent cacheUpdateEvent); - void CheckGitStatusCacheEvent(CacheUpdateEvent gitStatusCacheEvent); + void CheckGitStatusCacheEvent(CacheUpdateEvent cacheUpdateEvent); + void CheckGitLogCacheEvent(CacheUpdateEvent cacheUpdateEvent); /// /// Gets the name of the repository. @@ -60,6 +60,7 @@ public interface IRepository : IEquatable IUser User { get; set; } IList CurrentLocks { get; } string CurrentBranchName { get; } + List CurrentLog { get; } event Action OnCurrentBranchChanged; event Action OnCurrentRemoteChanged; @@ -68,7 +69,8 @@ public interface IRepository : IEquatable event Action> OnLocksChanged; event Action OnRepositoryInfoChanged; event Action OnRemoteBranchListChanged; - event Action OnRepositoryInfoCacheChanged; - event Action OnGitStatusCacheChanged; + event Action RepositoryInfoCacheUpdated; + event Action GitStatusCacheUpdated; + event Action GitLogCacheUpdated; } } \ No newline at end of file diff --git a/src/GitHub.Api/Git/Repository.cs b/src/GitHub.Api/Git/Repository.cs index dbcbe8464..55c767e5e 100644 --- a/src/GitHub.Api/Git/Repository.cs +++ b/src/GitHub.Api/Git/Repository.cs @@ -16,6 +16,7 @@ class Repository : IEquatable, IRepository private Dictionary remotes; private IRepositoryManager repositoryManager; private ICacheContainer cacheContainer; + public event Action OnCurrentBranchChanged; public event Action OnCurrentRemoteChanged; public event Action OnCurrentBranchUpdated; @@ -24,8 +25,9 @@ class Repository : IEquatable, IRepository public event Action OnRemoteBranchListChanged; public event Action OnRepositoryInfoChanged; - public event Action OnRepositoryInfoCacheChanged; - public event Action OnGitStatusCacheChanged; + public event Action RepositoryInfoCacheUpdated; + public event Action GitStatusCacheUpdated; + public event Action GitLogCacheUpdated; /// /// Initializes a new instance of the class. @@ -84,14 +86,15 @@ private void CacheContainer_OnCacheUpdated(CacheType cacheType, DateTimeOffset o break; case CacheType.GitLogCache: + FireGitLogCacheUpdated(offset); break; case CacheType.RepositoryInfoCache: - FireOnRepositoryInfoCacheChanged(offset); + FireRepositoryInfoCacheUpdated(offset); break; case CacheType.GitStatusCache: - FireOnGitStatusCacheChanged(offset); + FireGitStatusCacheUpdated(offset); break; case CacheType.GitLocksCache: @@ -105,16 +108,22 @@ private void CacheContainer_OnCacheUpdated(CacheType cacheType, DateTimeOffset o } } - private void FireOnRepositoryInfoCacheChanged(DateTimeOffset dateTimeOffset) + private void FireGitLogCacheUpdated(DateTimeOffset dateTimeOffset) + { + Logger.Trace("GitLogCacheUpdated {0}", dateTimeOffset); + GitLogCacheUpdated?.Invoke(new CacheUpdateEvent { UpdatedTimeString = dateTimeOffset.ToString() }); + } + + private void FireRepositoryInfoCacheUpdated(DateTimeOffset dateTimeOffset) { - Logger.Trace("OnRepositoryInfoCacheChanged {0}", dateTimeOffset); - OnRepositoryInfoCacheChanged?.Invoke(new CacheUpdateEvent { UpdatedTimeString = dateTimeOffset.ToString() }); + Logger.Trace("RepositoryInfoCacheUpdated {0}", dateTimeOffset); + RepositoryInfoCacheUpdated?.Invoke(new CacheUpdateEvent { UpdatedTimeString = dateTimeOffset.ToString() }); } - private void FireOnGitStatusCacheChanged(DateTimeOffset dateTimeOffset) + private void FireGitStatusCacheUpdated(DateTimeOffset dateTimeOffset) { - Logger.Trace("OnGitStatusCacheChanged {0}", dateTimeOffset); - OnGitStatusCacheChanged?.Invoke(new CacheUpdateEvent { UpdatedTimeString = dateTimeOffset.ToString() }); + Logger.Trace("GitStatusCacheUpdated {0}", dateTimeOffset); + GitStatusCacheUpdated?.Invoke(new CacheUpdateEvent { UpdatedTimeString = dateTimeOffset.ToString() }); } public void Initialize(IRepositoryManager initRepositoryManager) @@ -137,6 +146,7 @@ public void Initialize(IRepositoryManager initRepositoryManager) repositoryManager.OnGitUserLoaded += user => User = user; UpdateGitStatus(); + UpdateGitLog(); } public void Refresh() @@ -158,14 +168,6 @@ public ITask SetupRemote(string remote, string remoteUrl) } } - public ITask> Log() - { - if (repositoryManager == null) - return new FuncListTask(new NotReadyException().ToTask>()); - - return repositoryManager.Log(); - } - public ITask CommitAllFiles(string message, string body) { return repositoryManager.CommitAllFiles(message, body); @@ -215,34 +217,55 @@ public ITask ReleaseLock(string file, bool force) public void CheckRepositoryInfoCacheEvent(CacheUpdateEvent cacheUpdateEvent) { - bool raiseEvent; - IManagedCache managedCache = cacheContainer.RepositoryInfoCache; + var managedCache = cacheContainer.RepositoryInfoCache; + var raiseEvent = ShouldRaiseCacheEvent(cacheUpdateEvent, managedCache); - if (cacheUpdateEvent.UpdatedTimeString == null) + Logger.Trace("CheckRepositoryInfoCacheEvent Current:{0} Check:{1} Result:{2}", + managedCache.LastUpdatedAt, + cacheUpdateEvent.UpdatedTimeString ?? "[NULL]", + raiseEvent); + + if (raiseEvent) { - raiseEvent = managedCache.LastUpdatedAt != DateTimeOffset.MinValue; + FireRepositoryInfoCacheUpdated(managedCache.LastUpdatedAt); } - else + } + + public void CheckGitStatusCacheEvent(CacheUpdateEvent cacheUpdateEvent) + { + var managedCache = cacheContainer.GitStatusCache; + var raiseEvent = ShouldRaiseCacheEvent(cacheUpdateEvent, managedCache); + + Logger.Trace("CheckGitStatusCacheEvent Current:{0} Check:{1} Result:{2}", + managedCache.LastUpdatedAt, + cacheUpdateEvent.UpdatedTimeString ?? "[NULL]", + raiseEvent); + + if (raiseEvent) { - raiseEvent = managedCache.LastUpdatedAt.ToString() != cacheUpdateEvent.UpdatedTimeString; + FireGitStatusCacheUpdated(managedCache.LastUpdatedAt); } + } - Logger.Trace("CheckRepositoryInfoCacheEvent Current:{0} Check:{1} Result:{2}", + public void CheckGitLogCacheEvent(CacheUpdateEvent cacheUpdateEvent) + { + var managedCache = cacheContainer.GitLogCache; + var raiseEvent = ShouldRaiseCacheEvent(cacheUpdateEvent, managedCache); + + Logger.Trace("CheckGitLogCacheEvent Current:{0} Check:{1} Result:{2}", managedCache.LastUpdatedAt, cacheUpdateEvent.UpdatedTimeString ?? "[NULL]", raiseEvent); if (raiseEvent) { - FireOnRepositoryInfoCacheChanged(managedCache.LastUpdatedAt); + FireGitLogCacheUpdated(managedCache.LastUpdatedAt); } } - public void CheckGitStatusCacheEvent(CacheUpdateEvent cacheUpdateEvent) + private static bool ShouldRaiseCacheEvent(CacheUpdateEvent cacheUpdateEvent, IManagedCache managedCache) { bool raiseEvent; - IManagedCache managedCache = cacheContainer.GitStatusCache; - if (cacheUpdateEvent.UpdatedTimeString == null) { raiseEvent = managedCache.LastUpdatedAt != DateTimeOffset.MinValue; @@ -251,16 +274,7 @@ public void CheckGitStatusCacheEvent(CacheUpdateEvent cacheUpdateEvent) { raiseEvent = managedCache.LastUpdatedAt.ToString() != cacheUpdateEvent.UpdatedTimeString; } - - Logger.Trace("CheckGitStatusCacheEvent Current:{0} Check:{1} Result:{2}", - managedCache.LastUpdatedAt, - cacheUpdateEvent.UpdatedTimeString ?? "[NULL]", - raiseEvent); - - if (raiseEvent) - { - FireOnGitStatusCacheChanged(managedCache.LastUpdatedAt); - } + return raiseEvent; } /// @@ -311,6 +325,7 @@ private void RepositoryManager_OnRepositoryUpdated() { Logger.Trace("OnRepositoryUpdated"); UpdateGitStatus(); + UpdateGitLog(); } private void UpdateGitStatus() @@ -318,6 +333,11 @@ private void UpdateGitStatus() repositoryManager?.Status().ThenInUI((b, status) => { CurrentStatus = status; }).Start(); } + private void UpdateGitLog() + { + repositoryManager?.Log().ThenInUI((b, log) => { CurrentLog = log; }).Start(); + } + private void RepositoryManager_OnCurrentBranchUpdated(ConfigBranch? branch) { if (!Nullable.Equals(CurrentConfigBranch, branch)) @@ -529,6 +549,12 @@ public GitStatus CurrentStatus public GitRemote? CurrentRemote => cacheContainer.RepositoryInfoCache.CurrentGitRemote; + public List CurrentLog + { + get { return cacheContainer.GitLogCache.Log; } + set { cacheContainer.GitLogCache.Log = value; } + } + public UriString CloneUrl { get; private set; } public string Name { get; private set; } diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs index e9da84ebc..8d50f953f 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs @@ -483,6 +483,21 @@ public List Log ValidateData(); return log; } + set + { + var now = DateTimeOffset.Now; + var isUpdated = false; + + Logger.Trace("Updating: {0} gitLog:{1}", now, value); + + if (!log.SequenceEqual(value)) + { + log = value; + isUpdated = true; + } + + SaveData(now, isUpdated); + } } protected override void OnResetData() diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/CacheContainer.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/CacheContainer.cs index ddfb111d3..9a46297d6 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/CacheContainer.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/CacheContainer.cs @@ -4,6 +4,8 @@ namespace GitHub.Unity { public class CacheContainer : ICacheContainer { + private static ILogging Logger = Logging.GetLogger(); + private IBranchCache branchCache; private IGitLocksCache gitLocksCache; @@ -165,7 +167,7 @@ public IGitUserCache GitUserCache private void OnCacheUpdated(CacheType cacheType, DateTimeOffset datetime) { - //Logger.Trace("OnCacheUpdated cacheType:{0} datetime:{1}", cacheType, datetime); + Logger.Trace("OnCacheUpdated cacheType:{0} datetime:{1}", cacheType, datetime); if (CacheUpdated != null) { CacheUpdated.Invoke(cacheType, datetime); @@ -174,7 +176,7 @@ private void OnCacheUpdated(CacheType cacheType, DateTimeOffset datetime) private void OnCacheInvalidated(CacheType cacheType) { - //Logger.Trace("OnCacheInvalidated cacheType:{0}", cacheType); + Logger.Trace("OnCacheInvalidated cacheType:{0}", cacheType); if (CacheInvalidated != null) { CacheInvalidated.Invoke(cacheType); diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ChangesView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ChangesView.cs index f12bfeaa0..988d3df91 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ChangesView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ChangesView.cs @@ -37,7 +37,7 @@ public override void InitializeView(IView parent) tree.InitializeView(this); } - private void Repository_GitStatusCacheChanged(CacheUpdateEvent cacheUpdateEvent) + private void Repository_GitStatusCacheUpdated(CacheUpdateEvent cacheUpdateEvent) { new ActionTask(TaskManager.Token, () => { gitStatusUpdateEvent = cacheUpdateEvent; @@ -47,7 +47,7 @@ private void Repository_GitStatusCacheChanged(CacheUpdateEvent cacheUpdateEvent) { Affinity = TaskAffinity.UI }.Start(); } - private void Repository_RepositoryInfoCacheChanged(CacheUpdateEvent cacheUpdateEvent) + private void Repository_RepositoryInfoCacheUpdated(CacheUpdateEvent cacheUpdateEvent) { new ActionTask(TaskManager.Token, () => { repositoryInfoUpdateEvent = cacheUpdateEvent; @@ -61,17 +61,17 @@ private void AttachHandlers(IRepository repository) { if (repository == null) return; - repository.OnRepositoryInfoCacheChanged += Repository_RepositoryInfoCacheChanged; - repository.OnGitStatusCacheChanged += Repository_GitStatusCacheChanged; + repository.RepositoryInfoCacheUpdated += Repository_RepositoryInfoCacheUpdated; + repository.GitStatusCacheUpdated += Repository_GitStatusCacheUpdated; } - private void DetachHandlers(IRepository oldRepository) + private void DetachHandlers(IRepository repository) { - if (oldRepository == null) + if (repository == null) return; - oldRepository.OnRepositoryInfoCacheChanged -= Repository_RepositoryInfoCacheChanged; - oldRepository.OnGitStatusCacheChanged -= Repository_GitStatusCacheChanged; + repository.RepositoryInfoCacheUpdated -= Repository_RepositoryInfoCacheUpdated; + repository.GitStatusCacheUpdated -= Repository_GitStatusCacheUpdated; } public override void OnEnable() diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/HistoryView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/HistoryView.cs index 52cf73e89..861f444fa 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/HistoryView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/HistoryView.cs @@ -3,7 +3,6 @@ using System.Linq; using UnityEditor; using UnityEngine; -using Object = UnityEngine.Object; namespace GitHub.Unity { @@ -38,7 +37,6 @@ class HistoryView : Subview [NonSerialized] private float scrollOffset; [NonSerialized] private DateTimeOffset scrollTime = DateTimeOffset.Now; [NonSerialized] private int selectionIndex; - [NonSerialized] private bool logHasChanged; [NonSerialized] private bool useScrollTime; [SerializeField] private Vector2 detailsScroll; @@ -49,8 +47,18 @@ class HistoryView : Subview [SerializeField] private ChangesetTreeView changesetTree = new ChangesetTreeView(); [SerializeField] private List history = new List(); - [SerializeField] private string currentRemote; - [SerializeField] private bool isPublished; + [SerializeField] private string currentRemoteName; + [SerializeField] private bool hasRemote; + [SerializeField] private bool hasItemsToCommit; + + [SerializeField] private CacheUpdateEvent repositoryInfoUpdateEvent; + [NonSerialized] private bool repositoryInfoCacheHasUpdate; + + [SerializeField] private CacheUpdateEvent gitStatusUpdateEvent; + [NonSerialized] private bool gitStatusCacheHasUpdate; + + [SerializeField] private CacheUpdateEvent gitLogCacheUpdateEvent; + [NonSerialized] private bool gitLogCacheHasUpdate; public override void InitializeView(IView parent) { @@ -66,7 +74,13 @@ public override void OnEnable() { base.OnEnable(); AttachHandlers(Repository); - CheckLogCache(); + + if (Repository != null) + { + Repository.CheckGitLogCacheEvent(gitLogCacheUpdateEvent); + Repository.CheckGitStatusCacheEvent(gitStatusUpdateEvent); + Repository.CheckRepositoryInfoCacheEvent(repositoryInfoUpdateEvent); + } } public override void OnDisable() @@ -81,43 +95,39 @@ public override void OnDataUpdate() MaybeUpdateData(); } - public override void OnRepositoryChanged(IRepository oldRepository) + public override void OnGUI() { - base.OnRepositoryChanged(oldRepository); + OnEmbeddedGUI(); } - public override void OnSelectionChange() + private void Repository_GitStatusCacheUpdated(CacheUpdateEvent cacheUpdateEvent) { - + new ActionTask(TaskManager.Token, () => { + gitStatusUpdateEvent = cacheUpdateEvent; + gitStatusCacheHasUpdate = true; + Redraw(); + }) + { Affinity = TaskAffinity.UI }.Start(); } - public override void OnGUI() + private void Repository_GitLogCacheUpdated(CacheUpdateEvent cacheUpdateEvent) { - OnEmbeddedGUI(); + new ActionTask(TaskManager.Token, () => { + gitLogCacheUpdateEvent = cacheUpdateEvent; + gitLogCacheHasUpdate = true; + Redraw(); + }) + { Affinity = TaskAffinity.UI }.Start(); } - public void CheckLogCache() + private void Repository_RepositoryInfoCacheUpdated(CacheUpdateEvent cacheUpdateEvent) { - string firstItemCommitID = null; - if (history.Any()) - { - firstItemCommitID = history.First().CommitID; - } - - var cachedList = GitLogCache.Instance.Log; - - string firstCachedItemCommitID = null; - if (cachedList.Any()) - { - firstCachedItemCommitID = cachedList.First().CommitID; - } - - if (firstItemCommitID != firstCachedItemCommitID) - { - Logger.Trace("CommitID {0} != Cached CommitId {1}", firstItemCommitID ?? "[NULL]", firstCachedItemCommitID ?? "[NULL]"); - logHasChanged = true; - Redraw(); - } + new ActionTask(TaskManager.Token, () => { + repositoryInfoUpdateEvent = cacheUpdateEvent; + repositoryInfoCacheHasUpdate = true; + Redraw(); + }) + { Affinity = TaskAffinity.UI }.Start(); } private void AttachHandlers(IRepository repository) @@ -125,38 +135,51 @@ private void AttachHandlers(IRepository repository) if (repository == null) return; - //TODO: Handle this event - //repository.OnStatusChanged += UpdateStatusOnMainThread; + repository.GitStatusCacheUpdated += Repository_GitStatusCacheUpdated; + repository.GitLogCacheUpdated += Repository_GitLogCacheUpdated; + repository.RepositoryInfoCacheUpdated += Repository_RepositoryInfoCacheUpdated; } private void DetachHandlers(IRepository repository) { if (repository == null) return; - } - - private void UpdateStatusOnMainThread(GitStatus status) - { - new ActionTask(TaskManager.Token, _ => UpdateStatus(status)) - .ScheduleUI(TaskManager); - } - private void UpdateStatus(GitStatus status) - { - statusAhead = status.Ahead; - statusBehind = status.Behind; + repository.GitStatusCacheUpdated -= Repository_GitStatusCacheUpdated; + repository.GitLogCacheUpdated -= Repository_GitLogCacheUpdated; + repository.RepositoryInfoCacheUpdated -= Repository_RepositoryInfoCacheUpdated; } private void MaybeUpdateData() { - isPublished = Repository != null && Repository.CurrentRemote.HasValue; - currentRemote = isPublished ? Repository.CurrentRemote.Value.Name : "placeholder"; + if (Repository == null) + return; + + if (repositoryInfoCacheHasUpdate) + { + repositoryInfoCacheHasUpdate = false; + + var currentRemote = Repository.CurrentRemote; + hasRemote = currentRemote.HasValue; + currentRemoteName = hasRemote ? currentRemote.Value.Name : "placeholder"; + } + + if (gitStatusCacheHasUpdate) + { + gitStatusCacheHasUpdate = false; + + var currentStatus = Repository.CurrentStatus; + statusAhead = currentStatus.Ahead; + statusBehind = currentStatus.Behind; + hasItemsToCommit = currentStatus.Entries != null && + currentStatus.GetEntriesExcludingIgnoredAndUntracked().Any(); + } - if (logHasChanged) + if (gitLogCacheHasUpdate) { - logHasChanged = false; + gitLogCacheHasUpdate = false; - history = GitLogCache.Instance.Log; + history = Repository.CurrentLog; if (history.Any()) { @@ -204,9 +227,9 @@ public void OnEmbeddedGUI() { GUILayout.FlexibleSpace(); - if (isPublished) + if (hasRemote) { - EditorGUI.BeginDisabledGroup(currentRemote == null); + EditorGUI.BeginDisabledGroup(currentRemoteName == null); { // Fetch button var fetchClicked = GUILayout.Button(FetchButtonText, Styles.HistoryToolbarButtonStyle); @@ -221,7 +244,7 @@ public void OnEmbeddedGUI() if (pullClicked && EditorUtility.DisplayDialog(PullConfirmTitle, - String.Format(PullConfirmDescription, currentRemote), + String.Format(PullConfirmDescription, currentRemoteName), PullConfirmYes, PullConfirmCancel) ) @@ -232,14 +255,14 @@ public void OnEmbeddedGUI() EditorGUI.EndDisabledGroup(); // Push button - EditorGUI.BeginDisabledGroup(currentRemote == null || statusBehind != 0); + EditorGUI.BeginDisabledGroup(currentRemoteName == null || statusBehind != 0); { var pushButtonText = statusAhead > 0 ? String.Format(PushButtonCount, statusAhead) : PushButton; var pushClicked = GUILayout.Button(pushButtonText, Styles.HistoryToolbarButtonStyle); if (pushClicked && EditorUtility.DisplayDialog(PushConfirmTitle, - String.Format(PushConfirmDescription, currentRemote), + String.Format(PushConfirmDescription, currentRemoteName), PushConfirmYes, PushConfirmCancel) ) @@ -273,7 +296,7 @@ public void OnEmbeddedGUI() // Only update time scroll var lastScroll = scroll; scroll = GUILayout.BeginScrollView(scroll); - if (lastScroll != scroll && !logHasChanged) + if (lastScroll != scroll && !gitLogCacheHasUpdate) { scrollTime = history[historyStartIndex].Time; scrollOffset = scroll.y - historyStartIndex * EntryHeight; @@ -379,7 +402,7 @@ public void OnEmbeddedGUI() if (Event.current.type == EventType.Repaint) { CullHistory(); - logHasChanged = false; + gitLogCacheHasUpdate = false; if (newSelectionIndex >= 0 || newSelectionIndex == -2) { @@ -540,14 +563,12 @@ private void HistoryDetailsEntry(GitLogEntry entry) private void Pull() { - var status = Repository.CurrentStatus; - if (status.Entries != null && status.GetEntriesExcludingIgnoredAndUntracked().Any()) + if (hasItemsToCommit) { EditorUtility.DisplayDialog("Pull", "You need to commit your changes before pulling.", "Cancel"); } else { - var remote = Repository.CurrentRemote.HasValue ? Repository.CurrentRemote.Value.Name : String.Empty; Repository .Pull() // we need the error propagated from the original git command to handle things appropriately @@ -563,7 +584,7 @@ private void Pull() if (success) { EditorUtility.DisplayDialog(Localization.PullActionTitle, - String.Format(Localization.PullSuccessDescription, remote), + String.Format(Localization.PullSuccessDescription, currentRemoteName), Localization.Ok); } else @@ -579,14 +600,13 @@ private void Pull() private void Push() { - var remote = Repository.CurrentRemote.HasValue ? Repository.CurrentRemote.Value.Name : String.Empty; Repository .Push() .FinallyInUI((success, e) => { if (success) { EditorUtility.DisplayDialog(Localization.PushActionTitle, - String.Format(Localization.PushSuccessDescription, remote), + String.Format(Localization.PushSuccessDescription, currentRemoteName), Localization.Ok); } else diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs index 315ea1d65..1d5e2403c 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs @@ -269,10 +269,10 @@ private void AttachHandlers(IRepository repository) { if (repository == null) return; - repository.OnRepositoryInfoCacheChanged += Repository_RepositoryInfoCacheChanged; + repository.RepositoryInfoCacheUpdated += Repository_RepositoryInfoCacheUpdated; } - private void Repository_RepositoryInfoCacheChanged(CacheUpdateEvent cacheUpdateEvent) + private void Repository_RepositoryInfoCacheUpdated(CacheUpdateEvent cacheUpdateEvent) { new ActionTask(TaskManager.Token, () => { repositoryInfoUpdateEvent = cacheUpdateEvent; @@ -286,7 +286,7 @@ private void DetachHandlers(IRepository repository) if (repository == null) return; - repository.OnRepositoryInfoCacheChanged -= Repository_RepositoryInfoCacheChanged; + repository.RepositoryInfoCacheUpdated -= Repository_RepositoryInfoCacheUpdated; } private void DoHeaderGUI() From 475088075f8b97e360eb2392d7f0e2d4f01bcab0 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Mon, 30 Oct 2017 14:08:52 -0400 Subject: [PATCH 150/241] Removing branch favorite functionality --- .../Editor/GitHub.Unity/ApplicationCache.cs | 50 ---------- .../Editor/GitHub.Unity/UI/BranchesView.cs | 96 +------------------ 2 files changed, 1 insertion(+), 145 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs index 5200df7ec..d7a4df91b 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs @@ -123,56 +123,6 @@ public List RemoteBranches } } - [Location("views/branches.yaml", LocationAttribute.Location.LibraryFolder)] - sealed class Favorites : ScriptObjectSingleton - { - [SerializeField] private List favoriteBranches; - public List FavoriteBranches - { - get - { - if (favoriteBranches == null) - FavoriteBranches = new List(); - return favoriteBranches; - } - set - { - favoriteBranches = value; - Save(true); - } - } - - public void SetFavorite(string branchName) - { - if (FavoriteBranches.Contains(branchName)) - return; - FavoriteBranches.Add(branchName); - Save(true); - } - - public void UnsetFavorite(string branchName) - { - if (!FavoriteBranches.Contains(branchName)) - return; - FavoriteBranches.Remove(branchName); - Save(true); - } - - public void ToggleFavorite(string branchName) - { - if (FavoriteBranches.Contains(branchName)) - FavoriteBranches.Remove(branchName); - else - FavoriteBranches.Add(branchName); - Save(true); - } - - public bool IsFavorite(string branchName) - { - return FavoriteBranches.Contains(branchName); - } - } - [Location("cache/gitlog.yaml", LocationAttribute.Location.LibraryFolder)] sealed class GitLogCache : ScriptObjectSingleton { diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs index 8c00a6f63..c3174362c 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs @@ -24,8 +24,6 @@ class BranchesView : Subview private const string WarningCheckoutBranchExistsOK = "Ok"; private const string NewBranchCancelButton = "x"; private const string NewBranchConfirmButton = "Create"; - private const string FavoritesSetting = "Favorites"; - private const string FavoritesTitle = "Favorites"; private const string CreateBranchTitle = "Create Branch"; private const string LocalTitle = "Local branches"; private const string RemoteTitle = "Remote branches"; @@ -38,11 +36,9 @@ class BranchesView : Subview private bool showLocalBranches = true; private bool showRemoteBranches = true; - [NonSerialized] private List favorites = new List(); [NonSerialized] private int listID = -1; [NonSerialized] private BranchTreeNode newNodeSelection; [NonSerialized] private BranchesMode targetMode; - [NonSerialized] private bool favoritesHasChanged; [SerializeField] private BranchTreeNode activeBranchNode; [SerializeField] private BranchTreeNode localRoot; @@ -51,7 +47,6 @@ class BranchesView : Subview [SerializeField] private List remotes = new List(); [SerializeField] private Vector2 scroll; [SerializeField] private BranchTreeNode selectedNode; - [SerializeField] private List favoritesList = new List(); public override void InitializeView(IView parent) { @@ -63,7 +58,6 @@ public override void OnEnable() { base.OnEnable(); AttachHandlers(Repository); - favoritesHasChanged = true; Refresh(); } @@ -81,11 +75,6 @@ public override void OnDataUpdate() private void MaybeUpdateData() { - if (favoritesHasChanged) - { - favoritesList = Manager.LocalSettings.Get(FavoritesSetting, new List()); - favoritesHasChanged = false; - } } public override void OnRepositoryChanged(IRepository oldRepository) @@ -158,28 +147,6 @@ public void OnEmbeddedGUI() GUILayout.BeginVertical(Styles.CommitFileAreaStyle); { - // Favorites list - if (favorites.Count > 0) - { - GUILayout.Label(FavoritesTitle); - GUILayout.BeginHorizontal(); - { - GUILayout.BeginVertical(); - { - for (var index = 0; index < favorites.Count; ++index) - { - OnTreeNodeGUI(favorites[index]); - } - } - - GUILayout.EndVertical(); - } - - GUILayout.EndHorizontal(); - - GUILayout.Space(Styles.BranchListSeperation); - } - // Local branches and "create branch" button showLocalBranches = EditorGUILayout.Foldout(showLocalBranches, LocalTitle); if (showLocalBranches) @@ -262,16 +229,6 @@ public void OnEmbeddedGUI() private int CompareBranches(GitBranch a, GitBranch b) { - if (IsFavorite(a.Name)) - { - return -1; - } - - if (IsFavorite(b.Name)) - { - return 1; - } - if (a.Name.Equals("master")) { return -1; @@ -285,11 +242,6 @@ private int CompareBranches(GitBranch a, GitBranch b) return 0; } - private bool IsFavorite(string branchName) - { - return !String.IsNullOrEmpty(branchName) && favoritesList.Contains(branchName); - } - private void BuildTree(IEnumerable local, IEnumerable remote) { //Clear the selected node @@ -305,9 +257,6 @@ private void BuildTree(IEnumerable local, IEnumerable remo var tracking = new List>(); var localBranchNodes = new List(); - // Prepare for updated favorites listing - favorites.Clear(); - // Just build directly on the local root, keep track of active branch localRoot = new BranchTreeNode("", NodeType.Folder, false); for (var index = 0; index < localBranches.Count; ++index) @@ -335,12 +284,6 @@ private void BuildTree(IEnumerable local, IEnumerable remo } } - // Add to favorites - if (favoritesList.Contains(branch.Name)) - { - favorites.Add(node); - } - // Build into tree BuildTree(localRoot, node); } @@ -379,12 +322,6 @@ private void BuildTree(IEnumerable local, IEnumerable remo } } - // Add to favorites - if (favoritesList.Contains(branch.Name)) - { - favorites.Add(node); - } - // Build on the root of the remote, just like with locals BuildTree(remotes[remoteIndex].Root, node); } @@ -417,26 +354,6 @@ private void BuildTree(BranchTreeNode parent, BranchTreeNode child) BuildTree(folder, child); } - private void SetFavorite(BranchTreeNode branch, bool favorite) - { - if (string.IsNullOrEmpty(branch.Name)) - { - return; - } - - if (!favorite) - { - favorites.Remove(branch); - Manager.LocalSettings.Set(FavoritesSetting, favorites.Select(x => x.Name).ToList()); - } - else - { - favorites.Remove(branch); - favorites.Add(branch); - Manager.LocalSettings.Set(FavoritesSetting, favorites.Select(x => x.Name).ToList()); - } - } - private void OnButtonBarGUI() { if (mode == BranchesMode.Default) @@ -591,23 +508,12 @@ private void OnTreeNodeGUI(BranchTreeNode node) if (node.Type != NodeType.Folder) { - var favorite = IsFavorite(node.Name); if (Event.current.type == EventType.Repaint) { - GUI.DrawTexture(favoriteRect, favorite ? Styles.FavoriteIconOn : Styles.FavoriteIconOff); - } - else if (Event.current.type == EventType.MouseDown && favoriteRect.Contains(Event.current.mousePosition)) - { - SetFavorite(node, !favorite); - Event.current.Use(); + GUI.DrawTexture(favoriteRect, Styles.FavoriteIconOff); } } } - // Favorite status - else if (Event.current.type == EventType.Repaint && node.Type != NodeType.Folder && IsFavorite(node.Name)) - { - GUI.DrawTexture(favoriteRect, Styles.FavoriteIconOn); - } // The actual icon and label if (Event.current.type == EventType.Repaint) From eeb44d10a54f9d8d304178ed5a383f3adf1c2cbb Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Mon, 30 Oct 2017 16:53:41 -0400 Subject: [PATCH 151/241] Removing redundant interfaces --- src/GitHub.Api/Cache/CacheInterfaces.cs | 33 ++++++------------------- 1 file changed, 7 insertions(+), 26 deletions(-) diff --git a/src/GitHub.Api/Cache/CacheInterfaces.cs b/src/GitHub.Api/Cache/CacheInterfaces.cs index 93b674360..6a5a6cce4 100644 --- a/src/GitHub.Api/Cache/CacheInterfaces.cs +++ b/src/GitHub.Api/Cache/CacheInterfaces.cs @@ -42,55 +42,36 @@ public interface IManagedCache DateTimeOffset LastVerifiedAt { get; } } - public interface IGitLocks + public interface IGitLocksCache : IManagedCache { List GitLocks { get; } } - public interface IGitLocksCache : IManagedCache, IGitLocks - { } - - public interface IGitUser + public interface IGitUserCache : IManagedCache { User User { get; } } - public interface ITestCacheItem - { } - - public interface IGitUserCache : IManagedCache, IGitUser - { } - - public interface IGitStatus + public interface IGitStatusCache : IManagedCache { GitStatus GitStatus { get; set; } } - public interface IGitStatusCache : IManagedCache, IGitStatus - { } - - public interface IRepositoryInfo - { - ConfigRemote? CurrentConfigRemote { get; set; } - ConfigBranch? CurentConfigBranch { get; set; } - } - - public interface IRepositoryInfoCache : IManagedCache, IRepositoryInfo + public interface IRepositoryInfoCache : IManagedCache { GitRemote? CurrentGitRemote { get; set; } GitBranch? CurentGitBranch { get; set; } + ConfigRemote? CurrentConfigRemote { get; set; } + ConfigBranch? CurentConfigBranch { get; set; } } - public interface IBranch + public interface IBranchCache : IManagedCache { void UpdateData(List localBranchUpdate, List remoteBranchUpdate); List LocalBranches { get; } List RemoteBranches { get; } } - public interface IBranchCache : IManagedCache, IBranch - { } - public interface IGitLogCache : IManagedCache { List Log { get; set; } From ae253f95d41f1346d7d01e0c9a8c7f839ba7714b Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Mon, 30 Oct 2017 18:33:06 -0400 Subject: [PATCH 152/241] Gross copy pasta error with removing a remote branch --- src/GitHub.Api/Git/Repository.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/GitHub.Api/Git/Repository.cs b/src/GitHub.Api/Git/Repository.cs index a28a7b679..be4ccc7a5 100644 --- a/src/GitHub.Api/Git/Repository.cs +++ b/src/GitHub.Api/Git/Repository.cs @@ -303,9 +303,9 @@ private void RepositoryManager_OnRemoteBranchRemoved(string remote, string name) Dictionary branchList; if (remoteBranches.TryGetValue(remote, out branchList)) { - if (localBranches.ContainsKey(name)) + if (branchList.ContainsKey(name)) { - localBranches.Remove(name); + branchList.Remove(name); Logger.Trace("OnRemoteBranchListChanged"); OnRemoteBranchListChanged?.Invoke(); From 735dfd9324224ce6dca42ab761bef663f742a3c3 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Mon, 30 Oct 2017 18:59:56 -0400 Subject: [PATCH 153/241] Removing chain of Refresh that does nothing --- src/GitHub.Api/Git/IRepository.cs | 1 - src/GitHub.Api/Git/Repository.cs | 6 ----- src/GitHub.Api/Git/RepositoryManager.cs | 6 ----- .../GitHub.Unity/UI/ProjectWindowInterface.cs | 22 ------------------- 4 files changed, 35 deletions(-) diff --git a/src/GitHub.Api/Git/IRepository.cs b/src/GitHub.Api/Git/IRepository.cs index 61ce4dff3..4a9fb99a0 100644 --- a/src/GitHub.Api/Git/IRepository.cs +++ b/src/GitHub.Api/Git/IRepository.cs @@ -9,7 +9,6 @@ namespace GitHub.Unity public interface IRepository : IEquatable { void Initialize(IRepositoryManager repositoryManager); - void Refresh(); ITask CommitAllFiles(string message, string body); ITask CommitFiles(List files, string message, string body); ITask SetupRemote(string remoteName, string remoteUrl); diff --git a/src/GitHub.Api/Git/Repository.cs b/src/GitHub.Api/Git/Repository.cs index fd8b47e58..8c657c4ea 100644 --- a/src/GitHub.Api/Git/Repository.cs +++ b/src/GitHub.Api/Git/Repository.cs @@ -149,11 +149,6 @@ public void Initialize(IRepositoryManager initRepositoryManager) UpdateGitLog(); } - public void Refresh() - { - repositoryManager?.Refresh(); - } - public ITask SetupRemote(string remote, string remoteUrl) { Guard.ArgumentNotNullOrWhiteSpace(remote, "remote"); @@ -355,7 +350,6 @@ private void RepositoryManager_OnLocalBranchUpdated(string name) { Logger.Trace("OnCurrentBranchUpdated: {0}", name); OnCurrentBranchUpdated?.Invoke(); - Refresh(); } } diff --git a/src/GitHub.Api/Git/RepositoryManager.cs b/src/GitHub.Api/Git/RepositoryManager.cs index 18f74fe1c..b940eca93 100644 --- a/src/GitHub.Api/Git/RepositoryManager.cs +++ b/src/GitHub.Api/Git/RepositoryManager.cs @@ -24,7 +24,6 @@ public interface IRepositoryManager : IDisposable void Initialize(); void Start(); void Stop(); - void Refresh(); ITask CommitAllFiles(string message, string body); ITask CommitFiles(List files, string message, string body); ITask> Log(); @@ -176,11 +175,6 @@ public int WaitForEvents() return watcher.CheckAndProcessEvents(); } - public void Refresh() - { - Logger.Trace("Refresh"); - } - public ITask CommitAllFiles(string message, string body) { var add = GitClient.AddAll(); diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ProjectWindowInterface.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ProjectWindowInterface.cs index 3fe1fd2ca..764c4d429 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ProjectWindowInterface.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ProjectWindowInterface.cs @@ -126,28 +126,6 @@ private static void ContextMenu_Unlock() }) .Start(); } - public static void Run() - { - Refresh(); - } - - private static void OnPostprocessAllAssets(string[] imported, string[] deleted, string[] moveDestination, string[] moveSource) - { - Refresh(); - } - - private static void Refresh() - { - if (repository == null) - return; - if (initialized) - { - if (!DefaultEnvironment.OnWindows) - { - repository.Refresh(); - } - } - } private static void RunLocksUpdateOnMainThread(IEnumerable update) { From 95315d73957cb5e43e29d42aeac9ca6c14e5bb6e Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Tue, 31 Oct 2017 08:31:06 -0400 Subject: [PATCH 154/241] Removing additional unused parts of favorites --- .../Assets/Editor/GitHub.Unity/UI/BranchesView.cs | 9 --------- 1 file changed, 9 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs index c3174362c..9cd70d371 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs @@ -493,7 +493,6 @@ private void OnTreeNodeGUI(BranchTreeNode node) var style = node.Active ? Styles.BoldLabel : Styles.Label; var rect = GUILayoutUtility.GetRect(content, style, GUILayout.MaxHeight(EditorGUIUtility.singleLineHeight)); var clickRect = new Rect(0f, rect.y, Position.width, rect.height); - var favoriteRect = new Rect(clickRect.xMax - clickRect.height * 2f, clickRect.y, clickRect.height, clickRect.height); var selected = selectedNode == node; var keyboardFocus = GUIUtility.keyboardControl == listID; @@ -505,14 +504,6 @@ private void OnTreeNodeGUI(BranchTreeNode node) { style.Draw(clickRect, GUIContent.none, false, false, true, keyboardFocus); } - - if (node.Type != NodeType.Folder) - { - if (Event.current.type == EventType.Repaint) - { - GUI.DrawTexture(favoriteRect, Styles.FavoriteIconOff); - } - } } // The actual icon and label From fb92b546ab5804fed1a641d09974a0b6288ef2e9 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Tue, 31 Oct 2017 11:00:48 -0400 Subject: [PATCH 155/241] Adding SerializableDictionary --- .../Editor/GitHub.Unity/GitHub.Unity.csproj | 1 + .../GitHub.Unity/SerializableDictionary.cs | 43 +++++++++++++++++++ 2 files changed, 44 insertions(+) create mode 100644 src/UnityExtension/Assets/Editor/GitHub.Unity/SerializableDictionary.cs diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/GitHub.Unity.csproj b/src/UnityExtension/Assets/Editor/GitHub.Unity/GitHub.Unity.csproj index 4dfba8277..c59eaeca6 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/GitHub.Unity.csproj +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/GitHub.Unity.csproj @@ -80,6 +80,7 @@ + diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/SerializableDictionary.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/SerializableDictionary.cs new file mode 100644 index 000000000..18fb23c78 --- /dev/null +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/SerializableDictionary.cs @@ -0,0 +1,43 @@ +using System; +using System.Collections.Generic; +using UnityEngine; + + +namespace GitHub.Unity +{ + //http://answers.unity3d.com/answers/809221/view.html + + [Serializable] + public class SerializableDictionary : Dictionary, ISerializationCallbackReceiver + { + [SerializeField] + private List keys = new List(); + + [SerializeField] + private List values = new List(); + + // save the dictionary to lists + public void OnBeforeSerialize() + { + keys.Clear(); + values.Clear(); + foreach (KeyValuePair pair in this) + { + keys.Add(pair.Key); + values.Add(pair.Value); + } + } + + // load dictionary from lists + public void OnAfterDeserialize() + { + this.Clear(); + + if (keys.Count != values.Count) + throw new System.Exception(string.Format("there are {0} keys and {1} values after deserialization. Make sure that both key and value types are serializable.")); + + for (int i = 0; i < keys.Count; i++) + this.Add(keys[i], values[i]); + } + } +} \ No newline at end of file From 31e7af61428869859571c427c83e3d18458f840b Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Tue, 31 Oct 2017 16:35:54 -0400 Subject: [PATCH 156/241] Getting branches to work with the cache --- src/GitHub.Api/Cache/CacheInterfaces.cs | 39 +- src/GitHub.Api/Git/IRepository.cs | 15 +- src/GitHub.Api/Git/Repository.cs | 237 ++++------ src/GitHub.Api/Git/RepositoryManager.cs | 10 +- .../Editor/GitHub.Unity/ApplicationCache.cs | 410 ++++++++++++++---- .../Editor/GitHub.Unity/CacheContainer.cs | 21 - .../Editor/GitHub.Unity/UI/BranchesView.cs | 66 +-- .../Editor/GitHub.Unity/UI/ChangesView.cs | 20 +- .../Editor/GitHub.Unity/UI/HistoryView.cs | 20 +- .../Editor/GitHub.Unity/UI/SettingsView.cs | 7 - .../Assets/Editor/GitHub.Unity/UI/Window.cs | 18 +- .../Events/RepositoryManagerTests.cs | 60 +-- .../TestUtils/Events/IRepositoryListener.cs | 62 --- .../Events/IRepositoryManagerListener.cs | 8 +- src/tests/UnitTests/Git/RepositoryTests.cs | 23 +- 15 files changed, 553 insertions(+), 463 deletions(-) diff --git a/src/GitHub.Api/Cache/CacheInterfaces.cs b/src/GitHub.Api/Cache/CacheInterfaces.cs index 6a5a6cce4..5242a4849 100644 --- a/src/GitHub.Api/Cache/CacheInterfaces.cs +++ b/src/GitHub.Api/Cache/CacheInterfaces.cs @@ -7,7 +7,6 @@ public enum CacheType { BranchCache, GitLogCache, - RepositoryInfoCache, GitStatusCache, GitLocksCache, GitUserCache @@ -20,7 +19,6 @@ public interface ICacheContainer IBranchCache BranchCache { get; } IGitLogCache GitLogCache { get; } - IRepositoryInfoCache RepositoryInfoCache { get; } IGitStatusCache GitStatusCache { get; } IGitLocksCache GitLocksCache { get; } IGitUserCache GitUserCache { get; } @@ -57,19 +55,42 @@ public interface IGitStatusCache : IManagedCache GitStatus GitStatus { get; set; } } - public interface IRepositoryInfoCache : IManagedCache + public interface ILocalConfigBranchDictionary : IDictionary + { + + } + + public interface IRemoteConfigBranchDictionary : IDictionary> + { + + } + + public interface IConfigRemoteDictionary : IDictionary + { + + } + + public interface IBranchCache : IManagedCache { GitRemote? CurrentGitRemote { get; set; } GitBranch? CurentGitBranch { get; set; } ConfigRemote? CurrentConfigRemote { get; set; } ConfigBranch? CurentConfigBranch { get; set; } - } + + GitBranch[] LocalBranches { get; set; } + GitBranch[] RemoteBranches { get; set; } + GitRemote[] Remotes { get; set; } - public interface IBranchCache : IManagedCache - { - void UpdateData(List localBranchUpdate, List remoteBranchUpdate); - List LocalBranches { get; } - List RemoteBranches { get; } + ILocalConfigBranchDictionary LocalConfigBranches { get; } + IRemoteConfigBranchDictionary RemoteConfigBranches { get; } + IConfigRemoteDictionary ConfigRemotes { get; } + + void RemoveLocalBranch(string branch); + void AddLocalBranch(string branch); + void AddRemoteBranch(string remote, string branch); + void RemoveRemoteBranch(string remote, string branch); + void SetRemotes(IDictionary remoteDictionary, IDictionary> branchDictionary); + void SetLocals(IDictionary branchDictionary); } public interface IGitLogCache : IManagedCache diff --git a/src/GitHub.Api/Git/IRepository.cs b/src/GitHub.Api/Git/IRepository.cs index 4a9fb99a0..81e7ff784 100644 --- a/src/GitHub.Api/Git/IRepository.cs +++ b/src/GitHub.Api/Git/IRepository.cs @@ -20,7 +20,7 @@ public interface IRepository : IEquatable ITask RequestLock(string file); ITask ReleaseLock(string file, bool force); - void CheckRepositoryInfoCacheEvent(CacheUpdateEvent cacheUpdateEvent); + void CheckBranchCacheEvent(CacheUpdateEvent cacheUpdateEvent); void CheckGitStatusCacheEvent(CacheUpdateEvent cacheUpdateEvent); void CheckGitLogCacheEvent(CacheUpdateEvent cacheUpdateEvent); @@ -53,23 +53,18 @@ public interface IRepository : IEquatable /// GitBranch? CurrentBranch { get; } GitStatus CurrentStatus { get; } - IList Remotes { get; } - IEnumerable LocalBranches { get; } - IEnumerable RemoteBranches { get; } + GitRemote[] Remotes { get; } + GitBranch[] LocalBranches { get; } + GitBranch[] RemoteBranches { get; } IUser User { get; set; } IList CurrentLocks { get; } string CurrentBranchName { get; } List CurrentLog { get; } - event Action OnCurrentBranchChanged; - event Action OnCurrentRemoteChanged; - event Action OnLocalBranchListChanged; - event Action OnCurrentBranchUpdated; event Action> OnLocksChanged; event Action OnRepositoryInfoChanged; - event Action OnRemoteBranchListChanged; - event Action RepositoryInfoCacheUpdated; event Action GitStatusCacheUpdated; event Action GitLogCacheUpdated; + event Action BranchCacheUpdated; } } \ No newline at end of file diff --git a/src/GitHub.Api/Git/Repository.cs b/src/GitHub.Api/Git/Repository.cs index 8c657c4ea..a4187157a 100644 --- a/src/GitHub.Api/Git/Repository.cs +++ b/src/GitHub.Api/Git/Repository.cs @@ -1,4 +1,5 @@ using System; +using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; @@ -11,23 +12,15 @@ namespace GitHub.Unity class Repository : IEquatable, IRepository { private IList currentLocks; - private Dictionary localBranches = new Dictionary(); - private Dictionary> remoteBranches = new Dictionary>(); - private Dictionary remotes; private IRepositoryManager repositoryManager; private ICacheContainer cacheContainer; - public event Action OnCurrentBranchChanged; - public event Action OnCurrentRemoteChanged; - public event Action OnCurrentBranchUpdated; - public event Action OnLocalBranchListChanged; public event Action> OnLocksChanged; - public event Action OnRemoteBranchListChanged; public event Action OnRepositoryInfoChanged; - public event Action RepositoryInfoCacheUpdated; public event Action GitStatusCacheUpdated; public event Action GitLogCacheUpdated; + public event Action BranchCacheUpdated; /// /// Initializes a new instance of the class. @@ -61,9 +54,6 @@ private void CacheContainer_OnCacheInvalidated(CacheType cacheType) case CacheType.GitLogCache: break; - case CacheType.RepositoryInfoCache: - break; - case CacheType.GitStatusCache: break; @@ -83,16 +73,13 @@ private void CacheContainer_OnCacheUpdated(CacheType cacheType, DateTimeOffset o switch (cacheType) { case CacheType.BranchCache: + FireBranchCacheUpdated(offset); break; case CacheType.GitLogCache: FireGitLogCacheUpdated(offset); break; - case CacheType.RepositoryInfoCache: - FireRepositoryInfoCacheUpdated(offset); - break; - case CacheType.GitStatusCache: FireGitStatusCacheUpdated(offset); break; @@ -114,10 +101,10 @@ private void FireGitLogCacheUpdated(DateTimeOffset dateTimeOffset) GitLogCacheUpdated?.Invoke(new CacheUpdateEvent { UpdatedTimeString = dateTimeOffset.ToString() }); } - private void FireRepositoryInfoCacheUpdated(DateTimeOffset dateTimeOffset) + private void FireBranchCacheUpdated(DateTimeOffset dateTimeOffset) { - Logger.Trace("RepositoryInfoCacheUpdated {0}", dateTimeOffset); - RepositoryInfoCacheUpdated?.Invoke(new CacheUpdateEvent { UpdatedTimeString = dateTimeOffset.ToString() }); + Logger.Trace("BranchCacheUpdated {0}", dateTimeOffset); + BranchCacheUpdated?.Invoke(new CacheUpdateEvent { UpdatedTimeString = dateTimeOffset.ToString() }); } private void FireGitStatusCacheUpdated(DateTimeOffset dateTimeOffset) @@ -210,19 +197,19 @@ public ITask ReleaseLock(string file, bool force) return repositoryManager.UnlockFile(file, force); } - public void CheckRepositoryInfoCacheEvent(CacheUpdateEvent cacheUpdateEvent) + public void CheckBranchCacheEvent(CacheUpdateEvent cacheUpdateEvent) { - var managedCache = cacheContainer.RepositoryInfoCache; + var managedCache = cacheContainer.BranchCache; var raiseEvent = ShouldRaiseCacheEvent(cacheUpdateEvent, managedCache); - Logger.Trace("CheckRepositoryInfoCacheEvent Current:{0} Check:{1} Result:{2}", + Logger.Trace("CheckBranchCacheEvent Current:{0} Check:{1} Result:{2}", managedCache.LastUpdatedAt, cacheUpdateEvent.UpdatedTimeString ?? "[NULL]", raiseEvent); if (raiseEvent) { - FireRepositoryInfoCacheUpdated(managedCache.LastUpdatedAt); + FireBranchCacheUpdated(managedCache.LastUpdatedAt); } } @@ -307,12 +294,11 @@ private void RepositoryManager_OnCurrentRemoteUpdated(ConfigRemote? remote) { if (!Nullable.Equals(CurrentConfigRemote, remote)) { - CurrentConfigRemote = remote; - - Logger.Trace("OnCurrentRemoteChanged: {0}", remote.HasValue ? remote.Value.ToString() : "[NULL]"); - OnCurrentRemoteChanged?.Invoke(remote.HasValue ? remote.Value.Name : null); - - UpdateRepositoryInfo(); + new ActionTask(CancellationToken.None, () => { + CurrentConfigRemote = remote; + CurrentRemote = GetGitRemote(remote.Value); + UpdateRepositoryInfo(); + }) {Affinity = TaskAffinity.UI}.Start(); } } @@ -337,10 +323,16 @@ private void RepositoryManager_OnCurrentBranchUpdated(ConfigBranch? branch) { if (!Nullable.Equals(CurrentConfigBranch, branch)) { - CurrentConfigBranch = branch; - - Logger.Trace("OnCurrentBranchChanged: {0}", branch.HasValue ? branch.ToString() : "[NULL]"); - OnCurrentBranchChanged?.Invoke(branch.HasValue ? branch.Value.Name : null); + new ActionTask(CancellationToken.None, () => + { + var currentBranch = branch != null + ? (GitBranch?)GetLocalGitBranch(branch.Value) + : null; + + CurrentConfigBranch = branch; + CurrentBranch = currentBranch; + }) + { Affinity = TaskAffinity.UI }.Start(); } } @@ -349,28 +341,44 @@ private void RepositoryManager_OnLocalBranchUpdated(string name) if (name == CurrentConfigBranch?.Name) { Logger.Trace("OnCurrentBranchUpdated: {0}", name); - OnCurrentBranchUpdated?.Invoke(); } } - private void RepositoryManager_OnRemoteBranchListUpdated(Dictionary updatedRemotes, Dictionary> branches) + private void RepositoryManager_OnRemoteBranchListUpdated(IDictionary remotes, IDictionary> branches) { - remotes = updatedRemotes; - - Remotes = remotes.Select(pair => GetGitRemote(pair.Value)).ToArray(); - - remoteBranches = branches; + new ActionTask(CancellationToken.None, () => + { + cacheContainer.BranchCache.SetRemotes(remotes, branches); + UpdateRemoteAndRemoteBranches(); + }) + { Affinity = TaskAffinity.UI }.Start(); + } - Logger.Trace("OnRemoteBranchListChanged"); - OnRemoteBranchListChanged?.Invoke(); + private void UpdateRemoteAndRemoteBranches() + { + cacheContainer.BranchCache.Remotes = + cacheContainer.BranchCache.ConfigRemotes.Values + .Select(GetGitRemote) + .ToArray(); + + cacheContainer.BranchCache.RemoteBranches = + cacheContainer.BranchCache.RemoteConfigBranches.Values + .SelectMany(x => x.Values).Select(GetRemoteGitBranch) + .ToArray(); } - private void RepositoryManager_OnLocalBranchListUpdated(Dictionary branches) + private void RepositoryManager_OnLocalBranchListUpdated(IDictionary branches) { - localBranches = branches; + new ActionTask(CancellationToken.None, () => { + cacheContainer.BranchCache.SetLocals(branches); + UpdateLocalBranches(); + }) + { Affinity = TaskAffinity.UI }.Start(); + } - Logger.Trace("OnLocalBranchListChanged"); - OnLocalBranchListChanged?.Invoke(); + private void UpdateLocalBranches() + { + cacheContainer.BranchCache.LocalBranches = cacheContainer.BranchCache.LocalConfigBranches.Values.Select(GetLocalGitBranch).ToArray(); } private void UpdateRepositoryInfo() @@ -393,142 +401,81 @@ private void UpdateRepositoryInfo() private void RepositoryManager_OnLocalBranchRemoved(string name) { - if (localBranches.ContainsKey(name)) - { - localBranches.Remove(name); - - Logger.Trace("OnLocalBranchListChanged"); - OnLocalBranchListChanged?.Invoke(); - } - else + new ActionTask(CancellationToken.None, () => { - Logger.Warning("Branch {0} is not found", name); - } + cacheContainer.BranchCache.RemoveLocalBranch(name); + UpdateLocalBranches(); + }) + { Affinity = TaskAffinity.UI }.Start(); } private void RepositoryManager_OnLocalBranchAdded(string name) { - if (!localBranches.ContainsKey(name)) + new ActionTask(CancellationToken.None, () => { - var branch = repositoryManager.Config.GetBranch(name); - if (!branch.HasValue) - { - branch = new ConfigBranch { Name = name }; - } - localBranches.Add(name, branch.Value); - - Logger.Trace("OnLocalBranchListChanged"); - OnLocalBranchListChanged?.Invoke(); - } - else - { - Logger.Warning("Branch {0} is already present", name); - } + cacheContainer.BranchCache.AddLocalBranch(name); + UpdateLocalBranches(); + }) + { Affinity = TaskAffinity.UI }.Start(); } private void RepositoryManager_OnRemoteBranchAdded(string remote, string name) { - Dictionary branchList; - if (remoteBranches.TryGetValue(remote, out branchList)) - { - if (!branchList.ContainsKey(name)) - { - branchList.Add(name, new ConfigBranch { Name = name, Remote = remotes[remote] }); - - Logger.Trace("OnRemoteBranchListChanged"); - OnRemoteBranchListChanged?.Invoke(); - } - else - { - Logger.Warning("Branch {0} is already present in Remote {1}", name, remote); - } - } - else + new ActionTask(CancellationToken.None, () => { - Logger.Warning("Remote {0} is not found", remote); - } + cacheContainer.BranchCache.AddRemoteBranch(remote, name); + UpdateRemoteAndRemoteBranches(); + }) + { Affinity = TaskAffinity.UI }.Start(); } private void RepositoryManager_OnRemoteBranchRemoved(string remote, string name) { - Dictionary branchList; - if (remoteBranches.TryGetValue(remote, out branchList)) + new ActionTask(CancellationToken.None, () => { - if (branchList.ContainsKey(name)) - { - branchList.Remove(name); - - Logger.Trace("OnRemoteBranchListChanged"); - OnRemoteBranchListChanged?.Invoke(); - } - else - { - Logger.Warning("Branch {0} is not found in Remote {1}", name, remote); - } - } - else - { - Logger.Warning("Remote {0} is not found", remote); - } + cacheContainer.BranchCache.RemoveRemoteBranch(remote, name); + UpdateRemoteAndRemoteBranches(); + }) + { Affinity = TaskAffinity.UI }.Start(); } private GitBranch GetLocalGitBranch(ConfigBranch x) { var name = x.Name; var trackingName = x.IsTracking ? x.Remote.Value.Name + "/" + name : "[None]"; - var isActive = name == CurrentConfigBranch?.Name; + var isActive = name == CurrentBranchName; - return new GitBranch { - Name = name, - Tracking = trackingName, - IsActive = isActive - }; + return new GitBranch {Name= name, Tracking = trackingName, IsActive = isActive}; } - private GitBranch GetRemoteGitBranch(ConfigBranch x) + private static GitBranch GetRemoteGitBranch(ConfigBranch x) { var name = x.Remote.Value.Name + "/" + x.Name; - var trackingName = "[None]"; - return new GitBranch { - Name = name, - Tracking = trackingName, - IsActive = false - }; + return new GitBranch {Name= name}; } - private GitRemote GetGitRemote(ConfigRemote configRemote) + private static GitRemote GetGitRemote(ConfigRemote configRemote) { return new GitRemote { Name = configRemote.Name, Url = configRemote.Url }; } - public IList Remotes { get; private set; } + public GitRemote[] Remotes => cacheContainer.BranchCache.Remotes; - public IEnumerable LocalBranches => localBranches.Values.Select(GetLocalGitBranch); + public GitBranch[] LocalBranches => cacheContainer.BranchCache.LocalBranches; - public IEnumerable RemoteBranches => remoteBranches.Values.SelectMany(x => x.Values).Select(GetRemoteGitBranch); + public GitBranch[] RemoteBranches => cacheContainer.BranchCache.RemoteBranches; private ConfigBranch? CurrentConfigBranch { - get { return this.cacheContainer.RepositoryInfoCache.CurentConfigBranch; } - set - { - cacheContainer.RepositoryInfoCache.CurentConfigBranch = value; - cacheContainer.RepositoryInfoCache.CurentGitBranch = value != null - ? (GitBranch?)GetLocalGitBranch(value.Value) - : null; - } + get { return this.cacheContainer.BranchCache.CurentConfigBranch; } + set { cacheContainer.BranchCache.CurentConfigBranch = value;} } private ConfigRemote? CurrentConfigRemote { - get { return this.cacheContainer.RepositoryInfoCache.CurrentConfigRemote; } - set { - cacheContainer.RepositoryInfoCache.CurrentConfigRemote = value; - cacheContainer.RepositoryInfoCache.CurrentGitRemote = value != null - ? (GitRemote?) GetGitRemote(value.Value) - : null; - } + get { return this.cacheContainer.BranchCache.CurrentConfigRemote; } + set { cacheContainer.BranchCache.CurrentConfigRemote = value; } } public GitStatus CurrentStatus @@ -537,11 +484,19 @@ public GitStatus CurrentStatus set { cacheContainer.GitStatusCache.GitStatus = value; } } - public GitBranch? CurrentBranch => cacheContainer.RepositoryInfoCache.CurentGitBranch; + public GitBranch? CurrentBranch + { + get { return cacheContainer.BranchCache.CurentGitBranch; } + set { cacheContainer.BranchCache.CurentGitBranch = value; } + } public string CurrentBranchName => CurrentConfigBranch?.Name; - public GitRemote? CurrentRemote => cacheContainer.RepositoryInfoCache.CurrentGitRemote; + public GitRemote? CurrentRemote + { + get { return cacheContainer.BranchCache.CurrentGitRemote; } + set { cacheContainer.BranchCache.CurrentGitRemote = value; } + } public List CurrentLog { diff --git a/src/GitHub.Api/Git/RepositoryManager.cs b/src/GitHub.Api/Git/RepositoryManager.cs index b940eca93..ca499584d 100644 --- a/src/GitHub.Api/Git/RepositoryManager.cs +++ b/src/GitHub.Api/Git/RepositoryManager.cs @@ -12,12 +12,12 @@ public interface IRepositoryManager : IDisposable event Action OnGitUserLoaded; event Action OnIsBusyChanged; event Action OnLocalBranchAdded; - event Action> OnLocalBranchListUpdated; + event Action> OnLocalBranchListUpdated; event Action OnLocalBranchRemoved; event Action OnLocalBranchUpdated; event Action> OnLocksUpdated; event Action OnRemoteBranchAdded; - event Action, Dictionary>> OnRemoteBranchListUpdated; + event Action, IDictionary>> OnRemoteBranchListUpdated; event Action OnRemoteBranchRemoved; event Action OnRepositoryUpdated; @@ -107,12 +107,12 @@ class RepositoryManager : IRepositoryManager public event Action OnGitUserLoaded; public event Action OnIsBusyChanged; public event Action OnLocalBranchAdded; - public event Action> OnLocalBranchListUpdated; + public event Action> OnLocalBranchListUpdated; public event Action OnLocalBranchRemoved; public event Action OnLocalBranchUpdated; public event Action> OnLocksUpdated; public event Action OnRemoteBranchAdded; - public event Action, Dictionary>> OnRemoteBranchListUpdated; + public event Action, IDictionary>> OnRemoteBranchListUpdated; public event Action OnRemoteBranchRemoved; public event Action OnRepositoryUpdated; @@ -519,7 +519,7 @@ private void LoadRemotesFromConfig() Logger.Trace("LoadRemotesFromConfig"); var remotes = config.GetRemotes().ToArray().ToDictionary(x => x.Name, x => x); - var remoteBranches = new Dictionary>(); + var remoteBranches = new Dictionary>(); foreach (var remote in remotes.Keys) { diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs index cd2c63847..e778df670 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs @@ -1,8 +1,10 @@ using System; using System.Collections.Generic; using System.Linq; +using Octokit; using UnityEditor; using UnityEngine; +using Application = UnityEngine.Application; namespace GitHub.Unity { @@ -116,14 +118,6 @@ public void InvalidateData() SaveData(DateTimeOffset.Now, true); } - private void ResetData() - { - Logger.Trace("ResetData"); - OnResetData(); - } - - protected abstract void OnResetData(); - protected void SaveData(DateTimeOffset now, bool isUpdated) { if (isUpdated) @@ -187,79 +181,155 @@ public DateTimeOffset LastVerifiedAt protected ILogging Logger { get; private set; } } - [Location("cache/branches.yaml", LocationAttribute.Location.LibraryFolder)] - sealed class BranchCache : ManagedCacheBase, IBranchCache + [Serializable] + class LocalConfigBranchDictionary : SerializableDictionary, ILocalConfigBranchDictionary { - [SerializeField] private string lastUpdatedAtString = DateTimeOffset.MinValue.ToString(); - [SerializeField] private string lastVerifiedAtString = DateTimeOffset.MinValue.ToString(); - [SerializeField] private List localBranches = new List(); - [SerializeField] private List remoteBranches = new List(); + public LocalConfigBranchDictionary() + { } - public void UpdateData(List localBranchUpdate, List remoteBranchUpdate) + public LocalConfigBranchDictionary(IDictionary dictionary) : base() { - var now = DateTimeOffset.Now; - var isUpdated = false; - - Logger.Trace("Processing Update: {0}", now); - - var localBranchesIsNull = localBranches == null; - var localBranchUpdateIsNull = localBranchUpdate == null; - - if (localBranchesIsNull != localBranchUpdateIsNull || - !localBranchesIsNull && !localBranches.SequenceEqual(localBranchUpdate)) + foreach (var pair in dictionary) { - localBranches = localBranchUpdate; - isUpdated = true; + this.Add(pair.Key, pair.Value); } + } + } - var remoteBranchesIsNull = remoteBranches == null; - var remoteBranchUpdateIsNull = remoteBranchUpdate == null; + [Serializable] + class RemoteConfigBranchDictionary : SerializableDictionary>, IRemoteConfigBranchDictionary + { + public RemoteConfigBranchDictionary() + { } - if (remoteBranchesIsNull != remoteBranchUpdateIsNull || - !remoteBranchesIsNull && !remoteBranches.SequenceEqual(remoteBranchUpdate)) + public RemoteConfigBranchDictionary(IDictionary> dictionary) + { + foreach (var pair in dictionary) { - remoteBranches = remoteBranchUpdate; - isUpdated = true; + this.Add(pair.Key, new LocalConfigBranchDictionary(pair.Value)); } + } - SaveData(now, isUpdated); + IEnumerator>> IEnumerable>>.GetEnumerator() + { + throw new NotImplementedException(); + //return AsDictionary + // .Select(pair => new KeyValuePair>(pair.Key, pair.Value.AsDictionary)) + // .GetEnumerator(); } - public List LocalBranches { - get { return localBranches; } + void ICollection>>.Add(KeyValuePair> item) + { + throw new NotImplementedException(); + //Guard.ArgumentNotNull(item, "item"); + //Guard.ArgumentNotNull(item.Value, "item.Value"); + // + //var serializableDictionary = item.Value as SerializableDictionary; + //if (serializableDictionary == null) + //{ + // serializableDictionary = new SerializableDictionary(item.Value); + //} + // + //Add(item.Key, serializableDictionary); } - public List RemoteBranches + bool ICollection>>.Contains(KeyValuePair> item) { - get { return remoteBranches; } + throw new NotImplementedException(); } - public void UpdateData() + void ICollection>>.CopyTo(KeyValuePair>[] array, int arrayIndex) { - SaveData(DateTimeOffset.Now, false); + throw new NotImplementedException(); } - protected override void OnResetData() + bool ICollection>>.Remove(KeyValuePair> item) { - localBranches = new List(); - remoteBranches = new List(); + throw new NotImplementedException(); } - public override string LastUpdatedAtString + bool ICollection>>.IsReadOnly { - get { return lastUpdatedAtString; } - protected set { lastUpdatedAtString = value; } + get { throw new NotImplementedException(); } } - public override string LastVerifiedAtString + void IDictionary>.Add(string key, IDictionary value) { - get { return lastVerifiedAtString; } - protected set { lastVerifiedAtString = value; } + throw new NotImplementedException(); + } + + bool IDictionary>.TryGetValue(string key, out IDictionary value) + { + throw new NotImplementedException(); + //value = null; + // + //SerializableDictionary branches; + //if (TryGetValue(key, out branches)) + //{ + // value = branches.AsDictionary; + // return true; + //} + // + //return false; + } + + IDictionary IDictionary>.this[string key] + { + get + { + throw new NotImplementedException(); + //var dictionary = (IDictionary>)this; + //IDictionary value; + //if (!dictionary.TryGetValue(key, out value)) + //{ + // throw new KeyNotFoundException(); + //} + // + //return value; + } + set + { + throw new NotImplementedException(); + //var dictionary = (IDictionary>)this; + //dictionary.Add(key, value); + } + } + + ICollection IDictionary>.Keys + { + get + { + throw new NotImplementedException(); + } + } + + ICollection> IDictionary>.Values + { + get + { + throw new NotImplementedException(); + //return AsDictionary.Select(pair => pair.Value.AsDictionary).ToArray(); + } + } + } + + [Serializable] + class ConfigRemoteDictionary : SerializableDictionary, IConfigRemoteDictionary + { + public ConfigRemoteDictionary() + { } + + public ConfigRemoteDictionary(IDictionary dictionary) + { + foreach (var pair in dictionary) + { + this.Add(pair.Key, pair.Value); + } } } - [Location("cache/repoinfo.yaml", LocationAttribute.Location.LibraryFolder)] - sealed class RepositoryInfoCache : ManagedCacheBase, IRepositoryInfoCache + [Location("cache/branches.yaml", LocationAttribute.Location.LibraryFolder)] + sealed class BranchCache : ManagedCacheBase, IBranchCache { public static readonly ConfigBranch DefaultConfigBranch = new ConfigBranch(); public static readonly ConfigRemote DefaultConfigRemote = new ConfigRemote(); @@ -268,35 +338,26 @@ sealed class RepositoryInfoCache : ManagedCacheBase, IRepos [SerializeField] private string lastUpdatedAtString = DateTimeOffset.MinValue.ToString(); [SerializeField] private string lastVerifiedAtString = DateTimeOffset.MinValue.ToString(); + + [SerializeField] private GitBranch[] localBranches = new GitBranch[0]; + [SerializeField] private GitBranch[] remoteBranches = new GitBranch[0]; + [SerializeField] private GitRemote[] remotes = new GitRemote[0]; + + [SerializeField] private LocalConfigBranchDictionary localConfigBranches = new LocalConfigBranchDictionary(); + [SerializeField] private RemoteConfigBranchDictionary remoteConfigBranches = new RemoteConfigBranchDictionary(); + [SerializeField] private ConfigRemoteDictionary configRemotes = new ConfigRemoteDictionary(); + [SerializeField] private ConfigBranch gitConfigBranch; [SerializeField] private ConfigRemote gitConfigRemote; [SerializeField] private GitRemote gitRemote; [SerializeField] private GitBranch gitBranch; - protected override void OnResetData() - { - gitConfigBranch = DefaultConfigBranch; - gitConfigRemote = DefaultConfigRemote; - } - - public override string LastUpdatedAtString - { - get { return lastUpdatedAtString; } - protected set { lastUpdatedAtString = value; } - } - - public override string LastVerifiedAtString - { - get { return lastVerifiedAtString; } - protected set { lastVerifiedAtString = value; } - } - public ConfigRemote? CurrentConfigRemote { get { ValidateData(); - return gitConfigRemote.Equals(DefaultConfigRemote) ? (ConfigRemote?) null : gitConfigRemote; + return gitConfigRemote.Equals(DefaultConfigRemote) ? (ConfigRemote?)null : gitConfigRemote; } set { @@ -320,7 +381,7 @@ public ConfigBranch? CurentConfigBranch get { ValidateData(); - return gitConfigBranch.Equals(DefaultConfigBranch) ? (ConfigBranch?) null : gitConfigBranch; + return gitConfigBranch.Equals(DefaultConfigBranch) ? (ConfigBranch?)null : gitConfigBranch; } set { @@ -344,7 +405,7 @@ public GitRemote? CurrentGitRemote get { ValidateData(); - return gitRemote.Equals(DefaultGitRemote) ? (GitRemote?) null : gitRemote; + return gitRemote.Equals(DefaultGitRemote) ? (GitRemote?)null : gitRemote; } set { @@ -386,6 +447,191 @@ public GitBranch? CurentGitBranch SaveData(now, isUpdated); } } + + public GitBranch[] LocalBranches { + get { return localBranches; } + set + { + var now = DateTimeOffset.Now; + var isUpdated = false; + + Logger.Trace("Updating: {0} localBranches:{1}", now, value); + + var localBranchesIsNull = localBranches == null; + var valueIsNull = value == null; + + if (localBranchesIsNull != valueIsNull || + !localBranchesIsNull && !localBranches.SequenceEqual(value)) + { + localBranches = value; + isUpdated = true; + } + + SaveData(now, isUpdated); + } + } + + public ILocalConfigBranchDictionary LocalConfigBranches + { + get { return localConfigBranches; } + } + + public GitBranch[] RemoteBranches + { + get { return remoteBranches; } + set + { + var now = DateTimeOffset.Now; + var isUpdated = false; + + Logger.Trace("Updating: {0} remoteBranches:{1}", now, value); + + var remoteBranchesIsNull = remoteBranches == null; + var valueIsNull = value == null; + + if (remoteBranchesIsNull != valueIsNull || + !remoteBranchesIsNull && !remoteBranches.SequenceEqual(value)) + { + remoteBranches = value; + isUpdated = true; + } + + SaveData(now, isUpdated); + } + } + + public IRemoteConfigBranchDictionary RemoteConfigBranches + { + get { return remoteConfigBranches; } + } + + public GitRemote[] Remotes + { + get { return remotes; } + set + { + var now = DateTimeOffset.Now; + var isUpdated = false; + + Logger.Trace("Updating: {0} remotes:{1}", now, value); + + var remotesIsNull = remotes == null; + var valueIsNull = value == null; + + if (remotesIsNull != valueIsNull || + !remotesIsNull && !remotes.SequenceEqual(value)) + { + remotes = value; + isUpdated = true; + } + + SaveData(now, isUpdated); + } + } + + public IConfigRemoteDictionary ConfigRemotes + { + get { return configRemotes; } + } + + public void RemoveLocalBranch(string branch) + { + if (LocalConfigBranches.ContainsKey(branch)) + { + var now = DateTimeOffset.Now; + LocalConfigBranches.Remove(branch); + Logger.Trace("RemoveLocalBranch {0} branch:{1} ", now, branch); + SaveData(now, true); + } + else + { + Logger.Warning("Branch {0} is not found", branch); + } + } + + public void AddLocalBranch(string branch) + { + if (!LocalConfigBranches.ContainsKey(branch)) + { + var now = DateTimeOffset.Now; + LocalConfigBranches.Add(branch, new ConfigBranch { Name = branch }); + Logger.Trace("AddLocalBranch {0} branch:{1} ", now, branch); + SaveData(now, true); + } + else + { + Logger.Warning("Branch {0} is already present", branch); + } + } + + public void AddRemoteBranch(string remote, string branch) + { + IDictionary branchList; + if (RemoteConfigBranches.TryGetValue(remote, out branchList)) + { + if (!branchList.ContainsKey(branch)) + { + var now = DateTimeOffset.Now; + branchList.Add(branch, new ConfigBranch { Name = branch, Remote = ConfigRemotes[remote] }); + Logger.Trace("AddRemoteBranch {0} remote:{1} branch:{2} ", now, remote, branch); + SaveData(now, true); + } + else + { + Logger.Warning("Branch {0} is already present in Remote {1}", branch, remote); + } + } + else + { + Logger.Warning("Remote {0} is not found", remote); + } + } + + public void RemoveRemoteBranch(string remote, string branch) + { + IDictionary branchList; + if (RemoteConfigBranches.TryGetValue(remote, out branchList)) + { + if (branchList.ContainsKey(branch)) + { + var now = DateTimeOffset.Now; + branchList.Remove(branch); + Logger.Trace("RemoveRemoteBranch {0} remote:{1} branch:{2} ", now, remote, branch); + SaveData(now, true); + } + else + { + Logger.Warning("Branch {0} is not found in Remote {1}", branch, remote); + } + } + else + { + Logger.Warning("Remote {0} is not found", remote); + } + } + + public void SetRemotes(IDictionary remoteDictionary, IDictionary> branchDictionary) + { + configRemotes = new ConfigRemoteDictionary(remoteDictionary); + remoteConfigBranches = new RemoteConfigBranchDictionary(branchDictionary); + } + + public void SetLocals(IDictionary branchDictionary) + { + localConfigBranches = new LocalConfigBranchDictionary(branchDictionary); + } + + public override string LastUpdatedAtString + { + get { return lastUpdatedAtString; } + protected set { lastUpdatedAtString = value; } + } + + public override string LastVerifiedAtString + { + get { return lastVerifiedAtString; } + protected set { lastVerifiedAtString = value; } + } } [Location("cache/gitlog.yaml", LocationAttribute.Location.LibraryFolder)] @@ -437,11 +683,6 @@ public List Log } } - protected override void OnResetData() - { - log = new List(); - } - public override string LastUpdatedAtString { get { return lastUpdatedAtString; } @@ -502,11 +743,6 @@ public GitStatus GitStatus } } - protected override void OnResetData() - { - status = new GitStatus(); - } - public override string LastUpdatedAtString { get { return lastUpdatedAtString; } @@ -555,11 +791,6 @@ public List GitLocks } } - protected override void OnResetData() - { - locks = new List(); - } - public override string LastUpdatedAtString { get { return lastUpdatedAtString; } @@ -605,11 +836,6 @@ public User User } } - protected override void OnResetData() - { - user = null; - } - public override string LastUpdatedAtString { get { return lastUpdatedAtString; } diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/CacheContainer.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/CacheContainer.cs index 9a46297d6..ad9d4e6a1 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/CacheContainer.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/CacheContainer.cs @@ -16,8 +16,6 @@ public class CacheContainer : ICacheContainer private IGitUserCache gitUserCache; - private IRepositoryInfoCache repositoryInfoCache; - public event Action CacheInvalidated; public event Action CacheUpdated; @@ -32,9 +30,6 @@ private IManagedCache GetManagedCache(CacheType cacheType) case CacheType.GitLogCache: return GitLogCache; - case CacheType.RepositoryInfoCache: - return RepositoryInfoCache; - case CacheType.GitStatusCache: return GitStatusCache; @@ -58,7 +53,6 @@ public void ValidateAll() { BranchCache.ValidateData(); GitLogCache.ValidateData(); - RepositoryInfoCache.ValidateData(); GitStatusCache.ValidateData(); GitLocksCache.ValidateData(); GitUserCache.ValidateData(); @@ -73,7 +67,6 @@ public void InvalidateAll() { BranchCache.InvalidateData(); GitLogCache.InvalidateData(); - RepositoryInfoCache.InvalidateData(); GitStatusCache.InvalidateData(); GitLocksCache.InvalidateData(); GitUserCache.InvalidateData(); @@ -107,20 +100,6 @@ public IGitLogCache GitLogCache } } - public IRepositoryInfoCache RepositoryInfoCache - { - get - { - if (repositoryInfoCache == null) - { - repositoryInfoCache = Unity.RepositoryInfoCache.Instance; - repositoryInfoCache.CacheInvalidated += () => OnCacheInvalidated(CacheType.RepositoryInfoCache); - repositoryInfoCache.CacheUpdated += datetime => OnCacheUpdated(CacheType.RepositoryInfoCache, datetime); - } - return repositoryInfoCache; - } - } - public IGitStatusCache GitStatusCache { get diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs index 3a4f10081..925456f10 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs @@ -48,17 +48,36 @@ class BranchesView : Subview [SerializeField] private Vector2 scroll; [SerializeField] private BranchTreeNode selectedNode; + [SerializeField] private CacheUpdateEvent branchUpdateEvent; + [NonSerialized] private bool branchCacheHasUpdate; + [SerializeField] private GitBranch[] localBranches; + [SerializeField] private GitBranch[] remoteBranches; + public override void InitializeView(IView parent) { base.InitializeView(parent); targetMode = mode; } + private void Repository_BranchCacheUpdated(CacheUpdateEvent cacheUpdateEvent) + { + new ActionTask(TaskManager.Token, () => { + branchUpdateEvent = cacheUpdateEvent; + branchCacheHasUpdate = true; + Redraw(); + }) + { Affinity = TaskAffinity.UI }.Start(); + } + public override void OnEnable() { base.OnEnable(); AttachHandlers(Repository); - Refresh(); + + if (Repository != null) + { + Repository.CheckBranchCacheEvent(branchUpdateEvent); + } } public override void OnDisable() @@ -75,49 +94,32 @@ public override void OnDataUpdate() private void MaybeUpdateData() { + if (branchCacheHasUpdate) + { + branchCacheHasUpdate = false; + + localBranches = Repository.LocalBranches.ToArray(); + remoteBranches = Repository.RemoteBranches.ToArray(); + + + BuildTree(localBranches, remoteBranches); + } } private void AttachHandlers(IRepository repository) { if (repository == null) return; - repository.OnLocalBranchListChanged += RunUpdateBranchesOnMainThread; - repository.OnCurrentBranchChanged += HandleRepositoryBranchChangeEvent; - repository.OnCurrentRemoteChanged += HandleRepositoryBranchChangeEvent; + + repository.BranchCacheUpdated += Repository_BranchCacheUpdated; } private void DetachHandlers(IRepository repository) { if (repository == null) return; - repository.OnLocalBranchListChanged -= RunUpdateBranchesOnMainThread; - repository.OnCurrentBranchChanged -= HandleRepositoryBranchChangeEvent; - repository.OnCurrentRemoteChanged -= HandleRepositoryBranchChangeEvent; - } - - private void HandleRepositoryBranchChangeEvent(string obj) - { - RunUpdateBranchesOnMainThread(); - } - - public override void Refresh() - { - base.Refresh(); - UpdateBranches(); - } - - private void RunUpdateBranchesOnMainThread() - { - new ActionTask(TaskManager.Token, _ => UpdateBranches()) - .ScheduleUI(TaskManager); - } - - public void UpdateBranches() - { - if (Repository == null) - return; - BuildTree(Repository.LocalBranches, Repository.RemoteBranches); + repository.BranchCacheUpdated -= Repository_BranchCacheUpdated; } public override void OnGUI() @@ -550,7 +552,7 @@ private void OnTreeNodeGUI(BranchTreeNode node) var originName = selectedNode.Name.Substring(0, indexOfFirstSlash); var branchName = selectedNode.Name.Substring(indexOfFirstSlash + 1); - if (Repository.LocalBranches.Any(localBranch => localBranch.Name == branchName)) + if (localBranches.Any(localBranch => localBranch.Name == branchName)) { EditorUtility.DisplayDialog(WarningCheckoutBranchExistsTitle, String.Format(WarningCheckoutBranchExistsMessage, branchName), diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ChangesView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ChangesView.cs index 988d3df91..c58ebc468 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ChangesView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ChangesView.cs @@ -25,8 +25,8 @@ class ChangesView : Subview [SerializeField] private Vector2 horizontalScroll; [SerializeField] private ChangesetTreeView tree = new ChangesetTreeView(); - [SerializeField] private CacheUpdateEvent repositoryInfoUpdateEvent; - [NonSerialized] private bool repositoryInfoCacheHasUpdate; + [SerializeField] private CacheUpdateEvent branchUpdateEvent; + [NonSerialized] private bool branchCacheHasUpdate; [SerializeField] private CacheUpdateEvent gitStatusUpdateEvent; [NonSerialized] private bool gitStatusCacheHasUpdate; @@ -47,11 +47,11 @@ private void Repository_GitStatusCacheUpdated(CacheUpdateEvent cacheUpdateEvent) { Affinity = TaskAffinity.UI }.Start(); } - private void Repository_RepositoryInfoCacheUpdated(CacheUpdateEvent cacheUpdateEvent) + private void Repository_BranchCacheUpdated(CacheUpdateEvent cacheUpdateEvent) { new ActionTask(TaskManager.Token, () => { - repositoryInfoUpdateEvent = cacheUpdateEvent; - repositoryInfoCacheHasUpdate = true; + branchUpdateEvent = cacheUpdateEvent; + branchCacheHasUpdate = true; Redraw(); }) { Affinity = TaskAffinity.UI }.Start(); @@ -61,7 +61,7 @@ private void AttachHandlers(IRepository repository) { if (repository == null) return; - repository.RepositoryInfoCacheUpdated += Repository_RepositoryInfoCacheUpdated; + repository.BranchCacheUpdated += Repository_BranchCacheUpdated; repository.GitStatusCacheUpdated += Repository_GitStatusCacheUpdated; } @@ -70,7 +70,7 @@ private void DetachHandlers(IRepository repository) if (repository == null) return; - repository.RepositoryInfoCacheUpdated -= Repository_RepositoryInfoCacheUpdated; + repository.BranchCacheUpdated -= Repository_BranchCacheUpdated; repository.GitStatusCacheUpdated -= Repository_GitStatusCacheUpdated; } @@ -81,7 +81,7 @@ public override void OnEnable() if (Repository != null) { - Repository.CheckRepositoryInfoCacheEvent(repositoryInfoUpdateEvent); + Repository.CheckBranchCacheEvent(branchUpdateEvent); Repository.CheckGitStatusCacheEvent(gitStatusUpdateEvent); } } @@ -101,9 +101,9 @@ public override void OnDataUpdate() private void MaybeUpdateData() { - if (repositoryInfoCacheHasUpdate) + if (branchCacheHasUpdate) { - repositoryInfoCacheHasUpdate = false; + branchCacheHasUpdate = false; currentBranch = string.Format("[{0}]", Repository.CurrentBranchName); } diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/HistoryView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/HistoryView.cs index 861f444fa..3f92f40b7 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/HistoryView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/HistoryView.cs @@ -51,8 +51,8 @@ class HistoryView : Subview [SerializeField] private bool hasRemote; [SerializeField] private bool hasItemsToCommit; - [SerializeField] private CacheUpdateEvent repositoryInfoUpdateEvent; - [NonSerialized] private bool repositoryInfoCacheHasUpdate; + [SerializeField] private CacheUpdateEvent branchUpdateEvent; + [NonSerialized] private bool branchCacheHasUpdate; [SerializeField] private CacheUpdateEvent gitStatusUpdateEvent; [NonSerialized] private bool gitStatusCacheHasUpdate; @@ -79,7 +79,7 @@ public override void OnEnable() { Repository.CheckGitLogCacheEvent(gitLogCacheUpdateEvent); Repository.CheckGitStatusCacheEvent(gitStatusUpdateEvent); - Repository.CheckRepositoryInfoCacheEvent(repositoryInfoUpdateEvent); + Repository.CheckBranchCacheEvent(branchUpdateEvent); } } @@ -120,11 +120,11 @@ private void Repository_GitLogCacheUpdated(CacheUpdateEvent cacheUpdateEvent) { Affinity = TaskAffinity.UI }.Start(); } - private void Repository_RepositoryInfoCacheUpdated(CacheUpdateEvent cacheUpdateEvent) + private void Repository_BranchCacheUpdated(CacheUpdateEvent cacheUpdateEvent) { new ActionTask(TaskManager.Token, () => { - repositoryInfoUpdateEvent = cacheUpdateEvent; - repositoryInfoCacheHasUpdate = true; + branchUpdateEvent = cacheUpdateEvent; + branchCacheHasUpdate = true; Redraw(); }) { Affinity = TaskAffinity.UI }.Start(); @@ -137,7 +137,7 @@ private void AttachHandlers(IRepository repository) repository.GitStatusCacheUpdated += Repository_GitStatusCacheUpdated; repository.GitLogCacheUpdated += Repository_GitLogCacheUpdated; - repository.RepositoryInfoCacheUpdated += Repository_RepositoryInfoCacheUpdated; + repository.BranchCacheUpdated += Repository_BranchCacheUpdated; } private void DetachHandlers(IRepository repository) @@ -147,7 +147,7 @@ private void DetachHandlers(IRepository repository) repository.GitStatusCacheUpdated -= Repository_GitStatusCacheUpdated; repository.GitLogCacheUpdated -= Repository_GitLogCacheUpdated; - repository.RepositoryInfoCacheUpdated -= Repository_RepositoryInfoCacheUpdated; + repository.BranchCacheUpdated -= Repository_BranchCacheUpdated; } private void MaybeUpdateData() @@ -155,9 +155,9 @@ private void MaybeUpdateData() if (Repository == null) return; - if (repositoryInfoCacheHasUpdate) + if (branchCacheHasUpdate) { - repositoryInfoCacheHasUpdate = false; + branchCacheHasUpdate = false; var currentRemote = Repository.CurrentRemote; hasRemote = currentRemote.HasValue; diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/SettingsView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/SettingsView.cs index 0446adc08..79d433372 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/SettingsView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/SettingsView.cs @@ -99,7 +99,6 @@ private void AttachHandlers(IRepository repository) { if (repository == null) return; - repository.OnCurrentRemoteChanged += Repository_OnActiveRemoteChanged; repository.OnLocksChanged += RunLocksUpdateOnMainThread; } @@ -107,7 +106,6 @@ private void DetachHandlers(IRepository repository) { if (repository == null) return; - repository.OnCurrentRemoteChanged -= Repository_OnActiveRemoteChanged; repository.OnLocksChanged -= RunLocksUpdateOnMainThread; } @@ -182,11 +180,6 @@ private void MaybeUpdateData() } } - private void Repository_OnActiveRemoteChanged(string remote) - { - remoteHasChanged = true; - } - private void RunLocksUpdateOnMainThread(IEnumerable locks) { new ActionTask(TaskManager.Token, _ => OnLocksUpdate(locks)) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs index 1d5e2403c..8db054054 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs @@ -37,8 +37,8 @@ class Window : BaseWindow [SerializeField] private GUIContent repoBranchContent; [SerializeField] private GUIContent repoUrlContent; - [SerializeField] private CacheUpdateEvent repositoryInfoUpdateEvent; - [NonSerialized] private bool repositoryInfoCacheHasUpdate; + [SerializeField] private CacheUpdateEvent branchUpdateEvent; + [NonSerialized] private bool branchCacheHasUpdate; [NonSerialized] private bool hasRunMaybeUpdateDataWithRepository; [MenuItem(LaunchMenu)] @@ -97,7 +97,7 @@ public override void OnEnable() titleContent = new GUIContent(Title, Styles.SmallLogo); if (Repository != null) - Repository.CheckRepositoryInfoCacheEvent(repositoryInfoUpdateEvent); + Repository.CheckBranchCacheEvent(branchUpdateEvent); if (ActiveView != null) ActiveView.OnEnable(); @@ -194,7 +194,7 @@ private void MaybeUpdateData() if (Repository != null) { - if(!hasRunMaybeUpdateDataWithRepository || repositoryInfoCacheHasUpdate) + if(!hasRunMaybeUpdateDataWithRepository || branchCacheHasUpdate) { hasRunMaybeUpdateDataWithRepository = true; @@ -269,14 +269,14 @@ private void AttachHandlers(IRepository repository) { if (repository == null) return; - repository.RepositoryInfoCacheUpdated += Repository_RepositoryInfoCacheUpdated; + repository.BranchCacheUpdated += Repository_BranchCacheUpdated; } - private void Repository_RepositoryInfoCacheUpdated(CacheUpdateEvent cacheUpdateEvent) + private void Repository_BranchCacheUpdated(CacheUpdateEvent cacheUpdateEvent) { new ActionTask(TaskManager.Token, () => { - repositoryInfoUpdateEvent = cacheUpdateEvent; - repositoryInfoCacheHasUpdate = true; + branchUpdateEvent = cacheUpdateEvent; + branchCacheHasUpdate = true; Redraw(); }) { Affinity = TaskAffinity.UI }.Start(); } @@ -286,7 +286,7 @@ private void DetachHandlers(IRepository repository) if (repository == null) return; - repository.RepositoryInfoCacheUpdated -= Repository_RepositoryInfoCacheUpdated; + repository.BranchCacheUpdated -= Repository_BranchCacheUpdated; } private void DoHeaderGUI() diff --git a/src/tests/IntegrationTests/Events/RepositoryManagerTests.cs b/src/tests/IntegrationTests/Events/RepositoryManagerTests.cs index 59491de5b..7d5bb192f 100644 --- a/src/tests/IntegrationTests/Events/RepositoryManagerTests.cs +++ b/src/tests/IntegrationTests/Events/RepositoryManagerTests.cs @@ -123,8 +123,8 @@ public async Task ShouldDetectFileChanges() repositoryManagerListener.DidNotReceive().OnLocksUpdated(Args.EnumerableGitLock); repositoryManagerListener.DidNotReceive().OnCurrentBranchUpdated(Arg.Any()); repositoryManagerListener.DidNotReceive().OnCurrentRemoteUpdated(Arg.Any()); - repositoryManagerListener.DidNotReceive().OnLocalBranchListUpdated(Arg.Any>()); - repositoryManagerListener.DidNotReceive().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); + repositoryManagerListener.DidNotReceive().OnLocalBranchListUpdated(Arg.Any>()); + repositoryManagerListener.DidNotReceive().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); repositoryManagerListener.DidNotReceive().OnLocalBranchUpdated(Args.String); repositoryManagerListener.DidNotReceive().OnLocalBranchAdded(Args.String); repositoryManagerListener.DidNotReceive().OnLocalBranchRemoved(Args.String); @@ -182,8 +182,8 @@ public async Task ShouldAddAndCommitFiles() repositoryManagerListener.DidNotReceive().OnLocksUpdated(Args.EnumerableGitLock); repositoryManagerListener.DidNotReceive().OnCurrentBranchUpdated(Arg.Any()); repositoryManagerListener.DidNotReceive().OnCurrentRemoteUpdated(Arg.Any()); - repositoryManagerListener.DidNotReceive().OnLocalBranchListUpdated(Arg.Any>()); - repositoryManagerListener.DidNotReceive().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); + repositoryManagerListener.DidNotReceive().OnLocalBranchListUpdated(Arg.Any>()); + repositoryManagerListener.DidNotReceive().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); repositoryManagerListener.DidNotReceive().OnLocalBranchUpdated(Args.String); repositoryManagerListener.DidNotReceive().OnLocalBranchAdded(Args.String); repositoryManagerListener.DidNotReceive().OnLocalBranchRemoved(Args.String); @@ -208,8 +208,8 @@ await RepositoryManager repositoryManagerListener.DidNotReceive().OnLocksUpdated(Args.EnumerableGitLock); repositoryManagerListener.DidNotReceive().OnCurrentBranchUpdated(Arg.Any()); repositoryManagerListener.DidNotReceive().OnCurrentRemoteUpdated(Arg.Any()); - repositoryManagerListener.DidNotReceive().OnLocalBranchListUpdated(Arg.Any>()); - repositoryManagerListener.DidNotReceive().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); + repositoryManagerListener.DidNotReceive().OnLocalBranchListUpdated(Arg.Any>()); + repositoryManagerListener.DidNotReceive().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); repositoryManagerListener.Received().OnLocalBranchUpdated(expectedLocalBranch); repositoryManagerListener.DidNotReceive().OnLocalBranchAdded(Args.String); repositoryManagerListener.DidNotReceive().OnLocalBranchRemoved(Args.String); @@ -260,8 +260,8 @@ public async Task ShouldAddAndCommitAllFiles() repositoryManagerListener.DidNotReceive().OnLocksUpdated(Args.EnumerableGitLock); repositoryManagerListener.DidNotReceive().OnCurrentBranchUpdated(Arg.Any()); repositoryManagerListener.DidNotReceive().OnCurrentRemoteUpdated(Arg.Any()); - repositoryManagerListener.DidNotReceive().OnLocalBranchListUpdated(Arg.Any>()); - repositoryManagerListener.DidNotReceive().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); + repositoryManagerListener.DidNotReceive().OnLocalBranchListUpdated(Arg.Any>()); + repositoryManagerListener.DidNotReceive().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); repositoryManagerListener.DidNotReceive().OnLocalBranchUpdated(Args.String); repositoryManagerListener.DidNotReceive().OnLocalBranchAdded(Args.String); repositoryManagerListener.DidNotReceive().OnLocalBranchRemoved(Args.String); @@ -286,8 +286,8 @@ await RepositoryManager repositoryManagerListener.DidNotReceive().OnLocksUpdated(Args.EnumerableGitLock); repositoryManagerListener.DidNotReceive().OnCurrentBranchUpdated(Arg.Any()); repositoryManagerListener.DidNotReceive().OnCurrentRemoteUpdated(Arg.Any()); - repositoryManagerListener.DidNotReceive().OnLocalBranchListUpdated(Arg.Any>()); - repositoryManagerListener.DidNotReceive().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); + repositoryManagerListener.DidNotReceive().OnLocalBranchListUpdated(Arg.Any>()); + repositoryManagerListener.DidNotReceive().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); repositoryManagerListener.Received().OnLocalBranchUpdated(expectedLocalBranch); repositoryManagerListener.DidNotReceive().OnLocalBranchAdded(Args.String); repositoryManagerListener.DidNotReceive().OnLocalBranchRemoved(Args.String); @@ -328,8 +328,8 @@ public async Task ShouldDetectBranchChange() repositoryManagerListener.DidNotReceive().OnLocksUpdated(Args.EnumerableGitLock); repositoryManagerListener.Received().OnCurrentBranchUpdated(Arg.Any()); repositoryManagerListener.Received().OnCurrentRemoteUpdated(Arg.Any()); - repositoryManagerListener.DidNotReceive().OnLocalBranchListUpdated(Arg.Any>()); - repositoryManagerListener.DidNotReceive().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); + repositoryManagerListener.DidNotReceive().OnLocalBranchListUpdated(Arg.Any>()); + repositoryManagerListener.DidNotReceive().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); repositoryManagerListener.DidNotReceive().OnLocalBranchUpdated(Args.String); repositoryManagerListener.DidNotReceive().OnLocalBranchAdded(Args.String); repositoryManagerListener.DidNotReceive().OnLocalBranchRemoved(Args.String); @@ -408,8 +408,8 @@ public async Task ShouldDetectBranchDelete() repositoryManagerListener.DidNotReceive().OnLocksUpdated(Args.EnumerableGitLock); repositoryManagerListener.Received().OnCurrentBranchUpdated(Arg.Any()); repositoryManagerListener.Received().OnCurrentRemoteUpdated(Arg.Any()); - repositoryManagerListener.Received().OnLocalBranchListUpdated(Arg.Any>()); - repositoryManagerListener.Received().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); + repositoryManagerListener.Received().OnLocalBranchListUpdated(Arg.Any>()); + repositoryManagerListener.Received().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); repositoryManagerListener.DidNotReceive().OnLocalBranchUpdated(Args.String); repositoryManagerListener.DidNotReceive().OnLocalBranchAdded(Args.String); repositoryManagerListener.Received().OnLocalBranchRemoved(deletedBranch); @@ -482,8 +482,8 @@ public async Task ShouldDetectBranchCreate() repositoryManagerListener.DidNotReceive().OnLocksUpdated(Args.EnumerableGitLock); repositoryManagerListener.DidNotReceive().OnCurrentBranchUpdated(Arg.Any()); repositoryManagerListener.DidNotReceive().OnCurrentRemoteUpdated(Arg.Any()); - repositoryManagerListener.DidNotReceive().OnLocalBranchListUpdated(Arg.Any>()); - repositoryManagerListener.DidNotReceive().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); + repositoryManagerListener.DidNotReceive().OnLocalBranchListUpdated(Arg.Any>()); + repositoryManagerListener.DidNotReceive().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); repositoryManagerListener.DidNotReceive().OnLocalBranchUpdated(Args.String); repositoryManagerListener.Received().OnLocalBranchAdded(createdBranch1); repositoryManagerListener.DidNotReceive().OnLocalBranchRemoved(Args.String); @@ -560,8 +560,8 @@ public async Task ShouldDetectBranchCreate() repositoryManagerListener.DidNotReceive().OnLocksUpdated(Args.EnumerableGitLock); repositoryManagerListener.DidNotReceive().OnCurrentBranchUpdated(Arg.Any()); repositoryManagerListener.DidNotReceive().OnCurrentRemoteUpdated(Arg.Any()); - repositoryManagerListener.DidNotReceive().OnLocalBranchListUpdated(Arg.Any>()); - repositoryManagerListener.DidNotReceive().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); + repositoryManagerListener.DidNotReceive().OnLocalBranchListUpdated(Arg.Any>()); + repositoryManagerListener.DidNotReceive().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); repositoryManagerListener.DidNotReceive().OnLocalBranchUpdated(Args.String); repositoryManagerListener.Received().OnLocalBranchAdded(createdBranch2); repositoryManagerListener.DidNotReceive().OnLocalBranchRemoved(Args.String); @@ -708,8 +708,8 @@ public async Task ShouldDetectChangesToRemotes() repositoryManagerListener.DidNotReceive().OnLocksUpdated(Args.EnumerableGitLock); repositoryManagerListener.Received().OnCurrentBranchUpdated(Arg.Any()); repositoryManagerListener.Received().OnCurrentRemoteUpdated(Arg.Any()); - repositoryManagerListener.Received().OnLocalBranchListUpdated(Arg.Any>()); - repositoryManagerListener.Received().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); + repositoryManagerListener.Received().OnLocalBranchListUpdated(Arg.Any>()); + repositoryManagerListener.Received().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); repositoryManagerListener.DidNotReceive().OnLocalBranchUpdated(Args.String); repositoryManagerListener.DidNotReceive().OnLocalBranchAdded(Args.String); repositoryManagerListener.DidNotReceive().OnLocalBranchRemoved(Args.String); @@ -743,8 +743,8 @@ public async Task ShouldDetectChangesToRemotes() repositoryManagerListener.DidNotReceive().OnLocksUpdated(Args.EnumerableGitLock); repositoryManagerListener.Received().OnCurrentBranchUpdated(Arg.Any()); repositoryManagerListener.Received().OnCurrentRemoteUpdated(Arg.Any()); - repositoryManagerListener.Received().OnLocalBranchListUpdated(Arg.Any>()); - repositoryManagerListener.Received().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); + repositoryManagerListener.Received().OnLocalBranchListUpdated(Arg.Any>()); + repositoryManagerListener.Received().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); repositoryManagerListener.DidNotReceive().OnLocalBranchUpdated(Args.String); repositoryManagerListener.DidNotReceive().OnLocalBranchAdded(Args.String); repositoryManagerListener.DidNotReceive().OnLocalBranchRemoved(Args.String); @@ -882,8 +882,8 @@ await RepositoryManager.CreateBranch("branch2", "another/master") repositoryManagerListener.DidNotReceive().OnLocksUpdated(Args.EnumerableGitLock); repositoryManagerListener.Received().OnCurrentBranchUpdated(Arg.Any()); repositoryManagerListener.Received().OnCurrentRemoteUpdated(Arg.Any()); - repositoryManagerListener.Received().OnLocalBranchListUpdated(Arg.Any>()); - repositoryManagerListener.Received().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); + repositoryManagerListener.Received().OnLocalBranchListUpdated(Arg.Any>()); + repositoryManagerListener.Received().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); repositoryManagerListener.DidNotReceive().OnLocalBranchUpdated(Args.String); repositoryManagerListener.Received().OnLocalBranchAdded(Args.String); repositoryManagerListener.DidNotReceive().OnLocalBranchRemoved(Args.String); @@ -981,8 +981,8 @@ await RepositoryManager.SwitchBranch("branch2") repositoryManagerListener.DidNotReceive().OnLocksUpdated(Args.EnumerableGitLock); repositoryManagerListener.Received().OnCurrentBranchUpdated(Arg.Any()); repositoryManagerListener.Received().OnCurrentRemoteUpdated(Arg.Any()); - repositoryManagerListener.DidNotReceive().OnLocalBranchListUpdated(Arg.Any>()); - repositoryManagerListener.DidNotReceive().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); + repositoryManagerListener.DidNotReceive().OnLocalBranchListUpdated(Arg.Any>()); + repositoryManagerListener.DidNotReceive().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); repositoryManagerListener.DidNotReceive().OnLocalBranchUpdated(Args.String); repositoryManagerListener.DidNotReceive().OnLocalBranchAdded(Args.String); repositoryManagerListener.DidNotReceive().OnLocalBranchRemoved(Args.String); @@ -1094,8 +1094,8 @@ public async Task ShouldDetectGitPull() repositoryManagerListener.DidNotReceive().OnLocksUpdated(Args.EnumerableGitLock); repositoryManagerListener.DidNotReceive().OnCurrentBranchUpdated(Arg.Any()); repositoryManagerListener.DidNotReceive().OnCurrentRemoteUpdated(Arg.Any()); - repositoryManagerListener.DidNotReceive().OnLocalBranchListUpdated(Arg.Any>()); - repositoryManagerListener.DidNotReceive().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); + repositoryManagerListener.DidNotReceive().OnLocalBranchListUpdated(Arg.Any>()); + repositoryManagerListener.DidNotReceive().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); repositoryManagerListener.Received().OnLocalBranchUpdated(Args.String); repositoryManagerListener.DidNotReceive().OnLocalBranchAdded(Args.String); repositoryManagerListener.DidNotReceive().OnLocalBranchRemoved(Args.String); @@ -1223,8 +1223,8 @@ public async Task ShouldDetectGitFetch() repositoryManagerListener.DidNotReceive().OnLocksUpdated(Args.EnumerableGitLock); repositoryManagerListener.DidNotReceive().OnCurrentBranchUpdated(Arg.Any()); repositoryManagerListener.DidNotReceive().OnCurrentRemoteUpdated(Arg.Any()); - repositoryManagerListener.DidNotReceive().OnLocalBranchListUpdated(Arg.Any>()); - repositoryManagerListener.DidNotReceive().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); + repositoryManagerListener.DidNotReceive().OnLocalBranchListUpdated(Arg.Any>()); + repositoryManagerListener.DidNotReceive().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); repositoryManagerListener.DidNotReceive().OnLocalBranchUpdated(Args.String); repositoryManagerListener.DidNotReceive().OnLocalBranchAdded(Args.String); repositoryManagerListener.DidNotReceive().OnLocalBranchRemoved(Args.String); diff --git a/src/tests/TestUtils/Events/IRepositoryListener.cs b/src/tests/TestUtils/Events/IRepositoryListener.cs index 37baccda0..63d952ee5 100644 --- a/src/tests/TestUtils/Events/IRepositoryListener.cs +++ b/src/tests/TestUtils/Events/IRepositoryListener.cs @@ -9,11 +9,6 @@ namespace TestUtils.Events interface IRepositoryListener { void OnStatusChanged(GitStatus status); - void OnCurrentBranchChanged(string branch); - void OnCurrentRemoteChanged(string remote); - void OnLocalBranchListChanged(); - void OnRemoteBranchListChanged(); - void OnHeadChanged(); void OnLocksChanged(IEnumerable locks); void OnRepositoryInfoChanged(); } @@ -21,22 +16,12 @@ interface IRepositoryListener class RepositoryEvents { public EventWaitHandle OnStatusChanged { get; } = new AutoResetEvent(false); - public EventWaitHandle OnCurrentBranchChanged { get; } = new AutoResetEvent(false); - public EventWaitHandle OnCurrentRemoteChanged { get; } = new AutoResetEvent(false); - public EventWaitHandle OnLocalBranchListChanged { get; } = new AutoResetEvent(false); - public EventWaitHandle OnRemoteBranchListChanged { get; } = new AutoResetEvent(false); - public EventWaitHandle OnHeadChanged { get; } = new AutoResetEvent(false); public EventWaitHandle OnLocksChanged { get; } = new AutoResetEvent(false); public EventWaitHandle OnRepositoryInfoChanged { get; } = new AutoResetEvent(false); public void Reset() { OnStatusChanged.Reset(); - OnCurrentBranchChanged.Reset(); - OnCurrentRemoteChanged.Reset(); - OnLocalBranchListChanged.Reset(); - OnRemoteBranchListChanged.Reset(); - OnHeadChanged.Reset(); OnLocksChanged.Reset(); OnRepositoryInfoChanged.Reset(); } @@ -49,49 +34,6 @@ public static void AttachListener(this IRepositoryListener listener, { var logger = trace ? Logging.GetLogger() : null; - //TODO: Figure this out - //repository.OnStatusChanged += gitStatus => - //{ - // logger?.Trace("OnStatusChanged: {0}", gitStatus); - // listener.OnStatusChanged(gitStatus); - // repositoryEvents?.OnStatusChanged.Set(); - //}; - - repository.OnCurrentBranchChanged += name => - { - logger?.Debug("OnCurrentBranchChanged: {0}", name); - listener.OnCurrentBranchChanged(name); - repositoryEvents?.OnCurrentBranchChanged.Set(); - }; - - repository.OnCurrentRemoteChanged += name => - { - logger?.Debug("OnCurrentRemoteChanged: {0}", name); - listener.OnCurrentRemoteChanged(name); - repositoryEvents?.OnCurrentRemoteChanged.Set(); - }; - - repository.OnLocalBranchListChanged += () => - { - logger?.Debug("OnLocalBranchListChanged"); - listener.OnLocalBranchListChanged(); - repositoryEvents?.OnLocalBranchListChanged.Set(); - }; - - repository.OnRemoteBranchListChanged += () => - { - logger?.Debug("OnRemoteBranchListChanged"); - listener.OnRemoteBranchListChanged(); - repositoryEvents?.OnRemoteBranchListChanged.Set(); - }; - - repository.OnCurrentBranchUpdated += () => - { - logger?.Debug("OnHeadChanged"); - listener.OnHeadChanged(); - repositoryEvents?.OnHeadChanged.Set(); - }; - repository.OnLocksChanged += locks => { logger?.Debug("OnLocksChanged: {0}", locks); @@ -110,10 +52,6 @@ public static void AttachListener(this IRepositoryListener listener, public static void AssertDidNotReceiveAnyCalls(this IRepositoryListener repositoryListener) { repositoryListener.DidNotReceive().OnStatusChanged(Args.GitStatus); - repositoryListener.DidNotReceive().OnCurrentBranchChanged(Args.String); - repositoryListener.DidNotReceive().OnCurrentRemoteChanged(Args.String); - repositoryListener.DidNotReceive().OnLocalBranchListChanged(); - repositoryListener.DidNotReceive().OnHeadChanged(); repositoryListener.DidNotReceive().OnLocksChanged(Arg.Any>()); repositoryListener.DidNotReceive().OnRepositoryInfoChanged(); } diff --git a/src/tests/TestUtils/Events/IRepositoryManagerListener.cs b/src/tests/TestUtils/Events/IRepositoryManagerListener.cs index bf24392a1..07f116e99 100644 --- a/src/tests/TestUtils/Events/IRepositoryManagerListener.cs +++ b/src/tests/TestUtils/Events/IRepositoryManagerListener.cs @@ -12,8 +12,8 @@ interface IRepositoryManagerListener void OnIsBusyChanged(bool busy); void OnStatusUpdated(GitStatus status); void OnLocksUpdated(IEnumerable locks); - void OnLocalBranchListUpdated(Dictionary branchList); - void OnRemoteBranchListUpdated(Dictionary remotesList, Dictionary> remoteBranchList); + void OnLocalBranchListUpdated(IDictionary branchList); + void OnRemoteBranchListUpdated(IDictionary remotesList, IDictionary> remoteBranchList); void OnLocalBranchUpdated(string name); void OnLocalBranchAdded(string name); void OnLocalBranchRemoved(string name); @@ -176,8 +176,8 @@ public static void AssertDidNotReceiveAnyCalls(this IRepositoryManagerListener r repositoryManagerListener.DidNotReceive().OnLocksUpdated(Args.EnumerableGitLock); repositoryManagerListener.DidNotReceive().OnCurrentBranchUpdated(Arg.Any()); repositoryManagerListener.DidNotReceive().OnCurrentRemoteUpdated(Arg.Any()); - repositoryManagerListener.DidNotReceive().OnLocalBranchListUpdated(Arg.Any>()); - repositoryManagerListener.DidNotReceive().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); + repositoryManagerListener.DidNotReceive().OnLocalBranchListUpdated(Arg.Any>()); + repositoryManagerListener.DidNotReceive().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); repositoryManagerListener.DidNotReceive().OnLocalBranchUpdated(Args.String); repositoryManagerListener.DidNotReceive().OnLocalBranchAdded(Args.String); repositoryManagerListener.DidNotReceive().OnLocalBranchRemoved(Args.String); diff --git a/src/tests/UnitTests/Git/RepositoryTests.cs b/src/tests/UnitTests/Git/RepositoryTests.cs index 23dc4f358..2b385aa2e 100644 --- a/src/tests/UnitTests/Git/RepositoryTests.cs +++ b/src/tests/UnitTests/Git/RepositoryTests.cs @@ -83,33 +83,14 @@ public void Repository() repository.Initialize(repositoryManager); - string expectedBranch = null; - repository.OnCurrentBranchChanged += branch => { - expectedBranch = branch; - }; - - string expectedRemote = null; - repository.OnCurrentRemoteChanged += remote => { - expectedRemote = remote; - }; - - repositoryManager.OnLocalBranchListUpdated += Raise.Event>>(branchDictionary); + repositoryManager.OnLocalBranchListUpdated += Raise.Event>>(branchDictionary); - repositoryEvents.OnLocalBranchListChanged.WaitOne(repositoryEventsTimeout).Should().BeTrue("OnLocalBranchListChanged not raised"); - - repositoryManager.OnRemoteBranchListUpdated += Raise.Event, Dictionary>>>(remoteDictionary, remoteBranchDictionary); - - repositoryEvents.OnRemoteBranchListChanged.WaitOne(repositoryEventsTimeout).Should().BeTrue("OnRemoteBranchListChanged not raised"); + repositoryManager.OnRemoteBranchListUpdated += Raise.Event, IDictionary>>>(remoteDictionary, remoteBranchDictionary); repositoryManager.OnCurrentBranchUpdated += Raise.Event>(masterOriginBranch); repositoryManager.OnCurrentRemoteUpdated += Raise.Event>(origin); - repositoryEvents.OnCurrentBranchChanged.WaitOne(repositoryEventsTimeout).Should().BeTrue("OnCurrentBranchChanged not raised"); - repositoryEvents.OnCurrentRemoteChanged.WaitOne(repositoryEventsTimeout).Should().BeTrue("OnCurrentRemoteChanged not raised"); repositoryEvents.OnRepositoryInfoChanged.WaitOne(repositoryEventsTimeout).Should().BeTrue("OnRepositoryInfoChanged not raised"); - - expectedBranch.Should().Be("master"); - expectedRemote.Should().Be("origin"); } } } From 5c645cb878edb931863c2072596c7634b3b7a456 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Tue, 31 Oct 2017 17:38:19 -0400 Subject: [PATCH 157/241] Functionality to manage locks --- src/GitHub.Api/Cache/CacheInterfaces.cs | 2 +- src/GitHub.Api/Git/IRepository.cs | 5 +- src/GitHub.Api/Git/Repository.cs | 57 ++++++++++++------- src/GitHub.Api/Git/RepositoryManager.cs | 28 +++------ .../Editor/GitHub.Unity/ApplicationCache.cs | 38 ++++++------- .../GitHub.Unity/UI/ProjectWindowInterface.cs | 18 +----- .../Editor/GitHub.Unity/UI/SettingsView.cs | 6 -- .../TestUtils/Events/IRepositoryListener.cs | 7 --- .../Events/IRepositoryManagerListener.cs | 14 ----- 9 files changed, 64 insertions(+), 111 deletions(-) diff --git a/src/GitHub.Api/Cache/CacheInterfaces.cs b/src/GitHub.Api/Cache/CacheInterfaces.cs index 5242a4849..76c281756 100644 --- a/src/GitHub.Api/Cache/CacheInterfaces.cs +++ b/src/GitHub.Api/Cache/CacheInterfaces.cs @@ -42,7 +42,7 @@ public interface IManagedCache public interface IGitLocksCache : IManagedCache { - List GitLocks { get; } + List GitLocks { get; set; } } public interface IGitUserCache : IManagedCache diff --git a/src/GitHub.Api/Git/IRepository.cs b/src/GitHub.Api/Git/IRepository.cs index 81e7ff784..dfe4a7e59 100644 --- a/src/GitHub.Api/Git/IRepository.cs +++ b/src/GitHub.Api/Git/IRepository.cs @@ -16,7 +16,6 @@ public interface IRepository : IEquatable ITask Push(); ITask Fetch(); ITask Revert(string changeset); - ITask ListLocks(); ITask RequestLock(string file); ITask ReleaseLock(string file, bool force); @@ -57,14 +56,14 @@ public interface IRepository : IEquatable GitBranch[] LocalBranches { get; } GitBranch[] RemoteBranches { get; } IUser User { get; set; } - IList CurrentLocks { get; } + List CurrentLocks { get; } string CurrentBranchName { get; } List CurrentLog { get; } - event Action> OnLocksChanged; event Action OnRepositoryInfoChanged; event Action GitStatusCacheUpdated; event Action GitLogCacheUpdated; + event Action GitLockCacheUpdated; event Action BranchCacheUpdated; } } \ No newline at end of file diff --git a/src/GitHub.Api/Git/Repository.cs b/src/GitHub.Api/Git/Repository.cs index a4187157a..46e106970 100644 --- a/src/GitHub.Api/Git/Repository.cs +++ b/src/GitHub.Api/Git/Repository.cs @@ -11,15 +11,14 @@ namespace GitHub.Unity [DebuggerDisplay("{DebuggerDisplay,nq}")] class Repository : IEquatable, IRepository { - private IList currentLocks; private IRepositoryManager repositoryManager; private ICacheContainer cacheContainer; - public event Action> OnLocksChanged; public event Action OnRepositoryInfoChanged; public event Action GitStatusCacheUpdated; public event Action GitLogCacheUpdated; + public event Action GitLockCacheUpdated; public event Action BranchCacheUpdated; /// @@ -85,6 +84,7 @@ private void CacheContainer_OnCacheUpdated(CacheType cacheType, DateTimeOffset o break; case CacheType.GitLocksCache: + FireGitLocksCacheUpdated(offset); break; case CacheType.GitUserCache: @@ -113,6 +113,12 @@ private void FireGitStatusCacheUpdated(DateTimeOffset dateTimeOffset) GitStatusCacheUpdated?.Invoke(new CacheUpdateEvent { UpdatedTimeString = dateTimeOffset.ToString() }); } + private void FireGitLocksCacheUpdated(DateTimeOffset dateTimeOffset) + { + Logger.Trace("GitStatusCacheUpdated {0}", dateTimeOffset); + GitLockCacheUpdated?.Invoke(new CacheUpdateEvent { UpdatedTimeString = dateTimeOffset.ToString() }); + } + public void Initialize(IRepositoryManager initRepositoryManager) { Logger.Trace("Initialize"); @@ -122,7 +128,6 @@ public void Initialize(IRepositoryManager initRepositoryManager) repositoryManager.OnCurrentBranchUpdated += RepositoryManager_OnCurrentBranchUpdated; repositoryManager.OnCurrentRemoteUpdated += RepositoryManager_OnCurrentRemoteUpdated; repositoryManager.OnRepositoryUpdated += RepositoryManager_OnRepositoryUpdated; - repositoryManager.OnLocksUpdated += locks => CurrentLocks = locks; repositoryManager.OnLocalBranchListUpdated += RepositoryManager_OnLocalBranchListUpdated; repositoryManager.OnRemoteBranchListUpdated += RepositoryManager_OnRemoteBranchListUpdated; repositoryManager.OnLocalBranchUpdated += RepositoryManager_OnLocalBranchUpdated; @@ -134,6 +139,7 @@ public void Initialize(IRepositoryManager initRepositoryManager) UpdateGitStatus(); UpdateGitLog(); + UpdateLocks(); } public ITask SetupRemote(string remote, string remoteUrl) @@ -180,13 +186,6 @@ public ITask Revert(string changeset) return repositoryManager.Revert(changeset); } - public ITask ListLocks() - { - if (repositoryManager == null) - return new ActionTask(new NotReadyException().ToTask()); - return repositoryManager.ListLocks(false); - } - public ITask RequestLock(string file) { return repositoryManager.LockFile(file); @@ -245,6 +244,22 @@ public void CheckGitLogCacheEvent(CacheUpdateEvent cacheUpdateEvent) } } + public void CheckGitLocksCacheEvent(CacheUpdateEvent cacheUpdateEvent) + { + var managedCache = cacheContainer.GitLocksCache; + var raiseEvent = ShouldRaiseCacheEvent(cacheUpdateEvent, managedCache); + + Logger.Trace("CheckGitLocksCacheEvent Current:{0} Check:{1} Result:{2}", + managedCache.LastUpdatedAt, + cacheUpdateEvent.UpdatedTimeString ?? "[NULL]", + raiseEvent); + + if (raiseEvent) + { + FireGitLogCacheUpdated(managedCache.LastUpdatedAt); + } + } + private static bool ShouldRaiseCacheEvent(CacheUpdateEvent cacheUpdateEvent, IManagedCache managedCache) { bool raiseEvent; @@ -319,6 +334,11 @@ private void UpdateGitLog() repositoryManager?.Log().ThenInUI((b, log) => { CurrentLog = log; }).Start(); } + private void UpdateLocks() + { + repositoryManager?.ListLocks(false).ThenInUI((b, locks) => { CurrentLocks = locks; }).Start(); + } + private void RepositoryManager_OnCurrentBranchUpdated(ConfigBranch? branch) { if (!Nullable.Equals(CurrentConfigBranch, branch)) @@ -504,6 +524,12 @@ public List CurrentLog set { cacheContainer.GitLogCache.Log = value; } } + public List CurrentLocks + { + get { return cacheContainer.GitLocksCache.GitLocks; } + set { cacheContainer.GitLocksCache.GitLocks = value; } + } + public UriString CloneUrl { get; private set; } public string Name { get; private set; } @@ -527,17 +553,6 @@ public List CurrentLog public IUser User { get; set; } - public IList CurrentLocks - { - get { return currentLocks; } - private set - { - Logger.Trace("OnLocksChanged: {0}", value.ToString()); - currentLocks = value; - OnLocksChanged?.Invoke(value); - } - } - protected static ILogging Logger { get; } = Logging.GetLogger(); } diff --git a/src/GitHub.Api/Git/RepositoryManager.cs b/src/GitHub.Api/Git/RepositoryManager.cs index ca499584d..5a094a384 100644 --- a/src/GitHub.Api/Git/RepositoryManager.cs +++ b/src/GitHub.Api/Git/RepositoryManager.cs @@ -15,7 +15,6 @@ public interface IRepositoryManager : IDisposable event Action> OnLocalBranchListUpdated; event Action OnLocalBranchRemoved; event Action OnLocalBranchUpdated; - event Action> OnLocksUpdated; event Action OnRemoteBranchAdded; event Action, IDictionary>> OnRemoteBranchListUpdated; event Action OnRemoteBranchRemoved; @@ -38,7 +37,7 @@ public interface IRepositoryManager : IDisposable ITask SwitchBranch(string branch); ITask DeleteBranch(string branch, bool deleteUnmerged = false); ITask CreateBranch(string branch, string baseBranch); - ITask ListLocks(bool local); + ITask> ListLocks(bool local); ITask LockFile(string file); ITask UnlockFile(string file, bool force); int WaitForEvents(); @@ -110,7 +109,6 @@ class RepositoryManager : IRepositoryManager public event Action> OnLocalBranchListUpdated; public event Action OnLocalBranchRemoved; public event Action OnLocalBranchUpdated; - public event Action> OnLocksUpdated; public event Action OnRemoteBranchAdded; public event Action, IDictionary>> OnRemoteBranchListUpdated; public event Action OnRemoteBranchRemoved; @@ -281,35 +279,23 @@ public ITask CreateBranch(string branch, string baseBranch) return HookupHandlers(task); } - public ITask ListLocks(bool local) + public ITask> ListLocks(bool local) { - var task = GitClient - .ListLocks(local) - .Then((success, locks) => - { - if (success) - { - Logger.Trace("OnLocksUpdated"); - OnLocksUpdated?.Invoke(locks); - } - }); - return HookupHandlers(task); + var task = GitClient.ListLocks(local); + HookupHandlers(task); + return task; } public ITask LockFile(string file) { var task = GitClient.Lock(file); - HookupHandlers(task); - - return task.Then(ListLocks(false)); + return HookupHandlers(task); } public ITask UnlockFile(string file, bool force) { var task = GitClient.Unlock(file, force); - HookupHandlers(task).Schedule(taskManager); - - return task.Then(ListLocks(false)); + return HookupHandlers(task); } private void LoadGitUser() diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs index e778df670..ad2f0b0e2 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs @@ -761,33 +761,29 @@ sealed class GitLocksCache : ManagedCacheBase, IGitLocksCache { [SerializeField] private string lastUpdatedAtString = DateTimeOffset.MinValue.ToString(); [SerializeField] private string lastVerifiedAtString = DateTimeOffset.MinValue.ToString(); - [SerializeField] private List locks = new List(); - - public void UpdateData(List locksUpdate) - { - var now = DateTimeOffset.Now; - var isUpdated = false; - - Logger.Trace("Processing Update: {0}", now); - - var locksIsNull = locks == null; - var locksUpdateIsNull = locksUpdate == null; - - if (locksIsNull != locksUpdateIsNull || !locksIsNull && !locks.SequenceEqual(locksUpdate)) - { - locks = locksUpdate; - isUpdated = true; - } - - SaveData(now, isUpdated); - } + [SerializeField] private List gitLocks = new List(); public List GitLocks { get { ValidateData(); - return locks; + return gitLocks; + } + set + { + var now = DateTimeOffset.Now; + var isUpdated = false; + + Logger.Trace("Updating: {0} gitLocks:{1}", now, value); + + if (!gitLocks.SequenceEqual(value)) + { + gitLocks = value; + isUpdated = true; + } + + SaveData(now, isUpdated); } } diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ProjectWindowInterface.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ProjectWindowInterface.cs index 764c4d429..bdce7fc65 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ProjectWindowInterface.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ProjectWindowInterface.cs @@ -28,11 +28,11 @@ public static void Initialize(IRepository repo) EditorApplication.projectWindowItemOnGUI += OnProjectWindowItemGUI; initialized = true; repository = repo; + if (repository != null) { //TODO: Listen to status change event //repository.OnStatusChanged += RunStatusUpdateOnMainThread; - repository.OnLocksChanged += RunLocksUpdateOnMainThread; } } @@ -127,14 +127,6 @@ private static void ContextMenu_Unlock() .Start(); } - private static void RunLocksUpdateOnMainThread(IEnumerable update) - { - new ActionTask(EntryPoint.ApplicationManager.TaskManager.Token, _ => OnLocksUpdate(update)) - { - Affinity = TaskAffinity.UI - }.Start(); - } - private static void OnLocksUpdate(IEnumerable update) { if (update == null) @@ -156,14 +148,6 @@ private static void OnLocksUpdate(IEnumerable update) EditorApplication.RepaintProjectWindow(); } - private static void RunStatusUpdateOnMainThread(GitStatus update) - { - new ActionTask(EntryPoint.ApplicationManager.TaskManager.Token, _ => OnStatusUpdate(update)) - { - Affinity = TaskAffinity.UI - }.Start(); - } - private static void OnStatusUpdate(GitStatus update) { if (update.Entries == null) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/SettingsView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/SettingsView.cs index 79d433372..9771c1e19 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/SettingsView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/SettingsView.cs @@ -89,24 +89,18 @@ public override void Refresh() base.Refresh(); gitPathView.Refresh(); userSettingsView.Refresh(); - if (Repository != null && Repository.CurrentRemote.HasValue) - { - Repository.ListLocks().Start(); - } } private void AttachHandlers(IRepository repository) { if (repository == null) return; - repository.OnLocksChanged += RunLocksUpdateOnMainThread; } private void DetachHandlers(IRepository repository) { if (repository == null) return; - repository.OnLocksChanged -= RunLocksUpdateOnMainThread; } public override void OnGUI() diff --git a/src/tests/TestUtils/Events/IRepositoryListener.cs b/src/tests/TestUtils/Events/IRepositoryListener.cs index 63d952ee5..53150bf2d 100644 --- a/src/tests/TestUtils/Events/IRepositoryListener.cs +++ b/src/tests/TestUtils/Events/IRepositoryListener.cs @@ -34,13 +34,6 @@ public static void AttachListener(this IRepositoryListener listener, { var logger = trace ? Logging.GetLogger() : null; - repository.OnLocksChanged += locks => - { - logger?.Debug("OnLocksChanged: {0}", locks); - listener.OnLocksChanged(locks); - repositoryEvents?.OnLocksChanged.Set(); - }; - repository.OnRepositoryInfoChanged += () => { logger?.Debug("OnRepositoryInfoChanged"); diff --git a/src/tests/TestUtils/Events/IRepositoryManagerListener.cs b/src/tests/TestUtils/Events/IRepositoryManagerListener.cs index 07f116e99..3c858bf54 100644 --- a/src/tests/TestUtils/Events/IRepositoryManagerListener.cs +++ b/src/tests/TestUtils/Events/IRepositoryManagerListener.cs @@ -94,20 +94,6 @@ public static void AttachListener(this IRepositoryManagerListener listener, managerEvents?.OnIsNotBusy.Set(); }; - //TODO: Figure this out - //repositoryManager.OnStatusUpdated += status => { - // logger?.Debug("OnStatusUpdated: {0}", status); - // listener.OnStatusUpdated(status); - // managerEvents?.OnStatusUpdated.Set(); - //}; - - repositoryManager.OnLocksUpdated += locks => { - var lockArray = locks.ToArray(); - logger?.Trace("OnLocksUpdated Count:{0}", lockArray.Length); - listener.OnLocksUpdated(lockArray); - managerEvents?.OnLocksUpdated.Set(); - }; - repositoryManager.OnCurrentBranchUpdated += configBranch => { logger?.Trace("OnCurrentBranchUpdated"); listener.OnCurrentBranchUpdated(configBranch); From 675d364ef259c900ddb79f80b76f8bbad883750f Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Tue, 31 Oct 2017 17:50:43 -0400 Subject: [PATCH 158/241] ChangesView isBusy should default to false --- src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ChangesView.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ChangesView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ChangesView.cs index c58ebc468..8562a5da9 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ChangesView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ChangesView.cs @@ -17,7 +17,7 @@ class ChangesView : Subview private const string OneChangedFileLabel = "1 changed file"; private const string NoChangedFilesLabel = "No changed files"; - [NonSerialized] private bool isBusy = true; + [NonSerialized] private bool isBusy; [SerializeField] private string commitBody = ""; [SerializeField] private string commitMessage = ""; From 7545af67639831a491b3d9a2ee63833d0be2b2ec Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Tue, 31 Oct 2017 17:50:56 -0400 Subject: [PATCH 159/241] Updating git log and status after the current branch is updated --- src/GitHub.Api/Git/Repository.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/GitHub.Api/Git/Repository.cs b/src/GitHub.Api/Git/Repository.cs index 46e106970..054e8374b 100644 --- a/src/GitHub.Api/Git/Repository.cs +++ b/src/GitHub.Api/Git/Repository.cs @@ -360,7 +360,8 @@ private void RepositoryManager_OnLocalBranchUpdated(string name) { if (name == CurrentConfigBranch?.Name) { - Logger.Trace("OnCurrentBranchUpdated: {0}", name); + UpdateGitStatus(); + UpdateGitLog(); } } From cdae882efacc0b6cbfbc878acb452c8e9bef9d75 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Tue, 31 Oct 2017 18:58:25 -0400 Subject: [PATCH 160/241] Background updates of different caches --- src/GitHub.Api/Git/IRepository.cs | 2 +- src/GitHub.Api/Git/Repository.cs | 20 +++++++------ .../Editor/GitHub.Unity/ApplicationCache.cs | 24 +++++++-------- .../GitHub.Unity/UI/ProjectWindowInterface.cs | 29 +++++++++++++++++-- .../TestUtils/Events/IRepositoryListener.cs | 26 +---------------- src/tests/UnitTests/Git/RepositoryTests.cs | 2 -- 6 files changed, 51 insertions(+), 52 deletions(-) diff --git a/src/GitHub.Api/Git/IRepository.cs b/src/GitHub.Api/Git/IRepository.cs index dfe4a7e59..ea7f1ca6b 100644 --- a/src/GitHub.Api/Git/IRepository.cs +++ b/src/GitHub.Api/Git/IRepository.cs @@ -22,6 +22,7 @@ public interface IRepository : IEquatable void CheckBranchCacheEvent(CacheUpdateEvent cacheUpdateEvent); void CheckGitStatusCacheEvent(CacheUpdateEvent cacheUpdateEvent); void CheckGitLogCacheEvent(CacheUpdateEvent cacheUpdateEvent); + void CheckGitLocksCacheEvent(CacheUpdateEvent cacheUpdateEvent); /// /// Gets the name of the repository. @@ -60,7 +61,6 @@ public interface IRepository : IEquatable string CurrentBranchName { get; } List CurrentLog { get; } - event Action OnRepositoryInfoChanged; event Action GitStatusCacheUpdated; event Action GitLogCacheUpdated; event Action GitLockCacheUpdated; diff --git a/src/GitHub.Api/Git/Repository.cs b/src/GitHub.Api/Git/Repository.cs index 054e8374b..8b1eec65b 100644 --- a/src/GitHub.Api/Git/Repository.cs +++ b/src/GitHub.Api/Git/Repository.cs @@ -14,8 +14,6 @@ class Repository : IEquatable, IRepository private IRepositoryManager repositoryManager; private ICacheContainer cacheContainer; - public event Action OnRepositoryInfoChanged; - public event Action GitStatusCacheUpdated; public event Action GitLogCacheUpdated; public event Action GitLockCacheUpdated; @@ -139,7 +137,9 @@ public void Initialize(IRepositoryManager initRepositoryManager) UpdateGitStatus(); UpdateGitLog(); - UpdateLocks(); + + new ActionTask(CancellationToken.None, UpdateLocks) + { Affinity = TaskAffinity.UI }.Start(); } public ITask SetupRemote(string remote, string remoteUrl) @@ -173,7 +173,7 @@ public ITask Pull() public ITask Push() { - return repositoryManager.Push(CurrentRemote.Value.Name, CurrentBranch?.Name); + return repositoryManager.Push(CurrentRemote.Value.Name, CurrentBranch?.Name).Then(UpdateGitStatus); } public ITask Fetch() @@ -188,12 +188,12 @@ public ITask Revert(string changeset) public ITask RequestLock(string file) { - return repositoryManager.LockFile(file); + return repositoryManager.LockFile(file).Then(UpdateLocks); } public ITask ReleaseLock(string file, bool force) { - return repositoryManager.UnlockFile(file, force); + return repositoryManager.UnlockFile(file, force).Then(UpdateLocks); } public void CheckBranchCacheEvent(CacheUpdateEvent cacheUpdateEvent) @@ -336,7 +336,10 @@ private void UpdateGitLog() private void UpdateLocks() { - repositoryManager?.ListLocks(false).ThenInUI((b, locks) => { CurrentLocks = locks; }).Start(); + if (CurrentRemote.HasValue) + { + repositoryManager?.ListLocks(false).ThenInUI((b, locks) => { CurrentLocks = locks; }).Start(); + } } private void RepositoryManager_OnCurrentBranchUpdated(ConfigBranch? branch) @@ -351,6 +354,7 @@ private void RepositoryManager_OnCurrentBranchUpdated(ConfigBranch? branch) CurrentConfigBranch = branch; CurrentBranch = currentBranch; + UpdateLocalBranches(); }) { Affinity = TaskAffinity.UI }.Start(); } @@ -416,8 +420,6 @@ private void UpdateRepositoryInfo() Name = LocalPath.FileName; Logger.Trace("CloneUrl: [NULL]"); } - - OnRepositoryInfoChanged?.Invoke(); } private void RepositoryManager_OnLocalBranchRemoved(string name) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs index ad2f0b0e2..330b1591c 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs @@ -260,17 +260,16 @@ void IDictionary>.Add(string key, IDic bool IDictionary>.TryGetValue(string key, out IDictionary value) { - throw new NotImplementedException(); - //value = null; - // - //SerializableDictionary branches; - //if (TryGetValue(key, out branches)) - //{ - // value = branches.AsDictionary; - // return true; - //} - // - //return false; + value = null; + + SerializableDictionary branches; + if (TryGetValue(key, out branches)) + { + value = branches; + return true; + } + + return false; } IDictionary IDictionary>.this[string key] @@ -307,8 +306,7 @@ ICollection> IDictionary pair.Value.AsDictionary).ToArray(); + return Values.Cast>().ToArray(); } } } diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ProjectWindowInterface.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ProjectWindowInterface.cs index bdce7fc65..4f5aec52c 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ProjectWindowInterface.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ProjectWindowInterface.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Threading; using System.Threading.Tasks; using UnityEditor; using UnityEngine; @@ -19,6 +20,8 @@ class ProjectWindowInterface : AssetPostprocessor private static bool isBusy = false; private static ILogging logger; private static ILogging Logger { get { return logger = logger ?? Logging.GetLogger(); } } + private static CacheUpdateEvent gitStatusUpdateEvent; + private static CacheUpdateEvent gitLocksUpdateEvent; public static void Initialize(IRepository repo) { @@ -26,16 +29,38 @@ public static void Initialize(IRepository repo) EditorApplication.projectWindowItemOnGUI -= OnProjectWindowItemGUI; EditorApplication.projectWindowItemOnGUI += OnProjectWindowItemGUI; + initialized = true; repository = repo; if (repository != null) { - //TODO: Listen to status change event - //repository.OnStatusChanged += RunStatusUpdateOnMainThread; + repository.GitLockCacheUpdated += Repository_GitLockCacheUpdated; + repository.GitStatusCacheUpdated += Repository_GitStatusCacheUpdated; + + repository.CheckGitStatusCacheEvent(gitStatusUpdateEvent); + repository.CheckGitLocksCacheEvent(gitLocksUpdateEvent); } } + private static void Repository_GitStatusCacheUpdated(CacheUpdateEvent cacheUpdateEvent) + { + new ActionTask(CancellationToken.None, () => { + gitStatusUpdateEvent = cacheUpdateEvent; + OnStatusUpdate(repository.CurrentStatus); + }) + { Affinity = TaskAffinity.UI }.Start(); + } + + private static void Repository_GitLockCacheUpdated(CacheUpdateEvent cacheUpdateEvent) + { + new ActionTask(CancellationToken.None, () => { + gitLocksUpdateEvent = cacheUpdateEvent; + OnLocksUpdate(repository.CurrentLocks); + }) + { Affinity = TaskAffinity.UI }.Start(); + } + [MenuItem("Assets/Request Lock", true)] private static bool ContextMenu_CanLock() { diff --git a/src/tests/TestUtils/Events/IRepositoryListener.cs b/src/tests/TestUtils/Events/IRepositoryListener.cs index 53150bf2d..c1327ca11 100644 --- a/src/tests/TestUtils/Events/IRepositoryListener.cs +++ b/src/tests/TestUtils/Events/IRepositoryListener.cs @@ -1,29 +1,15 @@ -using System.Collections.Generic; -using System.Linq; -using System.Threading; using GitHub.Unity; -using NSubstitute; namespace TestUtils.Events { interface IRepositoryListener { - void OnStatusChanged(GitStatus status); - void OnLocksChanged(IEnumerable locks); - void OnRepositoryInfoChanged(); } class RepositoryEvents { - public EventWaitHandle OnStatusChanged { get; } = new AutoResetEvent(false); - public EventWaitHandle OnLocksChanged { get; } = new AutoResetEvent(false); - public EventWaitHandle OnRepositoryInfoChanged { get; } = new AutoResetEvent(false); - public void Reset() { - OnStatusChanged.Reset(); - OnLocksChanged.Reset(); - OnRepositoryInfoChanged.Reset(); } } @@ -32,21 +18,11 @@ static class RepositoryListenerExtensions public static void AttachListener(this IRepositoryListener listener, IRepository repository, RepositoryEvents repositoryEvents = null, bool trace = true) { - var logger = trace ? Logging.GetLogger() : null; - - repository.OnRepositoryInfoChanged += () => - { - logger?.Debug("OnRepositoryInfoChanged"); - listener.OnRepositoryInfoChanged(); - repositoryEvents?.OnRepositoryInfoChanged.Set(); - }; + //var logger = trace ? Logging.GetLogger() : null; } public static void AssertDidNotReceiveAnyCalls(this IRepositoryListener repositoryListener) { - repositoryListener.DidNotReceive().OnStatusChanged(Args.GitStatus); - repositoryListener.DidNotReceive().OnLocksChanged(Arg.Any>()); - repositoryListener.DidNotReceive().OnRepositoryInfoChanged(); } } }; \ No newline at end of file diff --git a/src/tests/UnitTests/Git/RepositoryTests.cs b/src/tests/UnitTests/Git/RepositoryTests.cs index 2b385aa2e..95e505c19 100644 --- a/src/tests/UnitTests/Git/RepositoryTests.cs +++ b/src/tests/UnitTests/Git/RepositoryTests.cs @@ -89,8 +89,6 @@ public void Repository() repositoryManager.OnCurrentBranchUpdated += Raise.Event>(masterOriginBranch); repositoryManager.OnCurrentRemoteUpdated += Raise.Event>(origin); - - repositoryEvents.OnRepositoryInfoChanged.WaitOne(repositoryEventsTimeout).Should().BeTrue("OnRepositoryInfoChanged not raised"); } } } From d43102d278aeac3bad63d506eb48520d0b6ca135 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Tue, 31 Oct 2017 19:17:00 -0400 Subject: [PATCH 161/241] Updating locks and remotes in SettingsView --- .../Editor/GitHub.Unity/UI/BranchesView.cs | 1 + .../Editor/GitHub.Unity/UI/ChangesView.cs | 1 + .../Editor/GitHub.Unity/UI/SettingsView.cs | 71 ++++++++++--------- 3 files changed, 41 insertions(+), 32 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs index 925456f10..6c161b413 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs @@ -50,6 +50,7 @@ class BranchesView : Subview [SerializeField] private CacheUpdateEvent branchUpdateEvent; [NonSerialized] private bool branchCacheHasUpdate; + [SerializeField] private GitBranch[] localBranches; [SerializeField] private GitBranch[] remoteBranches; diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ChangesView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ChangesView.cs index 8562a5da9..dc1837fbd 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ChangesView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ChangesView.cs @@ -61,6 +61,7 @@ private void AttachHandlers(IRepository repository) { if (repository == null) return; + repository.BranchCacheUpdated += Repository_BranchCacheUpdated; repository.GitStatusCacheUpdated += Repository_GitStatusCacheUpdated; } diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/SettingsView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/SettingsView.cs index 9771c1e19..e3a091918 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/SettingsView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/SettingsView.cs @@ -29,8 +29,6 @@ class SettingsView : Subview [SerializeField] private Vector2 scroll; [SerializeField] private int lockedFileSelection = -1; [SerializeField] private bool hasRemote; - [NonSerialized] private bool remoteHasChanged; - [NonSerialized] private bool locksHaveChanged; [SerializeField] private string newRepositoryRemoteUrl; @@ -40,6 +38,12 @@ class SettingsView : Subview [SerializeField] private GitPathView gitPathView = new GitPathView(); [SerializeField] private UserSettingsView userSettingsView = new UserSettingsView(); + [SerializeField] private CacheUpdateEvent branchUpdateEvent; + [NonSerialized] private bool branchCacheHasUpdate; + + [SerializeField] private CacheUpdateEvent gitLocksUpdateEvent; + [NonSerialized] private bool gitLocksCacheHasUpdate; + public override void InitializeView(IView parent) { base.InitializeView(parent); @@ -47,7 +51,6 @@ public override void InitializeView(IView parent) userSettingsView.InitializeView(this); } - public override void OnEnable() { base.OnEnable(); @@ -55,9 +58,13 @@ public override void OnEnable() userSettingsView.OnEnable(); AttachHandlers(Repository); - remoteHasChanged = true; + if (Repository != null) + { + Repository.CheckBranchCacheEvent(branchUpdateEvent); + Repository.CheckGitLocksCacheEvent(gitLocksUpdateEvent); + } + metricsHasChanged = true; - locksHaveChanged = true; } public override void OnDisable() @@ -95,6 +102,29 @@ private void AttachHandlers(IRepository repository) { if (repository == null) return; + + repository.BranchCacheUpdated += Repository_BranchCacheUpdated; + repository.GitLockCacheUpdated += Repository_GitLockCacheUpdated; + } + + private void Repository_GitLockCacheUpdated(CacheUpdateEvent cacheUpdateEvent) + { + new ActionTask(TaskManager.Token, () => { + gitLocksUpdateEvent = cacheUpdateEvent; + gitLocksCacheHasUpdate = true; + Redraw(); + }) + { Affinity = TaskAffinity.UI }.Start(); + } + + private void Repository_BranchCacheUpdated(CacheUpdateEvent cacheUpdateEvent) + { + new ActionTask(TaskManager.Token, () => { + branchUpdateEvent = cacheUpdateEvent; + branchCacheHasUpdate = true; + Redraw(); + }) + { Affinity = TaskAffinity.UI }.Start(); } private void DetachHandlers(IRepository repository) @@ -144,12 +174,9 @@ private void MaybeUpdateData() if (Repository == null) return; - if (!remoteHasChanged && !locksHaveChanged) - return; - - if (remoteHasChanged) + if (branchCacheHasUpdate) { - remoteHasChanged = false; + branchCacheHasUpdate = false; var activeRemote = Repository.CurrentRemote; hasRemote = activeRemote.HasValue && !String.IsNullOrEmpty(activeRemote.Value.Url); if (!hasRemote) @@ -164,9 +191,9 @@ private void MaybeUpdateData() } } - if (locksHaveChanged) + if (gitLocksCacheHasUpdate) { - locksHaveChanged = false; + gitLocksCacheHasUpdate = false; var repositoryCurrentLocks = Repository.CurrentLocks; lockedFiles = repositoryCurrentLocks != null ? repositoryCurrentLocks.ToList() @@ -174,26 +201,6 @@ private void MaybeUpdateData() } } - private void RunLocksUpdateOnMainThread(IEnumerable locks) - { - new ActionTask(TaskManager.Token, _ => OnLocksUpdate(locks)) - .ScheduleUI(TaskManager); - } - - private void OnLocksUpdate(IEnumerable update) - { - if (update == null) - { - return; - } - lockedFiles = update.ToList(); - if (lockedFiles.Count <= lockedFileSelection) - { - lockedFileSelection = -1; - } - Redraw(); - } - private void OnRepositorySettingsGUI() { GUILayout.Label(GitRepositoryTitle, EditorStyles.boldLabel); From 034ba9cc3137bc9a599794930edc2ea6cb82e05c Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Tue, 31 Oct 2017 20:06:45 -0400 Subject: [PATCH 162/241] Fixing exception message --- .../Assets/Editor/GitHub.Unity/SerializableDictionary.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/SerializableDictionary.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/SerializableDictionary.cs index 18fb23c78..0404f18fe 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/SerializableDictionary.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/SerializableDictionary.cs @@ -34,7 +34,7 @@ public void OnAfterDeserialize() this.Clear(); if (keys.Count != values.Count) - throw new System.Exception(string.Format("there are {0} keys and {1} values after deserialization. Make sure that both key and value types are serializable.")); + throw new Exception(string.Format("there are {0} keys and {1} values after deserialization. Make sure that both key and value types are serializable.", keys.Count, values.Count)); for (int i = 0; i < keys.Count; i++) this.Add(keys[i], values[i]); From af3bf88dfd8a5c2a3c9863f0f4662cf61b3a906e Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Wed, 1 Nov 2017 10:03:09 -0400 Subject: [PATCH 163/241] Making GitLock serializable --- src/GitHub.Api/Git/GitLock.cs | 22 +++++------- src/GitHub.Api/Git/GitObjectFactory.cs | 7 +++- .../Substitutes/SubstituteFactory.cs | 7 +++- .../UnitTests/IO/LockOutputProcessorTests.cs | 35 ++++++++++++++++--- 4 files changed, 50 insertions(+), 21 deletions(-) diff --git a/src/GitHub.Api/Git/GitLock.cs b/src/GitHub.Api/Git/GitLock.cs index b7ee35cdf..ddcdd9578 100644 --- a/src/GitHub.Api/Git/GitLock.cs +++ b/src/GitHub.Api/Git/GitLock.cs @@ -5,20 +5,14 @@ namespace GitHub.Unity [Serializable] public struct GitLock { - public static GitLock Default = new GitLock(null, null, null, -1); - - public readonly int ID; - public readonly string Path; - public readonly string FullPath; - public readonly string User; - - public GitLock(string path, string fullPath, string user, int id) - { - Path = path; - FullPath = fullPath; - User = user; - ID = id; - } + public static GitLock Default = new GitLock { + ID = -1 + }; + + public int ID; + public string Path; + public string FullPath; + public string User; public override bool Equals(object other) { diff --git a/src/GitHub.Api/Git/GitObjectFactory.cs b/src/GitHub.Api/Git/GitObjectFactory.cs index 489c0475a..6b5d763a5 100644 --- a/src/GitHub.Api/Git/GitObjectFactory.cs +++ b/src/GitHub.Api/Git/GitObjectFactory.cs @@ -26,7 +26,12 @@ public GitLock CreateGitLock(string path, string user, int id) var npath = new NPath(path).MakeAbsolute(); var fullPath = npath.RelativeTo(environment.RepositoryPath); - return new GitLock(path, fullPath, user, id); + return new GitLock { + Path = path, + FullPath = fullPath, + User = user, + ID = id + }; } } } diff --git a/src/tests/TestUtils/Substitutes/SubstituteFactory.cs b/src/tests/TestUtils/Substitutes/SubstituteFactory.cs index be5929f17..057a61b7f 100644 --- a/src/tests/TestUtils/Substitutes/SubstituteFactory.cs +++ b/src/tests/TestUtils/Substitutes/SubstituteFactory.cs @@ -325,7 +325,12 @@ public IGitObjectFactory CreateGitObjectFactory(string gitRepoPath) var user = (string)info[1]; var id = (int)info[2]; - return new GitLock(path, gitRepoPath + @"\" + path, user, id); + return new GitLock { + Path = path, + FullPath = gitRepoPath + @"\" + path, + User = user, + ID = id + }; }); return gitObjectFactory; diff --git a/src/tests/UnitTests/IO/LockOutputProcessorTests.cs b/src/tests/UnitTests/IO/LockOutputProcessorTests.cs index 9fc38097b..b035cc866 100644 --- a/src/tests/UnitTests/IO/LockOutputProcessorTests.cs +++ b/src/tests/UnitTests/IO/LockOutputProcessorTests.cs @@ -63,8 +63,18 @@ public void ShouldParseTwoLocksFormat1() }; var expected = new[] { - new GitLock("folder/somefile.png", TestRootPath + @"\folder/somefile.png", "GitHub User", 12), - new GitLock("somezip.zip", TestRootPath + @"\somezip.zip", "GitHub User", 21) + new GitLock { + Path = "folder/somefile.png", + FullPath = TestRootPath + @"\folder/somefile.png", + User = "GitHub User", + ID = 12 + }, + new GitLock { + Path = "somezip.zip", + FullPath = TestRootPath + @"\somezip.zip", + User = "GitHub User", + ID = 21 + } }; AssertProcessOutput(output, expected); @@ -81,8 +91,18 @@ public void ShouldParseTwoLocksFormat2() }; var expected = new[] { - new GitLock("folder/somefile.png", TestRootPath + @"\folder/somefile.png", "GitHub User", 12), - new GitLock("somezip.zip", TestRootPath + @"\somezip.zip", "GitHub User", 21) + new GitLock { + Path = "folder/somefile.png", + FullPath = TestRootPath + @"\folder/somefile.png", + User = "GitHub User", + ID = 12 + }, + new GitLock { + Path = "somezip.zip", + FullPath = TestRootPath + @"\somezip.zip", + User = "GitHub User", + ID = 21 + } }; AssertProcessOutput(output, expected); @@ -97,7 +117,12 @@ public void ShouldParseLocksOnFileWithNumericFirstLetter() }; var expected = new[] { - new GitLock("2_TurtleDoves.jpg", TestRootPath + @"\2_TurtleDoves.jpg", "Tree", 100) + new GitLock { + Path = "2_TurtleDoves.jpg", + FullPath = TestRootPath + @"\2_TurtleDoves.jpg", + User = "Tree", + ID = 100 + } }; AssertProcessOutput(output, expected); From 77dc4970c6bb64d36c5c459d8efcf556c1c2d32b Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Wed, 1 Nov 2017 11:23:44 -0400 Subject: [PATCH 164/241] I thought this would work --- .../Editor/GitHub.Unity/ApplicationCache.cs | 14 +++-- .../GitHub.Unity/SerializableDictionary.cs | 52 +++++++++++++++++++ 2 files changed, 63 insertions(+), 3 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs index 330b1591c..ec74f828c 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs @@ -197,7 +197,7 @@ public LocalConfigBranchDictionary(IDictionary dictionary) } [Serializable] - class RemoteConfigBranchDictionary : SerializableDictionary>, IRemoteConfigBranchDictionary + class RemoteConfigBranchDictionary : SerializableNestedDictionary, IRemoteConfigBranchDictionary { public RemoteConfigBranchDictionary() { } @@ -206,7 +206,7 @@ public RemoteConfigBranchDictionary(IDictionary valuePair.Key, valuePair => valuePair.Value)); } } @@ -262,7 +262,7 @@ bool IDictionary>.TryGetValue(string k { value = null; - SerializableDictionary branches; + Dictionary branches; if (TryGetValue(key, out branches)) { value = branches; @@ -610,13 +610,21 @@ public void RemoveRemoteBranch(string remote, string branch) public void SetRemotes(IDictionary remoteDictionary, IDictionary> branchDictionary) { + var now = DateTimeOffset.Now; configRemotes = new ConfigRemoteDictionary(remoteDictionary); remoteConfigBranches = new RemoteConfigBranchDictionary(branchDictionary); + Logger.Trace("SetRemotes {0}", now); + Logger.Trace("remoteDictionary.Length: {0}", remoteDictionary.Count); + Logger.Trace("branchDictionary.Length: {0}", branchDictionary.Count); + SaveData(now, true); } public void SetLocals(IDictionary branchDictionary) { + var now = DateTimeOffset.Now; localConfigBranches = new LocalConfigBranchDictionary(branchDictionary); + Logger.Trace("SetRemotes {0}", now); + SaveData(now, true); } public override string LastUpdatedAtString diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/SerializableDictionary.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/SerializableDictionary.cs index 0404f18fe..d0ce4ebf0 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/SerializableDictionary.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/SerializableDictionary.cs @@ -40,4 +40,56 @@ public void OnAfterDeserialize() this.Add(keys[i], values[i]); } } + + [Serializable] + public class ArrayContainer + { + [SerializeField] + public T[] Values = new T[0]; + } + + [Serializable] + public class SerializableNestedDictionary : Dictionary>, ISerializationCallbackReceiver + { + [SerializeField] private TKey[] keys = new TKey[0]; + [SerializeField] private ArrayContainer[] subKeys = new ArrayContainer[0]; + [SerializeField] private ArrayContainer[] subKeyValues = new ArrayContainer[0]; + + // save the dictionary to lists + public void OnBeforeSerialize() + { + var keyList = new List(); + var subKeysList = new List>(); + var subKeysValuesList = new List>(); + + foreach (var pair in this) + { + var pairKey = pair.Key; + keyList.Add(pairKey); + + var serializeSubKeys = new List(); + var serializeSubKeyValues = new List(); + + var subDictionary = pair.Value; + foreach (var subPair in subDictionary) + { + serializeSubKeys.Add(subPair.Key); + serializeSubKeyValues.Add(subPair.Value); + } + + subKeysList.Add(new ArrayContainer { Values = serializeSubKeys.ToArray() }); + subKeysValuesList.Add(new ArrayContainer { Values = serializeSubKeyValues.ToArray() }); + } + + keys = keyList.ToArray(); + subKeys = subKeysList.ToArray(); + subKeyValues = subKeysValuesList.ToArray(); + } + + // load dictionary from lists + public void OnAfterDeserialize() + { + this.Clear(); + } + } } \ No newline at end of file From 9898fd95f99083e8589163865aaacd7b17ff07be Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Wed, 1 Nov 2017 11:32:30 -0400 Subject: [PATCH 165/241] Proof the values are being set, just not serializing --- .../Assets/Editor/GitHub.Unity/ApplicationCache.cs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs index ec74f828c..c4986be73 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs @@ -613,9 +613,20 @@ public void SetRemotes(IDictionary remoteDictionary, IDict var now = DateTimeOffset.Now; configRemotes = new ConfigRemoteDictionary(remoteDictionary); remoteConfigBranches = new RemoteConfigBranchDictionary(branchDictionary); + Logger.Trace("SetRemotes {0}", now); + Logger.Trace("remoteDictionary.Length: {0}", remoteDictionary.Count); Logger.Trace("branchDictionary.Length: {0}", branchDictionary.Count); + + foreach (var remotePair in remoteConfigBranches) + { + foreach (var remotePairBranch in remotePair.Value) + { + Logger.Trace("remoteConfigBranches Remote:{0} Branch:{1} BranchObject:{2}", remotePair.Key, remotePairBranch.Key, remotePairBranch.Value); + } + } + SaveData(now, true); } From 854b1893121ccbcd21aa2c3f54e1ed0e80f4a71e Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Wed, 1 Nov 2017 11:35:36 -0400 Subject: [PATCH 166/241] A culprit has been discovered --- .../GitHub.Unity/SerializableDictionary.cs | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/SerializableDictionary.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/SerializableDictionary.cs index d0ce4ebf0..fdd828382 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/SerializableDictionary.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/SerializableDictionary.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Linq; using UnityEngine; @@ -42,25 +43,25 @@ public void OnAfterDeserialize() } [Serializable] - public class ArrayContainer + public class ArrayContainer { [SerializeField] - public T[] Values = new T[0]; + public object[] Values = new object[0]; } [Serializable] public class SerializableNestedDictionary : Dictionary>, ISerializationCallbackReceiver { [SerializeField] private TKey[] keys = new TKey[0]; - [SerializeField] private ArrayContainer[] subKeys = new ArrayContainer[0]; - [SerializeField] private ArrayContainer[] subKeyValues = new ArrayContainer[0]; + [SerializeField] private ArrayContainer[] subKeys = new ArrayContainer[0]; + [SerializeField] private ArrayContainer[] subKeyValues = new ArrayContainer[0]; // save the dictionary to lists public void OnBeforeSerialize() { var keyList = new List(); - var subKeysList = new List>(); - var subKeysValuesList = new List>(); + var subKeysList = new List(); + var subKeysValuesList = new List(); foreach (var pair in this) { @@ -77,8 +78,8 @@ public void OnBeforeSerialize() serializeSubKeyValues.Add(subPair.Value); } - subKeysList.Add(new ArrayContainer { Values = serializeSubKeys.ToArray() }); - subKeysValuesList.Add(new ArrayContainer { Values = serializeSubKeyValues.ToArray() }); + subKeysList.Add(new ArrayContainer { Values = serializeSubKeys.Cast().ToArray() }); + subKeysValuesList.Add(new ArrayContainer { Values = serializeSubKeyValues.Cast().ToArray() }); } keys = keyList.ToArray(); From eb4c2d019ab1fc626d36501f441b08e4d842037c Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Wed, 1 Nov 2017 11:49:48 -0400 Subject: [PATCH 167/241] Correctly serializing remote branch dictionaries --- .../Editor/GitHub.Unity/ApplicationCache.cs | 101 +++++++++++++++--- .../GitHub.Unity/SerializableDictionary.cs | 52 --------- 2 files changed, 87 insertions(+), 66 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs index c4986be73..82abc35d7 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs @@ -197,8 +197,28 @@ public LocalConfigBranchDictionary(IDictionary dictionary) } [Serializable] - class RemoteConfigBranchDictionary : SerializableNestedDictionary, IRemoteConfigBranchDictionary + public class ArrayContainer { + [SerializeField] public T[] Values = new T[0]; + } + + [Serializable] + public class StringArrayContainer: ArrayContainer + { + } + + [Serializable] + public class ConfigBranchArrayContainer : ArrayContainer + { + } + + [Serializable] + class RemoteConfigBranchDictionary : Dictionary>, ISerializationCallbackReceiver, IRemoteConfigBranchDictionary + { + [SerializeField] private string[] keys = new string[0]; + [SerializeField] private StringArrayContainer[] subKeys = new StringArrayContainer[0]; + [SerializeField] private ConfigBranchArrayContainer[] subKeyValues = new ConfigBranchArrayContainer[0]; + public RemoteConfigBranchDictionary() { } @@ -208,6 +228,72 @@ public RemoteConfigBranchDictionary(IDictionary valuePair.Key, valuePair => valuePair.Value)); } + } + + // save the dictionary to lists + public void OnBeforeSerialize() + { + var keyList = new List(); + var subKeysList = new List(); + var subKeysValuesList = new List(); + + foreach (var pair in this) + { + var pairKey = pair.Key; + keyList.Add(pairKey); + + var serializeSubKeys = new List(); + var serializeSubKeyValues = new List(); + + var subDictionary = pair.Value; + foreach (var subPair in subDictionary) + { + serializeSubKeys.Add(subPair.Key); + serializeSubKeyValues.Add(subPair.Value); + } + + subKeysList.Add(new StringArrayContainer { Values = serializeSubKeys.ToArray() }); + subKeysValuesList.Add(new ConfigBranchArrayContainer { Values = serializeSubKeyValues.ToArray() }); + } + + keys = keyList.ToArray(); + subKeys = subKeysList.ToArray(); + subKeyValues = subKeysValuesList.ToArray(); + } + + // load dictionary from lists + public void OnAfterDeserialize() + { + Clear(); + + if (keys.Length != subKeys.Length || subKeys.Length != subKeyValues.Length) + { + throw new Exception("Deserialization length mismatch"); + } + + for (var remoteIndex = 0; remoteIndex < keys.Length; remoteIndex++) + { + var remote = keys[remoteIndex]; + + var subKeyContainer = subKeys[remoteIndex]; + var subKeyValueContainer = subKeyValues[remoteIndex]; + + if (subKeyContainer.Values.Length != subKeyValueContainer.Values.Length) + { + throw new Exception("Deserialization length mismatch"); + } + + var branchesDictionary = new Dictionary(); + for (var branchIndex = 0; branchIndex < subKeyContainer.Values.Length; branchIndex++) + { + var remoteBranchKey = subKeyContainer.Values[branchIndex]; + var remoteBranch = subKeyValueContainer.Values[branchIndex]; + + branchesDictionary.Add(remoteBranchKey, remoteBranch); + } + + Add(remote, branchesDictionary); + } } IEnumerator>> IEnumerable>>.GetEnumerator() @@ -613,20 +699,7 @@ public void SetRemotes(IDictionary remoteDictionary, IDict var now = DateTimeOffset.Now; configRemotes = new ConfigRemoteDictionary(remoteDictionary); remoteConfigBranches = new RemoteConfigBranchDictionary(branchDictionary); - Logger.Trace("SetRemotes {0}", now); - - Logger.Trace("remoteDictionary.Length: {0}", remoteDictionary.Count); - Logger.Trace("branchDictionary.Length: {0}", branchDictionary.Count); - - foreach (var remotePair in remoteConfigBranches) - { - foreach (var remotePairBranch in remotePair.Value) - { - Logger.Trace("remoteConfigBranches Remote:{0} Branch:{1} BranchObject:{2}", remotePair.Key, remotePairBranch.Key, remotePairBranch.Value); - } - } - SaveData(now, true); } diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/SerializableDictionary.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/SerializableDictionary.cs index fdd828382..84b69c38e 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/SerializableDictionary.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/SerializableDictionary.cs @@ -41,56 +41,4 @@ public void OnAfterDeserialize() this.Add(keys[i], values[i]); } } - - [Serializable] - public class ArrayContainer - { - [SerializeField] - public object[] Values = new object[0]; - } - - [Serializable] - public class SerializableNestedDictionary : Dictionary>, ISerializationCallbackReceiver - { - [SerializeField] private TKey[] keys = new TKey[0]; - [SerializeField] private ArrayContainer[] subKeys = new ArrayContainer[0]; - [SerializeField] private ArrayContainer[] subKeyValues = new ArrayContainer[0]; - - // save the dictionary to lists - public void OnBeforeSerialize() - { - var keyList = new List(); - var subKeysList = new List(); - var subKeysValuesList = new List(); - - foreach (var pair in this) - { - var pairKey = pair.Key; - keyList.Add(pairKey); - - var serializeSubKeys = new List(); - var serializeSubKeyValues = new List(); - - var subDictionary = pair.Value; - foreach (var subPair in subDictionary) - { - serializeSubKeys.Add(subPair.Key); - serializeSubKeyValues.Add(subPair.Value); - } - - subKeysList.Add(new ArrayContainer { Values = serializeSubKeys.Cast().ToArray() }); - subKeysValuesList.Add(new ArrayContainer { Values = serializeSubKeyValues.Cast().ToArray() }); - } - - keys = keyList.ToArray(); - subKeys = subKeysList.ToArray(); - subKeyValues = subKeysValuesList.ToArray(); - } - - // load dictionary from lists - public void OnAfterDeserialize() - { - this.Clear(); - } - } } \ No newline at end of file From f81d00f691383238b31f4eed639799c5b67937b8 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Wed, 1 Nov 2017 12:48:27 -0400 Subject: [PATCH 168/241] Restoring RepositoryInfoCache --- src/GitHub.Api/Cache/CacheInterfaces.cs | 10 +- src/GitHub.Api/Git/IRepository.cs | 2 + src/GitHub.Api/Git/Repository.cs | 156 +++++++++--------- .../Editor/GitHub.Unity/ApplicationCache.cs | 95 ++++++----- .../Editor/GitHub.Unity/CacheContainer.cs | 16 ++ .../Assets/Editor/GitHub.Unity/UI/Window.cs | 19 ++- 6 files changed, 170 insertions(+), 128 deletions(-) diff --git a/src/GitHub.Api/Cache/CacheInterfaces.cs b/src/GitHub.Api/Cache/CacheInterfaces.cs index 76c281756..d7fe8ff7a 100644 --- a/src/GitHub.Api/Cache/CacheInterfaces.cs +++ b/src/GitHub.Api/Cache/CacheInterfaces.cs @@ -5,6 +5,7 @@ namespace GitHub.Unity { public enum CacheType { + RepositoryInfoCache, BranchCache, GitLogCache, GitStatusCache, @@ -22,6 +23,7 @@ public interface ICacheContainer IGitStatusCache GitStatusCache { get; } IGitLocksCache GitLocksCache { get; } IGitUserCache GitUserCache { get; } + IRepositoryInfoCache RepositoryInfoCache { get; } void Validate(CacheType cacheType); void ValidateAll(); void Invalidate(CacheType cacheType); @@ -72,8 +74,6 @@ public interface IConfigRemoteDictionary : IDictionary public interface IBranchCache : IManagedCache { - GitRemote? CurrentGitRemote { get; set; } - GitBranch? CurentGitBranch { get; set; } ConfigRemote? CurrentConfigRemote { get; set; } ConfigBranch? CurentConfigBranch { get; set; } @@ -93,6 +93,12 @@ public interface IBranchCache : IManagedCache void SetLocals(IDictionary branchDictionary); } + public interface IRepositoryInfoCache : IManagedCache + { + GitRemote? CurrentGitRemote { get; set; } + GitBranch? CurentGitBranch { get; set; } + } + public interface IGitLogCache : IManagedCache { List Log { get; set; } diff --git a/src/GitHub.Api/Git/IRepository.cs b/src/GitHub.Api/Git/IRepository.cs index ea7f1ca6b..8ce200ad2 100644 --- a/src/GitHub.Api/Git/IRepository.cs +++ b/src/GitHub.Api/Git/IRepository.cs @@ -19,6 +19,7 @@ public interface IRepository : IEquatable ITask RequestLock(string file); ITask ReleaseLock(string file, bool force); + void CheckRepositoryInfoCacheEvent(CacheUpdateEvent cacheUpdateEvent); void CheckBranchCacheEvent(CacheUpdateEvent cacheUpdateEvent); void CheckGitStatusCacheEvent(CacheUpdateEvent cacheUpdateEvent); void CheckGitLogCacheEvent(CacheUpdateEvent cacheUpdateEvent); @@ -65,5 +66,6 @@ public interface IRepository : IEquatable event Action GitLogCacheUpdated; event Action GitLockCacheUpdated; event Action BranchCacheUpdated; + event Action RepositoryInfoCacheUpdated; } } \ No newline at end of file diff --git a/src/GitHub.Api/Git/Repository.cs b/src/GitHub.Api/Git/Repository.cs index 8b1eec65b..0ce2eeb30 100644 --- a/src/GitHub.Api/Git/Repository.cs +++ b/src/GitHub.Api/Git/Repository.cs @@ -18,6 +18,7 @@ class Repository : IEquatable, IRepository public event Action GitLogCacheUpdated; public event Action GitLockCacheUpdated; public event Action BranchCacheUpdated; + public event Action RepositoryInfoCacheUpdated; /// /// Initializes a new instance of the class. @@ -88,6 +89,10 @@ private void CacheContainer_OnCacheUpdated(CacheType cacheType, DateTimeOffset o case CacheType.GitUserCache: break; + case CacheType.RepositoryInfoCache: + FireRepositoryInfoCacheUpdated(offset); + break; + default: throw new ArgumentOutOfRangeException(nameof(cacheType), cacheType, null); } @@ -117,6 +122,12 @@ private void FireGitLocksCacheUpdated(DateTimeOffset dateTimeOffset) GitLockCacheUpdated?.Invoke(new CacheUpdateEvent { UpdatedTimeString = dateTimeOffset.ToString() }); } + private void FireRepositoryInfoCacheUpdated(DateTimeOffset dateTimeOffset) + { + Logger.Trace("RepositoryInfoCacheUpdated {0}", dateTimeOffset); + RepositoryInfoCacheUpdated?.Invoke(new CacheUpdateEvent { UpdatedTimeString = dateTimeOffset.ToString() }); + } + public void Initialize(IRepositoryManager initRepositoryManager) { Logger.Trace("Initialize"); @@ -138,8 +149,7 @@ public void Initialize(IRepositoryManager initRepositoryManager) UpdateGitStatus(); UpdateGitLog(); - new ActionTask(CancellationToken.None, UpdateLocks) - { Affinity = TaskAffinity.UI }.Start(); + new ActionTask(CancellationToken.None, UpdateLocks) { Affinity = TaskAffinity.UI }.Start(); } public ITask SetupRemote(string remote, string remoteUrl) @@ -196,15 +206,27 @@ public ITask ReleaseLock(string file, bool force) return repositoryManager.UnlockFile(file, force).Then(UpdateLocks); } + public void CheckRepositoryInfoCacheEvent(CacheUpdateEvent cacheUpdateEvent) + { + var managedCache = cacheContainer.RepositoryInfoCache; + var raiseEvent = ShouldRaiseCacheEvent(cacheUpdateEvent, managedCache); + + Logger.Trace("CheckRepositoryInfoCacheEvent Current:{0} Check:{1} Result:{2}", managedCache.LastUpdatedAt, + cacheUpdateEvent.UpdatedTimeString ?? "[NULL]", raiseEvent); + + if (raiseEvent) + { + FireBranchCacheUpdated(managedCache.LastUpdatedAt); + } + } + public void CheckBranchCacheEvent(CacheUpdateEvent cacheUpdateEvent) { var managedCache = cacheContainer.BranchCache; var raiseEvent = ShouldRaiseCacheEvent(cacheUpdateEvent, managedCache); - Logger.Trace("CheckBranchCacheEvent Current:{0} Check:{1} Result:{2}", - managedCache.LastUpdatedAt, - cacheUpdateEvent.UpdatedTimeString ?? "[NULL]", - raiseEvent); + Logger.Trace("CheckBranchCacheEvent Current:{0} Check:{1} Result:{2}", managedCache.LastUpdatedAt, + cacheUpdateEvent.UpdatedTimeString ?? "[NULL]", raiseEvent); if (raiseEvent) { @@ -217,10 +239,8 @@ public void CheckGitStatusCacheEvent(CacheUpdateEvent cacheUpdateEvent) var managedCache = cacheContainer.GitStatusCache; var raiseEvent = ShouldRaiseCacheEvent(cacheUpdateEvent, managedCache); - Logger.Trace("CheckGitStatusCacheEvent Current:{0} Check:{1} Result:{2}", - managedCache.LastUpdatedAt, - cacheUpdateEvent.UpdatedTimeString ?? "[NULL]", - raiseEvent); + Logger.Trace("CheckGitStatusCacheEvent Current:{0} Check:{1} Result:{2}", managedCache.LastUpdatedAt, + cacheUpdateEvent.UpdatedTimeString ?? "[NULL]", raiseEvent); if (raiseEvent) { @@ -233,10 +253,8 @@ public void CheckGitLogCacheEvent(CacheUpdateEvent cacheUpdateEvent) var managedCache = cacheContainer.GitLogCache; var raiseEvent = ShouldRaiseCacheEvent(cacheUpdateEvent, managedCache); - Logger.Trace("CheckGitLogCacheEvent Current:{0} Check:{1} Result:{2}", - managedCache.LastUpdatedAt, - cacheUpdateEvent.UpdatedTimeString ?? "[NULL]", - raiseEvent); + Logger.Trace("CheckGitLogCacheEvent Current:{0} Check:{1} Result:{2}", managedCache.LastUpdatedAt, + cacheUpdateEvent.UpdatedTimeString ?? "[NULL]", raiseEvent); if (raiseEvent) { @@ -249,10 +267,8 @@ public void CheckGitLocksCacheEvent(CacheUpdateEvent cacheUpdateEvent) var managedCache = cacheContainer.GitLocksCache; var raiseEvent = ShouldRaiseCacheEvent(cacheUpdateEvent, managedCache); - Logger.Trace("CheckGitLocksCacheEvent Current:{0} Check:{1} Result:{2}", - managedCache.LastUpdatedAt, - cacheUpdateEvent.UpdatedTimeString ?? "[NULL]", - raiseEvent); + Logger.Trace("CheckGitLocksCacheEvent Current:{0} Check:{1} Result:{2}", managedCache.LastUpdatedAt, + cacheUpdateEvent.UpdatedTimeString ?? "[NULL]", raiseEvent); if (raiseEvent) { @@ -288,6 +304,7 @@ public override bool Equals(object obj) { if (ReferenceEquals(this, obj)) return true; + var other = obj as Repository; return Equals(other); } @@ -301,8 +318,8 @@ public bool Equals(IRepository other) { if (ReferenceEquals(this, other)) return true; - return other != null && - object.Equals(LocalPath, other.LocalPath); + + return other != null && object.Equals(LocalPath, other.LocalPath); } private void RepositoryManager_OnCurrentRemoteUpdated(ConfigRemote? remote) @@ -313,7 +330,7 @@ private void RepositoryManager_OnCurrentRemoteUpdated(ConfigRemote? remote) CurrentConfigRemote = remote; CurrentRemote = GetGitRemote(remote.Value); UpdateRepositoryInfo(); - }) {Affinity = TaskAffinity.UI}.Start(); + }) { Affinity = TaskAffinity.UI }.Start(); } } @@ -346,17 +363,13 @@ private void RepositoryManager_OnCurrentBranchUpdated(ConfigBranch? branch) { if (!Nullable.Equals(CurrentConfigBranch, branch)) { - new ActionTask(CancellationToken.None, () => - { - var currentBranch = branch != null - ? (GitBranch?)GetLocalGitBranch(branch.Value) - : null; + new ActionTask(CancellationToken.None, () => { + var currentBranch = branch != null ? (GitBranch?)GetLocalGitBranch(branch.Value) : null; CurrentConfigBranch = branch; CurrentBranch = currentBranch; UpdateLocalBranches(); - }) - { Affinity = TaskAffinity.UI }.Start(); + }) { Affinity = TaskAffinity.UI }.Start(); } } @@ -369,41 +382,36 @@ private void RepositoryManager_OnLocalBranchUpdated(string name) } } - private void RepositoryManager_OnRemoteBranchListUpdated(IDictionary remotes, IDictionary> branches) + private void RepositoryManager_OnRemoteBranchListUpdated(IDictionary remotes, + IDictionary> branches) { - new ActionTask(CancellationToken.None, () => - { + new ActionTask(CancellationToken.None, () => { cacheContainer.BranchCache.SetRemotes(remotes, branches); UpdateRemoteAndRemoteBranches(); - }) - { Affinity = TaskAffinity.UI }.Start(); + }) { Affinity = TaskAffinity.UI }.Start(); } private void UpdateRemoteAndRemoteBranches() { cacheContainer.BranchCache.Remotes = - cacheContainer.BranchCache.ConfigRemotes.Values - .Select(GetGitRemote) - .ToArray(); - - cacheContainer.BranchCache.RemoteBranches = - cacheContainer.BranchCache.RemoteConfigBranches.Values - .SelectMany(x => x.Values).Select(GetRemoteGitBranch) - .ToArray(); + cacheContainer.BranchCache.ConfigRemotes.Values.Select(GetGitRemote).ToArray(); + + cacheContainer.BranchCache.RemoteBranches = cacheContainer + .BranchCache.RemoteConfigBranches.Values.SelectMany(x => x.Values).Select(GetRemoteGitBranch).ToArray(); } private void RepositoryManager_OnLocalBranchListUpdated(IDictionary branches) { new ActionTask(CancellationToken.None, () => { - cacheContainer.BranchCache.SetLocals(branches); - UpdateLocalBranches(); - }) - { Affinity = TaskAffinity.UI }.Start(); + cacheContainer.BranchCache.SetLocals(branches); + UpdateLocalBranches(); + }) { Affinity = TaskAffinity.UI }.Start(); } private void UpdateLocalBranches() { - cacheContainer.BranchCache.LocalBranches = cacheContainer.BranchCache.LocalConfigBranches.Values.Select(GetLocalGitBranch).ToArray(); + cacheContainer.BranchCache.LocalBranches = cacheContainer + .BranchCache.LocalConfigBranches.Values.Select(GetLocalGitBranch).ToArray(); } private void UpdateRepositoryInfo() @@ -424,42 +432,34 @@ private void UpdateRepositoryInfo() private void RepositoryManager_OnLocalBranchRemoved(string name) { - new ActionTask(CancellationToken.None, () => - { + new ActionTask(CancellationToken.None, () => { cacheContainer.BranchCache.RemoveLocalBranch(name); UpdateLocalBranches(); - }) - { Affinity = TaskAffinity.UI }.Start(); + }) { Affinity = TaskAffinity.UI }.Start(); } private void RepositoryManager_OnLocalBranchAdded(string name) { - new ActionTask(CancellationToken.None, () => - { + new ActionTask(CancellationToken.None, () => { cacheContainer.BranchCache.AddLocalBranch(name); UpdateLocalBranches(); - }) - { Affinity = TaskAffinity.UI }.Start(); + }) { Affinity = TaskAffinity.UI }.Start(); } private void RepositoryManager_OnRemoteBranchAdded(string remote, string name) { - new ActionTask(CancellationToken.None, () => - { + new ActionTask(CancellationToken.None, () => { cacheContainer.BranchCache.AddRemoteBranch(remote, name); UpdateRemoteAndRemoteBranches(); - }) - { Affinity = TaskAffinity.UI }.Start(); + }) { Affinity = TaskAffinity.UI }.Start(); } private void RepositoryManager_OnRemoteBranchRemoved(string remote, string name) { - new ActionTask(CancellationToken.None, () => - { + new ActionTask(CancellationToken.None, () => { cacheContainer.BranchCache.RemoveRemoteBranch(remote, name); UpdateRemoteAndRemoteBranches(); - }) - { Affinity = TaskAffinity.UI }.Start(); + }) { Affinity = TaskAffinity.UI }.Start(); } private GitBranch GetLocalGitBranch(ConfigBranch x) @@ -468,14 +468,14 @@ private GitBranch GetLocalGitBranch(ConfigBranch x) var trackingName = x.IsTracking ? x.Remote.Value.Name + "/" + name : "[None]"; var isActive = name == CurrentBranchName; - return new GitBranch {Name= name, Tracking = trackingName, IsActive = isActive}; + return new GitBranch { Name = name, Tracking = trackingName, IsActive = isActive }; } private static GitBranch GetRemoteGitBranch(ConfigBranch x) { var name = x.Remote.Value.Name + "/" + x.Name; - return new GitBranch {Name= name}; + return new GitBranch { Name = name }; } private static GitRemote GetGitRemote(ConfigRemote configRemote) @@ -509,16 +509,16 @@ public GitStatus CurrentStatus public GitBranch? CurrentBranch { - get { return cacheContainer.BranchCache.CurentGitBranch; } - set { cacheContainer.BranchCache.CurentGitBranch = value; } + get { return cacheContainer.RepositoryInfoCache.CurentGitBranch; } + set { cacheContainer.RepositoryInfoCache.CurentGitBranch = value; } } public string CurrentBranchName => CurrentConfigBranch?.Name; public GitRemote? CurrentRemote { - get { return cacheContainer.BranchCache.CurrentGitRemote; } - set { cacheContainer.BranchCache.CurrentGitRemote = value; } + get { return cacheContainer.RepositoryInfoCache.CurrentGitRemote; } + set { cacheContainer.RepositoryInfoCache.CurrentGitRemote = value; } } public List CurrentLog @@ -541,18 +541,14 @@ public List CurrentLocks public string Owner => CloneUrl?.Owner ?? null; - public bool IsGitHub { get { return HostAddress.IsGitHubDotCom(CloneUrl); } } + public bool IsGitHub + { + get { return HostAddress.IsGitHubDotCom(CloneUrl); } + } - internal string DebuggerDisplay => String.Format( - CultureInfo.InvariantCulture, - "{0} Owner: {1} Name: {2} CloneUrl: {3} LocalPath: {4} Branch: {5} Remote: {6}", - GetHashCode(), - Owner, - Name, - CloneUrl, - LocalPath, - CurrentBranch, - CurrentRemote); + internal string DebuggerDisplay => String.Format(CultureInfo.InvariantCulture, + "{0} Owner: {1} Name: {2} CloneUrl: {3} LocalPath: {4} Branch: {5} Remote: {6}", GetHashCode(), Owner, Name, + CloneUrl, LocalPath, CurrentBranch, CurrentRemote); public IUser User { get; set; } @@ -582,4 +578,4 @@ public struct CacheUpdateEvent { public string UpdatedTimeString; } -} \ No newline at end of file +} diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs index 82abc35d7..ae1f2dbc2 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs @@ -412,47 +412,34 @@ public ConfigRemoteDictionary(IDictionary dictionary) } } - [Location("cache/branches.yaml", LocationAttribute.Location.LibraryFolder)] - sealed class BranchCache : ManagedCacheBase, IBranchCache + [Location("cache/repoinfo.yaml", LocationAttribute.Location.LibraryFolder)] + sealed class RepositoryInfoCache : ManagedCacheBase, IRepositoryInfoCache { - public static readonly ConfigBranch DefaultConfigBranch = new ConfigBranch(); - public static readonly ConfigRemote DefaultConfigRemote = new ConfigRemote(); public static readonly GitRemote DefaultGitRemote = new GitRemote(); public static readonly GitBranch DefaultGitBranch = new GitBranch(); [SerializeField] private string lastUpdatedAtString = DateTimeOffset.MinValue.ToString(); [SerializeField] private string lastVerifiedAtString = DateTimeOffset.MinValue.ToString(); - - [SerializeField] private GitBranch[] localBranches = new GitBranch[0]; - [SerializeField] private GitBranch[] remoteBranches = new GitBranch[0]; - [SerializeField] private GitRemote[] remotes = new GitRemote[0]; - - [SerializeField] private LocalConfigBranchDictionary localConfigBranches = new LocalConfigBranchDictionary(); - [SerializeField] private RemoteConfigBranchDictionary remoteConfigBranches = new RemoteConfigBranchDictionary(); - [SerializeField] private ConfigRemoteDictionary configRemotes = new ConfigRemoteDictionary(); - - [SerializeField] private ConfigBranch gitConfigBranch; - [SerializeField] private ConfigRemote gitConfigRemote; [SerializeField] private GitRemote gitRemote; [SerializeField] private GitBranch gitBranch; - public ConfigRemote? CurrentConfigRemote + public GitRemote? CurrentGitRemote { get { ValidateData(); - return gitConfigRemote.Equals(DefaultConfigRemote) ? (ConfigRemote?)null : gitConfigRemote; + return gitRemote.Equals(DefaultGitRemote) ? (GitRemote?)null : gitRemote; } set { var now = DateTimeOffset.Now; var isUpdated = false; - Logger.Trace("Updating: {0} gitConfigRemote:{1}", now, value); + Logger.Trace("Updating: {0} gitRemote:{1}", now, value); - if (!Nullable.Equals(gitConfigRemote, value)) + if (!Nullable.Equals(gitRemote, value)) { - gitConfigRemote = value ?? DefaultConfigRemote; + gitRemote = value ?? DefaultGitRemote; isUpdated = true; } @@ -460,23 +447,23 @@ public ConfigRemote? CurrentConfigRemote } } - public ConfigBranch? CurentConfigBranch + public GitBranch? CurentGitBranch { get { ValidateData(); - return gitConfigBranch.Equals(DefaultConfigBranch) ? (ConfigBranch?)null : gitConfigBranch; + return gitBranch.Equals(DefaultGitBranch) ? (GitBranch?)null : gitBranch; } set { var now = DateTimeOffset.Now; var isUpdated = false; - Logger.Trace("Updating: {0} gitConfigBranch:{1}", now, value); + Logger.Trace("Updating: {0} gitBranch:{1}", now, value); - if (!Nullable.Equals(gitConfigBranch, value)) + if (!Nullable.Equals(gitBranch, value)) { - gitConfigBranch = value ?? DefaultConfigBranch; + gitBranch = value ?? DefaultGitBranch; isUpdated = true; } @@ -484,23 +471,56 @@ public ConfigBranch? CurentConfigBranch } } - public GitRemote? CurrentGitRemote + public override string LastUpdatedAtString + { + get { return lastUpdatedAtString; } + protected set { lastUpdatedAtString = value; } + } + + public override string LastVerifiedAtString + { + get { return lastVerifiedAtString; } + protected set { lastVerifiedAtString = value; } + } + } + + [Location("cache/branches.yaml", LocationAttribute.Location.LibraryFolder)] + sealed class BranchCache : ManagedCacheBase, IBranchCache + { + public static readonly ConfigBranch DefaultConfigBranch = new ConfigBranch(); + public static readonly ConfigRemote DefaultConfigRemote = new ConfigRemote(); + + [SerializeField] private string lastUpdatedAtString = DateTimeOffset.MinValue.ToString(); + [SerializeField] private string lastVerifiedAtString = DateTimeOffset.MinValue.ToString(); + + [SerializeField] private ConfigBranch gitConfigBranch; + [SerializeField] private ConfigRemote gitConfigRemote; + + [SerializeField] private GitBranch[] localBranches = new GitBranch[0]; + [SerializeField] private GitBranch[] remoteBranches = new GitBranch[0]; + [SerializeField] private GitRemote[] remotes = new GitRemote[0]; + + [SerializeField] private LocalConfigBranchDictionary localConfigBranches = new LocalConfigBranchDictionary(); + [SerializeField] private RemoteConfigBranchDictionary remoteConfigBranches = new RemoteConfigBranchDictionary(); + [SerializeField] private ConfigRemoteDictionary configRemotes = new ConfigRemoteDictionary(); + + public ConfigRemote? CurrentConfigRemote { get { ValidateData(); - return gitRemote.Equals(DefaultGitRemote) ? (GitRemote?)null : gitRemote; + return gitConfigRemote.Equals(DefaultConfigRemote) ? (ConfigRemote?)null : gitConfigRemote; } set { var now = DateTimeOffset.Now; var isUpdated = false; - Logger.Trace("Updating: {0} gitRemote:{1}", now, value); + Logger.Trace("Updating: {0} gitConfigRemote:{1}", now, value); - if (!Nullable.Equals(gitRemote, value)) + if (!Nullable.Equals(gitConfigRemote, value)) { - gitRemote = value ?? DefaultGitRemote; + gitConfigRemote = value ?? DefaultConfigRemote; isUpdated = true; } @@ -508,23 +528,23 @@ public GitRemote? CurrentGitRemote } } - public GitBranch? CurentGitBranch + public ConfigBranch? CurentConfigBranch { get { ValidateData(); - return gitBranch.Equals(DefaultGitBranch) ? (GitBranch?)null : gitBranch; + return gitConfigBranch.Equals(DefaultConfigBranch) ? (ConfigBranch?)null : gitConfigBranch; } set { var now = DateTimeOffset.Now; var isUpdated = false; - Logger.Trace("Updating: {0} gitBranch:{1}", now, value); + Logger.Trace("Updating: {0} gitConfigBranch:{1}", now, value); - if (!Nullable.Equals(gitBranch, value)) + if (!Nullable.Equals(gitConfigBranch, value)) { - gitBranch = value ?? DefaultGitBranch; + gitConfigBranch = value ?? DefaultConfigBranch; isUpdated = true; } @@ -532,8 +552,9 @@ public GitBranch? CurentGitBranch } } - public GitBranch[] LocalBranches { - get { return localBranches; } + public GitBranch[] LocalBranches + { + get { return localBranches; } set { var now = DateTimeOffset.Now; diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/CacheContainer.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/CacheContainer.cs index ad9d4e6a1..063889808 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/CacheContainer.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/CacheContainer.cs @@ -6,6 +6,8 @@ public class CacheContainer : ICacheContainer { private static ILogging Logger = Logging.GetLogger(); + private IRepositoryInfoCache repositoryInfoCache; + private IBranchCache branchCache; private IGitLocksCache gitLocksCache; @@ -72,6 +74,20 @@ public void InvalidateAll() GitUserCache.InvalidateData(); } + public IRepositoryInfoCache RepositoryInfoCache + { + get + { + if (repositoryInfoCache == null) + { + repositoryInfoCache = Unity.RepositoryInfoCache.Instance; + repositoryInfoCache.CacheInvalidated += () => OnCacheInvalidated(CacheType.RepositoryInfoCache); + repositoryInfoCache.CacheUpdated += datetime => OnCacheUpdated(CacheType.RepositoryInfoCache, datetime); + } + return repositoryInfoCache; + } + } + public IBranchCache BranchCache { get diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs index 8db054054..3350be6f9 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs @@ -37,8 +37,9 @@ class Window : BaseWindow [SerializeField] private GUIContent repoBranchContent; [SerializeField] private GUIContent repoUrlContent; - [SerializeField] private CacheUpdateEvent branchUpdateEvent; - [NonSerialized] private bool branchCacheHasUpdate; + [SerializeField] private CacheUpdateEvent repositoryInfoUpdateEvent; + [NonSerialized] private bool repositoryInfoCacheHasUpdate; + [NonSerialized] private bool hasRunMaybeUpdateDataWithRepository; [MenuItem(LaunchMenu)] @@ -97,7 +98,7 @@ public override void OnEnable() titleContent = new GUIContent(Title, Styles.SmallLogo); if (Repository != null) - Repository.CheckBranchCacheEvent(branchUpdateEvent); + Repository.CheckRepositoryInfoCacheEvent(repositoryInfoUpdateEvent); if (ActiveView != null) ActiveView.OnEnable(); @@ -194,7 +195,7 @@ private void MaybeUpdateData() if (Repository != null) { - if(!hasRunMaybeUpdateDataWithRepository || branchCacheHasUpdate) + if(!hasRunMaybeUpdateDataWithRepository || repositoryInfoCacheHasUpdate) { hasRunMaybeUpdateDataWithRepository = true; @@ -269,14 +270,14 @@ private void AttachHandlers(IRepository repository) { if (repository == null) return; - repository.BranchCacheUpdated += Repository_BranchCacheUpdated; + repository.RepositoryInfoCacheUpdated += Repository_RepositoryInfoCacheUpdated; } - private void Repository_BranchCacheUpdated(CacheUpdateEvent cacheUpdateEvent) + private void Repository_RepositoryInfoCacheUpdated(CacheUpdateEvent cacheUpdateEvent) { new ActionTask(TaskManager.Token, () => { - branchUpdateEvent = cacheUpdateEvent; - branchCacheHasUpdate = true; + repositoryInfoUpdateEvent = cacheUpdateEvent; + repositoryInfoCacheHasUpdate = true; Redraw(); }) { Affinity = TaskAffinity.UI }.Start(); } @@ -286,7 +287,7 @@ private void DetachHandlers(IRepository repository) if (repository == null) return; - repository.BranchCacheUpdated -= Repository_BranchCacheUpdated; + repository.RepositoryInfoCacheUpdated -= Repository_RepositoryInfoCacheUpdated; } private void DoHeaderGUI() From f726c7f4cbf2b5166e6247d09d461977067294de Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Wed, 1 Nov 2017 12:54:53 -0400 Subject: [PATCH 169/241] No need to use the UriString when the string is available --- .../Assets/Editor/GitHub.Unity/UI/Window.cs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs index 3350be6f9..4e3496405 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs @@ -187,7 +187,6 @@ public override void Update() private void MaybeUpdateData() { - string updatedRepoBranch = null; string updatedRepoRemote = null; string updatedRepoUrl = DefaultRepoUrl; @@ -200,15 +199,16 @@ private void MaybeUpdateData() hasRunMaybeUpdateDataWithRepository = true; var repositoryCurrentBranch = Repository.CurrentBranch; - updatedRepoBranch = repositoryCurrentBranch.HasValue ? repositoryCurrentBranch.Value.Name : null; - - var repositoryCloneUrl = Repository.CloneUrl; - updatedRepoUrl = repositoryCloneUrl != null ? repositoryCloneUrl.ToString() : DefaultRepoUrl; + var updatedRepoBranch = repositoryCurrentBranch.HasValue ? repositoryCurrentBranch.Value.Name : null; var repositoryCurrentRemote = Repository.CurrentRemote; if (repositoryCurrentRemote.HasValue) { updatedRepoRemote = repositoryCurrentRemote.Value.Name; + if (repositoryCurrentRemote.Value.Url != null) + { + updatedRepoUrl = repositoryCurrentRemote.Value.Url; + } } if (repoRemote != updatedRepoRemote) From 52491d61fdf90ec09158573e878b88cfbacc81c6 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Wed, 1 Nov 2017 13:09:16 -0400 Subject: [PATCH 170/241] Populating repository name and clone uri from cache --- src/GitHub.Api/Git/Repository.cs | 46 +++++++++++++++---- src/GitHub.Api/Platform/DefaultEnvironment.cs | 2 +- .../BaseGitEnvironmentTest.cs | 2 +- src/tests/UnitTests/Git/RepositoryTests.cs | 2 +- 4 files changed, 41 insertions(+), 11 deletions(-) diff --git a/src/GitHub.Api/Git/Repository.cs b/src/GitHub.Api/Git/Repository.cs index 0ce2eeb30..ca92f0c7d 100644 --- a/src/GitHub.Api/Git/Repository.cs +++ b/src/GitHub.Api/Git/Repository.cs @@ -13,6 +13,8 @@ class Repository : IEquatable, IRepository { private IRepositoryManager repositoryManager; private ICacheContainer cacheContainer; + private UriString cloneUrl; + private string name; public event Action GitStatusCacheUpdated; public event Action GitLogCacheUpdated; @@ -23,22 +25,17 @@ class Repository : IEquatable, IRepository /// /// Initializes a new instance of the class. /// - /// The repository name. /// /// - public Repository(string name, NPath localPath, ICacheContainer container) + public Repository(NPath localPath, ICacheContainer container) { - Guard.ArgumentNotNullOrWhiteSpace(name, nameof(name)); Guard.ArgumentNotNull(localPath, nameof(localPath)); - Name = name; LocalPath = localPath; User = new User(); cacheContainer = container; - cacheContainer.CacheInvalidated += CacheContainer_OnCacheInvalidated; - cacheContainer.CacheUpdated += CacheContainer_OnCacheUpdated; } @@ -533,9 +530,42 @@ public List CurrentLocks set { cacheContainer.GitLocksCache.GitLocks = value; } } - public UriString CloneUrl { get; private set; } + public UriString CloneUrl + { + get + { + if (cloneUrl == null) + { + var currentRemote = CurrentRemote; + if (currentRemote.HasValue && currentRemote.Value.Url != null) + { + cloneUrl = new UriString(currentRemote.Value.Url); + } + } + return cloneUrl; + } + private set + { + cloneUrl = value; + } + } - public string Name { get; private set; } + public string Name + { + get + { + if (name == null) + { + var url = CloneUrl; + if (url != null) + { + name = url.RepositoryName; + } + } + return name; + } + private set { name = value; } + } public NPath LocalPath { get; private set; } diff --git a/src/GitHub.Api/Platform/DefaultEnvironment.cs b/src/GitHub.Api/Platform/DefaultEnvironment.cs index 30be45448..5077ad175 100644 --- a/src/GitHub.Api/Platform/DefaultEnvironment.cs +++ b/src/GitHub.Api/Platform/DefaultEnvironment.cs @@ -79,7 +79,7 @@ public void InitializeRepository(ICacheContainer cacheContainer, NPath expectedR { Logger.Trace("Determined expectedRepositoryPath:{0}", expectedRepositoryPath); RepositoryPath = expectedRepositoryPath; - Repository = new Repository(RepositoryPath.FileName, RepositoryPath, cacheContainer); + Repository = new Repository(RepositoryPath, cacheContainer); } } diff --git a/src/tests/IntegrationTests/BaseGitEnvironmentTest.cs b/src/tests/IntegrationTests/BaseGitEnvironmentTest.cs index 96151f82d..ee3b98dc4 100644 --- a/src/tests/IntegrationTests/BaseGitEnvironmentTest.cs +++ b/src/tests/IntegrationTests/BaseGitEnvironmentTest.cs @@ -33,7 +33,7 @@ protected async Task Initialize(NPath repoPath, NPath environmentP //TODO: Mock CacheContainer ICacheContainer cacheContainer = null; - Environment.Repository = new Repository("TestRepo", repoPath, cacheContainer); + Environment.Repository = new Repository(repoPath, cacheContainer); Environment.Repository.Initialize(RepositoryManager); RepositoryManager.Start(); diff --git a/src/tests/UnitTests/Git/RepositoryTests.cs b/src/tests/UnitTests/Git/RepositoryTests.cs index 95e505c19..97577c036 100644 --- a/src/tests/UnitTests/Git/RepositoryTests.cs +++ b/src/tests/UnitTests/Git/RepositoryTests.cs @@ -29,7 +29,7 @@ private static Repository LoadRepository() //TODO: Mock CacheContainer ICacheContainer cacheContainer = null; - return new Repository("TestRepo", @"C:\Repo".ToNPath(), cacheContainer); + return new Repository(@"C:\Repo".ToNPath(), cacheContainer); } private RepositoryEvents repositoryEvents; From dfb571a6e7d8a62b51ef4b11a995589ff526d7ae Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Wed, 1 Nov 2017 13:28:04 -0400 Subject: [PATCH 171/241] Removing RepositoryTests --- src/tests/UnitTests/Git/RepositoryTests.cs | 94 ---------------------- src/tests/UnitTests/UnitTests.csproj | 1 - 2 files changed, 95 deletions(-) delete mode 100644 src/tests/UnitTests/Git/RepositoryTests.cs diff --git a/src/tests/UnitTests/Git/RepositoryTests.cs b/src/tests/UnitTests/Git/RepositoryTests.cs deleted file mode 100644 index 97577c036..000000000 --- a/src/tests/UnitTests/Git/RepositoryTests.cs +++ /dev/null @@ -1,94 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using FluentAssertions; -using GitHub.Unity; -using NCrunch.Framework; -using NSubstitute; -using NUnit.Framework; -using TestUtils; -using TestUtils.Events; - -namespace UnitTests -{ - [TestFixture, Isolated, Ignore] - public class RepositoryTests - { - private static readonly SubstituteFactory SubstituteFactory = new SubstituteFactory(); - - private static Repository LoadRepository() - { - var fileSystem = SubstituteFactory.CreateFileSystem( - new CreateFileSystemOptions - { - - }); - - NPath.FileSystem = fileSystem; - - //TODO: Mock CacheContainer - ICacheContainer cacheContainer = null; - return new Repository(@"C:\Repo".ToNPath(), cacheContainer); - } - - private RepositoryEvents repositoryEvents; - private TimeSpan repositoryEventsTimeout; - - [SetUp] - public void OnSetup() - { - repositoryEvents = new RepositoryEvents(); - repositoryEventsTimeout = TimeSpan.FromSeconds(0.5); - } - - [Test] - public void Repository() - { - var repository = LoadRepository(); - var repositoryManager = Substitute.For(); - - var repositoryListener = Substitute.For(); - repositoryListener.AttachListener(repository, repositoryEvents); - - var origin = new ConfigRemote - { - Name = "origin", - Url = "https://github.com/someUser/someRepo.git" - }; - - var remotes = new[] { origin }; - - var remoteDictionary = remotes.ToDictionary(remote => remote.Name); - - var masterOriginBranch = new ConfigBranch { Name = "master", Remote = origin }; - - var branches = new[] { - masterOriginBranch, - new ConfigBranch { Name = "features/feature-1", Remote = origin } - }; - - var branchDictionary = branches.ToDictionary(branch => branch.Name); - - var remoteBranches = new[] { - new ConfigBranch { Name = "master", Remote = origin }, - new ConfigBranch { Name = "features/feature-1", Remote = origin }, - new ConfigBranch { Name = "features/feature-2", Remote = origin } - }; - - var remoteBranchDictionary = remoteBranches - .GroupBy(branch => branch.Remote.Value.Name) - .ToDictionary(grouping => grouping.Key, - grouping => grouping.ToDictionary(branch => branch.Name)); - - repository.Initialize(repositoryManager); - - repositoryManager.OnLocalBranchListUpdated += Raise.Event>>(branchDictionary); - - repositoryManager.OnRemoteBranchListUpdated += Raise.Event, IDictionary>>>(remoteDictionary, remoteBranchDictionary); - - repositoryManager.OnCurrentBranchUpdated += Raise.Event>(masterOriginBranch); - repositoryManager.OnCurrentRemoteUpdated += Raise.Event>(origin); - } - } -} diff --git a/src/tests/UnitTests/UnitTests.csproj b/src/tests/UnitTests/UnitTests.csproj index bf298220e..f5b4b5ed4 100644 --- a/src/tests/UnitTests/UnitTests.csproj +++ b/src/tests/UnitTests/UnitTests.csproj @@ -72,7 +72,6 @@ - From 95613fe97a6ee0fa9dcd1e23cd41cf9e16b33fe6 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Wed, 1 Nov 2017 14:33:42 -0400 Subject: [PATCH 172/241] Fixing update bug --- src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs index 4e3496405..aa79ba22e 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs @@ -205,7 +205,7 @@ private void MaybeUpdateData() if (repositoryCurrentRemote.HasValue) { updatedRepoRemote = repositoryCurrentRemote.Value.Name; - if (repositoryCurrentRemote.Value.Url != null) + if (!string.IsNullOrEmpty(repositoryCurrentRemote.Value.Url)) { updatedRepoUrl = repositoryCurrentRemote.Value.Url; } From 8921bd886d588ac68df50b07ef85e8fbecd56312 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Wed, 1 Nov 2017 14:45:40 -0400 Subject: [PATCH 173/241] Fixes after merge --- .../Assets/Editor/GitHub.Unity/UI/BranchesView.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs index 94f047b4a..b5a670d41 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs @@ -156,7 +156,7 @@ private void Render() } GUILayout.EndHorizontal(); - GUILayout.Label(FavoritesTitle); + var rect = GUILayoutUtility.GetLastRect(); OnTreeGUI(new Rect(0f, rect.height + Styles.CommitAreaPadding, Position.width, Position.height - rect.height + Styles.CommitAreaPadding)); } GUILayout.EndScrollView(); From 733df51df402b8685df8f742ed6600064c1187dc Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Wed, 1 Nov 2017 14:56:25 -0400 Subject: [PATCH 174/241] More fixes after the merge --- .../Editor/GitHub.Unity/UI/BranchesView.cs | 24 ++++++------------- 1 file changed, 7 insertions(+), 17 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs index ee5d08262..6f0baa8f8 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs @@ -49,8 +49,8 @@ class BranchesView : Subview [SerializeField] private CacheUpdateEvent branchUpdateEvent; [NonSerialized] private bool branchCacheHasUpdate; - [SerializeField] private GitBranch[] localBranches; - [SerializeField] private GitBranch[] remoteBranches; + [SerializeField] private List localBranches; + [SerializeField] private List remoteBranches; public override void InitializeView(IView parent) { @@ -96,21 +96,14 @@ private void MaybeUpdateData() { branchCacheHasUpdate = false; - localBranches = Repository.LocalBranches.ToArray(); - remoteBranches = Repository.RemoteBranches.ToArray(); + localBranches = Repository.LocalBranches.ToList(); + remoteBranches = Repository.RemoteBranches.ToList(); BuildTree(localBranches, remoteBranches); } disableDelete = treeLocals.SelectedNode == null || treeLocals.SelectedNode.IsFolder || treeLocals.SelectedNode.IsActive; - - } - - public override void Refresh() - { - base.Refresh(); - RefreshBranchList(); } public override void OnGUI() @@ -168,8 +161,8 @@ private void BuildTree(List localBranches, List remoteBran treeRemotes.RootFolderIcon = Styles.RootFolderIcon; treeRemotes.FolderIcon = Styles.FolderIcon; - treeLocals.Load(localBranches.Cast(), LocalTitle); - treeRemotes.Load(remoteBranches.Cast(), RemoteTitle); + treeLocals.Load(localBranches, LocalTitle); + treeRemotes.Load(remoteBranches, RemoteTitle); Redraw(); } @@ -287,9 +280,6 @@ private void OnButtonBarGUI() private void OnTreeGUI(Rect rect) { - if (!treeLocals.IsInitialized) - RefreshBranchList(); - if (treeLocals.FolderStyle == null) { treeLocals.FolderStyle = Styles.Foldout; @@ -501,7 +491,7 @@ private Hashtable Folders } } - public void Load(IEnumerable data, string title) + public void Load(IEnumerable data, string title) { foldersKeys.Clear(); Folders.Clear(); From 52f315c52e5cd353b9286013fb59c313114d6216 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Wed, 1 Nov 2017 18:01:23 -0400 Subject: [PATCH 175/241] Adding an optimization to usages of cache manager --- .../Editor/GitHub.Unity/UI/BranchesView.cs | 6 +++++- .../Editor/GitHub.Unity/UI/ChangesView.cs | 12 ++++++++++-- .../Editor/GitHub.Unity/UI/HistoryView.cs | 18 +++++++++++++++--- .../GitHub.Unity/UI/ProjectWindowInterface.cs | 14 +++++++++++--- .../Editor/GitHub.Unity/UI/SettingsView.cs | 12 ++++++++++-- .../Assets/Editor/GitHub.Unity/UI/Window.cs | 15 ++++++++++----- 6 files changed, 61 insertions(+), 16 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs index 6c161b413..e05d61b62 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs @@ -62,12 +62,16 @@ public override void InitializeView(IView parent) private void Repository_BranchCacheUpdated(CacheUpdateEvent cacheUpdateEvent) { - new ActionTask(TaskManager.Token, () => { + if (!branchUpdateEvent.Equals(cacheUpdateEvent)) + { + new ActionTask(TaskManager.Token, () => + { branchUpdateEvent = cacheUpdateEvent; branchCacheHasUpdate = true; Redraw(); }) { Affinity = TaskAffinity.UI }.Start(); + } } public override void OnEnable() diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ChangesView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ChangesView.cs index dc1837fbd..3f9b2f7f2 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ChangesView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ChangesView.cs @@ -39,22 +39,30 @@ public override void InitializeView(IView parent) private void Repository_GitStatusCacheUpdated(CacheUpdateEvent cacheUpdateEvent) { - new ActionTask(TaskManager.Token, () => { + if (!gitStatusUpdateEvent.Equals(cacheUpdateEvent)) + { + new ActionTask(TaskManager.Token, () => + { gitStatusUpdateEvent = cacheUpdateEvent; gitStatusCacheHasUpdate = true; Redraw(); }) { Affinity = TaskAffinity.UI }.Start(); + } } private void Repository_BranchCacheUpdated(CacheUpdateEvent cacheUpdateEvent) { - new ActionTask(TaskManager.Token, () => { + if (!branchUpdateEvent.Equals(cacheUpdateEvent)) + { + new ActionTask(TaskManager.Token, () => + { branchUpdateEvent = cacheUpdateEvent; branchCacheHasUpdate = true; Redraw(); }) { Affinity = TaskAffinity.UI }.Start(); + } } private void AttachHandlers(IRepository repository) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/HistoryView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/HistoryView.cs index 3f92f40b7..727cbdfb0 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/HistoryView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/HistoryView.cs @@ -102,32 +102,44 @@ public override void OnGUI() private void Repository_GitStatusCacheUpdated(CacheUpdateEvent cacheUpdateEvent) { - new ActionTask(TaskManager.Token, () => { + if (!gitStatusUpdateEvent.Equals(cacheUpdateEvent)) + { + new ActionTask(TaskManager.Token, () => + { gitStatusUpdateEvent = cacheUpdateEvent; gitStatusCacheHasUpdate = true; Redraw(); }) { Affinity = TaskAffinity.UI }.Start(); + } } private void Repository_GitLogCacheUpdated(CacheUpdateEvent cacheUpdateEvent) { - new ActionTask(TaskManager.Token, () => { + if (!gitLogCacheUpdateEvent.Equals(cacheUpdateEvent)) + { + new ActionTask(TaskManager.Token, () => + { gitLogCacheUpdateEvent = cacheUpdateEvent; gitLogCacheHasUpdate = true; Redraw(); }) { Affinity = TaskAffinity.UI }.Start(); + } } private void Repository_BranchCacheUpdated(CacheUpdateEvent cacheUpdateEvent) { - new ActionTask(TaskManager.Token, () => { + if (!branchUpdateEvent.Equals(cacheUpdateEvent)) + { + new ActionTask(TaskManager.Token, () => + { branchUpdateEvent = cacheUpdateEvent; branchCacheHasUpdate = true; Redraw(); }) { Affinity = TaskAffinity.UI }.Start(); + } } private void AttachHandlers(IRepository repository) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ProjectWindowInterface.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ProjectWindowInterface.cs index 4f5aec52c..e02fd6eb3 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ProjectWindowInterface.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ProjectWindowInterface.cs @@ -45,20 +45,28 @@ public static void Initialize(IRepository repo) private static void Repository_GitStatusCacheUpdated(CacheUpdateEvent cacheUpdateEvent) { - new ActionTask(CancellationToken.None, () => { + if (!gitStatusUpdateEvent.Equals(cacheUpdateEvent)) + { + new ActionTask(CancellationToken.None, () => + { gitStatusUpdateEvent = cacheUpdateEvent; OnStatusUpdate(repository.CurrentStatus); }) { Affinity = TaskAffinity.UI }.Start(); + } } private static void Repository_GitLockCacheUpdated(CacheUpdateEvent cacheUpdateEvent) { - new ActionTask(CancellationToken.None, () => { - gitLocksUpdateEvent = cacheUpdateEvent; + if (!gitStatusUpdateEvent.Equals(cacheUpdateEvent)) + { + new ActionTask(CancellationToken.None, () => + { + gitStatusUpdateEvent = cacheUpdateEvent; OnLocksUpdate(repository.CurrentLocks); }) { Affinity = TaskAffinity.UI }.Start(); + } } [MenuItem("Assets/Request Lock", true)] diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/SettingsView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/SettingsView.cs index e3a091918..74befadb1 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/SettingsView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/SettingsView.cs @@ -109,22 +109,30 @@ private void AttachHandlers(IRepository repository) private void Repository_GitLockCacheUpdated(CacheUpdateEvent cacheUpdateEvent) { - new ActionTask(TaskManager.Token, () => { + if (!gitLocksUpdateEvent.Equals(cacheUpdateEvent)) + { + new ActionTask(TaskManager.Token, () => + { gitLocksUpdateEvent = cacheUpdateEvent; gitLocksCacheHasUpdate = true; Redraw(); }) { Affinity = TaskAffinity.UI }.Start(); + } } private void Repository_BranchCacheUpdated(CacheUpdateEvent cacheUpdateEvent) { - new ActionTask(TaskManager.Token, () => { + if (!branchUpdateEvent.Equals(cacheUpdateEvent)) + { + new ActionTask(TaskManager.Token, () => + { branchUpdateEvent = cacheUpdateEvent; branchCacheHasUpdate = true; Redraw(); }) { Affinity = TaskAffinity.UI }.Start(); + } } private void DetachHandlers(IRepository repository) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs index aa79ba22e..f47f60e29 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs @@ -275,11 +275,16 @@ private void AttachHandlers(IRepository repository) private void Repository_RepositoryInfoCacheUpdated(CacheUpdateEvent cacheUpdateEvent) { - new ActionTask(TaskManager.Token, () => { - repositoryInfoUpdateEvent = cacheUpdateEvent; - repositoryInfoCacheHasUpdate = true; - Redraw(); - }) { Affinity = TaskAffinity.UI }.Start(); + if (!repositoryInfoUpdateEvent.Equals(cacheUpdateEvent)) + { + new ActionTask(TaskManager.Token, () => + { + repositoryInfoUpdateEvent = cacheUpdateEvent; + repositoryInfoCacheHasUpdate = true; + Redraw(); + }) + { Affinity = TaskAffinity.UI }.Start(); + } } private void DetachHandlers(IRepository repository) From d5f6d87f8e6d7cf430965cf3a75bf83eb7d5f586 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Wed, 1 Nov 2017 18:05:36 -0400 Subject: [PATCH 176/241] Fixing field usage --- .../Assets/Editor/GitHub.Unity/UI/ProjectWindowInterface.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ProjectWindowInterface.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ProjectWindowInterface.cs index e02fd6eb3..faadcbdff 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ProjectWindowInterface.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ProjectWindowInterface.cs @@ -58,11 +58,11 @@ private static void Repository_GitStatusCacheUpdated(CacheUpdateEvent cacheUpdat private static void Repository_GitLockCacheUpdated(CacheUpdateEvent cacheUpdateEvent) { - if (!gitStatusUpdateEvent.Equals(cacheUpdateEvent)) + if (!gitLocksUpdateEvent.Equals(cacheUpdateEvent)) { new ActionTask(CancellationToken.None, () => { - gitStatusUpdateEvent = cacheUpdateEvent; + gitLocksUpdateEvent = cacheUpdateEvent; OnLocksUpdate(repository.CurrentLocks); }) { Affinity = TaskAffinity.UI }.Start(); From 1d157043b7802ffe244ed376748596a3ddd7dfd2 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Wed, 1 Nov 2017 18:05:47 -0400 Subject: [PATCH 177/241] Removing unused field --- .../Assets/Editor/GitHub.Unity/UI/ProjectWindowInterface.cs | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ProjectWindowInterface.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ProjectWindowInterface.cs index faadcbdff..90e877ac1 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ProjectWindowInterface.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ProjectWindowInterface.cs @@ -15,7 +15,6 @@ class ProjectWindowInterface : AssetPostprocessor private static readonly List guids = new List(); private static readonly List guidsLocks = new List(); - private static bool initialized = false; private static IRepository repository; private static bool isBusy = false; private static ILogging logger; @@ -30,7 +29,6 @@ public static void Initialize(IRepository repo) EditorApplication.projectWindowItemOnGUI -= OnProjectWindowItemGUI; EditorApplication.projectWindowItemOnGUI += OnProjectWindowItemGUI; - initialized = true; repository = repo; if (repository != null) From cc41b22d83254a107ac6e9486384d8b62c992b05 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Wed, 1 Nov 2017 18:51:42 -0400 Subject: [PATCH 178/241] The relevant data is updated in RepositoryInfoCache not BranchCache --- .../Editor/GitHub.Unity/UI/HistoryView.cs | 22 +++++++++---------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/HistoryView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/HistoryView.cs index 727cbdfb0..c08046f16 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/HistoryView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/HistoryView.cs @@ -51,8 +51,8 @@ class HistoryView : Subview [SerializeField] private bool hasRemote; [SerializeField] private bool hasItemsToCommit; - [SerializeField] private CacheUpdateEvent branchUpdateEvent; - [NonSerialized] private bool branchCacheHasUpdate; + [SerializeField] private CacheUpdateEvent repositoryInfoUpdateEvent; + [NonSerialized] private bool repositoryInfoHasUpdate; [SerializeField] private CacheUpdateEvent gitStatusUpdateEvent; [NonSerialized] private bool gitStatusCacheHasUpdate; @@ -79,7 +79,7 @@ public override void OnEnable() { Repository.CheckGitLogCacheEvent(gitLogCacheUpdateEvent); Repository.CheckGitStatusCacheEvent(gitStatusUpdateEvent); - Repository.CheckBranchCacheEvent(branchUpdateEvent); + Repository.CheckRepositoryInfoCacheEvent(repositoryInfoUpdateEvent); } } @@ -128,14 +128,14 @@ private void Repository_GitLogCacheUpdated(CacheUpdateEvent cacheUpdateEvent) } } - private void Repository_BranchCacheUpdated(CacheUpdateEvent cacheUpdateEvent) + private void Repository_RepositoryInfoCacheUpdated(CacheUpdateEvent cacheUpdateEvent) { - if (!branchUpdateEvent.Equals(cacheUpdateEvent)) + if (!repositoryInfoUpdateEvent.Equals(cacheUpdateEvent)) { new ActionTask(TaskManager.Token, () => { - branchUpdateEvent = cacheUpdateEvent; - branchCacheHasUpdate = true; + repositoryInfoUpdateEvent = cacheUpdateEvent; + repositoryInfoHasUpdate = true; Redraw(); }) { Affinity = TaskAffinity.UI }.Start(); @@ -149,7 +149,7 @@ private void AttachHandlers(IRepository repository) repository.GitStatusCacheUpdated += Repository_GitStatusCacheUpdated; repository.GitLogCacheUpdated += Repository_GitLogCacheUpdated; - repository.BranchCacheUpdated += Repository_BranchCacheUpdated; + repository.RepositoryInfoCacheUpdated += Repository_RepositoryInfoCacheUpdated; } private void DetachHandlers(IRepository repository) @@ -159,7 +159,7 @@ private void DetachHandlers(IRepository repository) repository.GitStatusCacheUpdated -= Repository_GitStatusCacheUpdated; repository.GitLogCacheUpdated -= Repository_GitLogCacheUpdated; - repository.BranchCacheUpdated -= Repository_BranchCacheUpdated; + repository.RepositoryInfoCacheUpdated -= Repository_RepositoryInfoCacheUpdated; } private void MaybeUpdateData() @@ -167,9 +167,9 @@ private void MaybeUpdateData() if (Repository == null) return; - if (branchCacheHasUpdate) + if (repositoryInfoHasUpdate) { - branchCacheHasUpdate = false; + repositoryInfoHasUpdate = false; var currentRemote = Repository.CurrentRemote; hasRemote = currentRemote.HasValue; From fdd711df5d9b36a9868fda14d396135dec706b09 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Wed, 1 Nov 2017 10:03:09 -0400 Subject: [PATCH 179/241] Making GitLock serializable --- src/GitHub.Api/Git/GitLock.cs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/GitHub.Api/Git/GitLock.cs b/src/GitHub.Api/Git/GitLock.cs index b7ee35cdf..1267e7af4 100644 --- a/src/GitHub.Api/Git/GitLock.cs +++ b/src/GitHub.Api/Git/GitLock.cs @@ -5,12 +5,12 @@ namespace GitHub.Unity [Serializable] public struct GitLock { - public static GitLock Default = new GitLock(null, null, null, -1); + public static GitLock Default = new GitLock { ID = -1 }; - public readonly int ID; - public readonly string Path; - public readonly string FullPath; - public readonly string User; + public int ID; + public string Path; + public string FullPath; + public string User; public GitLock(string path, string fullPath, string user, int id) { From b292c859fe286cd48cc7cf74b6a84d4371151d3c Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Fri, 27 Oct 2017 09:44:16 -0400 Subject: [PATCH 180/241] Changing the struct GitBranch to use a default constructor and fields --- src/GitHub.Api/Git/GitBranch.cs | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/src/GitHub.Api/Git/GitBranch.cs b/src/GitHub.Api/Git/GitBranch.cs index 9080accce..733b845df 100644 --- a/src/GitHub.Api/Git/GitBranch.cs +++ b/src/GitHub.Api/Git/GitBranch.cs @@ -11,12 +11,15 @@ interface ITreeData [Serializable] public struct GitBranch : ITreeData { - private string name; - private string tracking; - private bool active; + public static GitBranch Default = new GitBranch(); + + public string name; + public string tracking; + public bool isActive; + public string Name { get { return name; } } public string Tracking { get { return tracking; } } - public bool IsActive { get { return active; } } + public bool IsActive { get { return isActive; } } public GitBranch(string name, string tracking, bool active) { @@ -24,7 +27,7 @@ public GitBranch(string name, string tracking, bool active) this.name = name; this.tracking = tracking; - this.active = active; + this.isActive = active; } public override string ToString() From 4d0379198261d64817fd6a5efd336fd6342000ee Mon Sep 17 00:00:00 2001 From: Andreia Gaita Date: Wed, 1 Nov 2017 19:33:17 -0700 Subject: [PATCH 181/241] Fix merge --- src/GitHub.Api/Git/GitObjectFactory.cs | 7 +- src/GitHub.Api/Git/Repository.cs | 5 +- .../BranchListOutputProcessor.cs | 7 +- .../Events/RepositoryManagerTests.cs | 516 +++--------------- .../IntegrationTests/Git/GitSetupTests.cs | 12 +- .../Process/ProcessManagerIntegrationTests.cs | 12 +- .../Substitutes/SubstituteFactory.cs | 7 +- .../IO/BranchListOutputProcessorTests.cs | 18 +- .../UnitTests/IO/LockOutputProcessorTests.cs | 35 +- 9 files changed, 103 insertions(+), 516 deletions(-) diff --git a/src/GitHub.Api/Git/GitObjectFactory.cs b/src/GitHub.Api/Git/GitObjectFactory.cs index 6b5d763a5..489c0475a 100644 --- a/src/GitHub.Api/Git/GitObjectFactory.cs +++ b/src/GitHub.Api/Git/GitObjectFactory.cs @@ -26,12 +26,7 @@ public GitLock CreateGitLock(string path, string user, int id) var npath = new NPath(path).MakeAbsolute(); var fullPath = npath.RelativeTo(environment.RepositoryPath); - return new GitLock { - Path = path, - FullPath = fullPath, - User = user, - ID = id - }; + return new GitLock(path, fullPath, user, id); } } } diff --git a/src/GitHub.Api/Git/Repository.cs b/src/GitHub.Api/Git/Repository.cs index ca92f0c7d..35c5861c7 100644 --- a/src/GitHub.Api/Git/Repository.cs +++ b/src/GitHub.Api/Git/Repository.cs @@ -1,5 +1,4 @@ using System; -using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; @@ -465,14 +464,14 @@ private GitBranch GetLocalGitBranch(ConfigBranch x) var trackingName = x.IsTracking ? x.Remote.Value.Name + "/" + name : "[None]"; var isActive = name == CurrentBranchName; - return new GitBranch { Name = name, Tracking = trackingName, IsActive = isActive }; + return new GitBranch(name, trackingName, isActive); } private static GitBranch GetRemoteGitBranch(ConfigBranch x) { var name = x.Remote.Value.Name + "/" + x.Name; - return new GitBranch { Name = name }; + return new GitBranch(name, "[None]", false); } private static GitRemote GetGitRemote(ConfigRemote configRemote) diff --git a/src/GitHub.Api/OutputProcessors/BranchListOutputProcessor.cs b/src/GitHub.Api/OutputProcessors/BranchListOutputProcessor.cs index 5df87e56b..cca8ed4ed 100644 --- a/src/GitHub.Api/OutputProcessors/BranchListOutputProcessor.cs +++ b/src/GitHub.Api/OutputProcessors/BranchListOutputProcessor.cs @@ -36,12 +36,7 @@ public override void LineReceived(string line) trackingName = proc.ReadChunk('[', ']'); } - var branch = new GitBranch - { - Name = name, - Tracking = trackingName, - IsActive = active - }; + var branch = new GitBranch(name, trackingName, active); RaiseOnEntry(branch); } diff --git a/src/tests/IntegrationTests/Events/RepositoryManagerTests.cs b/src/tests/IntegrationTests/Events/RepositoryManagerTests.cs index 7d5bb192f..30d8dfe02 100644 --- a/src/tests/IntegrationTests/Events/RepositoryManagerTests.cs +++ b/src/tests/IntegrationTests/Events/RepositoryManagerTests.cs @@ -47,21 +47,9 @@ public async Task ShouldDoNothingOnInitialize() Repository.CurrentRemote.Value.Name.Should().Be("origin"); Repository.CurrentRemote.Value.Url.Should().Be("https://github.com/EvilStanleyGoldman/IOTestsRepo.git"); Repository.LocalBranches.Should().BeEquivalentTo(new[] { - new GitBranch { - Name = "master", - Tracking = "origin/master", - IsActive = true - }, - new GitBranch { - Name = "feature/document", - Tracking = "origin/feature/document", - IsActive = false - }, - new GitBranch { - Name = "feature/other-feature", - Tracking = "origin/feature/other-feature", - IsActive = false - }, + new GitBranch("master", "origin/master", true), + new GitBranch("feature/document", "origin/feature/document", false), + new GitBranch("feature/other-feature", "origin/feature/other-feature", false), }); Repository.Remotes.Should().BeEquivalentTo(new GitRemote { @@ -69,21 +57,9 @@ public async Task ShouldDoNothingOnInitialize() Url = "https://github.com/EvilStanleyGoldman/IOTestsRepo.git" }); Repository.RemoteBranches.Should().BeEquivalentTo(new[] { - new GitBranch { - Name = "origin/master", - Tracking = "[None]", - IsActive = false - }, - new GitBranch { - Name = "origin/feature/document-2", - Tracking = "[None]", - IsActive = false - }, - new GitBranch { - Name = "origin/feature/other-feature", - Tracking = "[None]", - IsActive = false - }, + new GitBranch("origin/master", "[None]", false), + new GitBranch("origin/feature/document-2", "[None]", false), + new GitBranch("origin/feature/other-feature", "[None]", false), }); } @@ -350,42 +326,18 @@ public async Task ShouldDetectBranchChange() Repository.CurrentRemote.Value.Name.Should().Be("origin"); Repository.CurrentRemote.Value.Url.Should().Be("https://github.com/EvilStanleyGoldman/IOTestsRepo.git"); Repository.LocalBranches.Should().BeEquivalentTo(new[] { - new GitBranch { - Name = "master", - Tracking = "origin/master", - IsActive = false - }, - new GitBranch { - Name = "feature/document", - Tracking = "origin/feature/document", - IsActive = true - }, - new GitBranch { - Name = "feature/other-feature", - Tracking = "origin/feature/other-feature", - IsActive = false - }, + new GitBranch("master", "origin/master", false), + new GitBranch("feature/document", "origin/feature/document", true), + new GitBranch("feature/other-feature", "origin/feature/other-feature", false), }); Repository.Remotes.Should().BeEquivalentTo(new GitRemote { Name = "origin", Url = "https://github.com/EvilStanleyGoldman/IOTestsRepo.git" }); Repository.RemoteBranches.Should().BeEquivalentTo(new[] { - new GitBranch { - Name = "origin/master", - Tracking = "[None]", - IsActive = false - }, - new GitBranch { - Name = "origin/feature/document-2", - Tracking = "[None]", - IsActive = false - }, - new GitBranch { - Name = "origin/feature/other-feature", - Tracking = "[None]", - IsActive = false - }, + new GitBranch("origin/master", "[None]", false), + new GitBranch("origin/feature/document-2", "[None]", false), + new GitBranch("origin/feature/other-feature", "[None]", false), }); } @@ -428,16 +380,8 @@ public async Task ShouldDetectBranchDelete() Repository.CurrentRemote.Value.Name.Should().Be("origin"); Repository.CurrentRemote.Value.Url.Should().Be("https://github.com/EvilStanleyGoldman/IOTestsRepo.git"); Repository.LocalBranches.Should().BeEquivalentTo(new[] { - new GitBranch { - Name = "master", - Tracking = "origin/master", - IsActive = true - }, - new GitBranch { - Name = "feature/other-feature", - Tracking = "origin/feature/other-feature", - IsActive = false - }, + new GitBranch("master", "origin/master", true), + new GitBranch("feature/other-feature", "origin/feature/other-feature", false), }); Repository.Remotes.Should().BeEquivalentTo(new GitRemote { @@ -445,21 +389,9 @@ public async Task ShouldDetectBranchDelete() Url = "https://github.com/EvilStanleyGoldman/IOTestsRepo.git" }); Repository.RemoteBranches.Should().BeEquivalentTo(new[] { - new GitBranch { - Name = "origin/master", - Tracking = "[None]", - IsActive = false - }, - new GitBranch { - Name = "origin/feature/document-2", - Tracking = "[None]", - IsActive = false - }, - new GitBranch { - Name = "origin/feature/other-feature", - Tracking = "[None]", - IsActive = false - }, + new GitBranch("origin/master", "[None]", false), + new GitBranch("origin/feature/document-2", "[None]", false), + new GitBranch("origin/feature/other-feature", "[None]", false), }); } @@ -502,26 +434,10 @@ public async Task ShouldDetectBranchCreate() Repository.CurrentRemote.Value.Name.Should().Be("origin"); Repository.CurrentRemote.Value.Url.Should().Be("https://github.com/EvilStanleyGoldman/IOTestsRepo.git"); Repository.LocalBranches.Should().BeEquivalentTo(new[] { - new GitBranch { - Name = "master", - Tracking = "origin/master", - IsActive = true - }, - new GitBranch { - Name = "feature/document", - Tracking = "origin/feature/document", - IsActive = false - }, - new GitBranch { - Name = "feature/document2", - Tracking = "[None]", - IsActive = false - }, - new GitBranch { - Name = "feature/other-feature", - Tracking = "origin/feature/other-feature", - IsActive = false - }, + new GitBranch("master", "origin/master", true), + new GitBranch("feature/document", "origin/feature/document", false), + new GitBranch("feature/document2", "[None]", false), + new GitBranch("feature/other-feature", "origin/feature/other-feature", false), }); Repository.Remotes.Should().BeEquivalentTo(new GitRemote { @@ -529,21 +445,9 @@ public async Task ShouldDetectBranchCreate() Url = "https://github.com/EvilStanleyGoldman/IOTestsRepo.git" }); Repository.RemoteBranches.Should().BeEquivalentTo(new[] { - new GitBranch { - Name = "origin/master", - Tracking = "[None]", - IsActive = false - }, - new GitBranch { - Name = "origin/feature/document-2", - Tracking = "[None]", - IsActive = false - }, - new GitBranch { - Name = "origin/feature/other-feature", - Tracking = "[None]", - IsActive = false - }, + new GitBranch("origin/master", "[None]", false), + new GitBranch("origin/feature/document-2", "[None]", false), + new GitBranch("origin/feature/other-feature", "[None]", false), }); repositoryManagerListener.ClearReceivedCalls(); @@ -580,31 +484,11 @@ public async Task ShouldDetectBranchCreate() Repository.CurrentRemote.Value.Name.Should().Be("origin"); Repository.CurrentRemote.Value.Url.Should().Be("https://github.com/EvilStanleyGoldman/IOTestsRepo.git"); Repository.LocalBranches.Should().BeEquivalentTo(new[] { - new GitBranch { - Name = "master", - Tracking = "origin/master", - IsActive = true - }, - new GitBranch { - Name = "feature/document", - Tracking = "origin/feature/document", - IsActive = false - }, - new GitBranch { - Name = "feature/document2", - Tracking = "[None]", - IsActive = false - }, - new GitBranch { - Name = "feature2/document2", - Tracking = "[None]", - IsActive = false - }, - new GitBranch { - Name = "feature/other-feature", - Tracking = "origin/feature/other-feature", - IsActive = false - }, + new GitBranch("master", "origin/master", true), + new GitBranch("feature/document", "origin/feature/document", false), + new GitBranch("feature/document2", "[None]", false), + new GitBranch("feature2/document2", "[None]", false), + new GitBranch("feature/other-feature", "origin/feature/other-feature", false), }); Repository.Remotes.Should().BeEquivalentTo(new GitRemote { @@ -612,21 +496,9 @@ public async Task ShouldDetectBranchCreate() Url = "https://github.com/EvilStanleyGoldman/IOTestsRepo.git" }); Repository.RemoteBranches.Should().BeEquivalentTo(new[] { - new GitBranch { - Name = "origin/master", - Tracking = "[None]", - IsActive = false - }, - new GitBranch { - Name = "origin/feature/document-2", - Tracking = "[None]", - IsActive = false - }, - new GitBranch { - Name = "origin/feature/other-feature", - Tracking = "[None]", - IsActive = false - }, + new GitBranch("origin/master", "[None]", false), + new GitBranch("origin/feature/document-2", "[None]", false), + new GitBranch("origin/feature/other-feature", "[None]", false), }); } @@ -655,21 +527,9 @@ public async Task ShouldDetectChangesToRemotes() Repository.CurrentRemote.Value.Name.Should().Be("origin"); Repository.CurrentRemote.Value.Url.Should().Be("https://github.com/EvilStanleyGoldman/IOTestsRepo.git"); Repository.LocalBranches.Should().BeEquivalentTo(new[] { - new GitBranch { - Name = "master", - Tracking = "origin/master", - IsActive = true - }, - new GitBranch { - Name = "feature/document", - Tracking = "origin/feature/document", - IsActive = false - }, - new GitBranch { - Name = "feature/other-feature", - Tracking = "origin/feature/other-feature", - IsActive = false - }, + new GitBranch("master", "origin/master", true), + new GitBranch("feature/document", "origin/feature/document", false), + new GitBranch("feature/other-feature", "origin/feature/other-feature", false), }); Repository.Remotes.Should().BeEquivalentTo(new GitRemote { @@ -677,21 +537,9 @@ public async Task ShouldDetectChangesToRemotes() Url = "https://github.com/EvilStanleyGoldman/IOTestsRepo.git" }); Repository.RemoteBranches.Should().BeEquivalentTo(new[] { - new GitBranch { - Name = "origin/master", - Tracking = "[None]", - IsActive = false - }, - new GitBranch { - Name = "origin/feature/document-2", - Tracking = "[None]", - IsActive = false - }, - new GitBranch { - Name = "origin/feature/other-feature", - Tracking = "[None]", - IsActive = false - }, + new GitBranch("origin/master", "[None]", false), + new GitBranch("origin/feature/document-2", "[None]", false), + new GitBranch("origin/feature/other-feature", "[None]", false), }); await RepositoryManager.RemoteRemove("origin").StartAsAsync(); @@ -763,21 +611,9 @@ public async Task ShouldDetectChangesToRemotes() Repository.CurrentRemote.Value.Name.Should().Be("origin"); Repository.CurrentRemote.Value.Url.Should().Be("https://github.com/EvilShana/IOTestsRepo.git"); Repository.LocalBranches.Should().BeEquivalentTo(new[] { - new GitBranch { - Name = "master", - Tracking = "[None]", - IsActive = true - }, - new GitBranch { - Name = "feature/document", - Tracking = "[None]", - IsActive = false - }, - new GitBranch { - Name = "feature/other-feature", - Tracking = "[None]", - IsActive = false - }, + new GitBranch("master", "[None]", true), + new GitBranch("feature/document", "[None]", false), + new GitBranch("feature/other-feature", "[None]", false), }); Repository.Remotes.Should().BeEquivalentTo(new GitRemote { @@ -812,21 +648,9 @@ public async Task ShouldDetectChangesToRemotesWhenSwitchingBranches() Repository.CurrentRemote.Value.Name.Should().Be("origin"); Repository.CurrentRemote.Value.Url.Should().Be("https://github.com/EvilStanleyGoldman/IOTestsRepo.git"); Repository.LocalBranches.Should().BeEquivalentTo(new[] { - new GitBranch { - Name = "master", - Tracking = "origin/master", - IsActive = true - }, - new GitBranch { - Name = "feature/document", - Tracking = "origin/feature/document", - IsActive = false - }, - new GitBranch { - Name = "feature/other-feature", - Tracking = "origin/feature/other-feature", - IsActive = false - }, + new GitBranch("master", "origin/master", true), + new GitBranch("feature/document", "origin/feature/document", false), + new GitBranch("feature/other-feature", "origin/feature/other-feature", false), }); Repository.Remotes.Should().BeEquivalentTo(new GitRemote { @@ -838,36 +662,12 @@ public async Task ShouldDetectChangesToRemotesWhenSwitchingBranches() Url = "https://another.remote/Owner/Url.git" }); Repository.RemoteBranches.Should().BeEquivalentTo(new[] { - new GitBranch { - Name = "origin/master", - Tracking = "[None]", - IsActive = false - }, - new GitBranch { - Name = "origin/feature/document-2", - Tracking = "[None]", - IsActive = false - }, - new GitBranch { - Name = "origin/feature/other-feature", - Tracking = "[None]", - IsActive = false - }, - new GitBranch { - Name = "another/master", - Tracking = "[None]", - IsActive = false - }, - new GitBranch { - Name = "another/feature/document-2", - Tracking = "[None]", - IsActive = false - }, - new GitBranch { - Name = "another/feature/other-feature", - Tracking = "[None]", - IsActive = false - }, + new GitBranch("origin/master", "[None]", false), + new GitBranch("origin/feature/document-2", "[None]", false), + new GitBranch("origin/feature/other-feature", "[None]", false), + new GitBranch("another/master", "[None]", false), + new GitBranch("another/feature/document-2", "[None]", false), + new GitBranch("another/feature/other-feature", "[None]", false), }); await RepositoryManager.CreateBranch("branch2", "another/master") @@ -902,26 +702,10 @@ await RepositoryManager.CreateBranch("branch2", "another/master") Repository.CurrentRemote.Value.Name.Should().Be("origin"); Repository.CurrentRemote.Value.Url.Should().Be("https://github.com/EvilStanleyGoldman/IOTestsRepo.git"); Repository.LocalBranches.Should().BeEquivalentTo(new[] { - new GitBranch { - Name = "master", - Tracking = "origin/master", - IsActive = true - }, - new GitBranch { - Name = "branch2", - Tracking = "another/branch2", - IsActive = false - }, - new GitBranch { - Name = "feature/document", - Tracking = "origin/feature/document", - IsActive = false - }, - new GitBranch { - Name = "feature/other-feature", - Tracking = "origin/feature/other-feature", - IsActive = false - }, + new GitBranch("master", "origin/master", true), + new GitBranch("branch2", "another/branch2", false), + new GitBranch("feature/document", "origin/feature/document", false), + new GitBranch("feature/other-feature", "origin/feature/other-feature", false), }); Repository.Remotes.Should().BeEquivalentTo(new GitRemote { @@ -933,36 +717,12 @@ await RepositoryManager.CreateBranch("branch2", "another/master") Url = "https://another.remote/Owner/Url.git" }); Repository.RemoteBranches.Should().BeEquivalentTo(new[] { - new GitBranch { - Name = "origin/master", - Tracking = "[None]", - IsActive = false - }, - new GitBranch { - Name = "origin/feature/document-2", - Tracking = "[None]", - IsActive = false - }, - new GitBranch { - Name = "origin/feature/other-feature", - Tracking = "[None]", - IsActive = false - }, - new GitBranch { - Name = "another/master", - Tracking = "[None]", - IsActive = false - }, - new GitBranch { - Name = "another/feature/document-2", - Tracking = "[None]", - IsActive = false - }, - new GitBranch { - Name = "another/feature/other-feature", - Tracking = "[None]", - IsActive = false - }, + new GitBranch("origin/master", "[None]", false), + new GitBranch("origin/feature/document-2", "[None]", false), + new GitBranch("origin/feature/other-feature", "[None]", false), + new GitBranch("another/master", "[None]", false), + new GitBranch("another/feature/document-2", "[None]", false), + new GitBranch("another/feature/other-feature", "[None]", false), }); repositoryManagerListener.ClearReceivedCalls(); @@ -1001,26 +761,10 @@ await RepositoryManager.SwitchBranch("branch2") Repository.CurrentRemote.Value.Name.Should().Be("another"); Repository.CurrentRemote.Value.Url.Should().Be("https://another.remote/Owner/Url.git"); Repository.LocalBranches.Should().BeEquivalentTo(new[] { - new GitBranch { - Name = "master", - Tracking = "origin/master", - IsActive = false - }, - new GitBranch { - Name = "branch2", - Tracking = "another/branch2", - IsActive = true - }, - new GitBranch { - Name = "feature/document", - Tracking = "origin/feature/document", - IsActive = false - }, - new GitBranch { - Name = "feature/other-feature", - Tracking = "origin/feature/other-feature", - IsActive = false - }, + new GitBranch("master", "origin/master", false), + new GitBranch("branch2", "another/branch2", true), + new GitBranch("feature/document", "origin/feature/document", false), + new GitBranch("feature/other-feature", "origin/feature/other-feature", false), }); Repository.Remotes.Should().BeEquivalentTo(new GitRemote { @@ -1032,36 +776,12 @@ await RepositoryManager.SwitchBranch("branch2") Url = "https://another.remote/Owner/Url.git" }); Repository.RemoteBranches.Should().BeEquivalentTo(new[] { - new GitBranch { - Name = "origin/master", - Tracking = "[None]", - IsActive = false - }, - new GitBranch { - Name = "origin/feature/document-2", - Tracking = "[None]", - IsActive = false - }, - new GitBranch { - Name = "origin/feature/other-feature", - Tracking = "[None]", - IsActive = false - }, - new GitBranch { - Name = "another/master", - Tracking = "[None]", - IsActive = false - }, - new GitBranch { - Name = "another/feature/document-2", - Tracking = "[None]", - IsActive = false - }, - new GitBranch { - Name = "another/feature/other-feature", - Tracking = "[None]", - IsActive = false - }, + new GitBranch("origin/master", "[None]", false), + new GitBranch("origin/feature/document-2", "[None]", false), + new GitBranch("origin/feature/other-feature", "[None]", false), + new GitBranch("another/master", "[None]", false), + new GitBranch("another/feature/document-2", "[None]", false), + new GitBranch("another/feature/other-feature", "[None]", false), }); } @@ -1116,21 +836,9 @@ public async Task ShouldDetectGitPull() Repository.CurrentRemote.Value.Name.Should().Be("origin"); Repository.CurrentRemote.Value.Url.Should().Be("https://github.com/EvilStanleyGoldman/IOTestsRepo.git"); Repository.LocalBranches.Should().BeEquivalentTo(new[] { - new GitBranch { - Name = "master", - Tracking = "origin/master", - IsActive = true - }, - new GitBranch { - Name = "feature/document", - Tracking = "origin/feature/document", - IsActive = false - }, - new GitBranch { - Name = "feature/other-feature", - Tracking = "origin/feature/other-feature", - IsActive = false - }, + new GitBranch("master", "origin/master", true), + new GitBranch("feature/document", "origin/feature/document", false), + new GitBranch("feature/other-feature", "origin/feature/other-feature", false), }); Repository.Remotes.Should().BeEquivalentTo(new GitRemote { @@ -1138,21 +846,9 @@ public async Task ShouldDetectGitPull() Url = "https://github.com/EvilStanleyGoldman/IOTestsRepo.git" }); Repository.RemoteBranches.Should().BeEquivalentTo(new[] { - new GitBranch { - Name = "origin/master", - Tracking = "[None]", - IsActive = false - }, - new GitBranch { - Name = "origin/feature/document-2", - Tracking = "[None]", - IsActive = false - }, - new GitBranch { - Name = "origin/feature/other-feature", - Tracking = "[None]", - IsActive = false - }, + new GitBranch("origin/master", "[None]", false), + new GitBranch("origin/feature/document-2", "[None]", false), + new GitBranch("origin/feature/other-feature", "[None]", false), }); repositoryManagerEvents.Reset(); @@ -1184,11 +880,7 @@ public async Task ShouldDetectGitFetch() Repository.CurrentRemote.Value.Name.Should().Be("origin"); Repository.CurrentRemote.Value.Url.Should().Be("https://github.com/EvilStanleyGoldman/IOTestsRepo.git"); Repository.LocalBranches.Should().BeEquivalentTo(new[] { - new GitBranch { - Name = "feature/document", - Tracking = "origin/feature/document", - IsActive = false - }, + new GitBranch("feature/document", "origin/feature/document", false), }); Repository.Remotes.Should().BeEquivalentTo(new GitRemote { @@ -1196,21 +888,9 @@ public async Task ShouldDetectGitFetch() Url = "https://github.com/EvilStanleyGoldman/IOTestsRepo.git" }); Repository.RemoteBranches.Should().BeEquivalentTo(new[] { - new GitBranch { - Name = "origin/master", - Tracking = "[None]", - IsActive = false - }, - new GitBranch { - Name = "origin/feature/document", - Tracking = "[None]", - IsActive = false - }, - new GitBranch { - Name = "origin/feature/document-2", - Tracking = "[None]", - IsActive = false - }, + new GitBranch("origin/master", "[None]", false), + new GitBranch("origin/feature/document", "[None]", false), + new GitBranch("origin/feature/document-2", "[None]", false), }); await RepositoryManager.Fetch("origin").StartAsAsync(); @@ -1243,11 +923,7 @@ public async Task ShouldDetectGitFetch() Repository.CurrentRemote.Value.Name.Should().Be("origin"); Repository.CurrentRemote.Value.Url.Should().Be("https://github.com/EvilStanleyGoldman/IOTestsRepo.git"); Repository.LocalBranches.Should().BeEquivalentTo(new[] { - new GitBranch { - Name = "feature/document", - Tracking = "origin/feature/document", - IsActive = false - }, + new GitBranch("feature/document", "origin/feature/document", false), }); Repository.Remotes.Should().BeEquivalentTo(new GitRemote { @@ -1255,31 +931,11 @@ public async Task ShouldDetectGitFetch() Url = "https://github.com/EvilStanleyGoldman/IOTestsRepo.git" }); Repository.RemoteBranches.Should().BeEquivalentTo(new[] { - new GitBranch { - Name = "origin/master", - Tracking = "[None]", - IsActive = false - }, - new GitBranch { - Name = "origin/feature/document", - Tracking = "[None]", - IsActive = false - }, - new GitBranch { - Name = "origin/feature/document-2", - Tracking = "[None]", - IsActive = false - }, - new GitBranch { - Name = "origin/feature/new-feature", - Tracking = "[None]", - IsActive = false - }, - new GitBranch { - Name = "origin/feature/other-feature", - Tracking = "[None]", - IsActive = false - }, + new GitBranch("origin/master", "[None]", false), + new GitBranch("origin/feature/document", "[None]", false), + new GitBranch("origin/feature/document-2", "[None]", false), + new GitBranch("origin/feature/new-feature", "[None]", false), + new GitBranch("origin/feature/other-feature", "[None]", false), }); } } diff --git a/src/tests/IntegrationTests/Git/GitSetupTests.cs b/src/tests/IntegrationTests/Git/GitSetupTests.cs index 4e239dd94..1a18cdc8b 100644 --- a/src/tests/IntegrationTests/Git/GitSetupTests.cs +++ b/src/tests/IntegrationTests/Git/GitSetupTests.cs @@ -63,16 +63,8 @@ public async Task InstallGit() .StartAsAsync(); gitBranches.Should().BeEquivalentTo( - new GitBranch { - Name = "master", - Tracking = "origin/master: behind 1", - IsActive = true - }, - new GitBranch { - Name = "feature/document", - Tracking = "origin/feature/document", - IsActive = false - }); + new GitBranch("master", "origin/master: behind 1", true), + new GitBranch("feature/document", "origin/feature/document", false)); } diff --git a/src/tests/IntegrationTests/Process/ProcessManagerIntegrationTests.cs b/src/tests/IntegrationTests/Process/ProcessManagerIntegrationTests.cs index db6a90e7b..8766b3798 100644 --- a/src/tests/IntegrationTests/Process/ProcessManagerIntegrationTests.cs +++ b/src/tests/IntegrationTests/Process/ProcessManagerIntegrationTests.cs @@ -23,16 +23,8 @@ public async Task BranchListTest() .StartAsAsync(); gitBranches.Should().BeEquivalentTo( - new GitBranch { - Name = "master", - Tracking = "origin/master: behind 1", - IsActive = true - }, - new GitBranch { - Name = "feature/document", - Tracking = "origin/feature/document", - IsActive = false - }); + new GitBranch("master", "origin/master: behind 1", true), + new GitBranch("feature/document", "origin/feature/document", false)); } [Test] diff --git a/src/tests/TestUtils/Substitutes/SubstituteFactory.cs b/src/tests/TestUtils/Substitutes/SubstituteFactory.cs index e2185fb06..49b82fc1f 100644 --- a/src/tests/TestUtils/Substitutes/SubstituteFactory.cs +++ b/src/tests/TestUtils/Substitutes/SubstituteFactory.cs @@ -325,12 +325,7 @@ public IGitObjectFactory CreateGitObjectFactory(string gitRepoPath) var user = (string)info[1]; var id = (int)info[2]; - return new GitLock { - Path = path, - FullPath = gitRepoPath + @"\" + path, - User = user, - ID = id - }; + return new GitLock(path, gitRepoPath + @"\" + path, user, id); }); return gitObjectFactory; diff --git a/src/tests/UnitTests/IO/BranchListOutputProcessorTests.cs b/src/tests/UnitTests/IO/BranchListOutputProcessorTests.cs index 6fb9fc7fa..64d265bdf 100644 --- a/src/tests/UnitTests/IO/BranchListOutputProcessorTests.cs +++ b/src/tests/UnitTests/IO/BranchListOutputProcessorTests.cs @@ -20,21 +20,9 @@ public void ShouldProcessOutput() AssertProcessOutput(output, new[] { - new GitBranch { - Name = "master", - Tracking = "origin/master", - IsActive = true - }, - new GitBranch { - Name = "feature/feature-1", - Tracking = "", - IsActive = false - }, - new GitBranch { - Name = "bugfixes/bugfix-1", - Tracking = "origin/bugfixes/bugfix-1", - IsActive = false - }, + new GitBranch("master", "origin/master", true), + new GitBranch("feature/feature-1", "", false), + new GitBranch("bugfixes/bugfix-1", "origin/bugfixes/bugfix-1", false), }); } diff --git a/src/tests/UnitTests/IO/LockOutputProcessorTests.cs b/src/tests/UnitTests/IO/LockOutputProcessorTests.cs index b035cc866..9fc38097b 100644 --- a/src/tests/UnitTests/IO/LockOutputProcessorTests.cs +++ b/src/tests/UnitTests/IO/LockOutputProcessorTests.cs @@ -63,18 +63,8 @@ public void ShouldParseTwoLocksFormat1() }; var expected = new[] { - new GitLock { - Path = "folder/somefile.png", - FullPath = TestRootPath + @"\folder/somefile.png", - User = "GitHub User", - ID = 12 - }, - new GitLock { - Path = "somezip.zip", - FullPath = TestRootPath + @"\somezip.zip", - User = "GitHub User", - ID = 21 - } + new GitLock("folder/somefile.png", TestRootPath + @"\folder/somefile.png", "GitHub User", 12), + new GitLock("somezip.zip", TestRootPath + @"\somezip.zip", "GitHub User", 21) }; AssertProcessOutput(output, expected); @@ -91,18 +81,8 @@ public void ShouldParseTwoLocksFormat2() }; var expected = new[] { - new GitLock { - Path = "folder/somefile.png", - FullPath = TestRootPath + @"\folder/somefile.png", - User = "GitHub User", - ID = 12 - }, - new GitLock { - Path = "somezip.zip", - FullPath = TestRootPath + @"\somezip.zip", - User = "GitHub User", - ID = 21 - } + new GitLock("folder/somefile.png", TestRootPath + @"\folder/somefile.png", "GitHub User", 12), + new GitLock("somezip.zip", TestRootPath + @"\somezip.zip", "GitHub User", 21) }; AssertProcessOutput(output, expected); @@ -117,12 +97,7 @@ public void ShouldParseLocksOnFileWithNumericFirstLetter() }; var expected = new[] { - new GitLock { - Path = "2_TurtleDoves.jpg", - FullPath = TestRootPath + @"\2_TurtleDoves.jpg", - User = "Tree", - ID = 100 - } + new GitLock("2_TurtleDoves.jpg", TestRootPath + @"\2_TurtleDoves.jpg", "Tree", 100) }; AssertProcessOutput(output, expected); From 90535f22193dcdb5d8698e41472e8f957bc7ae9d Mon Sep 17 00:00:00 2001 From: Andreia Gaita Date: Wed, 1 Nov 2017 20:08:32 -0700 Subject: [PATCH 182/241] Move CacheContainer into environment and use a mock for the tests --- src/GitHub.Api/Application/ApplicationManagerBase.cs | 4 +--- src/GitHub.Api/Application/IApplicationManager.cs | 1 - src/GitHub.Api/Platform/DefaultEnvironment.cs | 9 ++++++++- src/GitHub.Api/Platform/IEnvironment.cs | 2 +- .../Assets/Editor/GitHub.Unity/ApplicationCache.cs | 4 ++-- .../Assets/Editor/GitHub.Unity/ApplicationManager.cs | 1 - src/tests/IntegrationTests/BaseGitEnvironmentTest.cs | 7 ++++--- .../Git/IntegrationTestEnvironment.cs | 12 +++++------- 8 files changed, 21 insertions(+), 19 deletions(-) diff --git a/src/GitHub.Api/Application/ApplicationManagerBase.cs b/src/GitHub.Api/Application/ApplicationManagerBase.cs index 0267c023c..ffa1bf77d 100644 --- a/src/GitHub.Api/Application/ApplicationManagerBase.cs +++ b/src/GitHub.Api/Application/ApplicationManagerBase.cs @@ -116,7 +116,7 @@ public ITask InitializeRepository() .Then(GitClient.Commit("Initial commit", null)) .Then(_ => { - Environment.InitializeRepository(CacheContainer); + Environment.InitializeRepository(); RestartRepository(); }) .ThenInUI(InitializeUI); @@ -214,9 +214,7 @@ public void Dispose() public ISettings LocalSettings { get; protected set; } public ISettings SystemSettings { get; protected set; } public ISettings UserSettings { get; protected set; } - public ICacheContainer CacheContainer { get; protected set; } public IUsageTracker UsageTracker { get; protected set; } - protected TaskScheduler UIScheduler { get; private set; } protected SynchronizationContext SynchronizationContext { get; private set; } protected IRepositoryManager RepositoryManager { get { return repositoryManager; } } diff --git a/src/GitHub.Api/Application/IApplicationManager.cs b/src/GitHub.Api/Application/IApplicationManager.cs index a9bfabf22..fd59878a8 100644 --- a/src/GitHub.Api/Application/IApplicationManager.cs +++ b/src/GitHub.Api/Application/IApplicationManager.cs @@ -15,7 +15,6 @@ public interface IApplicationManager : IDisposable ISettings LocalSettings { get; } ISettings UserSettings { get; } ITaskManager TaskManager { get; } - ICacheContainer CacheContainer { get; } IGitClient GitClient { get; } IUsageTracker UsageTracker { get; } diff --git a/src/GitHub.Api/Platform/DefaultEnvironment.cs b/src/GitHub.Api/Platform/DefaultEnvironment.cs index 5077ad175..7301e3875 100644 --- a/src/GitHub.Api/Platform/DefaultEnvironment.cs +++ b/src/GitHub.Api/Platform/DefaultEnvironment.cs @@ -7,6 +7,7 @@ namespace GitHub.Unity public class DefaultEnvironment : IEnvironment { private const string logFile = "github-unity.log"; + private ICacheContainer cacheContainer; public NPath LogPath { get; } public DefaultEnvironment() @@ -35,6 +36,12 @@ public DefaultEnvironment() LogPath = UserCachePath.Combine(logFile); } + public DefaultEnvironment(ICacheContainer cacheContainer) + : this() + { + this.cacheContainer = cacheContainer; + } + public void Initialize(string unityVersion, NPath extensionInstallPath, NPath unityPath, NPath assetsPath) { ExtensionInstallPath = extensionInstallPath; @@ -44,7 +51,7 @@ public void Initialize(string unityVersion, NPath extensionInstallPath, NPath un UnityVersion = unityVersion; } - public void InitializeRepository(ICacheContainer cacheContainer, NPath expectedRepositoryPath = null) + public void InitializeRepository(NPath expectedRepositoryPath = null) { Guard.NotNull(this, FileSystem, nameof(FileSystem)); diff --git a/src/GitHub.Api/Platform/IEnvironment.cs b/src/GitHub.Api/Platform/IEnvironment.cs index ddc534fe8..1c42158ad 100644 --- a/src/GitHub.Api/Platform/IEnvironment.cs +++ b/src/GitHub.Api/Platform/IEnvironment.cs @@ -5,7 +5,7 @@ namespace GitHub.Unity public interface IEnvironment { void Initialize(string unityVersion, NPath extensionInstallPath, NPath unityPath, NPath assetsPath); - void InitializeRepository(ICacheContainer cacheContainer, NPath expectedRepositoryPath = null); + void InitializeRepository(NPath expectedRepositoryPath = null); string ExpandEnvironmentVariables(string name); string GetEnvironmentVariable(string v); string GetSpecialFolder(Environment.SpecialFolder folder); diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs index ae1f2dbc2..36974fb8d 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs @@ -67,7 +67,7 @@ public IEnvironment Environment { if (environment == null) { - environment = new DefaultEnvironment(); + environment = new DefaultEnvironment(new CacheContainer()); if (unityApplication == null) { unityAssetsPath = Application.dataPath; @@ -77,7 +77,7 @@ public IEnvironment Environment } environment.Initialize(unityVersion, extensionInstallPath.ToNPath(), unityApplication.ToNPath(), unityAssetsPath.ToNPath()); - environment.InitializeRepository(EntryPoint.ApplicationManager.CacheContainer, !String.IsNullOrEmpty(repositoryPath) + environment.InitializeRepository(!String.IsNullOrEmpty(repositoryPath) ? repositoryPath.ToNPath() : null); Flush(); diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationManager.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationManager.cs index 5b15205e7..cb3a46c6a 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationManager.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationManager.cs @@ -19,7 +19,6 @@ public ApplicationManager(IMainThreadSynchronizationContext synchronizationConte { ListenToUnityExit(); Initialize(); - CacheContainer = new CacheContainer(); } protected override void SetupMetrics() diff --git a/src/tests/IntegrationTests/BaseGitEnvironmentTest.cs b/src/tests/IntegrationTests/BaseGitEnvironmentTest.cs index ee3b98dc4..892878acf 100644 --- a/src/tests/IntegrationTests/BaseGitEnvironmentTest.cs +++ b/src/tests/IntegrationTests/BaseGitEnvironmentTest.cs @@ -2,6 +2,7 @@ using System.Threading; using GitHub.Unity; using System.Threading.Tasks; +using NSubstitute; namespace IntegrationTests { @@ -14,7 +15,9 @@ protected async Task Initialize(NPath repoPath, NPath environmentP SyncContext = new ThreadSynchronizationContext(TaskManager.Token); TaskManager.UIScheduler = new SynchronizationContextTaskScheduler(SyncContext); - Environment = new IntegrationTestEnvironment(repoPath, SolutionDirectory, environmentPath, enableEnvironmentTrace); + //TODO: Mock CacheContainer + ICacheContainer cacheContainer = Substitute.For(); + Environment = new IntegrationTestEnvironment(cacheContainer, repoPath, SolutionDirectory, environmentPath, enableEnvironmentTrace); var gitSetup = new GitInstaller(Environment, TaskManager.Token); await gitSetup.SetupIfNeeded(); @@ -31,8 +34,6 @@ protected async Task Initialize(NPath repoPath, NPath environmentP RepositoryManager = GitHub.Unity.RepositoryManager.CreateInstance(Platform, TaskManager, GitClient, repoPath); RepositoryManager.Initialize(); - //TODO: Mock CacheContainer - ICacheContainer cacheContainer = null; Environment.Repository = new Repository(repoPath, cacheContainer); Environment.Repository.Initialize(RepositoryManager); diff --git a/src/tests/IntegrationTests/Git/IntegrationTestEnvironment.cs b/src/tests/IntegrationTests/Git/IntegrationTestEnvironment.cs index bd790f28d..62158eac2 100644 --- a/src/tests/IntegrationTests/Git/IntegrationTestEnvironment.cs +++ b/src/tests/IntegrationTests/Git/IntegrationTestEnvironment.cs @@ -12,10 +12,10 @@ class IntegrationTestEnvironment : IEnvironment private DefaultEnvironment defaultEnvironment; - public IntegrationTestEnvironment(NPath repoPath, NPath solutionDirectory, NPath environmentPath = null, + public IntegrationTestEnvironment(ICacheContainer cacheContainer, NPath repoPath, NPath solutionDirectory, NPath environmentPath = null, bool enableTrace = false) { - defaultEnvironment = new DefaultEnvironment(); + defaultEnvironment = new DefaultEnvironment(cacheContainer); defaultEnvironment.FileSystem.SetCurrentDirectory(repoPath); environmentPath = environmentPath ?? defaultEnvironment.GetSpecialFolder(Environment.SpecialFolder.LocalApplicationData) @@ -28,10 +28,8 @@ public IntegrationTestEnvironment(NPath repoPath, NPath solutionDirectory, NPath var installPath = solutionDirectory.Parent.Parent.Combine("src", "GitHub.Api"); - //TODO: Mock CacheContainer - ICacheContainer cacheContainer = null; Initialize(UnityVersion, installPath, solutionDirectory, repoPath.Combine("Assets")); - InitializeRepository(cacheContainer); + InitializeRepository(); this.enableTrace = enableTrace; @@ -47,9 +45,9 @@ public void Initialize(string unityVersion, NPath extensionInstallPath, NPath un defaultEnvironment.Initialize(unityVersion, extensionInstallPath, unityPath, assetsPath); } - public void InitializeRepository(ICacheContainer cacheContainer, NPath expectedPath = null) + public void InitializeRepository(NPath expectedPath = null) { - defaultEnvironment.InitializeRepository(cacheContainer, expectedPath); + defaultEnvironment.InitializeRepository(expectedPath); } public string ExpandEnvironmentVariables(string name) From 58cb0521896e3223312715526e6a180678422dc1 Mon Sep 17 00:00:00 2001 From: Andreia Gaita Date: Wed, 1 Nov 2017 21:09:00 -0700 Subject: [PATCH 183/241] AuthenticationView can handle its own message logic --- .../GitHub.Unity/UI/AuthenticationView.cs | 47 ++++++++----------- .../Editor/GitHub.Unity/UI/PopupWindow.cs | 37 +-------------- 2 files changed, 21 insertions(+), 63 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/AuthenticationView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/AuthenticationView.cs index 0bb15fb25..467ab768b 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/AuthenticationView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/AuthenticationView.cs @@ -9,6 +9,8 @@ class AuthenticationView : Subview { private static readonly Vector2 viewSize = new Vector2(290, 290); + private const string CredentialsNeedRefreshMessage = "We've detected that your stored credentials are out of sync with your current user. This can happen if you have signed in to git outside of Unity. Sign in again to refresh your credentials."; + private const string NeedAuthenticationMessage = "We need you to authenticate first"; private const string WindowTitle = "Authenticate"; private const string UsernameLabel = "Username"; private const string PasswordLabel = "Password"; @@ -41,14 +43,25 @@ public override void InitializeView(IView parent) Size = viewSize; } - public override void OnEnable() + public void Initialize(Exception exception) { - base.OnEnable(); - } + var usernameMismatchException = exception as TokenUsernameMismatchException; + if (usernameMismatchException != null) + { + message = CredentialsNeedRefreshMessage; + username = usernameMismatchException.CachedUsername; + } - public override void OnDisable() - { - base.OnDisable(); + var keychainEmptyException = exception as KeychainEmptyException; + if (keychainEmptyException != null) + { + message = NeedAuthenticationMessage; + } + + if (usernameMismatchException == null && keychainEmptyException == null) + { + message = exception.Message; + } } public override void OnGUI() @@ -81,27 +94,7 @@ public override void OnGUI() } GUILayout.EndScrollView(); } - - public void SetMessage(string value) - { - message = value; - } - - public void ClearMessage() - { - message = null; - } - - public void SetUsername(string value) - { - username = value; - } - - public void ClearUsername() - { - username = string.Empty; - } - + private void HandleEnterPressed() { if (Event.current.type != EventType.KeyDown) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PopupWindow.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PopupWindow.cs index 80a626517..86a62cb75 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PopupWindow.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PopupWindow.cs @@ -7,9 +7,6 @@ namespace GitHub.Unity [Serializable] class PopupWindow : BaseWindow { - private const string CredentialsNeedRefreshMessage = "We've detected that your stored credentials are out of sync with your current user. This can happen if you have signed in to git outside of Unity. Sign in again to refresh your credentials."; - private const string NeedAuthenticationMessage = "We need you to authenticate first"; - public enum PopupViewType { None, @@ -63,32 +60,8 @@ private void Open(PopupViewType popupViewType, Action onClose) }, exception => { Logger.Trace("User required validation opening AuthenticationView"); - - string message = null; - string username = null; - - var usernameMismatchException = exception as TokenUsernameMismatchException; - if (usernameMismatchException != null) - { - message = CredentialsNeedRefreshMessage; - username = usernameMismatchException.CachedUsername; - } - - var keychainEmptyException = exception as KeychainEmptyException; - if (keychainEmptyException != null) - { - message = NeedAuthenticationMessage; - } - - if (usernameMismatchException == null && keychainEmptyException == null) - { - message = exception.Message; - } - + authenticationView.Initialize(exception); OpenInternal(PopupViewType.AuthenticationView, completedAuthentication => { - authenticationView.ClearMessage(); - authenticationView.ClearUsername(); - if (completedAuthentication) { Logger.Trace("User completed validation opening view: {0}", popupViewType.ToString()); @@ -98,11 +71,6 @@ private void Open(PopupViewType popupViewType, Action onClose) }); shouldCloseOnFinish = false; - authenticationView.SetMessage(message); - if (username != null) - { - authenticationView.SetUsername(username); - } }); } else @@ -120,10 +88,7 @@ private void OpenInternal(PopupViewType popupViewType, Action onClose) } ActiveViewType = popupViewType; - titleContent = new GUIContent(ActiveView.Title, Styles.SmallLogo); - OnEnable(); Show(); - Refresh(); } public IApiClient Client From 3709d5220b6ff8503f8e83850b95f864b0d63f03 Mon Sep 17 00:00:00 2001 From: Andreia Gaita Date: Wed, 1 Nov 2017 21:35:32 -0700 Subject: [PATCH 184/241] Resetting the UI when going back or finishing --- .../GitHub.Unity/UI/AuthenticationView.cs | 21 +++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/AuthenticationView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/AuthenticationView.cs index 467ab768b..c7795c05a 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/AuthenticationView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/AuthenticationView.cs @@ -26,10 +26,10 @@ class AuthenticationView : Subview [SerializeField] private string username = string.Empty; [SerializeField] private string two2fa = string.Empty; [SerializeField] private string message; + [SerializeField] private string errorMessage; + [SerializeField] private bool need2fa; - [NonSerialized] private bool need2fa; [NonSerialized] private bool isBusy; - [NonSerialized] private string errorMessage; [NonSerialized] private bool enterPressed; [NonSerialized] private string password = string.Empty; [NonSerialized] private AuthenticationService authenticationService; @@ -39,6 +39,7 @@ public override void InitializeView(IView parent) { base.InitializeView(parent); need2fa = isBusy = false; + message = errorMessage = null; Title = WindowTitle; Size = viewSize; } @@ -167,8 +168,7 @@ private void OnGUI2FA() if (GUILayout.Button(BackButton)) { GUI.FocusControl(null); - need2fa = false; - Redraw(); + Clear(); } if (GUILayout.Button(TwofaButton) || (!isBusy && enterPressed)) @@ -189,7 +189,7 @@ private void OnGUI2FA() private void DoRequire2fa(string msg) { - Logger.Trace("Strating 2FA - Message:\"{0}\"", msg); + Logger.Trace("Starting 2FA - Message:\"{0}\"", msg); need2fa = true; errorMessage = msg; @@ -197,19 +197,28 @@ private void DoRequire2fa(string msg) Redraw(); } + private void Clear() + { + need2fa = false; + errorMessage = null; + isBusy = false; + Redraw(); + } + private void DoResult(bool success, string msg) { Logger.Trace("DoResult - Success:{0} Message:\"{1}\"", success, msg); - errorMessage = msg; isBusy = false; if (success == true) { + Clear(); Finish(true); } else { + errorMessage = msg; Redraw(); } } From 18c19dfaa549b196d15b2b66760ff44b5ca8350e Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 2 Nov 2017 12:18:55 -0400 Subject: [PATCH 185/241] Adding events to repository that better represent the values that are changing --- src/GitHub.Api/Git/IRepository.cs | 28 ++-- src/GitHub.Api/Git/Repository.cs | 156 ++++++++++++------ .../Editor/GitHub.Unity/UI/BranchesView.cs | 22 +-- .../Editor/GitHub.Unity/UI/ChangesView.cs | 44 ++--- .../Editor/GitHub.Unity/UI/HistoryView.cs | 70 ++++---- .../GitHub.Unity/UI/ProjectWindowInterface.cs | 47 +++--- .../Editor/GitHub.Unity/UI/SettingsView.cs | 48 +++--- .../Assets/Editor/GitHub.Unity/UI/Window.cs | 21 ++- 8 files changed, 245 insertions(+), 191 deletions(-) diff --git a/src/GitHub.Api/Git/IRepository.cs b/src/GitHub.Api/Git/IRepository.cs index 8ce200ad2..7e2d279fa 100644 --- a/src/GitHub.Api/Git/IRepository.cs +++ b/src/GitHub.Api/Git/IRepository.cs @@ -19,11 +19,15 @@ public interface IRepository : IEquatable ITask RequestLock(string file); ITask ReleaseLock(string file, bool force); - void CheckRepositoryInfoCacheEvent(CacheUpdateEvent cacheUpdateEvent); - void CheckBranchCacheEvent(CacheUpdateEvent cacheUpdateEvent); - void CheckGitStatusCacheEvent(CacheUpdateEvent cacheUpdateEvent); - void CheckGitLogCacheEvent(CacheUpdateEvent cacheUpdateEvent); - void CheckGitLocksCacheEvent(CacheUpdateEvent cacheUpdateEvent); + void CheckLogChangedEvent(CacheUpdateEvent gitLogCacheUpdateEvent); + void CheckStatusChangedEvent(CacheUpdateEvent cacheUpdateEvent); + void CheckCurrentBranchChangedEvent(CacheUpdateEvent cacheUpdateEvent); + void CheckCurrentRemoteChangedEvent(CacheUpdateEvent cacheUpdateEvent); + void CheckCurrentBranchAndRemoteChangedEvent(CacheUpdateEvent cacheUpdateEvent); + void CheckLocalBranchListChangedEvent(CacheUpdateEvent cacheUpdateEvent); + void CheckLocksChangedEvent(CacheUpdateEvent cacheUpdateEvent); + void CheckRemoteBranchListChangedEvent(CacheUpdateEvent cacheUpdateEvent); + void CheckLocalAndRemoteBranchListChangedEvent(CacheUpdateEvent cacheUpdateEvent); /// /// Gets the name of the repository. @@ -62,10 +66,14 @@ public interface IRepository : IEquatable string CurrentBranchName { get; } List CurrentLog { get; } - event Action GitStatusCacheUpdated; - event Action GitLogCacheUpdated; - event Action GitLockCacheUpdated; - event Action BranchCacheUpdated; - event Action RepositoryInfoCacheUpdated; + event Action LogChanged; + event Action StatusChanged; + event Action CurrentBranchChanged; + event Action CurrentRemoteChanged; + event Action CurrentBranchAndRemoteChanged; + event Action LocalBranchListChanged; + event Action LocksChanged; + event Action RemoteBranchListChanged; + event Action LocalAndRemoteBranchListChanged; } } \ No newline at end of file diff --git a/src/GitHub.Api/Git/Repository.cs b/src/GitHub.Api/Git/Repository.cs index 35c5861c7..78e6ea7ee 100644 --- a/src/GitHub.Api/Git/Repository.cs +++ b/src/GitHub.Api/Git/Repository.cs @@ -15,12 +15,6 @@ class Repository : IEquatable, IRepository private UriString cloneUrl; private string name; - public event Action GitStatusCacheUpdated; - public event Action GitLogCacheUpdated; - public event Action GitLockCacheUpdated; - public event Action BranchCacheUpdated; - public event Action RepositoryInfoCacheUpdated; - /// /// Initializes a new instance of the class. /// @@ -64,29 +58,30 @@ private void CacheContainer_OnCacheInvalidated(CacheType cacheType) private void CacheContainer_OnCacheUpdated(CacheType cacheType, DateTimeOffset offset) { + var cacheUpdateEvent = new CacheUpdateEvent { UpdatedTimeString = offset.ToString() }; switch (cacheType) { case CacheType.BranchCache: - FireBranchCacheUpdated(offset); + HandleBranchCacheUpdatedEvent(cacheUpdateEvent); break; case CacheType.GitLogCache: - FireGitLogCacheUpdated(offset); + HandleGitLogCacheUpdatedEvent(cacheUpdateEvent); break; case CacheType.GitStatusCache: - FireGitStatusCacheUpdated(offset); + HandleGitStatucCacheUpdatedEvent(cacheUpdateEvent); break; case CacheType.GitLocksCache: - FireGitLocksCacheUpdated(offset); + HandleGitLocksCacheUpdatedEvent(cacheUpdateEvent); break; case CacheType.GitUserCache: break; case CacheType.RepositoryInfoCache: - FireRepositoryInfoCacheUpdated(offset); + HandleRepositoryInfoCacheUpdatedEvent(cacheUpdateEvent); break; default: @@ -94,34 +89,38 @@ private void CacheContainer_OnCacheUpdated(CacheType cacheType, DateTimeOffset o } } - private void FireGitLogCacheUpdated(DateTimeOffset dateTimeOffset) + private void HandleRepositoryInfoCacheUpdatedEvent(CacheUpdateEvent cacheUpdateEvent) { - Logger.Trace("GitLogCacheUpdated {0}", dateTimeOffset); - GitLogCacheUpdated?.Invoke(new CacheUpdateEvent { UpdatedTimeString = dateTimeOffset.ToString() }); + Logger.Trace("RepositoryInfoCache Updated {0}", cacheUpdateEvent.UpdatedTimeString); + CurrentBranchChanged?.Invoke(cacheUpdateEvent); + CurrentRemoteChanged?.Invoke(cacheUpdateEvent); + CurrentBranchAndRemoteChanged?.Invoke(cacheUpdateEvent); } - private void FireBranchCacheUpdated(DateTimeOffset dateTimeOffset) + private void HandleGitLocksCacheUpdatedEvent(CacheUpdateEvent cacheUpdateEvent) { - Logger.Trace("BranchCacheUpdated {0}", dateTimeOffset); - BranchCacheUpdated?.Invoke(new CacheUpdateEvent { UpdatedTimeString = dateTimeOffset.ToString() }); + Logger.Trace("GitLocksCache Updated {0}", cacheUpdateEvent.UpdatedTimeString); + LocksChanged?.Invoke(cacheUpdateEvent); } - private void FireGitStatusCacheUpdated(DateTimeOffset dateTimeOffset) + private void HandleGitStatucCacheUpdatedEvent(CacheUpdateEvent cacheUpdateEvent) { - Logger.Trace("GitStatusCacheUpdated {0}", dateTimeOffset); - GitStatusCacheUpdated?.Invoke(new CacheUpdateEvent { UpdatedTimeString = dateTimeOffset.ToString() }); + Logger.Trace("GitStatusCache Updated {0}", cacheUpdateEvent.UpdatedTimeString); + StatusChanged?.Invoke(cacheUpdateEvent); } - private void FireGitLocksCacheUpdated(DateTimeOffset dateTimeOffset) + private void HandleGitLogCacheUpdatedEvent(CacheUpdateEvent cacheUpdateEvent) { - Logger.Trace("GitStatusCacheUpdated {0}", dateTimeOffset); - GitLockCacheUpdated?.Invoke(new CacheUpdateEvent { UpdatedTimeString = dateTimeOffset.ToString() }); + Logger.Trace("GitLogCache Updated {0}", cacheUpdateEvent.UpdatedTimeString); + LogChanged?.Invoke(cacheUpdateEvent); } - private void FireRepositoryInfoCacheUpdated(DateTimeOffset dateTimeOffset) + private void HandleBranchCacheUpdatedEvent(CacheUpdateEvent cacheUpdateEvent) { - Logger.Trace("RepositoryInfoCacheUpdated {0}", dateTimeOffset); - RepositoryInfoCacheUpdated?.Invoke(new CacheUpdateEvent { UpdatedTimeString = dateTimeOffset.ToString() }); + Logger.Trace("BranchCache Updated {0}", cacheUpdateEvent.UpdatedTimeString); + LocalBranchListChanged?.Invoke(cacheUpdateEvent); + RemoteBranchListChanged?.Invoke(cacheUpdateEvent); + LocalAndRemoteBranchListChanged?.Invoke(cacheUpdateEvent); } public void Initialize(IRepositoryManager initRepositoryManager) @@ -202,73 +201,116 @@ public ITask ReleaseLock(string file, bool force) return repositoryManager.UnlockFile(file, force).Then(UpdateLocks); } - public void CheckRepositoryInfoCacheEvent(CacheUpdateEvent cacheUpdateEvent) + public void CheckLogChangedEvent(CacheUpdateEvent cacheUpdateEvent) { - var managedCache = cacheContainer.RepositoryInfoCache; - var raiseEvent = ShouldRaiseCacheEvent(cacheUpdateEvent, managedCache); + CacheUpdateEvent cacheUpdateEvent1 = cacheUpdateEvent; + var managedCache = cacheContainer.GitLogCache; + var raiseEvent = ShouldRaiseCacheEvent(cacheUpdateEvent1, managedCache); - Logger.Trace("CheckRepositoryInfoCacheEvent Current:{0} Check:{1} Result:{2}", managedCache.LastUpdatedAt, - cacheUpdateEvent.UpdatedTimeString ?? "[NULL]", raiseEvent); + Logger.Trace("CheckGitLogCacheEvent Current:{0} Check:{1} Result:{2}", managedCache.LastUpdatedAt, + cacheUpdateEvent1.UpdatedTimeString ?? "[NULL]", raiseEvent); if (raiseEvent) { - FireBranchCacheUpdated(managedCache.LastUpdatedAt); + var dateTimeOffset = managedCache.LastUpdatedAt; + var updateEvent = new CacheUpdateEvent { UpdatedTimeString = dateTimeOffset.ToString() }; + HandleGitLogCacheUpdatedEvent(updateEvent); } } - public void CheckBranchCacheEvent(CacheUpdateEvent cacheUpdateEvent) + public void CheckStatusChangedEvent(CacheUpdateEvent cacheUpdateEvent) { - var managedCache = cacheContainer.BranchCache; - var raiseEvent = ShouldRaiseCacheEvent(cacheUpdateEvent, managedCache); + CacheUpdateEvent cacheUpdateEvent1 = cacheUpdateEvent; + var managedCache = cacheContainer.GitStatusCache; + var raiseEvent = ShouldRaiseCacheEvent(cacheUpdateEvent1, managedCache); - Logger.Trace("CheckBranchCacheEvent Current:{0} Check:{1} Result:{2}", managedCache.LastUpdatedAt, - cacheUpdateEvent.UpdatedTimeString ?? "[NULL]", raiseEvent); + Logger.Trace("CheckGitStatusCacheEvent Current:{0} Check:{1} Result:{2}", managedCache.LastUpdatedAt, + cacheUpdateEvent1.UpdatedTimeString ?? "[NULL]", raiseEvent); if (raiseEvent) { - FireBranchCacheUpdated(managedCache.LastUpdatedAt); + var dateTimeOffset = managedCache.LastUpdatedAt; + var updateEvent = new CacheUpdateEvent { UpdatedTimeString = dateTimeOffset.ToString() }; + HandleGitStatucCacheUpdatedEvent(updateEvent); } } - public void CheckGitStatusCacheEvent(CacheUpdateEvent cacheUpdateEvent) + public void CheckCurrentBranchChangedEvent(CacheUpdateEvent cacheUpdateEvent) { - var managedCache = cacheContainer.GitStatusCache; + CheckRepositoryInfoCacheEvent(cacheUpdateEvent); + } + + public void CheckCurrentRemoteChangedEvent(CacheUpdateEvent cacheUpdateEvent) + { + CheckRepositoryInfoCacheEvent(cacheUpdateEvent); + } + + public void CheckCurrentBranchAndRemoteChangedEvent(CacheUpdateEvent cacheUpdateEvent) + { + CheckRepositoryInfoCacheEvent(cacheUpdateEvent); + } + + private void CheckRepositoryInfoCacheEvent(CacheUpdateEvent cacheUpdateEvent) + { + var managedCache = cacheContainer.RepositoryInfoCache; var raiseEvent = ShouldRaiseCacheEvent(cacheUpdateEvent, managedCache); - Logger.Trace("CheckGitStatusCacheEvent Current:{0} Check:{1} Result:{2}", managedCache.LastUpdatedAt, + Logger.Trace("CheckRepositoryInfoCacheEvent Current:{0} Check:{1} Result:{2}", managedCache.LastUpdatedAt, cacheUpdateEvent.UpdatedTimeString ?? "[NULL]", raiseEvent); if (raiseEvent) { - FireGitStatusCacheUpdated(managedCache.LastUpdatedAt); + var dateTimeOffset = managedCache.LastUpdatedAt; + var updateEvent = new CacheUpdateEvent { UpdatedTimeString = dateTimeOffset.ToString() }; + HandleRepositoryInfoCacheUpdatedEvent(updateEvent); } } - public void CheckGitLogCacheEvent(CacheUpdateEvent cacheUpdateEvent) + public void CheckLocksChangedEvent(CacheUpdateEvent cacheUpdateEvent) { - var managedCache = cacheContainer.GitLogCache; - var raiseEvent = ShouldRaiseCacheEvent(cacheUpdateEvent, managedCache); + CacheUpdateEvent cacheUpdateEvent1 = cacheUpdateEvent; + var managedCache = cacheContainer.GitLocksCache; + var raiseEvent = ShouldRaiseCacheEvent(cacheUpdateEvent1, managedCache); - Logger.Trace("CheckGitLogCacheEvent Current:{0} Check:{1} Result:{2}", managedCache.LastUpdatedAt, - cacheUpdateEvent.UpdatedTimeString ?? "[NULL]", raiseEvent); + Logger.Trace("CheckGitLocksCacheEvent Current:{0} Check:{1} Result:{2}", managedCache.LastUpdatedAt, + cacheUpdateEvent1.UpdatedTimeString ?? "[NULL]", raiseEvent); if (raiseEvent) { - FireGitLogCacheUpdated(managedCache.LastUpdatedAt); + var dateTimeOffset = managedCache.LastUpdatedAt; + var updateEvent = new CacheUpdateEvent { UpdatedTimeString = dateTimeOffset.ToString() }; + HandleGitLocksCacheUpdatedEvent(updateEvent); } } - public void CheckGitLocksCacheEvent(CacheUpdateEvent cacheUpdateEvent) + public void CheckLocalBranchListChangedEvent(CacheUpdateEvent cacheUpdateEvent) { - var managedCache = cacheContainer.GitLocksCache; + CheckBranchCacheEvent(cacheUpdateEvent); + } + + public void CheckRemoteBranchListChangedEvent(CacheUpdateEvent cacheUpdateEvent) + { + CheckBranchCacheEvent(cacheUpdateEvent); + } + + public void CheckLocalAndRemoteBranchListChangedEvent(CacheUpdateEvent cacheUpdateEvent) + { + CheckBranchCacheEvent(cacheUpdateEvent); + } + + private void CheckBranchCacheEvent(CacheUpdateEvent cacheUpdateEvent) + { + var managedCache = cacheContainer.BranchCache; var raiseEvent = ShouldRaiseCacheEvent(cacheUpdateEvent, managedCache); - Logger.Trace("CheckGitLocksCacheEvent Current:{0} Check:{1} Result:{2}", managedCache.LastUpdatedAt, + Logger.Trace("CheckBranchCacheEvent Current:{0} Check:{1} Result:{2}", managedCache.LastUpdatedAt, cacheUpdateEvent.UpdatedTimeString ?? "[NULL]", raiseEvent); if (raiseEvent) { - FireGitLogCacheUpdated(managedCache.LastUpdatedAt); + var dateTimeOffset = managedCache.LastUpdatedAt; + var updateEvent = new CacheUpdateEvent { UpdatedTimeString = dateTimeOffset.ToString() }; + HandleBranchCacheUpdatedEvent(updateEvent); } } @@ -523,6 +565,16 @@ public List CurrentLog set { cacheContainer.GitLogCache.Log = value; } } + public event Action LogChanged; + public event Action StatusChanged; + public event Action CurrentBranchChanged; + public event Action CurrentRemoteChanged; + public event Action CurrentBranchAndRemoteChanged; + public event Action LocalBranchListChanged; + public event Action LocksChanged; + public event Action RemoteBranchListChanged; + public event Action LocalAndRemoteBranchListChanged; + public List CurrentLocks { get { return cacheContainer.GitLocksCache.GitLocks; } diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs index e05d61b62..614238f86 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs @@ -48,8 +48,8 @@ class BranchesView : Subview [SerializeField] private Vector2 scroll; [SerializeField] private BranchTreeNode selectedNode; - [SerializeField] private CacheUpdateEvent branchUpdateEvent; - [NonSerialized] private bool branchCacheHasUpdate; + [SerializeField] private CacheUpdateEvent lastLocalAndRemoteBranchListChangedEvent; + [NonSerialized] private bool localAndRemoteBranchListHasUpdate; [SerializeField] private GitBranch[] localBranches; [SerializeField] private GitBranch[] remoteBranches; @@ -60,14 +60,14 @@ public override void InitializeView(IView parent) targetMode = mode; } - private void Repository_BranchCacheUpdated(CacheUpdateEvent cacheUpdateEvent) + private void RepositoryOnLocalAndRemoteBranchListChanged(CacheUpdateEvent cacheUpdateEvent) { - if (!branchUpdateEvent.Equals(cacheUpdateEvent)) + if (!lastLocalAndRemoteBranchListChangedEvent.Equals(cacheUpdateEvent)) { new ActionTask(TaskManager.Token, () => { - branchUpdateEvent = cacheUpdateEvent; - branchCacheHasUpdate = true; + lastLocalAndRemoteBranchListChangedEvent = cacheUpdateEvent; + localAndRemoteBranchListHasUpdate = true; Redraw(); }) { Affinity = TaskAffinity.UI }.Start(); @@ -81,7 +81,7 @@ public override void OnEnable() if (Repository != null) { - Repository.CheckBranchCacheEvent(branchUpdateEvent); + Repository.CheckLocalAndRemoteBranchListChangedEvent(lastLocalAndRemoteBranchListChangedEvent); } } @@ -99,9 +99,9 @@ public override void OnDataUpdate() private void MaybeUpdateData() { - if (branchCacheHasUpdate) + if (localAndRemoteBranchListHasUpdate) { - branchCacheHasUpdate = false; + localAndRemoteBranchListHasUpdate = false; localBranches = Repository.LocalBranches.ToArray(); remoteBranches = Repository.RemoteBranches.ToArray(); @@ -116,7 +116,7 @@ private void AttachHandlers(IRepository repository) if (repository == null) return; - repository.BranchCacheUpdated += Repository_BranchCacheUpdated; + repository.LocalAndRemoteBranchListChanged += RepositoryOnLocalAndRemoteBranchListChanged; } private void DetachHandlers(IRepository repository) @@ -124,7 +124,7 @@ private void DetachHandlers(IRepository repository) if (repository == null) return; - repository.BranchCacheUpdated -= Repository_BranchCacheUpdated; + repository.LocalAndRemoteBranchListChanged -= RepositoryOnLocalAndRemoteBranchListChanged; } public override void OnGUI() diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ChangesView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ChangesView.cs index 3f9b2f7f2..823acf93a 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ChangesView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ChangesView.cs @@ -25,11 +25,11 @@ class ChangesView : Subview [SerializeField] private Vector2 horizontalScroll; [SerializeField] private ChangesetTreeView tree = new ChangesetTreeView(); - [SerializeField] private CacheUpdateEvent branchUpdateEvent; - [NonSerialized] private bool branchCacheHasUpdate; + [SerializeField] private CacheUpdateEvent lastCurrentBranchChangedEvent; + [NonSerialized] private bool currentBranchHasUpdate; - [SerializeField] private CacheUpdateEvent gitStatusUpdateEvent; - [NonSerialized] private bool gitStatusCacheHasUpdate; + [SerializeField] private CacheUpdateEvent lastStatusChangedEvent; + [NonSerialized] private bool currentStatusHasUpdate; public override void InitializeView(IView parent) { @@ -37,28 +37,28 @@ public override void InitializeView(IView parent) tree.InitializeView(this); } - private void Repository_GitStatusCacheUpdated(CacheUpdateEvent cacheUpdateEvent) + private void RepositoryOnStatusChanged(CacheUpdateEvent cacheUpdateEvent) { - if (!gitStatusUpdateEvent.Equals(cacheUpdateEvent)) + if (!lastStatusChangedEvent.Equals(cacheUpdateEvent)) { new ActionTask(TaskManager.Token, () => { - gitStatusUpdateEvent = cacheUpdateEvent; - gitStatusCacheHasUpdate = true; + lastStatusChangedEvent = cacheUpdateEvent; + currentStatusHasUpdate = true; Redraw(); }) { Affinity = TaskAffinity.UI }.Start(); } } - private void Repository_BranchCacheUpdated(CacheUpdateEvent cacheUpdateEvent) + private void RepositoryOnCurrentBranchChanged(CacheUpdateEvent cacheUpdateEvent) { - if (!branchUpdateEvent.Equals(cacheUpdateEvent)) + if (!lastCurrentBranchChangedEvent.Equals(cacheUpdateEvent)) { new ActionTask(TaskManager.Token, () => { - branchUpdateEvent = cacheUpdateEvent; - branchCacheHasUpdate = true; + lastCurrentBranchChangedEvent = cacheUpdateEvent; + currentBranchHasUpdate = true; Redraw(); }) { Affinity = TaskAffinity.UI }.Start(); @@ -70,8 +70,8 @@ private void AttachHandlers(IRepository repository) if (repository == null) return; - repository.BranchCacheUpdated += Repository_BranchCacheUpdated; - repository.GitStatusCacheUpdated += Repository_GitStatusCacheUpdated; + repository.CurrentBranchChanged += RepositoryOnCurrentBranchChanged; + repository.StatusChanged += RepositoryOnStatusChanged; } private void DetachHandlers(IRepository repository) @@ -79,8 +79,8 @@ private void DetachHandlers(IRepository repository) if (repository == null) return; - repository.BranchCacheUpdated -= Repository_BranchCacheUpdated; - repository.GitStatusCacheUpdated -= Repository_GitStatusCacheUpdated; + repository.CurrentBranchChanged -= RepositoryOnCurrentBranchChanged; + repository.StatusChanged -= RepositoryOnStatusChanged; } public override void OnEnable() @@ -90,8 +90,8 @@ public override void OnEnable() if (Repository != null) { - Repository.CheckBranchCacheEvent(branchUpdateEvent); - Repository.CheckGitStatusCacheEvent(gitStatusUpdateEvent); + Repository.CheckCurrentBranchChangedEvent(lastCurrentBranchChangedEvent); + Repository.CheckStatusChangedEvent(lastStatusChangedEvent); } } @@ -110,15 +110,15 @@ public override void OnDataUpdate() private void MaybeUpdateData() { - if (branchCacheHasUpdate) + if (currentBranchHasUpdate) { - branchCacheHasUpdate = false; + currentBranchHasUpdate = false; currentBranch = string.Format("[{0}]", Repository.CurrentBranchName); } - if (gitStatusCacheHasUpdate) + if (currentStatusHasUpdate) { - gitStatusCacheHasUpdate = false; + currentStatusHasUpdate = false; var gitStatus = Repository.CurrentStatus; tree.UpdateEntries(gitStatus.Entries.Where(x => x.Status != GitFileStatus.Ignored).ToList()); } diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/HistoryView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/HistoryView.cs index c08046f16..6c2488c8e 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/HistoryView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/HistoryView.cs @@ -51,14 +51,14 @@ class HistoryView : Subview [SerializeField] private bool hasRemote; [SerializeField] private bool hasItemsToCommit; - [SerializeField] private CacheUpdateEvent repositoryInfoUpdateEvent; - [NonSerialized] private bool repositoryInfoHasUpdate; + [SerializeField] private CacheUpdateEvent lastCurrentRemoteChangedEvent; + [NonSerialized] private bool currentRemoteHasUpdate; - [SerializeField] private CacheUpdateEvent gitStatusUpdateEvent; - [NonSerialized] private bool gitStatusCacheHasUpdate; + [SerializeField] private CacheUpdateEvent lastStatusChangedEvent; + [NonSerialized] private bool currentStatusHasUpdate; - [SerializeField] private CacheUpdateEvent gitLogCacheUpdateEvent; - [NonSerialized] private bool gitLogCacheHasUpdate; + [SerializeField] private CacheUpdateEvent lastLogChangedEvent; + [NonSerialized] private bool currentLogHasUpdate; public override void InitializeView(IView parent) { @@ -77,9 +77,9 @@ public override void OnEnable() if (Repository != null) { - Repository.CheckGitLogCacheEvent(gitLogCacheUpdateEvent); - Repository.CheckGitStatusCacheEvent(gitStatusUpdateEvent); - Repository.CheckRepositoryInfoCacheEvent(repositoryInfoUpdateEvent); + Repository.CheckLogChangedEvent(lastLogChangedEvent); + Repository.CheckStatusChangedEvent(lastStatusChangedEvent); + Repository.CheckCurrentRemoteChangedEvent(lastCurrentRemoteChangedEvent); } } @@ -100,42 +100,42 @@ public override void OnGUI() OnEmbeddedGUI(); } - private void Repository_GitStatusCacheUpdated(CacheUpdateEvent cacheUpdateEvent) + private void RepositoryOnStatusChanged(CacheUpdateEvent cacheUpdateEvent) { - if (!gitStatusUpdateEvent.Equals(cacheUpdateEvent)) + if (!lastStatusChangedEvent.Equals(cacheUpdateEvent)) { new ActionTask(TaskManager.Token, () => { - gitStatusUpdateEvent = cacheUpdateEvent; - gitStatusCacheHasUpdate = true; + lastStatusChangedEvent = cacheUpdateEvent; + currentStatusHasUpdate = true; Redraw(); }) { Affinity = TaskAffinity.UI }.Start(); } } - private void Repository_GitLogCacheUpdated(CacheUpdateEvent cacheUpdateEvent) + private void RepositoryOnLogChanged(CacheUpdateEvent cacheUpdateEvent) { - if (!gitLogCacheUpdateEvent.Equals(cacheUpdateEvent)) + if (!lastLogChangedEvent.Equals(cacheUpdateEvent)) { new ActionTask(TaskManager.Token, () => { - gitLogCacheUpdateEvent = cacheUpdateEvent; - gitLogCacheHasUpdate = true; + lastLogChangedEvent = cacheUpdateEvent; + currentLogHasUpdate = true; Redraw(); }) { Affinity = TaskAffinity.UI }.Start(); } } - private void Repository_RepositoryInfoCacheUpdated(CacheUpdateEvent cacheUpdateEvent) + private void RepositoryOnCurrentRemoteChanged(CacheUpdateEvent cacheUpdateEvent) { - if (!repositoryInfoUpdateEvent.Equals(cacheUpdateEvent)) + if (!lastCurrentRemoteChangedEvent.Equals(cacheUpdateEvent)) { new ActionTask(TaskManager.Token, () => { - repositoryInfoUpdateEvent = cacheUpdateEvent; - repositoryInfoHasUpdate = true; + lastCurrentRemoteChangedEvent = cacheUpdateEvent; + currentRemoteHasUpdate = true; Redraw(); }) { Affinity = TaskAffinity.UI }.Start(); @@ -147,9 +147,9 @@ private void AttachHandlers(IRepository repository) if (repository == null) return; - repository.GitStatusCacheUpdated += Repository_GitStatusCacheUpdated; - repository.GitLogCacheUpdated += Repository_GitLogCacheUpdated; - repository.RepositoryInfoCacheUpdated += Repository_RepositoryInfoCacheUpdated; + repository.StatusChanged += RepositoryOnStatusChanged; + repository.LogChanged += RepositoryOnLogChanged; + repository.CurrentRemoteChanged += RepositoryOnCurrentRemoteChanged; } private void DetachHandlers(IRepository repository) @@ -157,9 +157,9 @@ private void DetachHandlers(IRepository repository) if (repository == null) return; - repository.GitStatusCacheUpdated -= Repository_GitStatusCacheUpdated; - repository.GitLogCacheUpdated -= Repository_GitLogCacheUpdated; - repository.RepositoryInfoCacheUpdated -= Repository_RepositoryInfoCacheUpdated; + repository.StatusChanged -= RepositoryOnStatusChanged; + repository.LogChanged -= RepositoryOnLogChanged; + repository.CurrentRemoteChanged -= RepositoryOnCurrentRemoteChanged; } private void MaybeUpdateData() @@ -167,18 +167,18 @@ private void MaybeUpdateData() if (Repository == null) return; - if (repositoryInfoHasUpdate) + if (currentRemoteHasUpdate) { - repositoryInfoHasUpdate = false; + currentRemoteHasUpdate = false; var currentRemote = Repository.CurrentRemote; hasRemote = currentRemote.HasValue; currentRemoteName = hasRemote ? currentRemote.Value.Name : "placeholder"; } - if (gitStatusCacheHasUpdate) + if (currentStatusHasUpdate) { - gitStatusCacheHasUpdate = false; + currentStatusHasUpdate = false; var currentStatus = Repository.CurrentStatus; statusAhead = currentStatus.Ahead; @@ -187,9 +187,9 @@ private void MaybeUpdateData() currentStatus.GetEntriesExcludingIgnoredAndUntracked().Any(); } - if (gitLogCacheHasUpdate) + if (currentLogHasUpdate) { - gitLogCacheHasUpdate = false; + currentLogHasUpdate = false; history = Repository.CurrentLog; @@ -308,7 +308,7 @@ public void OnEmbeddedGUI() // Only update time scroll var lastScroll = scroll; scroll = GUILayout.BeginScrollView(scroll); - if (lastScroll != scroll && !gitLogCacheHasUpdate) + if (lastScroll != scroll && !currentLogHasUpdate) { scrollTime = history[historyStartIndex].Time; scrollOffset = scroll.y - historyStartIndex * EntryHeight; @@ -414,7 +414,7 @@ public void OnEmbeddedGUI() if (Event.current.type == EventType.Repaint) { CullHistory(); - gitLogCacheHasUpdate = false; + currentLogHasUpdate = false; if (newSelectionIndex >= 0 || newSelectionIndex == -2) { diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ProjectWindowInterface.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ProjectWindowInterface.cs index 90e877ac1..ec838d6ee 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ProjectWindowInterface.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ProjectWindowInterface.cs @@ -19,8 +19,8 @@ class ProjectWindowInterface : AssetPostprocessor private static bool isBusy = false; private static ILogging logger; private static ILogging Logger { get { return logger = logger ?? Logging.GetLogger(); } } - private static CacheUpdateEvent gitStatusUpdateEvent; - private static CacheUpdateEvent gitLocksUpdateEvent; + private static CacheUpdateEvent lastRepositoryStatusChangedEvent; + private static CacheUpdateEvent lastLocksChangedEvent; public static void Initialize(IRepository repo) { @@ -33,35 +33,38 @@ public static void Initialize(IRepository repo) if (repository != null) { - repository.GitLockCacheUpdated += Repository_GitLockCacheUpdated; - repository.GitStatusCacheUpdated += Repository_GitStatusCacheUpdated; + repository.StatusChanged += RepositoryOnStatusChanged; + repository.LocksChanged += RepositoryOnLocksChanged; - repository.CheckGitStatusCacheEvent(gitStatusUpdateEvent); - repository.CheckGitLocksCacheEvent(gitLocksUpdateEvent); + repository.CheckStatusChangedEvent(lastRepositoryStatusChangedEvent); + repository.CheckLocksChangedEvent(lastLocksChangedEvent); } } - private static void Repository_GitStatusCacheUpdated(CacheUpdateEvent cacheUpdateEvent) + private static void RepositoryOnStatusChanged(CacheUpdateEvent cacheUpdateEvent) { - if (!gitStatusUpdateEvent.Equals(cacheUpdateEvent)) + if (!lastRepositoryStatusChangedEvent.Equals(cacheUpdateEvent)) { new ActionTask(CancellationToken.None, () => { - gitStatusUpdateEvent = cacheUpdateEvent; - OnStatusUpdate(repository.CurrentStatus); + lastRepositoryStatusChangedEvent = cacheUpdateEvent; + entries.Clear(); + entries.AddRange(repository.CurrentStatus.Entries); + OnStatusUpdate(); }) { Affinity = TaskAffinity.UI }.Start(); } } - private static void Repository_GitLockCacheUpdated(CacheUpdateEvent cacheUpdateEvent) + private static void RepositoryOnLocksChanged(CacheUpdateEvent cacheUpdateEvent) { - if (!gitLocksUpdateEvent.Equals(cacheUpdateEvent)) + if (!lastLocksChangedEvent.Equals(cacheUpdateEvent)) { new ActionTask(CancellationToken.None, () => { - gitLocksUpdateEvent = cacheUpdateEvent; - OnLocksUpdate(repository.CurrentLocks); + lastLocksChangedEvent = cacheUpdateEvent; + locks = repository.CurrentLocks; + OnLocksUpdate(); }) { Affinity = TaskAffinity.UI }.Start(); } @@ -158,13 +161,13 @@ private static void ContextMenu_Unlock() .Start(); } - private static void OnLocksUpdate(IEnumerable update) + private static void OnLocksUpdate() { - if (update == null) + if (locks == null) { return; } - locks = update.ToList(); + locks = locks.ToList(); guidsLocks.Clear(); foreach (var lck in locks) @@ -179,16 +182,8 @@ private static void OnLocksUpdate(IEnumerable update) EditorApplication.RepaintProjectWindow(); } - private static void OnStatusUpdate(GitStatus update) + private static void OnStatusUpdate() { - if (update.Entries == null) - { - return; - } - - entries.Clear(); - entries.AddRange(update.Entries); - guids.Clear(); for (var index = 0; index < entries.Count; ++index) { diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/SettingsView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/SettingsView.cs index 74befadb1..5223dab24 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/SettingsView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/SettingsView.cs @@ -38,11 +38,11 @@ class SettingsView : Subview [SerializeField] private GitPathView gitPathView = new GitPathView(); [SerializeField] private UserSettingsView userSettingsView = new UserSettingsView(); - [SerializeField] private CacheUpdateEvent branchUpdateEvent; - [NonSerialized] private bool branchCacheHasUpdate; + [SerializeField] private CacheUpdateEvent lastCurrentRemoteChangedEvent; + [NonSerialized] private bool currentRemoteHasUpdate; - [SerializeField] private CacheUpdateEvent gitLocksUpdateEvent; - [NonSerialized] private bool gitLocksCacheHasUpdate; + [SerializeField] private CacheUpdateEvent lastLocksChangedEvent; + [NonSerialized] private bool currentLocksHasUpdate; public override void InitializeView(IView parent) { @@ -60,8 +60,8 @@ public override void OnEnable() if (Repository != null) { - Repository.CheckBranchCacheEvent(branchUpdateEvent); - Repository.CheckGitLocksCacheEvent(gitLocksUpdateEvent); + Repository.CheckCurrentRemoteChangedEvent(lastCurrentRemoteChangedEvent); + Repository.CheckLocksChangedEvent(lastLocksChangedEvent); } metricsHasChanged = true; @@ -103,32 +103,32 @@ private void AttachHandlers(IRepository repository) if (repository == null) return; - repository.BranchCacheUpdated += Repository_BranchCacheUpdated; - repository.GitLockCacheUpdated += Repository_GitLockCacheUpdated; + repository.CurrentRemoteChanged += RepositoryOnCurrentRemoteChanged; + repository.LocksChanged += RepositoryOnLocksChanged; } - private void Repository_GitLockCacheUpdated(CacheUpdateEvent cacheUpdateEvent) + private void RepositoryOnLocksChanged(CacheUpdateEvent cacheUpdateEvent) { - if (!gitLocksUpdateEvent.Equals(cacheUpdateEvent)) + if (!lastLocksChangedEvent.Equals(cacheUpdateEvent)) { new ActionTask(TaskManager.Token, () => { - gitLocksUpdateEvent = cacheUpdateEvent; - gitLocksCacheHasUpdate = true; + lastLocksChangedEvent = cacheUpdateEvent; + currentLocksHasUpdate = true; Redraw(); }) { Affinity = TaskAffinity.UI }.Start(); } } - private void Repository_BranchCacheUpdated(CacheUpdateEvent cacheUpdateEvent) + private void RepositoryOnCurrentRemoteChanged(CacheUpdateEvent cacheUpdateEvent) { - if (!branchUpdateEvent.Equals(cacheUpdateEvent)) + if (!lastCurrentRemoteChangedEvent.Equals(cacheUpdateEvent)) { new ActionTask(TaskManager.Token, () => { - branchUpdateEvent = cacheUpdateEvent; - branchCacheHasUpdate = true; + lastCurrentRemoteChangedEvent = cacheUpdateEvent; + currentRemoteHasUpdate = true; Redraw(); }) { Affinity = TaskAffinity.UI }.Start(); @@ -182,11 +182,11 @@ private void MaybeUpdateData() if (Repository == null) return; - if (branchCacheHasUpdate) + if (currentRemoteHasUpdate) { - branchCacheHasUpdate = false; - var activeRemote = Repository.CurrentRemote; - hasRemote = activeRemote.HasValue && !String.IsNullOrEmpty(activeRemote.Value.Url); + currentRemoteHasUpdate = false; + var currentRemote = Repository.CurrentRemote; + hasRemote = currentRemote.HasValue && !String.IsNullOrEmpty(currentRemote.Value.Url); if (!hasRemote) { repositoryRemoteName = DefaultRepositoryRemoteName; @@ -194,14 +194,14 @@ private void MaybeUpdateData() } else { - repositoryRemoteName = activeRemote.Value.Name; - newRepositoryRemoteUrl = repositoryRemoteUrl = activeRemote.Value.Url; + repositoryRemoteName = currentRemote.Value.Name; + newRepositoryRemoteUrl = repositoryRemoteUrl = currentRemote.Value.Url; } } - if (gitLocksCacheHasUpdate) + if (currentLocksHasUpdate) { - gitLocksCacheHasUpdate = false; + currentLocksHasUpdate = false; var repositoryCurrentLocks = Repository.CurrentLocks; lockedFiles = repositoryCurrentLocks != null ? repositoryCurrentLocks.ToList() diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs index f47f60e29..a465beacc 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs @@ -37,8 +37,8 @@ class Window : BaseWindow [SerializeField] private GUIContent repoBranchContent; [SerializeField] private GUIContent repoUrlContent; - [SerializeField] private CacheUpdateEvent repositoryInfoUpdateEvent; - [NonSerialized] private bool repositoryInfoCacheHasUpdate; + [SerializeField] private CacheUpdateEvent lastCurrentBranchAndRemoteChangedEvent; + [NonSerialized] private bool currentBranchAndRemoteHasUpdate; [NonSerialized] private bool hasRunMaybeUpdateDataWithRepository; @@ -98,7 +98,7 @@ public override void OnEnable() titleContent = new GUIContent(Title, Styles.SmallLogo); if (Repository != null) - Repository.CheckRepositoryInfoCacheEvent(repositoryInfoUpdateEvent); + Repository.CheckCurrentBranchAndRemoteChangedEvent(lastCurrentBranchAndRemoteChangedEvent); if (ActiveView != null) ActiveView.OnEnable(); @@ -194,7 +194,7 @@ private void MaybeUpdateData() if (Repository != null) { - if(!hasRunMaybeUpdateDataWithRepository || repositoryInfoCacheHasUpdate) + if(!hasRunMaybeUpdateDataWithRepository || currentBranchAndRemoteHasUpdate) { hasRunMaybeUpdateDataWithRepository = true; @@ -270,17 +270,17 @@ private void AttachHandlers(IRepository repository) { if (repository == null) return; - repository.RepositoryInfoCacheUpdated += Repository_RepositoryInfoCacheUpdated; + repository.CurrentBranchAndRemoteChanged += RepositoryOnCurrentBranchAndRemoteChanged; } - private void Repository_RepositoryInfoCacheUpdated(CacheUpdateEvent cacheUpdateEvent) + private void RepositoryOnCurrentBranchAndRemoteChanged(CacheUpdateEvent cacheUpdateEvent) { - if (!repositoryInfoUpdateEvent.Equals(cacheUpdateEvent)) + if (!lastCurrentBranchAndRemoteChangedEvent.Equals(cacheUpdateEvent)) { new ActionTask(TaskManager.Token, () => { - repositoryInfoUpdateEvent = cacheUpdateEvent; - repositoryInfoCacheHasUpdate = true; + lastCurrentBranchAndRemoteChangedEvent = cacheUpdateEvent; + currentBranchAndRemoteHasUpdate = true; Redraw(); }) { Affinity = TaskAffinity.UI }.Start(); @@ -291,8 +291,7 @@ private void DetachHandlers(IRepository repository) { if (repository == null) return; - - repository.RepositoryInfoCacheUpdated -= Repository_RepositoryInfoCacheUpdated; + repository.CurrentBranchAndRemoteChanged -= RepositoryOnCurrentBranchAndRemoteChanged; } private void DoHeaderGUI() From 6af5853b8548cbf9d7f125fc201b1df2c829e940 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 2 Nov 2017 12:25:18 -0400 Subject: [PATCH 186/241] Updating log messages --- src/GitHub.Api/Git/Repository.cs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/GitHub.Api/Git/Repository.cs b/src/GitHub.Api/Git/Repository.cs index 78e6ea7ee..602b7b313 100644 --- a/src/GitHub.Api/Git/Repository.cs +++ b/src/GitHub.Api/Git/Repository.cs @@ -207,7 +207,7 @@ public void CheckLogChangedEvent(CacheUpdateEvent cacheUpdateEvent) var managedCache = cacheContainer.GitLogCache; var raiseEvent = ShouldRaiseCacheEvent(cacheUpdateEvent1, managedCache); - Logger.Trace("CheckGitLogCacheEvent Current:{0} Check:{1} Result:{2}", managedCache.LastUpdatedAt, + Logger.Trace("Check GitLogCache CacheUpdateEvent Current:{0} Check:{1} Result:{2}", managedCache.LastUpdatedAt, cacheUpdateEvent1.UpdatedTimeString ?? "[NULL]", raiseEvent); if (raiseEvent) @@ -224,7 +224,7 @@ public void CheckStatusChangedEvent(CacheUpdateEvent cacheUpdateEvent) var managedCache = cacheContainer.GitStatusCache; var raiseEvent = ShouldRaiseCacheEvent(cacheUpdateEvent1, managedCache); - Logger.Trace("CheckGitStatusCacheEvent Current:{0} Check:{1} Result:{2}", managedCache.LastUpdatedAt, + Logger.Trace("Check GitStatusCache CacheUpdateEvent Current:{0} Check:{1} Result:{2}", managedCache.LastUpdatedAt, cacheUpdateEvent1.UpdatedTimeString ?? "[NULL]", raiseEvent); if (raiseEvent) @@ -255,7 +255,7 @@ private void CheckRepositoryInfoCacheEvent(CacheUpdateEvent cacheUpdateEvent) var managedCache = cacheContainer.RepositoryInfoCache; var raiseEvent = ShouldRaiseCacheEvent(cacheUpdateEvent, managedCache); - Logger.Trace("CheckRepositoryInfoCacheEvent Current:{0} Check:{1} Result:{2}", managedCache.LastUpdatedAt, + Logger.Trace("Check RepositoryInfoCache CacheUpdateEvent Current:{0} Check:{1} Result:{2}", managedCache.LastUpdatedAt, cacheUpdateEvent.UpdatedTimeString ?? "[NULL]", raiseEvent); if (raiseEvent) @@ -272,7 +272,7 @@ public void CheckLocksChangedEvent(CacheUpdateEvent cacheUpdateEvent) var managedCache = cacheContainer.GitLocksCache; var raiseEvent = ShouldRaiseCacheEvent(cacheUpdateEvent1, managedCache); - Logger.Trace("CheckGitLocksCacheEvent Current:{0} Check:{1} Result:{2}", managedCache.LastUpdatedAt, + Logger.Trace("Check GitLocksCache CacheUpdateEvent Current:{0} Check:{1} Result:{2}", managedCache.LastUpdatedAt, cacheUpdateEvent1.UpdatedTimeString ?? "[NULL]", raiseEvent); if (raiseEvent) @@ -303,7 +303,7 @@ private void CheckBranchCacheEvent(CacheUpdateEvent cacheUpdateEvent) var managedCache = cacheContainer.BranchCache; var raiseEvent = ShouldRaiseCacheEvent(cacheUpdateEvent, managedCache); - Logger.Trace("CheckBranchCacheEvent Current:{0} Check:{1} Result:{2}", managedCache.LastUpdatedAt, + Logger.Trace("Check BranchCache CacheUpdateEvent Current:{0} Check:{1} Result:{2}", managedCache.LastUpdatedAt, cacheUpdateEvent.UpdatedTimeString ?? "[NULL]", raiseEvent); if (raiseEvent) From 742a1a345cfbdeb4d2b90e77d34fb00015315655 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 2 Nov 2017 12:40:34 -0400 Subject: [PATCH 187/241] Isolating cache access to properties --- src/GitHub.Api/Git/Repository.cs | 35 +++++++++++++++++++++++--------- 1 file changed, 25 insertions(+), 10 deletions(-) diff --git a/src/GitHub.Api/Git/Repository.cs b/src/GitHub.Api/Git/Repository.cs index 35c5861c7..885711824 100644 --- a/src/GitHub.Api/Git/Repository.cs +++ b/src/GitHub.Api/Git/Repository.cs @@ -389,11 +389,9 @@ private void RepositoryManager_OnRemoteBranchListUpdated(IDictionary x.Values).Select(GetRemoteGitBranch).ToArray(); + RemoteBranches = RemoteConfigBranches.Values.SelectMany(x => x.Values).Select(GetRemoteGitBranch).ToArray(); } private void RepositoryManager_OnLocalBranchListUpdated(IDictionary branches) @@ -406,8 +404,7 @@ private void RepositoryManager_OnLocalBranchListUpdated(IDictionary cacheContainer.BranchCache.Remotes; + private IRemoteConfigBranchDictionary RemoteConfigBranches => cacheContainer.BranchCache.RemoteConfigBranches; - public GitBranch[] LocalBranches => cacheContainer.BranchCache.LocalBranches; + private IConfigRemoteDictionary ConfigRemotes => cacheContainer.BranchCache.ConfigRemotes; - public GitBranch[] RemoteBranches => cacheContainer.BranchCache.RemoteBranches; + private ILocalConfigBranchDictionary LocalConfigBranches => cacheContainer.BranchCache.LocalConfigBranches; + + public GitRemote[] Remotes + { + get { return cacheContainer.BranchCache.Remotes; } + set { cacheContainer.BranchCache.Remotes = value; } + } + + public GitBranch[] LocalBranches + { + get { return cacheContainer.BranchCache.LocalBranches; } + set { cacheContainer.BranchCache.LocalBranches = value; } + } + + public GitBranch[] RemoteBranches + { + get { return cacheContainer.BranchCache.RemoteBranches; } + set { cacheContainer.BranchCache.RemoteBranches = value; } + } private ConfigBranch? CurrentConfigBranch { get { return this.cacheContainer.BranchCache.CurentConfigBranch; } - set { cacheContainer.BranchCache.CurentConfigBranch = value;} + set { cacheContainer.BranchCache.CurentConfigBranch = value; } } private ConfigRemote? CurrentConfigRemote From f0f57cb004cd4a96f909c408903a7d562efa52fb Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 2 Nov 2017 13:46:13 -0400 Subject: [PATCH 188/241] Removing OnRepositoryChanged --- .../Assets/Editor/GitHub.Unity/UI/HistoryView.cs | 5 ----- .../Assets/Editor/GitHub.Unity/UI/SettingsView.cs | 7 ------- .../Assets/Editor/GitHub.Unity/UI/Subview.cs | 3 --- src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs | 4 ---- 4 files changed, 19 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/HistoryView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/HistoryView.cs index b5760279e..dfdfef89e 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/HistoryView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/HistoryView.cs @@ -84,11 +84,6 @@ public override void OnDataUpdate() MaybeUpdateData(); } - public override void OnRepositoryChanged(IRepository oldRepository) - { - base.OnRepositoryChanged(oldRepository); - } - public override void OnSelectionChange() { diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/SettingsView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/SettingsView.cs index 0446adc08..0ea2240df 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/SettingsView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/SettingsView.cs @@ -77,13 +77,6 @@ public override void OnDataUpdate() MaybeUpdateData(); } - public override void OnRepositoryChanged(IRepository oldRepository) - { - base.OnRepositoryChanged(oldRepository); - gitPathView.OnRepositoryChanged(oldRepository); - userSettingsView.OnRepositoryChanged(oldRepository); - } - public override void Refresh() { base.Refresh(); diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Subview.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Subview.cs index 186a879a7..b6a4d84f7 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Subview.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Subview.cs @@ -48,9 +48,6 @@ public virtual void Finish(bool result) Parent.Finish(result); } - public virtual void OnRepositoryChanged(IRepository oldRepository) - {} - protected IView Parent { get; private set; } public IApplicationManager Manager { get { return Parent.Manager; } } public IRepository Repository { get { return Parent.Repository; } } diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs index f9a32fa25..c7e799cea 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs @@ -140,10 +140,6 @@ public override void OnRepositoryChanged(IRepository oldRepository) } UpdateActiveTab(); - - if (ActiveView != null) - ActiveView.OnRepositoryChanged(oldRepository); - UpdateLog(); } From 474dcc71a8d44a5d436320aacb225ebcb7581f9a Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 2 Nov 2017 15:13:25 -0400 Subject: [PATCH 189/241] Changing the title content when the view changes --- src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PopupWindow.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PopupWindow.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PopupWindow.cs index 86a62cb75..fb9df1cd9 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PopupWindow.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PopupWindow.cs @@ -88,6 +88,7 @@ private void OpenInternal(PopupViewType popupViewType, Action onClose) } ActiveViewType = popupViewType; + titleContent = new GUIContent(ActiveView.Title, Styles.SmallLogo); Show(); } From 16031fe2f55a7639be283a348207af4677d6d558 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 2 Nov 2017 15:48:46 -0400 Subject: [PATCH 190/241] Firing OnEnable when we switch the ActiveView --- src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PopupWindow.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PopupWindow.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PopupWindow.cs index fb9df1cd9..c682e0860 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PopupWindow.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PopupWindow.cs @@ -88,6 +88,7 @@ private void OpenInternal(PopupViewType popupViewType, Action onClose) } ActiveViewType = popupViewType; + ActiveView.OnEnable(); titleContent = new GUIContent(ActiveView.Title, Styles.SmallLogo); Show(); } From d0c64268dfd4a8b9aa80a82c98df523f61247599 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 2 Nov 2017 15:48:59 -0400 Subject: [PATCH 191/241] Calling Redraw when we switch the ActiveView --- src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PopupWindow.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PopupWindow.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PopupWindow.cs index c682e0860..68b32ff23 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PopupWindow.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PopupWindow.cs @@ -91,6 +91,7 @@ private void OpenInternal(PopupViewType popupViewType, Action onClose) ActiveView.OnEnable(); titleContent = new GUIContent(ActiveView.Title, Styles.SmallLogo); Show(); + Redraw(); } public IApiClient Client From 8c6cdfac35860e7ee9181767b53ca13aebe4892a Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 2 Nov 2017 15:53:05 -0400 Subject: [PATCH 192/241] Redraw after organizations are loaded --- src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs index 16c3aca36..0e95e4e73 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs @@ -117,6 +117,8 @@ private void LoadOwners() owners = new[] { OwnersDefaultText, username }.Union(publishOwners).ToArray(); isBusy = false; + + Redraw(); }, exception => { isBusy = false; From b108e06d1d4c482aef37a1e96ece7c504dfd05ca Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 2 Nov 2017 16:18:00 -0400 Subject: [PATCH 193/241] Changing the log output for KeychainEmptyException --- src/GitHub.Api/Application/ApiClient.cs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/GitHub.Api/Application/ApiClient.cs b/src/GitHub.Api/Application/ApiClient.cs index 83b6603a1..d456e35af 100644 --- a/src/GitHub.Api/Application/ApiClient.cs +++ b/src/GitHub.Api/Application/ApiClient.cs @@ -258,6 +258,11 @@ private async Task GetCurrentUserInternal() return (await githubClient.User.Current()).ToGitHubUser(); } + catch (KeychainEmptyException) + { + logger.Warning("Keychain is empty"); + throw; + } catch (Exception ex) { logger.Error(ex, "Error Getting Current User"); From 5e87e9a49f4a74ecc1c91289fb21d4a4ad84c832 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 2 Nov 2017 16:39:23 -0400 Subject: [PATCH 194/241] Removing unused code --- .../Editor/GitHub.Unity/UI/PublishView.cs | 23 ------------------- 1 file changed, 23 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs index 0e95e4e73..0c3cbad01 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs @@ -123,29 +123,6 @@ private void LoadOwners() { isBusy = false; - var tokenUsernameMismatchException = exception as TokenUsernameMismatchException; - if (tokenUsernameMismatchException != null) - { - Logger.Trace("Token Username Mismatch"); - - var shouldProceed = EditorUtility.DisplayDialog(AuthenticationChangedTitle, - string.Format(AuthenticationChangedMessageFormat, - tokenUsernameMismatchException.CachedUsername, - tokenUsernameMismatchException.CurrentUsername), AuthenticationChangedProceed, AuthenticationChangedLogout); - - if (shouldProceed) - { - //Proceed as current user - - } - else - { - //Logout current user and try again - - } - return; - } - var keychainEmptyException = exception as KeychainEmptyException; if (keychainEmptyException != null) { From 684659deb74f3db26293842663b9b3b1be3725eb Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 2 Nov 2017 16:40:43 -0400 Subject: [PATCH 195/241] Removing some unused constant strings --- .../Assets/Editor/GitHub.Unity/UI/PublishView.cs | 5 ----- 1 file changed, 5 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs index 0c3cbad01..99ab79516 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs @@ -12,7 +12,6 @@ class PublishView : Subview private static readonly Vector2 viewSize = new Vector2(400, 350); private const string WindowTitle = "Publish"; - private const string Header = "Publish this repository to GitHub"; private const string PrivateRepoMessage = "You choose who can see and commit to this repository"; private const string PublicRepoMessage = "Anyone can see this repository. You choose who can commit"; private const string PublishViewCreateButton = "Publish"; @@ -23,10 +22,6 @@ class PublishView : Subview private const string CreatePrivateRepositoryLabel = "Make repository private"; private const string PublishLimitPrivateRepositoriesError = "You are currently at your limit of private repositories"; private const string PublishToGithubLabel = "Publish to GitHub"; - private const string AuthenticationChangedMessageFormat = "You were authenticated as \"{0}\", but you are now authenticated as \"{1}\". Would you like to proceed or logout?"; - private const string AuthenticationChangedTitle = "Authentication Changed"; - private const string AuthenticationChangedProceed = "Proceed"; - private const string AuthenticationChangedLogout = "Logout"; [SerializeField] private string username; [SerializeField] private string[] owners = { OwnersDefaultText }; From 72f6432a848c2e7aec932dd77de1ef477bf48343 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 2 Nov 2017 16:47:34 -0400 Subject: [PATCH 196/241] Removing some unused references to favorites --- .../Assets/Editor/GitHub.Unity/UI/BranchesView.cs | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs index 1c2edfeb3..89a0577ea 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs @@ -36,11 +36,9 @@ class BranchesView : Subview [NonSerialized] private int listID = -1; [NonSerialized] private BranchesMode targetMode; - [NonSerialized] private List favoritesList; [SerializeField] private Tree treeLocals = new Tree(); [SerializeField] private Tree treeRemotes = new Tree(); - [SerializeField] private Tree treeFavorites = new Tree(); [SerializeField] private BranchesMode mode = BranchesMode.Default; [SerializeField] private string newBranchName; [SerializeField] private Vector2 scroll; From daed451099158811cf68b104effe15f3397c8eda Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 2 Nov 2017 16:48:19 -0400 Subject: [PATCH 197/241] Removing unused function parameters --- .../Assets/Editor/GitHub.Unity/UI/BranchesView.cs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs index 89a0577ea..9d37417a8 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs @@ -101,8 +101,7 @@ private void MaybeUpdateData() localBranches = Repository.LocalBranches.ToList(); remoteBranches = Repository.RemoteBranches.ToList(); - - BuildTree(localBranches, remoteBranches); + BuildTree(); } disableDelete = treeLocals.SelectedNode == null || treeLocals.SelectedNode.IsFolder || treeLocals.SelectedNode.IsActive; @@ -147,7 +146,7 @@ private void Render() GUILayout.EndScrollView(); } - private void BuildTree(List localBranches, List remoteBranches) + private void BuildTree() { localBranches.Sort(CompareBranches); remoteBranches.Sort(CompareBranches); From 2a6e2dd5ea7b36a39d06137b013e4b5d64b806b1 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 2 Nov 2017 16:55:47 -0400 Subject: [PATCH 198/241] Data hiding --- src/GitHub.Api/Git/GitBranch.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/GitHub.Api/Git/GitBranch.cs b/src/GitHub.Api/Git/GitBranch.cs index 733b845df..fb0297628 100644 --- a/src/GitHub.Api/Git/GitBranch.cs +++ b/src/GitHub.Api/Git/GitBranch.cs @@ -13,9 +13,9 @@ public struct GitBranch : ITreeData { public static GitBranch Default = new GitBranch(); - public string name; - public string tracking; - public bool isActive; + private string name; + private string tracking; + private bool isActive; public string Name { get { return name; } } public string Tracking { get { return tracking; } } From 18779df797680f73a855307bf05ffdcecc96da4f Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 2 Nov 2017 16:57:41 -0400 Subject: [PATCH 199/241] Following struct with Default pattern in GitRemote --- src/GitHub.Api/Git/GitRemote.cs | 58 +++++++++++++++++++++++++++++---- 1 file changed, 51 insertions(+), 7 deletions(-) diff --git a/src/GitHub.Api/Git/GitRemote.cs b/src/GitHub.Api/Git/GitRemote.cs index d5478d897..72e52e474 100644 --- a/src/GitHub.Api/Git/GitRemote.cs +++ b/src/GitHub.Api/Git/GitRemote.cs @@ -14,13 +14,57 @@ public enum GitRemoteFunction [Serializable] public struct GitRemote { - public string Name; - public string Url; - public string Login; - public string User; - public string Token; - public string Host; - public GitRemoteFunction Function; + public static GitRemote Default = new GitRemote(); + + private string name; + private string url; + private string login; + private string user; + private string host; + private GitRemoteFunction function; + + public string Name + { + get { return name; } + } + + public string Url + { + get { return url; } + } + + public string Login + { + get { return login; } + } + + public string User + { + get { return user; } + } + + public string Token { get; } + + public string Host + { + get { return host; } + } + + public GitRemoteFunction Function + { + get { return function; } + } + + public GitRemote(string name, string url, string login, string user, string token, string host, GitRemoteFunction function) + { + this.name = name; + this.url = url; + this.login = login; + this.user = user; + Token = token; + this.host = host; + this.function = function; + } public override string ToString() { From 9e7a370cacfb1a237cc8cc789d9633509b29f9ee Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 2 Nov 2017 16:57:50 -0400 Subject: [PATCH 200/241] Utilizing struct defaults --- .../Assets/Editor/GitHub.Unity/ApplicationCache.cs | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs index 36974fb8d..3f77f6a3a 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs @@ -415,9 +415,6 @@ public ConfigRemoteDictionary(IDictionary dictionary) [Location("cache/repoinfo.yaml", LocationAttribute.Location.LibraryFolder)] sealed class RepositoryInfoCache : ManagedCacheBase, IRepositoryInfoCache { - public static readonly GitRemote DefaultGitRemote = new GitRemote(); - public static readonly GitBranch DefaultGitBranch = new GitBranch(); - [SerializeField] private string lastUpdatedAtString = DateTimeOffset.MinValue.ToString(); [SerializeField] private string lastVerifiedAtString = DateTimeOffset.MinValue.ToString(); [SerializeField] private GitRemote gitRemote; @@ -428,7 +425,7 @@ public GitRemote? CurrentGitRemote get { ValidateData(); - return gitRemote.Equals(DefaultGitRemote) ? (GitRemote?)null : gitRemote; + return gitRemote.Equals(GitRemote.Default) ? (GitRemote?)null : gitRemote; } set { @@ -439,7 +436,7 @@ public GitRemote? CurrentGitRemote if (!Nullable.Equals(gitRemote, value)) { - gitRemote = value ?? DefaultGitRemote; + gitRemote = value ?? GitRemote.Default; isUpdated = true; } @@ -452,7 +449,7 @@ public GitBranch? CurentGitBranch get { ValidateData(); - return gitBranch.Equals(DefaultGitBranch) ? (GitBranch?)null : gitBranch; + return gitBranch.Equals(GitBranch.Default) ? (GitBranch?)null : gitBranch; } set { @@ -463,7 +460,7 @@ public GitBranch? CurentGitBranch if (!Nullable.Equals(gitBranch, value)) { - gitBranch = value ?? DefaultGitBranch; + gitBranch = value ?? GitBranch.Default; isUpdated = true; } From 30dd82224417194b6424de07e08af394bbf5eec3 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 2 Nov 2017 17:12:19 -0400 Subject: [PATCH 201/241] Fixing errors caused by the changes to GitRemote --- src/GitHub.Api/Git/GitRemote.cs | 19 +++++++++++++++++-- src/GitHub.Api/Git/Repository.cs | 2 +- .../RemoteListOutputProcessor.cs | 10 +--------- 3 files changed, 19 insertions(+), 12 deletions(-) diff --git a/src/GitHub.Api/Git/GitRemote.cs b/src/GitHub.Api/Git/GitRemote.cs index 72e52e474..11ab96807 100644 --- a/src/GitHub.Api/Git/GitRemote.cs +++ b/src/GitHub.Api/Git/GitRemote.cs @@ -22,6 +22,7 @@ public struct GitRemote private string user; private string host; private GitRemoteFunction function; + private readonly string token; public string Name { @@ -43,7 +44,10 @@ public string User get { return user; } } - public string Token { get; } + public string Token + { + get { return token; } + } public string Host { @@ -61,11 +65,22 @@ public GitRemote(string name, string url, string login, string user, string toke this.url = url; this.login = login; this.user = user; - Token = token; + this.token = token; this.host = host; this.function = function; } + public GitRemote(string name, string url) + { + this.name = name; + this.url = url; + login = null; + user = null; + token = null; + host = null; + function = GitRemoteFunction.Unknown; + } + public override string ToString() { var sb = new StringBuilder(); diff --git a/src/GitHub.Api/Git/Repository.cs b/src/GitHub.Api/Git/Repository.cs index 885711824..f81eb416b 100644 --- a/src/GitHub.Api/Git/Repository.cs +++ b/src/GitHub.Api/Git/Repository.cs @@ -473,7 +473,7 @@ private static GitBranch GetRemoteGitBranch(ConfigBranch x) private static GitRemote GetGitRemote(ConfigRemote configRemote) { - return new GitRemote { Name = configRemote.Name, Url = configRemote.Url }; + return new GitRemote(configRemote.Name, configRemote.Url); } private IRemoteConfigBranchDictionary RemoteConfigBranches => cacheContainer.BranchCache.RemoteConfigBranches; diff --git a/src/GitHub.Api/OutputProcessors/RemoteListOutputProcessor.cs b/src/GitHub.Api/OutputProcessors/RemoteListOutputProcessor.cs index dbb854cf7..9eb4d9d04 100644 --- a/src/GitHub.Api/OutputProcessors/RemoteListOutputProcessor.cs +++ b/src/GitHub.Api/OutputProcessors/RemoteListOutputProcessor.cs @@ -99,15 +99,7 @@ private void ReturnRemote() currentUrl = currentUrl.Substring(user.Length + 1); } - RaiseOnEntry(new GitRemote - { - Name = currentName, - Host = host, - Url = currentUrl, - User = user, - Function = remoteFunction - }); - + RaiseOnEntry(new GitRemote(currentName, currentUrl, null, user, null, host, remoteFunction)); Reset(); } From e372d137d2a04933cd68b42b58759442d8e162cd Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 2 Nov 2017 17:35:50 -0400 Subject: [PATCH 202/241] More fixes around GitRemote --- src/GitHub.Api/Git/GitRemote.cs | 26 ++++- .../RemoteListOutputProcessor.cs | 2 +- .../Events/RepositoryManagerTests.cs | 95 ++++--------------- .../Process/ProcessManagerIntegrationTests.cs | 8 +- .../IO/RemoteListOutputProcessorTests.cs | 76 +++++---------- 5 files changed, 69 insertions(+), 138 deletions(-) diff --git a/src/GitHub.Api/Git/GitRemote.cs b/src/GitHub.Api/Git/GitRemote.cs index 11ab96807..bc64c3be6 100644 --- a/src/GitHub.Api/Git/GitRemote.cs +++ b/src/GitHub.Api/Git/GitRemote.cs @@ -59,15 +59,37 @@ public GitRemoteFunction Function get { return function; } } - public GitRemote(string name, string url, string login, string user, string token, string host, GitRemoteFunction function) + public GitRemote(string name, string host, string url, GitRemoteFunction function, string user, string login, string token) { this.name = name; this.url = url; - this.login = login; + this.host = host; + this.function = function; this.user = user; + this.login = login; this.token = token; + } + + public GitRemote(string name, string host, string url, GitRemoteFunction function, string user) + { + this.name = name; + this.url = url; + this.host = host; + this.function = function; + this.user = user; + login = null; + token = null; + } + + public GitRemote(string name, string host, string url, GitRemoteFunction function) + { + this.name = name; + this.url = url; this.host = host; this.function = function; + this.user = null; + this.login = null; + this.token = null; } public GitRemote(string name, string url) diff --git a/src/GitHub.Api/OutputProcessors/RemoteListOutputProcessor.cs b/src/GitHub.Api/OutputProcessors/RemoteListOutputProcessor.cs index 9eb4d9d04..293ebf142 100644 --- a/src/GitHub.Api/OutputProcessors/RemoteListOutputProcessor.cs +++ b/src/GitHub.Api/OutputProcessors/RemoteListOutputProcessor.cs @@ -99,7 +99,7 @@ private void ReturnRemote() currentUrl = currentUrl.Substring(user.Length + 1); } - RaiseOnEntry(new GitRemote(currentName, currentUrl, null, user, null, host, remoteFunction)); + RaiseOnEntry(new GitRemote(currentName, host, currentUrl, remoteFunction, user, null, null)); Reset(); } diff --git a/src/tests/IntegrationTests/Events/RepositoryManagerTests.cs b/src/tests/IntegrationTests/Events/RepositoryManagerTests.cs index 30d8dfe02..9521d6198 100644 --- a/src/tests/IntegrationTests/Events/RepositoryManagerTests.cs +++ b/src/tests/IntegrationTests/Events/RepositoryManagerTests.cs @@ -51,11 +51,7 @@ public async Task ShouldDoNothingOnInitialize() new GitBranch("feature/document", "origin/feature/document", false), new GitBranch("feature/other-feature", "origin/feature/other-feature", false), }); - Repository.Remotes.Should().BeEquivalentTo(new GitRemote - { - Name = "origin", - Url = "https://github.com/EvilStanleyGoldman/IOTestsRepo.git" - }); + Repository.Remotes.Should().BeEquivalentTo(new GitRemote("origin", "https://github.com/EvilStanleyGoldman/IOTestsRepo.git")); Repository.RemoteBranches.Should().BeEquivalentTo(new[] { new GitBranch("origin/master", "[None]", false), new GitBranch("origin/feature/document-2", "[None]", false), @@ -330,10 +326,7 @@ public async Task ShouldDetectBranchChange() new GitBranch("feature/document", "origin/feature/document", true), new GitBranch("feature/other-feature", "origin/feature/other-feature", false), }); - Repository.Remotes.Should().BeEquivalentTo(new GitRemote { - Name = "origin", - Url = "https://github.com/EvilStanleyGoldman/IOTestsRepo.git" - }); + Repository.Remotes.Should().BeEquivalentTo(new GitRemote("origin", "https://github.com/EvilStanleyGoldman/IOTestsRepo.git")); Repository.RemoteBranches.Should().BeEquivalentTo(new[] { new GitBranch("origin/master", "[None]", false), new GitBranch("origin/feature/document-2", "[None]", false), @@ -383,11 +376,7 @@ public async Task ShouldDetectBranchDelete() new GitBranch("master", "origin/master", true), new GitBranch("feature/other-feature", "origin/feature/other-feature", false), }); - Repository.Remotes.Should().BeEquivalentTo(new GitRemote - { - Name = "origin", - Url = "https://github.com/EvilStanleyGoldman/IOTestsRepo.git" - }); + Repository.Remotes.Should().BeEquivalentTo(new GitRemote("origin","https://github.com/EvilStanleyGoldman/IOTestsRepo.git")); Repository.RemoteBranches.Should().BeEquivalentTo(new[] { new GitBranch("origin/master", "[None]", false), new GitBranch("origin/feature/document-2", "[None]", false), @@ -439,11 +428,7 @@ public async Task ShouldDetectBranchCreate() new GitBranch("feature/document2", "[None]", false), new GitBranch("feature/other-feature", "origin/feature/other-feature", false), }); - Repository.Remotes.Should().BeEquivalentTo(new GitRemote - { - Name = "origin", - Url = "https://github.com/EvilStanleyGoldman/IOTestsRepo.git" - }); + Repository.Remotes.Should().BeEquivalentTo(new GitRemote("origin","https://github.com/EvilStanleyGoldman/IOTestsRepo.git")); Repository.RemoteBranches.Should().BeEquivalentTo(new[] { new GitBranch("origin/master", "[None]", false), new GitBranch("origin/feature/document-2", "[None]", false), @@ -490,11 +475,7 @@ public async Task ShouldDetectBranchCreate() new GitBranch("feature2/document2", "[None]", false), new GitBranch("feature/other-feature", "origin/feature/other-feature", false), }); - Repository.Remotes.Should().BeEquivalentTo(new GitRemote - { - Name = "origin", - Url = "https://github.com/EvilStanleyGoldman/IOTestsRepo.git" - }); + Repository.Remotes.Should().BeEquivalentTo(new GitRemote("origin","https://github.com/EvilStanleyGoldman/IOTestsRepo.git")); Repository.RemoteBranches.Should().BeEquivalentTo(new[] { new GitBranch("origin/master", "[None]", false), new GitBranch("origin/feature/document-2", "[None]", false), @@ -531,11 +512,7 @@ public async Task ShouldDetectChangesToRemotes() new GitBranch("feature/document", "origin/feature/document", false), new GitBranch("feature/other-feature", "origin/feature/other-feature", false), }); - Repository.Remotes.Should().BeEquivalentTo(new GitRemote - { - Name = "origin", - Url = "https://github.com/EvilStanleyGoldman/IOTestsRepo.git" - }); + Repository.Remotes.Should().BeEquivalentTo(new GitRemote("origin","https://github.com/EvilStanleyGoldman/IOTestsRepo.git")); Repository.RemoteBranches.Should().BeEquivalentTo(new[] { new GitBranch("origin/master", "[None]", false), new GitBranch("origin/feature/document-2", "[None]", false), @@ -615,11 +592,7 @@ public async Task ShouldDetectChangesToRemotes() new GitBranch("feature/document", "[None]", false), new GitBranch("feature/other-feature", "[None]", false), }); - Repository.Remotes.Should().BeEquivalentTo(new GitRemote - { - Name = "origin", - Url = "https://github.com/EvilShana/IOTestsRepo.git" - }); + Repository.Remotes.Should().BeEquivalentTo(new GitRemote("origin","https://github.com/EvilShana/IOTestsRepo.git")); Repository.RemoteBranches.Should().BeEmpty(); } @@ -652,15 +625,9 @@ public async Task ShouldDetectChangesToRemotesWhenSwitchingBranches() new GitBranch("feature/document", "origin/feature/document", false), new GitBranch("feature/other-feature", "origin/feature/other-feature", false), }); - Repository.Remotes.Should().BeEquivalentTo(new GitRemote - { - Name = "origin", - Url = "https://github.com/EvilStanleyGoldman/IOTestsRepo.git" - }, new GitRemote - { - Name = "another", - Url = "https://another.remote/Owner/Url.git" - }); + Repository.Remotes.Should().BeEquivalentTo( + new GitRemote("origin","https://github.com/EvilStanleyGoldman/IOTestsRepo.git"), + new GitRemote("another","https://another.remote/Owner/Url.git")); Repository.RemoteBranches.Should().BeEquivalentTo(new[] { new GitBranch("origin/master", "[None]", false), new GitBranch("origin/feature/document-2", "[None]", false), @@ -707,15 +674,9 @@ await RepositoryManager.CreateBranch("branch2", "another/master") new GitBranch("feature/document", "origin/feature/document", false), new GitBranch("feature/other-feature", "origin/feature/other-feature", false), }); - Repository.Remotes.Should().BeEquivalentTo(new GitRemote - { - Name = "origin", - Url = "https://github.com/EvilStanleyGoldman/IOTestsRepo.git" - }, new GitRemote - { - Name = "another", - Url = "https://another.remote/Owner/Url.git" - }); + Repository.Remotes.Should().BeEquivalentTo( + new GitRemote("origin","https://github.com/EvilStanleyGoldman/IOTestsRepo.git"), + new GitRemote("another","https://another.remote/Owner/Url.git")); Repository.RemoteBranches.Should().BeEquivalentTo(new[] { new GitBranch("origin/master", "[None]", false), new GitBranch("origin/feature/document-2", "[None]", false), @@ -766,15 +727,9 @@ await RepositoryManager.SwitchBranch("branch2") new GitBranch("feature/document", "origin/feature/document", false), new GitBranch("feature/other-feature", "origin/feature/other-feature", false), }); - Repository.Remotes.Should().BeEquivalentTo(new GitRemote - { - Name = "origin", - Url = "https://github.com/EvilStanleyGoldman/IOTestsRepo.git" - }, new GitRemote - { - Name = "another", - Url = "https://another.remote/Owner/Url.git" - }); + Repository.Remotes.Should().BeEquivalentTo( + new GitRemote("origin","https://github.com/EvilStanleyGoldman/IOTestsRepo.git"), + new GitRemote("another","https://another.remote/Owner/Url.git")); Repository.RemoteBranches.Should().BeEquivalentTo(new[] { new GitBranch("origin/master", "[None]", false), new GitBranch("origin/feature/document-2", "[None]", false), @@ -840,11 +795,7 @@ public async Task ShouldDetectGitPull() new GitBranch("feature/document", "origin/feature/document", false), new GitBranch("feature/other-feature", "origin/feature/other-feature", false), }); - Repository.Remotes.Should().BeEquivalentTo(new GitRemote - { - Name = "origin", - Url = "https://github.com/EvilStanleyGoldman/IOTestsRepo.git" - }); + Repository.Remotes.Should().BeEquivalentTo(new GitRemote("origin","https://github.com/EvilStanleyGoldman/IOTestsRepo.git")); Repository.RemoteBranches.Should().BeEquivalentTo(new[] { new GitBranch("origin/master", "[None]", false), new GitBranch("origin/feature/document-2", "[None]", false), @@ -882,11 +833,7 @@ public async Task ShouldDetectGitFetch() Repository.LocalBranches.Should().BeEquivalentTo(new[] { new GitBranch("feature/document", "origin/feature/document", false), }); - Repository.Remotes.Should().BeEquivalentTo(new GitRemote - { - Name = "origin", - Url = "https://github.com/EvilStanleyGoldman/IOTestsRepo.git" - }); + Repository.Remotes.Should().BeEquivalentTo(new GitRemote("origin","https://github.com/EvilStanleyGoldman/IOTestsRepo.git")); Repository.RemoteBranches.Should().BeEquivalentTo(new[] { new GitBranch("origin/master", "[None]", false), new GitBranch("origin/feature/document", "[None]", false), @@ -925,11 +872,7 @@ public async Task ShouldDetectGitFetch() Repository.LocalBranches.Should().BeEquivalentTo(new[] { new GitBranch("feature/document", "origin/feature/document", false), }); - Repository.Remotes.Should().BeEquivalentTo(new GitRemote - { - Name = "origin", - Url = "https://github.com/EvilStanleyGoldman/IOTestsRepo.git" - }); + Repository.Remotes.Should().BeEquivalentTo(new GitRemote("origin","https://github.com/EvilStanleyGoldman/IOTestsRepo.git")); Repository.RemoteBranches.Should().BeEquivalentTo(new[] { new GitBranch("origin/master", "[None]", false), new GitBranch("origin/feature/document", "[None]", false), diff --git a/src/tests/IntegrationTests/Process/ProcessManagerIntegrationTests.cs b/src/tests/IntegrationTests/Process/ProcessManagerIntegrationTests.cs index 8766b3798..a4db8abb0 100644 --- a/src/tests/IntegrationTests/Process/ProcessManagerIntegrationTests.cs +++ b/src/tests/IntegrationTests/Process/ProcessManagerIntegrationTests.cs @@ -126,13 +126,7 @@ public async Task RemoteListTest() .GetGitRemoteEntries(TestRepoMasterCleanSynchronized) .StartAsAsync(); - gitRemotes.Should().BeEquivalentTo(new GitRemote() - { - Name = "origin", - Url = "https://github.com/EvilStanleyGoldman/IOTestsRepo.git", - Host = "github.com", - Function = GitRemoteFunction.Both - }); + gitRemotes.Should().BeEquivalentTo(new GitRemote("origin","https://github.com/EvilStanleyGoldman/IOTestsRepo.git","github.com",GitRemoteFunction.Both)); } [Test] diff --git a/src/tests/UnitTests/IO/RemoteListOutputProcessorTests.cs b/src/tests/UnitTests/IO/RemoteListOutputProcessorTests.cs index 5a2e4fb44..2cb3a14e1 100644 --- a/src/tests/UnitTests/IO/RemoteListOutputProcessorTests.cs +++ b/src/tests/UnitTests/IO/RemoteListOutputProcessorTests.cs @@ -18,15 +18,13 @@ public void ShouldParseSingleHttpsBothWaysRemote() null }; + var name = "origin"; + var host = "github.com"; + var url = "https://github.com/github/VisualStudio.git"; + var function = GitRemoteFunction.Both; AssertProcessOutput(output, new[] { - new GitRemote - { - Function = GitRemoteFunction.Both, - Name = "origin", - Host = "github.com", - Url = "https://github.com/github/VisualStudio.git", - } + new GitRemote(name, host, url, function) }); } @@ -39,15 +37,13 @@ public void ShouldParseSingleHttpsFetchOnlyRemote() null }; + var name = "origin"; + var function = GitRemoteFunction.Fetch; + var host = "github.com"; + var url = "https://github.com/github/VisualStudio.git"; AssertProcessOutput(output, new[] { - new GitRemote - { - Function = GitRemoteFunction.Fetch, - Name = "origin", - Host = "github.com", - Url = "https://github.com/github/VisualStudio.git", - } + new GitRemote(name, host, url, function) }); } @@ -60,15 +56,13 @@ public void ShouldParseSingleHttpsPushOnlyRemote() null }; + var name = "origin"; + var function = GitRemoteFunction.Fetch; + var host = "github.com"; + var url = "https://github.com/github/VisualStudio.git"; AssertProcessOutput(output, new[] { - new GitRemote - { - Function = GitRemoteFunction.Push, - Name = "origin", - Host = "github.com", - Url = "https://github.com/github/VisualStudio.git", - } + new GitRemote(name, host, url, function) }); } @@ -82,16 +76,14 @@ public void ShouldParseSingleSSHRemote() null }; + var function = GitRemoteFunction.Both; + var name = "origin"; + var host = "github.com"; + var url = "github.com:StanleyGoldman/VisualStudio.git"; + var user = "git"; AssertProcessOutput(output, new[] { - new GitRemote - { - Function = GitRemoteFunction.Both, - Name = "origin", - Host = "github.com", - Url = "github.com:StanleyGoldman/VisualStudio.git", - User = "git" - }, + new GitRemote(name, host, url, function, user) }); } @@ -110,29 +102,9 @@ public void ShouldParseMultipleRemotes() AssertProcessOutput(output, new[] { - new GitRemote - { - Function = GitRemoteFunction.Both, - Name = "origin", - Host = "github.com", - Url = "https://github.com/github/VisualStudio.git", - }, - new GitRemote - { - Function = GitRemoteFunction.Both, - Name = "stanleygoldman", - Host = "github.com", - Url = "github.com:StanleyGoldman/VisualStudio.git", - User = "git" - }, - new GitRemote - { - Function = GitRemoteFunction.Fetch, - Name = "fetchOnly", - Host = "github.com", - Url = "github.com:StanleyGoldman/VisualStudio2.git", - User = "git" - }, + new GitRemote("origin", "github.com", "https://github.com/github/VisualStudio.git", GitRemoteFunction.Both), + new GitRemote("stanleygoldman", "github.com", "github.com:StanleyGoldman/VisualStudio.git", GitRemoteFunction.Both, "https://github.com/github/VisualStudio.git"), + new GitRemote("fetchOnly", "github.com", "github.com:StanleyGoldman/VisualStudio2.git", GitRemoteFunction.Fetch,"git") }); } From 33f6e9fd7c09e537a01f15d3c59a546b59623261 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 2 Nov 2017 17:44:31 -0400 Subject: [PATCH 203/241] Fixing unit tests --- src/tests/UnitTests/IO/RemoteListOutputProcessorTests.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/tests/UnitTests/IO/RemoteListOutputProcessorTests.cs b/src/tests/UnitTests/IO/RemoteListOutputProcessorTests.cs index 2cb3a14e1..1d3b015a6 100644 --- a/src/tests/UnitTests/IO/RemoteListOutputProcessorTests.cs +++ b/src/tests/UnitTests/IO/RemoteListOutputProcessorTests.cs @@ -57,7 +57,7 @@ public void ShouldParseSingleHttpsPushOnlyRemote() }; var name = "origin"; - var function = GitRemoteFunction.Fetch; + var function = GitRemoteFunction.Push; var host = "github.com"; var url = "https://github.com/github/VisualStudio.git"; AssertProcessOutput(output, new[] @@ -103,7 +103,7 @@ public void ShouldParseMultipleRemotes() AssertProcessOutput(output, new[] { new GitRemote("origin", "github.com", "https://github.com/github/VisualStudio.git", GitRemoteFunction.Both), - new GitRemote("stanleygoldman", "github.com", "github.com:StanleyGoldman/VisualStudio.git", GitRemoteFunction.Both, "https://github.com/github/VisualStudio.git"), + new GitRemote("stanleygoldman", "github.com", "github.com:StanleyGoldman/VisualStudio.git", GitRemoteFunction.Both, "git"), new GitRemote("fetchOnly", "github.com", "github.com:StanleyGoldman/VisualStudio2.git", GitRemoteFunction.Fetch,"git") }); } From d402c55b69815a8cd98e2380e580ea06b99ca087 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 2 Nov 2017 17:51:16 -0400 Subject: [PATCH 204/241] Update to Git LFS 2.3.4 --- src/GitHub.Api/Helpers/Constants.cs | 2 +- src/GitHub.Api/Installer/GitInstaller.cs | 4 ++-- src/GitHub.Api/PlatformResources/mac/git-lfs.zip | 4 ++-- src/GitHub.Api/PlatformResources/windows/git-lfs.zip | 4 ++-- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/GitHub.Api/Helpers/Constants.cs b/src/GitHub.Api/Helpers/Constants.cs index d89de8360..1f3fbe702 100644 --- a/src/GitHub.Api/Helpers/Constants.cs +++ b/src/GitHub.Api/Helpers/Constants.cs @@ -11,6 +11,6 @@ static class Constants public const string TraceLoggingKey = "EnableTraceLogging"; public static readonly Version MinimumGitVersion = new Version(2, 11, 0); - public static readonly Version MinimumGitLfsVersion = new Version(2, 2, 0); + public static readonly Version MinimumGitLfsVersion = new Version(2, 3, 4); } } \ No newline at end of file diff --git a/src/GitHub.Api/Installer/GitInstaller.cs b/src/GitHub.Api/Installer/GitInstaller.cs index ee18a262e..f54765298 100644 --- a/src/GitHub.Api/Installer/GitInstaller.cs +++ b/src/GitHub.Api/Installer/GitInstaller.cs @@ -6,8 +6,8 @@ namespace GitHub.Unity { class GitInstaller : IGitInstaller { - public const string WindowsGitLfsExecutableMD5 = "ef51379a06577bcdeef372d297d6cd7f"; - public const string MacGitLfsExecutableMD5 = "2b324cbfbb9196cf6a3c0a0918c434c7"; + public const string WindowsGitLfsExecutableMD5 = "177bb14d0c08f665a24f0d5516c3b080"; + public const string MacGitLfsExecutableMD5 = "f81a1a065a26a4123193e8fd96c561ad"; private const string PortableGitExpectedVersion = "f02737a78695063deace08e96d5042710d3e32db"; private const string PackageName = "PortableGit"; diff --git a/src/GitHub.Api/PlatformResources/mac/git-lfs.zip b/src/GitHub.Api/PlatformResources/mac/git-lfs.zip index 1ef246ea3..3932710f3 100644 --- a/src/GitHub.Api/PlatformResources/mac/git-lfs.zip +++ b/src/GitHub.Api/PlatformResources/mac/git-lfs.zip @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:8b30e08751549f70f052eda49e0e2875ce006c98d013a17c46943b830f22e867 -size 2780647 +oid sha256:5bde4722bdbb24ec6651aa2ab559bfa6e85d31ee9e4195c81f6d6fa7548cacc6 +size 2905910 diff --git a/src/GitHub.Api/PlatformResources/windows/git-lfs.zip b/src/GitHub.Api/PlatformResources/windows/git-lfs.zip index 82a637cce..5a56712a7 100644 --- a/src/GitHub.Api/PlatformResources/windows/git-lfs.zip +++ b/src/GitHub.Api/PlatformResources/windows/git-lfs.zip @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:64b2e9186ff553f2e4afe4db38b21d27e3dde08f3347ff8ea88c667dfcefb92f -size 2807324 +oid sha256:6a4699fe6028a3727d76b218a10a7e9c6276f097b8ebd782f2e7b3418dacda07 +size 2652291 From 5888025dc521a718a4256ee480d46076eba38347 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 2 Nov 2017 17:55:06 -0400 Subject: [PATCH 205/241] Updating unit test --- src/tests/IntegrationTests/GitClientTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tests/IntegrationTests/GitClientTests.cs b/src/tests/IntegrationTests/GitClientTests.cs index 3f40aa892..8acc3e70a 100644 --- a/src/tests/IntegrationTests/GitClientTests.cs +++ b/src/tests/IntegrationTests/GitClientTests.cs @@ -39,7 +39,7 @@ public async Task ShouldGetGitLfsVersion() var versionResult = version.Result; if (Environment.IsWindows) { - versionResult.Should().Be(new Version(2, 3, 0)); + versionResult.Should().Be(new Version(2, 3, 4)); } else { From 01736cb9ee935ddab330f6ac61a9a43fd1eecc2a Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 2 Nov 2017 17:56:58 -0400 Subject: [PATCH 206/241] Fixing unit test --- .../IntegrationTests/Process/ProcessManagerIntegrationTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tests/IntegrationTests/Process/ProcessManagerIntegrationTests.cs b/src/tests/IntegrationTests/Process/ProcessManagerIntegrationTests.cs index a4db8abb0..f1f6b77bb 100644 --- a/src/tests/IntegrationTests/Process/ProcessManagerIntegrationTests.cs +++ b/src/tests/IntegrationTests/Process/ProcessManagerIntegrationTests.cs @@ -126,7 +126,7 @@ public async Task RemoteListTest() .GetGitRemoteEntries(TestRepoMasterCleanSynchronized) .StartAsAsync(); - gitRemotes.Should().BeEquivalentTo(new GitRemote("origin","https://github.com/EvilStanleyGoldman/IOTestsRepo.git","github.com",GitRemoteFunction.Both)); + gitRemotes.Should().BeEquivalentTo(new GitRemote("origin", "github.com", "https://github.com/EvilStanleyGoldman/IOTestsRepo.git", GitRemoteFunction.Both)); } [Test] From 59b5a23733c5b1d6ec6ed16a1ec50d6c731ce05f Mon Sep 17 00:00:00 2001 From: Andreia Gaita Date: Thu, 2 Nov 2017 15:44:54 -0700 Subject: [PATCH 207/241] Ooops we should be looking at the 64 bit location for the Unity dlls too --- common/properties.props | 1 + 1 file changed, 1 insertion(+) diff --git a/common/properties.props b/common/properties.props index 21be6dba0..9d7fd40c6 100644 --- a/common/properties.props +++ b/common/properties.props @@ -7,6 +7,7 @@ $(SolutionDir)\script\lib\ $(SolutionDir)\lib\ + C:\Program Files\Unity\Editor\Data\Managed\ C:\Program Files (x86)\Unity\Editor\Data\Managed\ \Applications\Unity\Unity.app\Contents\Managed\ Debug From 4d44b461859569dbaa20b33a5ad5fdd070c5698e Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Fri, 3 Nov 2017 11:37:51 -0400 Subject: [PATCH 208/241] Code cleanup --- .../Assets/Editor/GitHub.Unity/UI/BranchesView.cs | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs index 9d37417a8..24864879a 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs @@ -452,10 +452,8 @@ public class Tree [SerializeField] public GUIStyle TreeNodeStyle; [SerializeField] public GUIStyle ActiveTreeNodeStyle; - [NonSerialized] - private Stack indents = new Stack(); - [NonSerialized] - private Hashtable folders; + [NonSerialized] private Stack indents = new Stack(); + [NonSerialized] private Hashtable folders; public bool IsInitialized { get { return nodes != null && nodes.Count > 0 && !String.IsNullOrEmpty(nodes[0].Name); } } public bool RequiresRepaint { get; private set; } From 4a3db62c538d8f880f0bbb4e19c927a11daa72b4 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Fri, 3 Nov 2017 11:38:18 -0400 Subject: [PATCH 209/241] Preventing render if there are no nodes --- .../Assets/Editor/GitHub.Unity/UI/BranchesView.cs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs index 24864879a..2460f92f2 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs @@ -558,6 +558,9 @@ public void Load(IEnumerable data, string title) public Rect Render(Rect rect, Action singleClick = null, Action doubleClick = null) { + if (!nodes.Any()) + return rect; + RequiresRepaint = false; rect = new Rect(0f, rect.y, rect.width, ItemHeight); From ffe502795a734589251f2ebd6d9b333be03e736f Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Fri, 3 Nov 2017 15:20:58 -0400 Subject: [PATCH 210/241] Removing redundant variable --- src/GitHub.Api/Git/Repository.cs | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/src/GitHub.Api/Git/Repository.cs b/src/GitHub.Api/Git/Repository.cs index b9277ed31..3d6b00cb6 100644 --- a/src/GitHub.Api/Git/Repository.cs +++ b/src/GitHub.Api/Git/Repository.cs @@ -203,12 +203,11 @@ public ITask ReleaseLock(string file, bool force) public void CheckLogChangedEvent(CacheUpdateEvent cacheUpdateEvent) { - CacheUpdateEvent cacheUpdateEvent1 = cacheUpdateEvent; var managedCache = cacheContainer.GitLogCache; - var raiseEvent = ShouldRaiseCacheEvent(cacheUpdateEvent1, managedCache); + var raiseEvent = ShouldRaiseCacheEvent(cacheUpdateEvent, managedCache); Logger.Trace("Check GitLogCache CacheUpdateEvent Current:{0} Check:{1} Result:{2}", managedCache.LastUpdatedAt, - cacheUpdateEvent1.UpdatedTimeString ?? "[NULL]", raiseEvent); + cacheUpdateEvent.UpdatedTimeString ?? "[NULL]", raiseEvent); if (raiseEvent) { @@ -220,12 +219,11 @@ public void CheckLogChangedEvent(CacheUpdateEvent cacheUpdateEvent) public void CheckStatusChangedEvent(CacheUpdateEvent cacheUpdateEvent) { - CacheUpdateEvent cacheUpdateEvent1 = cacheUpdateEvent; var managedCache = cacheContainer.GitStatusCache; - var raiseEvent = ShouldRaiseCacheEvent(cacheUpdateEvent1, managedCache); + var raiseEvent = ShouldRaiseCacheEvent(cacheUpdateEvent, managedCache); Logger.Trace("Check GitStatusCache CacheUpdateEvent Current:{0} Check:{1} Result:{2}", managedCache.LastUpdatedAt, - cacheUpdateEvent1.UpdatedTimeString ?? "[NULL]", raiseEvent); + cacheUpdateEvent.UpdatedTimeString ?? "[NULL]", raiseEvent); if (raiseEvent) { From 9fca98c054944f08fea21bbded88b4d807250c77 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Fri, 3 Nov 2017 16:22:05 -0400 Subject: [PATCH 211/241] Combining RepositoryManager OnCurrentBranchUpdated & OnCurrentRemoteUpdated to OnCurrentBranchAndRemoteUpdated --- src/GitHub.Api/Git/Repository.cs | 24 +++++----- src/GitHub.Api/Git/RepositoryManager.cs | 10 ++--- .../Events/RepositoryManagerTests.cs | 45 +++++++------------ .../Events/IRepositoryManagerListener.cs | 26 ++++------- src/tests/UnitTests/Git/RepositoryTests.cs | 3 +- 5 files changed, 37 insertions(+), 71 deletions(-) diff --git a/src/GitHub.Api/Git/Repository.cs b/src/GitHub.Api/Git/Repository.cs index be4ccc7a5..b58d0ad8f 100644 --- a/src/GitHub.Api/Git/Repository.cs +++ b/src/GitHub.Api/Git/Repository.cs @@ -49,8 +49,7 @@ public void Initialize(IRepositoryManager repositoryManager) this.repositoryManager = repositoryManager; - repositoryManager.OnCurrentBranchUpdated += RepositoryManager_OnCurrentBranchUpdated; - repositoryManager.OnCurrentRemoteUpdated += RepositoryManager_OnCurrentRemoteUpdated; + repositoryManager.OnCurrentBranchAndRemoteUpdated += RepositoryManager_OnCurrentBranchAndRemoteUpdated; repositoryManager.OnStatusUpdated += status => CurrentStatus = status; repositoryManager.OnLocksUpdated += locks => CurrentLocks = locks; repositoryManager.OnLocalBranchListUpdated += RepositoryManager_OnLocalBranchListUpdated; @@ -168,8 +167,16 @@ public bool Equals(IRepository other) object.Equals(LocalPath, other.LocalPath); } - private void RepositoryManager_OnCurrentRemoteUpdated(ConfigRemote? remote) + private void RepositoryManager_OnCurrentBranchAndRemoteUpdated(ConfigBranch? branch, ConfigRemote? remote) { + if (!Nullable.Equals(currentBranch, branch)) + { + currentBranch = branch; + + Logger.Trace("OnCurrentBranchChanged: {0}", currentBranch.HasValue ? currentBranch.ToString() : "[NULL]"); + OnCurrentBranchChanged?.Invoke(currentBranch.HasValue ? currentBranch.Value.Name : null); + } + if (!Nullable.Equals(currentRemote, remote)) { currentRemote = remote; @@ -181,17 +188,6 @@ private void RepositoryManager_OnCurrentRemoteUpdated(ConfigRemote? remote) } } - private void RepositoryManager_OnCurrentBranchUpdated(ConfigBranch? branch) - { - if (!Nullable.Equals(currentBranch, branch)) - { - currentBranch = branch; - - Logger.Trace("OnCurrentBranchChanged: {0}", currentBranch.HasValue ? currentBranch.ToString() : "[NULL]"); - OnCurrentBranchChanged?.Invoke(currentBranch.HasValue ? currentBranch.Value.Name : null); - } - } - private void RepositoryManager_OnLocalBranchUpdated(string name) { if (name == currentBranch?.Name) diff --git a/src/GitHub.Api/Git/RepositoryManager.cs b/src/GitHub.Api/Git/RepositoryManager.cs index 7a4e20426..1b1a41c9d 100644 --- a/src/GitHub.Api/Git/RepositoryManager.cs +++ b/src/GitHub.Api/Git/RepositoryManager.cs @@ -7,8 +7,7 @@ namespace GitHub.Unity { public interface IRepositoryManager : IDisposable { - event Action OnCurrentBranchUpdated; - event Action OnCurrentRemoteUpdated; + event Action OnCurrentBranchAndRemoteUpdated; event Action OnGitUserLoaded; event Action OnIsBusyChanged; event Action OnLocalBranchAdded; @@ -102,8 +101,7 @@ class RepositoryManager : IRepositoryManager private bool isBusy; - public event Action OnCurrentBranchUpdated; - public event Action OnCurrentRemoteUpdated; + public event Action OnCurrentBranchAndRemoteUpdated; public event Action OnGitUserLoaded; public event Action OnIsBusyChanged; public event Action OnLocalBranchAdded; @@ -458,10 +456,8 @@ private void UpdateCurrentBranchAndRemote(string head) } Logger.Trace("OnCurrentBranchUpdated: {0}", branch.HasValue ? branch.Value.ToString() : "[NULL]"); - OnCurrentBranchUpdated?.Invoke(branch); - Logger.Trace("OnCurrentRemoteUpdated: {0}", remote.HasValue ? remote.Value.ToString() : "[NULL]"); - OnCurrentRemoteUpdated?.Invoke(remote); + OnCurrentBranchAndRemoteUpdated?.Invoke(branch, remote); } private void Watcher_OnIndexChanged() diff --git a/src/tests/IntegrationTests/Events/RepositoryManagerTests.cs b/src/tests/IntegrationTests/Events/RepositoryManagerTests.cs index 8340ed120..6f8450981 100644 --- a/src/tests/IntegrationTests/Events/RepositoryManagerTests.cs +++ b/src/tests/IntegrationTests/Events/RepositoryManagerTests.cs @@ -96,8 +96,7 @@ public async Task ShouldDetectFileChanges() repositoryManagerListener.Received().OnIsBusyChanged(Args.Bool); repositoryManagerListener.Received().OnStatusUpdated(Args.GitStatus); repositoryManagerListener.DidNotReceive().OnLocksUpdated(Args.EnumerableGitLock); - repositoryManagerListener.DidNotReceive().OnCurrentBranchUpdated(Arg.Any()); - repositoryManagerListener.DidNotReceive().OnCurrentRemoteUpdated(Arg.Any()); + repositoryManagerListener.DidNotReceive().OnCurrentBranchAndRemoteUpdated(Arg.Any(), Arg.Any()); repositoryManagerListener.DidNotReceive().OnLocalBranchListUpdated(Arg.Any>()); repositoryManagerListener.DidNotReceive().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); repositoryManagerListener.DidNotReceive().OnLocalBranchUpdated(Args.String); @@ -155,8 +154,7 @@ public async Task ShouldAddAndCommitFiles() repositoryManagerListener.Received().OnIsBusyChanged(Args.Bool); repositoryManagerListener.Received().OnStatusUpdated(Args.GitStatus); repositoryManagerListener.DidNotReceive().OnLocksUpdated(Args.EnumerableGitLock); - repositoryManagerListener.DidNotReceive().OnCurrentBranchUpdated(Arg.Any()); - repositoryManagerListener.DidNotReceive().OnCurrentRemoteUpdated(Arg.Any()); + repositoryManagerListener.DidNotReceive().OnCurrentBranchAndRemoteUpdated(Arg.Any(), Arg.Any()); repositoryManagerListener.DidNotReceive().OnLocalBranchListUpdated(Arg.Any>()); repositoryManagerListener.DidNotReceive().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); repositoryManagerListener.DidNotReceive().OnLocalBranchUpdated(Args.String); @@ -181,8 +179,7 @@ await RepositoryManager repositoryManagerListener.Received().OnIsBusyChanged(Args.Bool); repositoryManagerListener.DidNotReceive().OnStatusUpdated(Args.GitStatus); repositoryManagerListener.DidNotReceive().OnLocksUpdated(Args.EnumerableGitLock); - repositoryManagerListener.DidNotReceive().OnCurrentBranchUpdated(Arg.Any()); - repositoryManagerListener.DidNotReceive().OnCurrentRemoteUpdated(Arg.Any()); + repositoryManagerListener.DidNotReceive().OnCurrentBranchAndRemoteUpdated(Arg.Any(), Arg.Any()); repositoryManagerListener.DidNotReceive().OnLocalBranchListUpdated(Arg.Any>()); repositoryManagerListener.DidNotReceive().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); repositoryManagerListener.Received().OnLocalBranchUpdated(expectedLocalBranch); @@ -232,8 +229,7 @@ public async Task ShouldAddAndCommitAllFiles() repositoryManagerListener.Received().OnIsBusyChanged(Args.Bool); repositoryManagerListener.Received().OnStatusUpdated(Args.GitStatus); repositoryManagerListener.DidNotReceive().OnLocksUpdated(Args.EnumerableGitLock); - repositoryManagerListener.DidNotReceive().OnCurrentBranchUpdated(Arg.Any()); - repositoryManagerListener.DidNotReceive().OnCurrentRemoteUpdated(Arg.Any()); + repositoryManagerListener.DidNotReceive().OnCurrentBranchAndRemoteUpdated(Arg.Any(), Arg.Any()); repositoryManagerListener.DidNotReceive().OnLocalBranchListUpdated(Arg.Any>()); repositoryManagerListener.DidNotReceive().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); repositoryManagerListener.DidNotReceive().OnLocalBranchUpdated(Args.String); @@ -258,8 +254,7 @@ await RepositoryManager repositoryManagerListener.Received().OnIsBusyChanged(Args.Bool); repositoryManagerListener.DidNotReceive().OnStatusUpdated(Args.GitStatus); repositoryManagerListener.DidNotReceive().OnLocksUpdated(Args.EnumerableGitLock); - repositoryManagerListener.DidNotReceive().OnCurrentBranchUpdated(Arg.Any()); - repositoryManagerListener.DidNotReceive().OnCurrentRemoteUpdated(Arg.Any()); + repositoryManagerListener.DidNotReceive().OnCurrentBranchAndRemoteUpdated(Arg.Any(), Arg.Any()); repositoryManagerListener.DidNotReceive().OnLocalBranchListUpdated(Arg.Any>()); repositoryManagerListener.DidNotReceive().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); repositoryManagerListener.Received().OnLocalBranchUpdated(expectedLocalBranch); @@ -299,8 +294,7 @@ public async Task ShouldDetectBranchChange() repositoryManagerListener.Received().OnIsBusyChanged(Args.Bool); repositoryManagerListener.Received().OnStatusUpdated(Args.GitStatus); repositoryManagerListener.DidNotReceive().OnLocksUpdated(Args.EnumerableGitLock); - repositoryManagerListener.Received().OnCurrentBranchUpdated(Arg.Any()); - repositoryManagerListener.Received().OnCurrentRemoteUpdated(Arg.Any()); + repositoryManagerListener.Received().OnCurrentBranchAndRemoteUpdated(Arg.Any(), Arg.Any()); repositoryManagerListener.DidNotReceive().OnLocalBranchListUpdated(Arg.Any>()); repositoryManagerListener.DidNotReceive().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); repositoryManagerListener.DidNotReceive().OnLocalBranchUpdated(Args.String); @@ -355,8 +349,7 @@ public async Task ShouldDetectBranchDelete() repositoryManagerListener.Received().OnIsBusyChanged(Args.Bool); repositoryManagerListener.DidNotReceive().OnStatusUpdated(Args.GitStatus); repositoryManagerListener.DidNotReceive().OnLocksUpdated(Args.EnumerableGitLock); - repositoryManagerListener.Received().OnCurrentBranchUpdated(Arg.Any()); - repositoryManagerListener.Received().OnCurrentRemoteUpdated(Arg.Any()); + repositoryManagerListener.Received().OnCurrentBranchAndRemoteUpdated(Arg.Any(), Arg.Any()); repositoryManagerListener.Received().OnLocalBranchListUpdated(Arg.Any>()); repositoryManagerListener.Received().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); repositoryManagerListener.DidNotReceive().OnLocalBranchUpdated(Args.String); @@ -409,8 +402,7 @@ public async Task ShouldDetectBranchCreate() repositoryManagerListener.Received().OnIsBusyChanged(Args.Bool); repositoryManagerListener.DidNotReceive().OnStatusUpdated(Args.GitStatus); repositoryManagerListener.DidNotReceive().OnLocksUpdated(Args.EnumerableGitLock); - repositoryManagerListener.DidNotReceive().OnCurrentBranchUpdated(Arg.Any()); - repositoryManagerListener.DidNotReceive().OnCurrentRemoteUpdated(Arg.Any()); + repositoryManagerListener.DidNotReceive().OnCurrentBranchAndRemoteUpdated(Arg.Any(), Arg.Any()); repositoryManagerListener.DidNotReceive().OnLocalBranchListUpdated(Arg.Any>()); repositoryManagerListener.DidNotReceive().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); repositoryManagerListener.DidNotReceive().OnLocalBranchUpdated(Args.String); @@ -459,8 +451,7 @@ public async Task ShouldDetectBranchCreate() repositoryManagerListener.Received().OnIsBusyChanged(Args.Bool); repositoryManagerListener.DidNotReceive().OnStatusUpdated(Args.GitStatus); repositoryManagerListener.DidNotReceive().OnLocksUpdated(Args.EnumerableGitLock); - repositoryManagerListener.DidNotReceive().OnCurrentBranchUpdated(Arg.Any()); - repositoryManagerListener.DidNotReceive().OnCurrentRemoteUpdated(Arg.Any()); + repositoryManagerListener.DidNotReceive().OnCurrentBranchAndRemoteUpdated(Arg.Any(), Arg.Any()); repositoryManagerListener.DidNotReceive().OnLocalBranchListUpdated(Arg.Any>()); repositoryManagerListener.DidNotReceive().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); repositoryManagerListener.DidNotReceive().OnLocalBranchUpdated(Args.String); @@ -551,8 +542,7 @@ public async Task ShouldDetectChangesToRemotes() repositoryManagerListener.Received().OnIsBusyChanged(Args.Bool); repositoryManagerListener.DidNotReceive().OnStatusUpdated(Args.GitStatus); repositoryManagerListener.DidNotReceive().OnLocksUpdated(Args.EnumerableGitLock); - repositoryManagerListener.Received().OnCurrentBranchUpdated(Arg.Any()); - repositoryManagerListener.Received().OnCurrentRemoteUpdated(Arg.Any()); + repositoryManagerListener.Received().OnCurrentBranchAndRemoteUpdated(Arg.Any(), Arg.Any()); repositoryManagerListener.Received().OnLocalBranchListUpdated(Arg.Any>()); repositoryManagerListener.Received().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); repositoryManagerListener.DidNotReceive().OnLocalBranchUpdated(Args.String); @@ -586,8 +576,7 @@ public async Task ShouldDetectChangesToRemotes() repositoryManagerListener.Received().OnIsBusyChanged(Args.Bool); repositoryManagerListener.DidNotReceive().OnStatusUpdated(Args.GitStatus); repositoryManagerListener.DidNotReceive().OnLocksUpdated(Args.EnumerableGitLock); - repositoryManagerListener.Received().OnCurrentBranchUpdated(Arg.Any()); - repositoryManagerListener.Received().OnCurrentRemoteUpdated(Arg.Any()); + repositoryManagerListener.Received().OnCurrentBranchAndRemoteUpdated(Arg.Any(), Arg.Any()); repositoryManagerListener.Received().OnLocalBranchListUpdated(Arg.Any>()); repositoryManagerListener.Received().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); repositoryManagerListener.DidNotReceive().OnLocalBranchUpdated(Args.String); @@ -677,8 +666,7 @@ await RepositoryManager.CreateBranch("branch2", "another/master") repositoryManagerListener.Received().OnIsBusyChanged(Args.Bool); repositoryManagerListener.DidNotReceive().OnStatusUpdated(Args.GitStatus); repositoryManagerListener.DidNotReceive().OnLocksUpdated(Args.EnumerableGitLock); - repositoryManagerListener.Received().OnCurrentBranchUpdated(Arg.Any()); - repositoryManagerListener.Received().OnCurrentRemoteUpdated(Arg.Any()); + repositoryManagerListener.Received().OnCurrentBranchAndRemoteUpdated(Arg.Any(), Arg.Any()); repositoryManagerListener.Received().OnLocalBranchListUpdated(Arg.Any>()); repositoryManagerListener.Received().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); repositoryManagerListener.DidNotReceive().OnLocalBranchUpdated(Args.String); @@ -736,8 +724,7 @@ await RepositoryManager.SwitchBranch("branch2") repositoryManagerListener.Received().OnIsBusyChanged(Args.Bool); repositoryManagerListener.Received().OnStatusUpdated(Args.GitStatus); repositoryManagerListener.DidNotReceive().OnLocksUpdated(Args.EnumerableGitLock); - repositoryManagerListener.Received().OnCurrentBranchUpdated(Arg.Any()); - repositoryManagerListener.Received().OnCurrentRemoteUpdated(Arg.Any()); + repositoryManagerListener.Received().OnCurrentBranchAndRemoteUpdated(Arg.Any(), Arg.Any()); repositoryManagerListener.DidNotReceive().OnLocalBranchListUpdated(Arg.Any>()); repositoryManagerListener.DidNotReceive().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); repositoryManagerListener.DidNotReceive().OnLocalBranchUpdated(Args.String); @@ -808,8 +795,7 @@ public async Task ShouldDetectGitPull() repositoryManagerListener.Received().OnIsBusyChanged(Args.Bool); repositoryManagerListener.Received().OnStatusUpdated(Args.GitStatus); repositoryManagerListener.DidNotReceive().OnLocksUpdated(Args.EnumerableGitLock); - repositoryManagerListener.DidNotReceive().OnCurrentBranchUpdated(Arg.Any()); - repositoryManagerListener.DidNotReceive().OnCurrentRemoteUpdated(Arg.Any()); + repositoryManagerListener.DidNotReceive().OnCurrentBranchAndRemoteUpdated(Arg.Any(), Arg.Any()); repositoryManagerListener.DidNotReceive().OnLocalBranchListUpdated(Arg.Any>()); repositoryManagerListener.DidNotReceive().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); repositoryManagerListener.Received().OnLocalBranchUpdated(Args.String); @@ -897,8 +883,7 @@ public async Task ShouldDetectGitFetch() repositoryManagerListener.Received().OnIsBusyChanged(Args.Bool); repositoryManagerListener.DidNotReceive().OnStatusUpdated(Args.GitStatus); repositoryManagerListener.DidNotReceive().OnLocksUpdated(Args.EnumerableGitLock); - repositoryManagerListener.DidNotReceive().OnCurrentBranchUpdated(Arg.Any()); - repositoryManagerListener.DidNotReceive().OnCurrentRemoteUpdated(Arg.Any()); + repositoryManagerListener.DidNotReceive().OnCurrentBranchAndRemoteUpdated(Arg.Any(), Arg.Any()); repositoryManagerListener.DidNotReceive().OnLocalBranchListUpdated(Arg.Any>()); repositoryManagerListener.DidNotReceive().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); repositoryManagerListener.DidNotReceive().OnLocalBranchUpdated(Args.String); diff --git a/src/tests/TestUtils/Events/IRepositoryManagerListener.cs b/src/tests/TestUtils/Events/IRepositoryManagerListener.cs index 1f7432652..5552cd1e2 100644 --- a/src/tests/TestUtils/Events/IRepositoryManagerListener.cs +++ b/src/tests/TestUtils/Events/IRepositoryManagerListener.cs @@ -20,8 +20,7 @@ interface IRepositoryManagerListener void OnRemoteBranchAdded(string origin, string name); void OnRemoteBranchRemoved(string origin, string name); void OnGitUserLoaded(IUser user); - void OnCurrentBranchUpdated(ConfigBranch? configBranch); - void OnCurrentRemoteUpdated(ConfigRemote? configRemote); + void OnCurrentBranchAndRemoteUpdated(ConfigBranch? configBranch, ConfigRemote? configRemote); } class RepositoryManagerEvents @@ -30,8 +29,7 @@ class RepositoryManagerEvents public EventWaitHandle OnIsNotBusy { get; } = new AutoResetEvent(false); public EventWaitHandle OnStatusUpdated { get; } = new AutoResetEvent(false); public EventWaitHandle OnLocksUpdated { get; } = new AutoResetEvent(false); - public EventWaitHandle OnCurrentBranchUpdated { get; } = new AutoResetEvent(false); - public EventWaitHandle OnCurrentRemoteUpdated { get; } = new AutoResetEvent(false); + public EventWaitHandle OnCurrentBranchAndRemoteUpdated { get; } = new AutoResetEvent(false); public EventWaitHandle OnHeadUpdated { get; } = new AutoResetEvent(false); public EventWaitHandle OnLocalBranchListUpdated { get; } = new AutoResetEvent(false); public EventWaitHandle OnRemoteBranchListUpdated { get; } = new AutoResetEvent(false); @@ -48,8 +46,7 @@ public void Reset() OnIsNotBusy.Reset(); OnStatusUpdated.Reset(); OnLocksUpdated.Reset(); - OnCurrentBranchUpdated.Reset(); - OnCurrentRemoteUpdated.Reset(); + OnCurrentBranchAndRemoteUpdated.Reset(); OnHeadUpdated.Reset(); OnLocalBranchListUpdated.Reset(); OnRemoteBranchListUpdated.Reset(); @@ -107,16 +104,10 @@ public static void AttachListener(this IRepositoryManagerListener listener, managerEvents?.OnLocksUpdated.Set(); }; - repositoryManager.OnCurrentBranchUpdated += configBranch => { - logger?.Trace("OnCurrentBranchUpdated"); - listener.OnCurrentBranchUpdated(configBranch); - managerEvents?.OnCurrentBranchUpdated.Set(); - }; - - repositoryManager.OnCurrentRemoteUpdated += configRemote => { - logger?.Trace("OnCurrentRemoteUpdated"); - listener.OnCurrentRemoteUpdated(configRemote); - managerEvents?.OnCurrentRemoteUpdated.Set(); + repositoryManager.OnCurrentBranchAndRemoteUpdated += (configBranch, configRemote) => { + logger?.Trace("OnCurrentBranchAndRemoteUpdated"); + listener.OnCurrentBranchAndRemoteUpdated(configBranch, configRemote); + managerEvents?.OnCurrentBranchAndRemoteUpdated.Set(); }; repositoryManager.OnLocalBranchListUpdated += branchList => { @@ -173,8 +164,7 @@ public static void AssertDidNotReceiveAnyCalls(this IRepositoryManagerListener r repositoryManagerListener.DidNotReceive().OnIsBusyChanged(Args.Bool); repositoryManagerListener.DidNotReceive().OnStatusUpdated(Args.GitStatus); repositoryManagerListener.DidNotReceive().OnLocksUpdated(Args.EnumerableGitLock); - repositoryManagerListener.DidNotReceive().OnCurrentBranchUpdated(Arg.Any()); - repositoryManagerListener.DidNotReceive().OnCurrentRemoteUpdated(Arg.Any()); + repositoryManagerListener.DidNotReceive().OnCurrentBranchAndRemoteUpdated(Arg.Any(), Arg.Any()); repositoryManagerListener.DidNotReceive().OnLocalBranchListUpdated(Arg.Any>()); repositoryManagerListener.DidNotReceive().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); repositoryManagerListener.DidNotReceive().OnLocalBranchUpdated(Args.String); diff --git a/src/tests/UnitTests/Git/RepositoryTests.cs b/src/tests/UnitTests/Git/RepositoryTests.cs index 368d4a86b..30dafb4f5 100644 --- a/src/tests/UnitTests/Git/RepositoryTests.cs +++ b/src/tests/UnitTests/Git/RepositoryTests.cs @@ -99,8 +99,7 @@ public void Repository() repositoryEvents.OnRemoteBranchListChanged.WaitOne(repositoryEventsTimeout).Should().BeTrue("OnRemoteBranchListChanged not raised"); - repositoryManager.OnCurrentBranchUpdated += Raise.Event>(masterOriginBranch); - repositoryManager.OnCurrentRemoteUpdated += Raise.Event>(origin); + repositoryManager.OnCurrentBranchAndRemoteUpdated += Raise.Event>(masterOriginBranch, origin); repositoryEvents.OnCurrentBranchChanged.WaitOne(repositoryEventsTimeout).Should().BeTrue("OnCurrentBranchChanged not raised"); repositoryEvents.OnCurrentRemoteChanged.WaitOne(repositoryEventsTimeout).Should().BeTrue("OnCurrentRemoteChanged not raised"); From 4009c5513da13270c48261892f4c2378290ff4a7 Mon Sep 17 00:00:00 2001 From: Andreia Gaita Date: Fri, 3 Nov 2017 15:28:46 -0700 Subject: [PATCH 212/241] Doing the same view switching logic that Window has --- .../Editor/GitHub.Unity/UI/PopupWindow.cs | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PopupWindow.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PopupWindow.cs index 68b32ff23..fae687bea 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PopupWindow.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PopupWindow.cs @@ -87,11 +87,23 @@ private void OpenInternal(PopupViewType popupViewType, Action onClose) OnClose += onClose; } + var fromView = ActiveView; ActiveViewType = popupViewType; - ActiveView.OnEnable(); - titleContent = new GUIContent(ActiveView.Title, Styles.SmallLogo); + SwitchView(fromView, ActiveView); Show(); - Redraw(); + } + + private void SwitchView(Subview fromView, Subview toView) + { + GUI.FocusControl(null); + + if (fromView != null) + fromView.OnDisable(); + toView.OnEnable(); + titleContent = new GUIContent(ActiveView.Title, Styles.SmallLogo); + + // this triggers a repaint + Repaint(); } public IApiClient Client From 1fb203456ca53183e3bccf374db92846ba61a189 Mon Sep 17 00:00:00 2001 From: Andreia Gaita Date: Fri, 3 Nov 2017 15:48:36 -0700 Subject: [PATCH 213/241] Relayout code --- .../Editor/GitHub.Unity/UI/PopupWindow.cs | 154 +++++++++--------- 1 file changed, 77 insertions(+), 77 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PopupWindow.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PopupWindow.cs index fae687bea..b7c860686 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PopupWindow.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PopupWindow.cs @@ -14,13 +14,13 @@ public enum PopupViewType AuthenticationView, } - [SerializeField] private bool shouldCloseOnFinish; + [NonSerialized] private IApiClient client; + [SerializeField] private PopupViewType activeViewType; [SerializeField] private AuthenticationView authenticationView; - [SerializeField] private PublishView publishView; [SerializeField] private LoadingView loadingView; - - [NonSerialized] private IApiClient client; + [SerializeField] private PublishView publishView; + [SerializeField] private bool shouldCloseOnFinish; public event Action OnClose; @@ -39,6 +39,79 @@ public static PopupWindow OpenWindow(PopupViewType popupViewType, Action o return popupWindow; } + public override void Initialize(IApplicationManager applicationManager) + { + base.Initialize(applicationManager); + + publishView = publishView ?? new PublishView(); + authenticationView = authenticationView ?? new AuthenticationView(); + loadingView = loadingView ?? new LoadingView(); + + publishView.InitializeView(this); + authenticationView.InitializeView(this); + loadingView.InitializeView(this); + + titleContent = new GUIContent(ActiveView.Title, Styles.SmallLogo); + } + + public override void OnEnable() + { + base.OnEnable(); + minSize = maxSize = ActiveView.Size; + ActiveView.OnEnable(); + } + + public override void OnDisable() + { + base.OnDisable(); + ActiveView.OnDisable(); + } + + public override void OnDataUpdate() + { + base.OnDataUpdate(); + ActiveView.OnDataUpdate(); + } + + public override void OnUI() + { + base.OnUI(); + ActiveView.OnGUI(); + } + + public override void Refresh() + { + base.Refresh(); + ActiveView.Refresh(); + } + + public override void OnSelectionChange() + { + base.OnSelectionChange(); + ActiveView.OnSelectionChange(); + } + + public override void Finish(bool result) + { + OnClose.SafeInvoke(result); + OnClose = null; + + if (shouldCloseOnFinish) + { + shouldCloseOnFinish = false; + Close(); + } + + base.Finish(result); + } + + public override void OnDestroy() + { + base.OnDestroy(); + OnClose.SafeInvoke(false); + OnClose = null; + } + private void Open(PopupViewType popupViewType, Action onClose) { OnClose.SafeInvoke(false); @@ -130,79 +203,6 @@ public IApiClient Client } } - public override void Initialize(IApplicationManager applicationManager) - { - base.Initialize(applicationManager); - - publishView = publishView ?? new PublishView(); - authenticationView = authenticationView ?? new AuthenticationView(); - loadingView = loadingView ?? new LoadingView(); - - publishView.InitializeView(this); - authenticationView.InitializeView(this); - loadingView.InitializeView(this); - - titleContent = new GUIContent(ActiveView.Title, Styles.SmallLogo); - } - - public override void OnEnable() - { - base.OnEnable(); - minSize = maxSize = ActiveView.Size; - ActiveView.OnEnable(); - } - - public override void OnDisable() - { - base.OnDisable(); - ActiveView.OnDisable(); - } - - public override void OnDataUpdate() - { - base.OnDataUpdate(); - ActiveView.OnDataUpdate(); - } - - public override void OnUI() - { - base.OnUI(); - ActiveView.OnGUI(); - } - - public override void Refresh() - { - base.Refresh(); - ActiveView.Refresh(); - } - - public override void OnSelectionChange() - { - base.OnSelectionChange(); - ActiveView.OnSelectionChange(); - } - - public override void Finish(bool result) - { - OnClose.SafeInvoke(result); - OnClose = null; - - if (shouldCloseOnFinish) - { - shouldCloseOnFinish = false; - Close(); - } - - base.Finish(result); - } - - public override void OnDestroy() - { - base.OnDestroy(); - OnClose.SafeInvoke(false); - OnClose = null; - } - private Subview ActiveView { get From 2d1aa12dcc199ea5e14d569c481ca65636ac2877 Mon Sep 17 00:00:00 2001 From: Andreia Gaita Date: Wed, 1 Nov 2017 15:10:33 -0700 Subject: [PATCH 214/241] Work around the ABI breakage Unity is eventually going to remove the full UnityEngine DLL so this hopefully ensures we never have to worry about this codepath again --- .../Editor/GitHub.Unity/Misc/Utility.cs | 38 +++++++++++++------ 1 file changed, 27 insertions(+), 11 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/Misc/Utility.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/Misc/Utility.cs index 0deb4c975..5816c47cf 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/Misc/Utility.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/Misc/Utility.cs @@ -32,26 +32,42 @@ static class StreamExtensions static StreamExtensions() { - var t = Assembly.Load("UnityEngine.dll").GetType("UnityEngine.ImageConversion", false, false); - if (t != null) + // 5.6 + // looking for Texture2D.LoadImage(byte[] data) + loadImage = typeof(Texture2D).GetMethods().FirstOrDefault(x => x.Name == "LoadImage" && x.GetParameters().Length == 1); + if (loadImage != null) { - // looking for ImageConversion.LoadImage(this Texture2D tex, byte[] data) - loadImage = t.GetMethods().FirstOrDefault(x => x.Name == "LoadImage" && x.GetParameters().Length == 2); invokeLoadImage = (tex, ms) => { - loadImage.Invoke(null, new object[] { tex, ms.ToArray() }); + loadImage.Invoke(tex, new object[] { ms.ToArray() }); return tex; }; } else { - // looking for Texture2D.LoadImage(byte[] data) - loadImage = typeof(Texture2D).GetMethods().FirstOrDefault(x => x.Name == "LoadImage" && x.GetParameters().Length == 1); - invokeLoadImage = (tex, ms) => + // 2017.1 + var t = typeof(Texture2D).Assembly.GetType("UnityEngine.ImageConversion", false, false); + if (t == null) { - loadImage.Invoke(tex, new object[] { ms.ToArray() }); - return tex; - }; + // 2017.2 and above + t = Assembly.Load("UnityEngine.ImageConversionModule").GetType("UnityEngine.ImageConversion", false, false); + } + + if (t != null) + { + // looking for ImageConversion.LoadImage(this Texture2D tex, byte[] data) + loadImage = t.GetMethods().FirstOrDefault(x => x.Name == "LoadImage" && x.GetParameters().Length == 2); + invokeLoadImage = (tex, ms) => + { + loadImage.Invoke(null, new object[] { tex, ms.ToArray() }); + return tex; + }; + } + } + + if (loadImage == null) + { + Logging.Error("Could not find ImageConversion.LoadImage method"); } } From c2e14c5983be2b86c628e11c7022b521d81c6a32 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Mon, 6 Nov 2017 09:17:32 -0500 Subject: [PATCH 215/241] Changing RepositoryManager OnLocalBranchListUpdated and OnRemoteBranchListUpdated to use Dictionary instead of IDictionary --- src/GitHub.Api/Cache/CacheInterfaces.cs | 4 +- src/GitHub.Api/Git/Repository.cs | 6 +- src/GitHub.Api/Git/RepositoryManager.cs | 10 ++-- .../Editor/GitHub.Unity/ApplicationCache.cs | 6 +- .../Events/RepositoryManagerTests.cs | 60 +++++++++---------- .../Events/IRepositoryManagerListener.cs | 8 +-- 6 files changed, 47 insertions(+), 47 deletions(-) diff --git a/src/GitHub.Api/Cache/CacheInterfaces.cs b/src/GitHub.Api/Cache/CacheInterfaces.cs index d7fe8ff7a..a303520fa 100644 --- a/src/GitHub.Api/Cache/CacheInterfaces.cs +++ b/src/GitHub.Api/Cache/CacheInterfaces.cs @@ -89,8 +89,8 @@ public interface IBranchCache : IManagedCache void AddLocalBranch(string branch); void AddRemoteBranch(string remote, string branch); void RemoveRemoteBranch(string remote, string branch); - void SetRemotes(IDictionary remoteDictionary, IDictionary> branchDictionary); - void SetLocals(IDictionary branchDictionary); + void SetRemotes(Dictionary remoteDictionary, Dictionary> branchDictionary); + void SetLocals(Dictionary branchDictionary); } public interface IRepositoryInfoCache : IManagedCache diff --git a/src/GitHub.Api/Git/Repository.cs b/src/GitHub.Api/Git/Repository.cs index 3d6b00cb6..b9cd40e0c 100644 --- a/src/GitHub.Api/Git/Repository.cs +++ b/src/GitHub.Api/Git/Repository.cs @@ -418,8 +418,8 @@ private void RepositoryManager_OnLocalBranchUpdated(string name) } } - private void RepositoryManager_OnRemoteBranchListUpdated(IDictionary remotes, - IDictionary> branches) + private void RepositoryManager_OnRemoteBranchListUpdated(Dictionary remotes, + Dictionary> branches) { new ActionTask(CancellationToken.None, () => { cacheContainer.BranchCache.SetRemotes(remotes, branches); @@ -434,7 +434,7 @@ private void UpdateRemoteAndRemoteBranches() RemoteBranches = RemoteConfigBranches.Values.SelectMany(x => x.Values).Select(GetRemoteGitBranch).ToArray(); } - private void RepositoryManager_OnLocalBranchListUpdated(IDictionary branches) + private void RepositoryManager_OnLocalBranchListUpdated(Dictionary branches) { new ActionTask(CancellationToken.None, () => { cacheContainer.BranchCache.SetLocals(branches); diff --git a/src/GitHub.Api/Git/RepositoryManager.cs b/src/GitHub.Api/Git/RepositoryManager.cs index 5a094a384..da90df8fb 100644 --- a/src/GitHub.Api/Git/RepositoryManager.cs +++ b/src/GitHub.Api/Git/RepositoryManager.cs @@ -12,11 +12,11 @@ public interface IRepositoryManager : IDisposable event Action OnGitUserLoaded; event Action OnIsBusyChanged; event Action OnLocalBranchAdded; - event Action> OnLocalBranchListUpdated; + event Action> OnLocalBranchListUpdated; event Action OnLocalBranchRemoved; event Action OnLocalBranchUpdated; event Action OnRemoteBranchAdded; - event Action, IDictionary>> OnRemoteBranchListUpdated; + event Action, Dictionary>> OnRemoteBranchListUpdated; event Action OnRemoteBranchRemoved; event Action OnRepositoryUpdated; @@ -106,11 +106,11 @@ class RepositoryManager : IRepositoryManager public event Action OnGitUserLoaded; public event Action OnIsBusyChanged; public event Action OnLocalBranchAdded; - public event Action> OnLocalBranchListUpdated; + public event Action> OnLocalBranchListUpdated; public event Action OnLocalBranchRemoved; public event Action OnLocalBranchUpdated; public event Action OnRemoteBranchAdded; - public event Action, IDictionary>> OnRemoteBranchListUpdated; + public event Action, Dictionary>> OnRemoteBranchListUpdated; public event Action OnRemoteBranchRemoved; public event Action OnRepositoryUpdated; @@ -505,7 +505,7 @@ private void LoadRemotesFromConfig() Logger.Trace("LoadRemotesFromConfig"); var remotes = config.GetRemotes().ToArray().ToDictionary(x => x.Name, x => x); - var remoteBranches = new Dictionary>(); + var remoteBranches = new Dictionary>(); foreach (var remote in remotes.Keys) { diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs index 3f77f6a3a..55c9ffd38 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/ApplicationCache.cs @@ -222,7 +222,7 @@ class RemoteConfigBranchDictionary : Dictionary> dictionary) + public RemoteConfigBranchDictionary(Dictionary> dictionary) { foreach (var pair in dictionary) { @@ -712,7 +712,7 @@ public void RemoveRemoteBranch(string remote, string branch) } } - public void SetRemotes(IDictionary remoteDictionary, IDictionary> branchDictionary) + public void SetRemotes(Dictionary remoteDictionary, Dictionary> branchDictionary) { var now = DateTimeOffset.Now; configRemotes = new ConfigRemoteDictionary(remoteDictionary); @@ -721,7 +721,7 @@ public void SetRemotes(IDictionary remoteDictionary, IDict SaveData(now, true); } - public void SetLocals(IDictionary branchDictionary) + public void SetLocals(Dictionary branchDictionary) { var now = DateTimeOffset.Now; localConfigBranches = new LocalConfigBranchDictionary(branchDictionary); diff --git a/src/tests/IntegrationTests/Events/RepositoryManagerTests.cs b/src/tests/IntegrationTests/Events/RepositoryManagerTests.cs index 9521d6198..c0807e8eb 100644 --- a/src/tests/IntegrationTests/Events/RepositoryManagerTests.cs +++ b/src/tests/IntegrationTests/Events/RepositoryManagerTests.cs @@ -95,8 +95,8 @@ public async Task ShouldDetectFileChanges() repositoryManagerListener.DidNotReceive().OnLocksUpdated(Args.EnumerableGitLock); repositoryManagerListener.DidNotReceive().OnCurrentBranchUpdated(Arg.Any()); repositoryManagerListener.DidNotReceive().OnCurrentRemoteUpdated(Arg.Any()); - repositoryManagerListener.DidNotReceive().OnLocalBranchListUpdated(Arg.Any>()); - repositoryManagerListener.DidNotReceive().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); + repositoryManagerListener.DidNotReceive().OnLocalBranchListUpdated(Arg.Any>()); + repositoryManagerListener.DidNotReceive().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); repositoryManagerListener.DidNotReceive().OnLocalBranchUpdated(Args.String); repositoryManagerListener.DidNotReceive().OnLocalBranchAdded(Args.String); repositoryManagerListener.DidNotReceive().OnLocalBranchRemoved(Args.String); @@ -154,8 +154,8 @@ public async Task ShouldAddAndCommitFiles() repositoryManagerListener.DidNotReceive().OnLocksUpdated(Args.EnumerableGitLock); repositoryManagerListener.DidNotReceive().OnCurrentBranchUpdated(Arg.Any()); repositoryManagerListener.DidNotReceive().OnCurrentRemoteUpdated(Arg.Any()); - repositoryManagerListener.DidNotReceive().OnLocalBranchListUpdated(Arg.Any>()); - repositoryManagerListener.DidNotReceive().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); + repositoryManagerListener.DidNotReceive().OnLocalBranchListUpdated(Arg.Any>()); + repositoryManagerListener.DidNotReceive().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); repositoryManagerListener.DidNotReceive().OnLocalBranchUpdated(Args.String); repositoryManagerListener.DidNotReceive().OnLocalBranchAdded(Args.String); repositoryManagerListener.DidNotReceive().OnLocalBranchRemoved(Args.String); @@ -180,8 +180,8 @@ await RepositoryManager repositoryManagerListener.DidNotReceive().OnLocksUpdated(Args.EnumerableGitLock); repositoryManagerListener.DidNotReceive().OnCurrentBranchUpdated(Arg.Any()); repositoryManagerListener.DidNotReceive().OnCurrentRemoteUpdated(Arg.Any()); - repositoryManagerListener.DidNotReceive().OnLocalBranchListUpdated(Arg.Any>()); - repositoryManagerListener.DidNotReceive().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); + repositoryManagerListener.DidNotReceive().OnLocalBranchListUpdated(Arg.Any>()); + repositoryManagerListener.DidNotReceive().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); repositoryManagerListener.Received().OnLocalBranchUpdated(expectedLocalBranch); repositoryManagerListener.DidNotReceive().OnLocalBranchAdded(Args.String); repositoryManagerListener.DidNotReceive().OnLocalBranchRemoved(Args.String); @@ -232,8 +232,8 @@ public async Task ShouldAddAndCommitAllFiles() repositoryManagerListener.DidNotReceive().OnLocksUpdated(Args.EnumerableGitLock); repositoryManagerListener.DidNotReceive().OnCurrentBranchUpdated(Arg.Any()); repositoryManagerListener.DidNotReceive().OnCurrentRemoteUpdated(Arg.Any()); - repositoryManagerListener.DidNotReceive().OnLocalBranchListUpdated(Arg.Any>()); - repositoryManagerListener.DidNotReceive().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); + repositoryManagerListener.DidNotReceive().OnLocalBranchListUpdated(Arg.Any>()); + repositoryManagerListener.DidNotReceive().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); repositoryManagerListener.DidNotReceive().OnLocalBranchUpdated(Args.String); repositoryManagerListener.DidNotReceive().OnLocalBranchAdded(Args.String); repositoryManagerListener.DidNotReceive().OnLocalBranchRemoved(Args.String); @@ -258,8 +258,8 @@ await RepositoryManager repositoryManagerListener.DidNotReceive().OnLocksUpdated(Args.EnumerableGitLock); repositoryManagerListener.DidNotReceive().OnCurrentBranchUpdated(Arg.Any()); repositoryManagerListener.DidNotReceive().OnCurrentRemoteUpdated(Arg.Any()); - repositoryManagerListener.DidNotReceive().OnLocalBranchListUpdated(Arg.Any>()); - repositoryManagerListener.DidNotReceive().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); + repositoryManagerListener.DidNotReceive().OnLocalBranchListUpdated(Arg.Any>()); + repositoryManagerListener.DidNotReceive().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); repositoryManagerListener.Received().OnLocalBranchUpdated(expectedLocalBranch); repositoryManagerListener.DidNotReceive().OnLocalBranchAdded(Args.String); repositoryManagerListener.DidNotReceive().OnLocalBranchRemoved(Args.String); @@ -300,8 +300,8 @@ public async Task ShouldDetectBranchChange() repositoryManagerListener.DidNotReceive().OnLocksUpdated(Args.EnumerableGitLock); repositoryManagerListener.Received().OnCurrentBranchUpdated(Arg.Any()); repositoryManagerListener.Received().OnCurrentRemoteUpdated(Arg.Any()); - repositoryManagerListener.DidNotReceive().OnLocalBranchListUpdated(Arg.Any>()); - repositoryManagerListener.DidNotReceive().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); + repositoryManagerListener.DidNotReceive().OnLocalBranchListUpdated(Arg.Any>()); + repositoryManagerListener.DidNotReceive().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); repositoryManagerListener.DidNotReceive().OnLocalBranchUpdated(Args.String); repositoryManagerListener.DidNotReceive().OnLocalBranchAdded(Args.String); repositoryManagerListener.DidNotReceive().OnLocalBranchRemoved(Args.String); @@ -353,8 +353,8 @@ public async Task ShouldDetectBranchDelete() repositoryManagerListener.DidNotReceive().OnLocksUpdated(Args.EnumerableGitLock); repositoryManagerListener.Received().OnCurrentBranchUpdated(Arg.Any()); repositoryManagerListener.Received().OnCurrentRemoteUpdated(Arg.Any()); - repositoryManagerListener.Received().OnLocalBranchListUpdated(Arg.Any>()); - repositoryManagerListener.Received().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); + repositoryManagerListener.Received().OnLocalBranchListUpdated(Arg.Any>()); + repositoryManagerListener.Received().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); repositoryManagerListener.DidNotReceive().OnLocalBranchUpdated(Args.String); repositoryManagerListener.DidNotReceive().OnLocalBranchAdded(Args.String); repositoryManagerListener.Received().OnLocalBranchRemoved(deletedBranch); @@ -403,8 +403,8 @@ public async Task ShouldDetectBranchCreate() repositoryManagerListener.DidNotReceive().OnLocksUpdated(Args.EnumerableGitLock); repositoryManagerListener.DidNotReceive().OnCurrentBranchUpdated(Arg.Any()); repositoryManagerListener.DidNotReceive().OnCurrentRemoteUpdated(Arg.Any()); - repositoryManagerListener.DidNotReceive().OnLocalBranchListUpdated(Arg.Any>()); - repositoryManagerListener.DidNotReceive().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); + repositoryManagerListener.DidNotReceive().OnLocalBranchListUpdated(Arg.Any>()); + repositoryManagerListener.DidNotReceive().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); repositoryManagerListener.DidNotReceive().OnLocalBranchUpdated(Args.String); repositoryManagerListener.Received().OnLocalBranchAdded(createdBranch1); repositoryManagerListener.DidNotReceive().OnLocalBranchRemoved(Args.String); @@ -449,8 +449,8 @@ public async Task ShouldDetectBranchCreate() repositoryManagerListener.DidNotReceive().OnLocksUpdated(Args.EnumerableGitLock); repositoryManagerListener.DidNotReceive().OnCurrentBranchUpdated(Arg.Any()); repositoryManagerListener.DidNotReceive().OnCurrentRemoteUpdated(Arg.Any()); - repositoryManagerListener.DidNotReceive().OnLocalBranchListUpdated(Arg.Any>()); - repositoryManagerListener.DidNotReceive().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); + repositoryManagerListener.DidNotReceive().OnLocalBranchListUpdated(Arg.Any>()); + repositoryManagerListener.DidNotReceive().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); repositoryManagerListener.DidNotReceive().OnLocalBranchUpdated(Args.String); repositoryManagerListener.Received().OnLocalBranchAdded(createdBranch2); repositoryManagerListener.DidNotReceive().OnLocalBranchRemoved(Args.String); @@ -533,8 +533,8 @@ public async Task ShouldDetectChangesToRemotes() repositoryManagerListener.DidNotReceive().OnLocksUpdated(Args.EnumerableGitLock); repositoryManagerListener.Received().OnCurrentBranchUpdated(Arg.Any()); repositoryManagerListener.Received().OnCurrentRemoteUpdated(Arg.Any()); - repositoryManagerListener.Received().OnLocalBranchListUpdated(Arg.Any>()); - repositoryManagerListener.Received().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); + repositoryManagerListener.Received().OnLocalBranchListUpdated(Arg.Any>()); + repositoryManagerListener.Received().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); repositoryManagerListener.DidNotReceive().OnLocalBranchUpdated(Args.String); repositoryManagerListener.DidNotReceive().OnLocalBranchAdded(Args.String); repositoryManagerListener.DidNotReceive().OnLocalBranchRemoved(Args.String); @@ -568,8 +568,8 @@ public async Task ShouldDetectChangesToRemotes() repositoryManagerListener.DidNotReceive().OnLocksUpdated(Args.EnumerableGitLock); repositoryManagerListener.Received().OnCurrentBranchUpdated(Arg.Any()); repositoryManagerListener.Received().OnCurrentRemoteUpdated(Arg.Any()); - repositoryManagerListener.Received().OnLocalBranchListUpdated(Arg.Any>()); - repositoryManagerListener.Received().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); + repositoryManagerListener.Received().OnLocalBranchListUpdated(Arg.Any>()); + repositoryManagerListener.Received().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); repositoryManagerListener.DidNotReceive().OnLocalBranchUpdated(Args.String); repositoryManagerListener.DidNotReceive().OnLocalBranchAdded(Args.String); repositoryManagerListener.DidNotReceive().OnLocalBranchRemoved(Args.String); @@ -649,8 +649,8 @@ await RepositoryManager.CreateBranch("branch2", "another/master") repositoryManagerListener.DidNotReceive().OnLocksUpdated(Args.EnumerableGitLock); repositoryManagerListener.Received().OnCurrentBranchUpdated(Arg.Any()); repositoryManagerListener.Received().OnCurrentRemoteUpdated(Arg.Any()); - repositoryManagerListener.Received().OnLocalBranchListUpdated(Arg.Any>()); - repositoryManagerListener.Received().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); + repositoryManagerListener.Received().OnLocalBranchListUpdated(Arg.Any>()); + repositoryManagerListener.Received().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); repositoryManagerListener.DidNotReceive().OnLocalBranchUpdated(Args.String); repositoryManagerListener.Received().OnLocalBranchAdded(Args.String); repositoryManagerListener.DidNotReceive().OnLocalBranchRemoved(Args.String); @@ -702,8 +702,8 @@ await RepositoryManager.SwitchBranch("branch2") repositoryManagerListener.DidNotReceive().OnLocksUpdated(Args.EnumerableGitLock); repositoryManagerListener.Received().OnCurrentBranchUpdated(Arg.Any()); repositoryManagerListener.Received().OnCurrentRemoteUpdated(Arg.Any()); - repositoryManagerListener.DidNotReceive().OnLocalBranchListUpdated(Arg.Any>()); - repositoryManagerListener.DidNotReceive().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); + repositoryManagerListener.DidNotReceive().OnLocalBranchListUpdated(Arg.Any>()); + repositoryManagerListener.DidNotReceive().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); repositoryManagerListener.DidNotReceive().OnLocalBranchUpdated(Args.String); repositoryManagerListener.DidNotReceive().OnLocalBranchAdded(Args.String); repositoryManagerListener.DidNotReceive().OnLocalBranchRemoved(Args.String); @@ -769,8 +769,8 @@ public async Task ShouldDetectGitPull() repositoryManagerListener.DidNotReceive().OnLocksUpdated(Args.EnumerableGitLock); repositoryManagerListener.DidNotReceive().OnCurrentBranchUpdated(Arg.Any()); repositoryManagerListener.DidNotReceive().OnCurrentRemoteUpdated(Arg.Any()); - repositoryManagerListener.DidNotReceive().OnLocalBranchListUpdated(Arg.Any>()); - repositoryManagerListener.DidNotReceive().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); + repositoryManagerListener.DidNotReceive().OnLocalBranchListUpdated(Arg.Any>()); + repositoryManagerListener.DidNotReceive().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); repositoryManagerListener.Received().OnLocalBranchUpdated(Args.String); repositoryManagerListener.DidNotReceive().OnLocalBranchAdded(Args.String); repositoryManagerListener.DidNotReceive().OnLocalBranchRemoved(Args.String); @@ -850,8 +850,8 @@ public async Task ShouldDetectGitFetch() repositoryManagerListener.DidNotReceive().OnLocksUpdated(Args.EnumerableGitLock); repositoryManagerListener.DidNotReceive().OnCurrentBranchUpdated(Arg.Any()); repositoryManagerListener.DidNotReceive().OnCurrentRemoteUpdated(Arg.Any()); - repositoryManagerListener.DidNotReceive().OnLocalBranchListUpdated(Arg.Any>()); - repositoryManagerListener.DidNotReceive().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); + repositoryManagerListener.DidNotReceive().OnLocalBranchListUpdated(Arg.Any>()); + repositoryManagerListener.DidNotReceive().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); repositoryManagerListener.DidNotReceive().OnLocalBranchUpdated(Args.String); repositoryManagerListener.DidNotReceive().OnLocalBranchAdded(Args.String); repositoryManagerListener.DidNotReceive().OnLocalBranchRemoved(Args.String); diff --git a/src/tests/TestUtils/Events/IRepositoryManagerListener.cs b/src/tests/TestUtils/Events/IRepositoryManagerListener.cs index 3c858bf54..7d67fd700 100644 --- a/src/tests/TestUtils/Events/IRepositoryManagerListener.cs +++ b/src/tests/TestUtils/Events/IRepositoryManagerListener.cs @@ -12,8 +12,8 @@ interface IRepositoryManagerListener void OnIsBusyChanged(bool busy); void OnStatusUpdated(GitStatus status); void OnLocksUpdated(IEnumerable locks); - void OnLocalBranchListUpdated(IDictionary branchList); - void OnRemoteBranchListUpdated(IDictionary remotesList, IDictionary> remoteBranchList); + void OnLocalBranchListUpdated(Dictionary branchList); + void OnRemoteBranchListUpdated(Dictionary remotesList, Dictionary> remoteBranchList); void OnLocalBranchUpdated(string name); void OnLocalBranchAdded(string name); void OnLocalBranchRemoved(string name); @@ -162,8 +162,8 @@ public static void AssertDidNotReceiveAnyCalls(this IRepositoryManagerListener r repositoryManagerListener.DidNotReceive().OnLocksUpdated(Args.EnumerableGitLock); repositoryManagerListener.DidNotReceive().OnCurrentBranchUpdated(Arg.Any()); repositoryManagerListener.DidNotReceive().OnCurrentRemoteUpdated(Arg.Any()); - repositoryManagerListener.DidNotReceive().OnLocalBranchListUpdated(Arg.Any>()); - repositoryManagerListener.DidNotReceive().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); + repositoryManagerListener.DidNotReceive().OnLocalBranchListUpdated(Arg.Any>()); + repositoryManagerListener.DidNotReceive().OnRemoteBranchListUpdated(Arg.Any>(), Arg.Any>>()); repositoryManagerListener.DidNotReceive().OnLocalBranchUpdated(Args.String); repositoryManagerListener.DidNotReceive().OnLocalBranchAdded(Args.String); repositoryManagerListener.DidNotReceive().OnLocalBranchRemoved(Args.String); From 1dc8762323f2a801e2d4f6b9b5d0ba9c82c22c30 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Mon, 6 Nov 2017 09:24:19 -0500 Subject: [PATCH 216/241] Removing main thread wrapper --- src/GitHub.Api/Git/RepositoryManager.cs | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/src/GitHub.Api/Git/RepositoryManager.cs b/src/GitHub.Api/Git/RepositoryManager.cs index da90df8fb..c031e88f2 100644 --- a/src/GitHub.Api/Git/RepositoryManager.cs +++ b/src/GitHub.Api/Git/RepositoryManager.cs @@ -425,16 +425,11 @@ private void UpdateCurrentBranchAndRemote(string head) } } - new ActionTask(taskManager.Token, () => { - Logger.Trace("OnCurrentBranchUpdated: {0}", branch.HasValue ? branch.Value.ToString() : "[NULL]"); - OnCurrentBranchUpdated?.Invoke(branch); + Logger.Trace("OnCurrentBranchUpdated: {0}", branch.HasValue ? branch.Value.ToString() : "[NULL]"); + OnCurrentBranchUpdated?.Invoke(branch); - Logger.Trace("OnCurrentRemoteUpdated: {0}", remote.HasValue ? remote.Value.ToString() : "[NULL]"); - OnCurrentRemoteUpdated?.Invoke(remote); - }) - { - Affinity = TaskAffinity.UI - }.Start(); + Logger.Trace("OnCurrentRemoteUpdated: {0}", remote.HasValue ? remote.Value.ToString() : "[NULL]"); + OnCurrentRemoteUpdated?.Invoke(remote); } private void Watcher_OnIndexChanged() From 1b27c29f2b9a0c86804827891219eef90c76eb7d Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Mon, 6 Nov 2017 09:28:57 -0500 Subject: [PATCH 217/241] Making property setters private --- src/GitHub.Api/Git/Repository.cs | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/GitHub.Api/Git/Repository.cs b/src/GitHub.Api/Git/Repository.cs index b9cd40e0c..23264acd5 100644 --- a/src/GitHub.Api/Git/Repository.cs +++ b/src/GitHub.Api/Git/Repository.cs @@ -525,19 +525,19 @@ private static GitRemote GetGitRemote(ConfigRemote configRemote) public GitRemote[] Remotes { get { return cacheContainer.BranchCache.Remotes; } - set { cacheContainer.BranchCache.Remotes = value; } + private set { cacheContainer.BranchCache.Remotes = value; } } public GitBranch[] LocalBranches { get { return cacheContainer.BranchCache.LocalBranches; } - set { cacheContainer.BranchCache.LocalBranches = value; } + private set { cacheContainer.BranchCache.LocalBranches = value; } } public GitBranch[] RemoteBranches { get { return cacheContainer.BranchCache.RemoteBranches; } - set { cacheContainer.BranchCache.RemoteBranches = value; } + private set { cacheContainer.BranchCache.RemoteBranches = value; } } private ConfigBranch? CurrentConfigBranch @@ -555,13 +555,13 @@ private ConfigRemote? CurrentConfigRemote public GitStatus CurrentStatus { get { return cacheContainer.GitStatusCache.GitStatus; } - set { cacheContainer.GitStatusCache.GitStatus = value; } + private set { cacheContainer.GitStatusCache.GitStatus = value; } } public GitBranch? CurrentBranch { get { return cacheContainer.RepositoryInfoCache.CurentGitBranch; } - set { cacheContainer.RepositoryInfoCache.CurentGitBranch = value; } + private set { cacheContainer.RepositoryInfoCache.CurentGitBranch = value; } } public string CurrentBranchName => CurrentConfigBranch?.Name; @@ -569,13 +569,13 @@ public GitBranch? CurrentBranch public GitRemote? CurrentRemote { get { return cacheContainer.RepositoryInfoCache.CurrentGitRemote; } - set { cacheContainer.RepositoryInfoCache.CurrentGitRemote = value; } + private set { cacheContainer.RepositoryInfoCache.CurrentGitRemote = value; } } public List CurrentLog { get { return cacheContainer.GitLogCache.Log; } - set { cacheContainer.GitLogCache.Log = value; } + private set { cacheContainer.GitLogCache.Log = value; } } public event Action LogChanged; @@ -591,7 +591,7 @@ public List CurrentLog public List CurrentLocks { get { return cacheContainer.GitLocksCache.GitLocks; } - set { cacheContainer.GitLocksCache.GitLocks = value; } + private set { cacheContainer.GitLocksCache.GitLocks = value; } } public UriString CloneUrl From 48564ff73211def1b8c3d14ff272c1121f4fb932 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Mon, 6 Nov 2017 09:33:52 -0500 Subject: [PATCH 218/241] Moving Repository events to the top of the file --- src/GitHub.Api/Git/Repository.cs | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/src/GitHub.Api/Git/Repository.cs b/src/GitHub.Api/Git/Repository.cs index 23264acd5..c2b04c9ed 100644 --- a/src/GitHub.Api/Git/Repository.cs +++ b/src/GitHub.Api/Git/Repository.cs @@ -15,6 +15,16 @@ class Repository : IEquatable, IRepository private UriString cloneUrl; private string name; + public event Action LogChanged; + public event Action StatusChanged; + public event Action CurrentBranchChanged; + public event Action CurrentRemoteChanged; + public event Action CurrentBranchAndRemoteChanged; + public event Action LocalBranchListChanged; + public event Action LocksChanged; + public event Action RemoteBranchListChanged; + public event Action LocalAndRemoteBranchListChanged; + /// /// Initializes a new instance of the class. /// @@ -578,16 +588,6 @@ public List CurrentLog private set { cacheContainer.GitLogCache.Log = value; } } - public event Action LogChanged; - public event Action StatusChanged; - public event Action CurrentBranchChanged; - public event Action CurrentRemoteChanged; - public event Action CurrentBranchAndRemoteChanged; - public event Action LocalBranchListChanged; - public event Action LocksChanged; - public event Action RemoteBranchListChanged; - public event Action LocalAndRemoteBranchListChanged; - public List CurrentLocks { get { return cacheContainer.GitLocksCache.GitLocks; } From 37e78a7597da71f57d1d2f1fb41f16c8fbf36181 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Mon, 6 Nov 2017 09:35:32 -0500 Subject: [PATCH 219/241] Moving Then and Start calls to separate lines --- src/GitHub.Api/Git/Repository.cs | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/src/GitHub.Api/Git/Repository.cs b/src/GitHub.Api/Git/Repository.cs index c2b04c9ed..84cac10e7 100644 --- a/src/GitHub.Api/Git/Repository.cs +++ b/src/GitHub.Api/Git/Repository.cs @@ -188,7 +188,8 @@ public ITask Pull() public ITask Push() { - return repositoryManager.Push(CurrentRemote.Value.Name, CurrentBranch?.Name).Then(UpdateGitStatus); + return repositoryManager.Push(CurrentRemote.Value.Name, CurrentBranch?.Name) + .Then(UpdateGitStatus); } public ITask Fetch() @@ -203,12 +204,14 @@ public ITask Revert(string changeset) public ITask RequestLock(string file) { - return repositoryManager.LockFile(file).Then(UpdateLocks); + return repositoryManager.LockFile(file) + .Then(UpdateLocks); } public ITask ReleaseLock(string file, bool force) { - return repositoryManager.UnlockFile(file, force).Then(UpdateLocks); + return repositoryManager.UnlockFile(file, force) + .Then(UpdateLocks); } public void CheckLogChangedEvent(CacheUpdateEvent cacheUpdateEvent) @@ -389,19 +392,25 @@ private void RepositoryManager_OnRepositoryUpdated() private void UpdateGitStatus() { - repositoryManager?.Status().ThenInUI((b, status) => { CurrentStatus = status; }).Start(); + repositoryManager?.Status() + .ThenInUI((b, status) => { CurrentStatus = status; }) + .Start(); } private void UpdateGitLog() { - repositoryManager?.Log().ThenInUI((b, log) => { CurrentLog = log; }).Start(); + repositoryManager?.Log() + .ThenInUI((b, log) => { CurrentLog = log; }) + .Start(); } private void UpdateLocks() { if (CurrentRemote.HasValue) { - repositoryManager?.ListLocks(false).ThenInUI((b, locks) => { CurrentLocks = locks; }).Start(); + repositoryManager?.ListLocks(false) + .ThenInUI((b, locks) => { CurrentLocks = locks; }) + .Start(); } } From a3f365889cbfaf366a0ee63c5f8564d4dea28e1a Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Mon, 6 Nov 2017 09:37:00 -0500 Subject: [PATCH 220/241] Corrected method name spelling --- src/GitHub.Api/Git/Repository.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/GitHub.Api/Git/Repository.cs b/src/GitHub.Api/Git/Repository.cs index 84cac10e7..415d99461 100644 --- a/src/GitHub.Api/Git/Repository.cs +++ b/src/GitHub.Api/Git/Repository.cs @@ -80,7 +80,7 @@ private void CacheContainer_OnCacheUpdated(CacheType cacheType, DateTimeOffset o break; case CacheType.GitStatusCache: - HandleGitStatucCacheUpdatedEvent(cacheUpdateEvent); + HandleGitStatusCacheUpdatedEvent(cacheUpdateEvent); break; case CacheType.GitLocksCache: @@ -113,7 +113,7 @@ private void HandleGitLocksCacheUpdatedEvent(CacheUpdateEvent cacheUpdateEvent) LocksChanged?.Invoke(cacheUpdateEvent); } - private void HandleGitStatucCacheUpdatedEvent(CacheUpdateEvent cacheUpdateEvent) + private void HandleGitStatusCacheUpdatedEvent(CacheUpdateEvent cacheUpdateEvent) { Logger.Trace("GitStatusCache Updated {0}", cacheUpdateEvent.UpdatedTimeString); StatusChanged?.Invoke(cacheUpdateEvent); @@ -242,7 +242,7 @@ public void CheckStatusChangedEvent(CacheUpdateEvent cacheUpdateEvent) { var dateTimeOffset = managedCache.LastUpdatedAt; var updateEvent = new CacheUpdateEvent { UpdatedTimeString = dateTimeOffset.ToString() }; - HandleGitStatucCacheUpdatedEvent(updateEvent); + HandleGitStatusCacheUpdatedEvent(updateEvent); } } From efc90b6b336d0e5a9af9000f90d235376f97a7cf Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Mon, 6 Nov 2017 09:38:42 -0500 Subject: [PATCH 221/241] Moving private methods after public methods --- src/GitHub.Api/Git/Repository.cs | 218 +++++++++++++++---------------- 1 file changed, 109 insertions(+), 109 deletions(-) diff --git a/src/GitHub.Api/Git/Repository.cs b/src/GitHub.Api/Git/Repository.cs index 415d99461..9a53daae8 100644 --- a/src/GitHub.Api/Git/Repository.cs +++ b/src/GitHub.Api/Git/Repository.cs @@ -42,97 +42,6 @@ public Repository(NPath localPath, ICacheContainer container) cacheContainer.CacheUpdated += CacheContainer_OnCacheUpdated; } - private void CacheContainer_OnCacheInvalidated(CacheType cacheType) - { - switch (cacheType) - { - case CacheType.BranchCache: - break; - - case CacheType.GitLogCache: - break; - - case CacheType.GitStatusCache: - break; - - case CacheType.GitLocksCache: - break; - - case CacheType.GitUserCache: - break; - - default: - throw new ArgumentOutOfRangeException(nameof(cacheType), cacheType, null); - } - } - - private void CacheContainer_OnCacheUpdated(CacheType cacheType, DateTimeOffset offset) - { - var cacheUpdateEvent = new CacheUpdateEvent { UpdatedTimeString = offset.ToString() }; - switch (cacheType) - { - case CacheType.BranchCache: - HandleBranchCacheUpdatedEvent(cacheUpdateEvent); - break; - - case CacheType.GitLogCache: - HandleGitLogCacheUpdatedEvent(cacheUpdateEvent); - break; - - case CacheType.GitStatusCache: - HandleGitStatusCacheUpdatedEvent(cacheUpdateEvent); - break; - - case CacheType.GitLocksCache: - HandleGitLocksCacheUpdatedEvent(cacheUpdateEvent); - break; - - case CacheType.GitUserCache: - break; - - case CacheType.RepositoryInfoCache: - HandleRepositoryInfoCacheUpdatedEvent(cacheUpdateEvent); - break; - - default: - throw new ArgumentOutOfRangeException(nameof(cacheType), cacheType, null); - } - } - - private void HandleRepositoryInfoCacheUpdatedEvent(CacheUpdateEvent cacheUpdateEvent) - { - Logger.Trace("RepositoryInfoCache Updated {0}", cacheUpdateEvent.UpdatedTimeString); - CurrentBranchChanged?.Invoke(cacheUpdateEvent); - CurrentRemoteChanged?.Invoke(cacheUpdateEvent); - CurrentBranchAndRemoteChanged?.Invoke(cacheUpdateEvent); - } - - private void HandleGitLocksCacheUpdatedEvent(CacheUpdateEvent cacheUpdateEvent) - { - Logger.Trace("GitLocksCache Updated {0}", cacheUpdateEvent.UpdatedTimeString); - LocksChanged?.Invoke(cacheUpdateEvent); - } - - private void HandleGitStatusCacheUpdatedEvent(CacheUpdateEvent cacheUpdateEvent) - { - Logger.Trace("GitStatusCache Updated {0}", cacheUpdateEvent.UpdatedTimeString); - StatusChanged?.Invoke(cacheUpdateEvent); - } - - private void HandleGitLogCacheUpdatedEvent(CacheUpdateEvent cacheUpdateEvent) - { - Logger.Trace("GitLogCache Updated {0}", cacheUpdateEvent.UpdatedTimeString); - LogChanged?.Invoke(cacheUpdateEvent); - } - - private void HandleBranchCacheUpdatedEvent(CacheUpdateEvent cacheUpdateEvent) - { - Logger.Trace("BranchCache Updated {0}", cacheUpdateEvent.UpdatedTimeString); - LocalBranchListChanged?.Invoke(cacheUpdateEvent); - RemoteBranchListChanged?.Invoke(cacheUpdateEvent); - LocalAndRemoteBranchListChanged?.Invoke(cacheUpdateEvent); - } - public void Initialize(IRepositoryManager initRepositoryManager) { Logger.Trace("Initialize"); @@ -309,6 +218,38 @@ public void CheckLocalAndRemoteBranchListChangedEvent(CacheUpdateEvent cacheUpda CheckBranchCacheEvent(cacheUpdateEvent); } + /// + /// Note: We don't consider CloneUrl a part of the hash code because it can change during the lifetime + /// of a repository. Equals takes care of any hash collisions because of this + /// + /// + public override int GetHashCode() + { + return LocalPath.GetHashCode(); + } + + public override bool Equals(object obj) + { + if (ReferenceEquals(this, obj)) + return true; + + var other = obj as Repository; + return Equals(other); + } + + public bool Equals(Repository other) + { + return Equals((IRepository)other); + } + + public bool Equals(IRepository other) + { + if (ReferenceEquals(this, other)) + return true; + + return other != null && object.Equals(LocalPath, other.LocalPath); + } + private void CheckBranchCacheEvent(CacheUpdateEvent cacheUpdateEvent) { var managedCache = cacheContainer.BranchCache; @@ -339,36 +280,95 @@ private static bool ShouldRaiseCacheEvent(CacheUpdateEvent cacheUpdateEvent, IMa return raiseEvent; } - /// - /// Note: We don't consider CloneUrl a part of the hash code because it can change during the lifetime - /// of a repository. Equals takes care of any hash collisions because of this - /// - /// - public override int GetHashCode() + private void CacheContainer_OnCacheInvalidated(CacheType cacheType) { - return LocalPath.GetHashCode(); + switch (cacheType) + { + case CacheType.BranchCache: + break; + + case CacheType.GitLogCache: + break; + + case CacheType.GitStatusCache: + break; + + case CacheType.GitLocksCache: + break; + + case CacheType.GitUserCache: + break; + + default: + throw new ArgumentOutOfRangeException(nameof(cacheType), cacheType, null); + } } - public override bool Equals(object obj) + private void CacheContainer_OnCacheUpdated(CacheType cacheType, DateTimeOffset offset) { - if (ReferenceEquals(this, obj)) - return true; + var cacheUpdateEvent = new CacheUpdateEvent { UpdatedTimeString = offset.ToString() }; + switch (cacheType) + { + case CacheType.BranchCache: + HandleBranchCacheUpdatedEvent(cacheUpdateEvent); + break; - var other = obj as Repository; - return Equals(other); + case CacheType.GitLogCache: + HandleGitLogCacheUpdatedEvent(cacheUpdateEvent); + break; + + case CacheType.GitStatusCache: + HandleGitStatusCacheUpdatedEvent(cacheUpdateEvent); + break; + + case CacheType.GitLocksCache: + HandleGitLocksCacheUpdatedEvent(cacheUpdateEvent); + break; + + case CacheType.GitUserCache: + break; + + case CacheType.RepositoryInfoCache: + HandleRepositoryInfoCacheUpdatedEvent(cacheUpdateEvent); + break; + + default: + throw new ArgumentOutOfRangeException(nameof(cacheType), cacheType, null); + } } - public bool Equals(Repository other) + private void HandleRepositoryInfoCacheUpdatedEvent(CacheUpdateEvent cacheUpdateEvent) { - return Equals((IRepository)other); + Logger.Trace("RepositoryInfoCache Updated {0}", cacheUpdateEvent.UpdatedTimeString); + CurrentBranchChanged?.Invoke(cacheUpdateEvent); + CurrentRemoteChanged?.Invoke(cacheUpdateEvent); + CurrentBranchAndRemoteChanged?.Invoke(cacheUpdateEvent); } - public bool Equals(IRepository other) + private void HandleGitLocksCacheUpdatedEvent(CacheUpdateEvent cacheUpdateEvent) { - if (ReferenceEquals(this, other)) - return true; + Logger.Trace("GitLocksCache Updated {0}", cacheUpdateEvent.UpdatedTimeString); + LocksChanged?.Invoke(cacheUpdateEvent); + } - return other != null && object.Equals(LocalPath, other.LocalPath); + private void HandleGitStatusCacheUpdatedEvent(CacheUpdateEvent cacheUpdateEvent) + { + Logger.Trace("GitStatusCache Updated {0}", cacheUpdateEvent.UpdatedTimeString); + StatusChanged?.Invoke(cacheUpdateEvent); + } + + private void HandleGitLogCacheUpdatedEvent(CacheUpdateEvent cacheUpdateEvent) + { + Logger.Trace("GitLogCache Updated {0}", cacheUpdateEvent.UpdatedTimeString); + LogChanged?.Invoke(cacheUpdateEvent); + } + + private void HandleBranchCacheUpdatedEvent(CacheUpdateEvent cacheUpdateEvent) + { + Logger.Trace("BranchCache Updated {0}", cacheUpdateEvent.UpdatedTimeString); + LocalBranchListChanged?.Invoke(cacheUpdateEvent); + RemoteBranchListChanged?.Invoke(cacheUpdateEvent); + LocalAndRemoteBranchListChanged?.Invoke(cacheUpdateEvent); } private void RepositoryManager_OnCurrentRemoteUpdated(ConfigRemote? remote) From c29492cb5f054ac79b1704e41ce444de40ed5346 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Mon, 6 Nov 2017 09:41:21 -0500 Subject: [PATCH 222/241] Fixing spacing issue --- src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs index b28274ffb..045b9b462 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs @@ -191,7 +191,7 @@ private void MaybeUpdateData() if (Repository != null) { - if(!hasRunMaybeUpdateDataWithRepository || currentBranchAndRemoteHasUpdate) + if (!hasRunMaybeUpdateDataWithRepository || currentBranchAndRemoteHasUpdate) { hasRunMaybeUpdateDataWithRepository = true; From bae6029e53f44e402260e341fb19d432ba470bee Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Mon, 6 Nov 2017 10:44:38 -0500 Subject: [PATCH 223/241] Moving the property value check to the main thread --- src/GitHub.Api/Git/Repository.cs | 34 ++++++++++++++++---------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/src/GitHub.Api/Git/Repository.cs b/src/GitHub.Api/Git/Repository.cs index 9a53daae8..45caf2274 100644 --- a/src/GitHub.Api/Git/Repository.cs +++ b/src/GitHub.Api/Git/Repository.cs @@ -373,14 +373,14 @@ private void HandleBranchCacheUpdatedEvent(CacheUpdateEvent cacheUpdateEvent) private void RepositoryManager_OnCurrentRemoteUpdated(ConfigRemote? remote) { - if (!Nullable.Equals(CurrentConfigRemote, remote)) - { - new ActionTask(CancellationToken.None, () => { - CurrentConfigRemote = remote; - CurrentRemote = GetGitRemote(remote.Value); - UpdateRepositoryInfo(); - }) { Affinity = TaskAffinity.UI }.Start(); - } + new ActionTask(CancellationToken.None, () => { + if (!Nullable.Equals(CurrentConfigRemote, remote)) + { + CurrentConfigRemote = remote; + CurrentRemote = GetGitRemote(remote.Value); + UpdateRepositoryInfo(); + } + }) { Affinity = TaskAffinity.UI }.Start(); } private void RepositoryManager_OnRepositoryUpdated() @@ -416,16 +416,16 @@ private void UpdateLocks() private void RepositoryManager_OnCurrentBranchUpdated(ConfigBranch? branch) { - if (!Nullable.Equals(CurrentConfigBranch, branch)) - { - new ActionTask(CancellationToken.None, () => { - var currentBranch = branch != null ? (GitBranch?)GetLocalGitBranch(branch.Value) : null; + new ActionTask(CancellationToken.None, () => { + if (!Nullable.Equals(CurrentConfigBranch, branch)) + { + var currentBranch = branch != null ? (GitBranch?)GetLocalGitBranch(branch.Value) : null; - CurrentConfigBranch = branch; - CurrentBranch = currentBranch; - UpdateLocalBranches(); - }) { Affinity = TaskAffinity.UI }.Start(); - } + CurrentConfigBranch = branch; + CurrentBranch = currentBranch; + UpdateLocalBranches(); + } + }) { Affinity = TaskAffinity.UI }.Start(); } private void RepositoryManager_OnLocalBranchUpdated(string name) From f28a24b6a6b316b3833340fdf949d9984561ca78 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Mon, 6 Nov 2017 10:56:14 -0500 Subject: [PATCH 224/241] Removing unneccessary flag --- src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs index 045b9b462..75db4098c 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/Window.cs @@ -40,8 +40,6 @@ class Window : BaseWindow [SerializeField] private CacheUpdateEvent lastCurrentBranchAndRemoteChangedEvent; [NonSerialized] private bool currentBranchAndRemoteHasUpdate; - [NonSerialized] private bool hasRunMaybeUpdateDataWithRepository; - [MenuItem(LaunchMenu)] public static void Window_GitHub() { @@ -191,10 +189,8 @@ private void MaybeUpdateData() if (Repository != null) { - if (!hasRunMaybeUpdateDataWithRepository || currentBranchAndRemoteHasUpdate) + if (currentBranchAndRemoteHasUpdate) { - hasRunMaybeUpdateDataWithRepository = true; - var repositoryCurrentBranch = Repository.CurrentBranch; var updatedRepoBranch = repositoryCurrentBranch.HasValue ? repositoryCurrentBranch.Value.Name : null; From aff469880bea43986fa5759fb409f1528eb6deaa Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Mon, 6 Nov 2017 11:24:46 -0500 Subject: [PATCH 225/241] Moving method --- .../Editor/GitHub.Unity/UI/BranchesView.cs | 28 +++++++++---------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs index 614238f86..bd3b70c7b 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs @@ -60,20 +60,6 @@ public override void InitializeView(IView parent) targetMode = mode; } - private void RepositoryOnLocalAndRemoteBranchListChanged(CacheUpdateEvent cacheUpdateEvent) - { - if (!lastLocalAndRemoteBranchListChangedEvent.Equals(cacheUpdateEvent)) - { - new ActionTask(TaskManager.Token, () => - { - lastLocalAndRemoteBranchListChangedEvent = cacheUpdateEvent; - localAndRemoteBranchListHasUpdate = true; - Redraw(); - }) - { Affinity = TaskAffinity.UI }.Start(); - } - } - public override void OnEnable() { base.OnEnable(); @@ -97,6 +83,20 @@ public override void OnDataUpdate() MaybeUpdateData(); } + private void RepositoryOnLocalAndRemoteBranchListChanged(CacheUpdateEvent cacheUpdateEvent) + { + if (!lastLocalAndRemoteBranchListChangedEvent.Equals(cacheUpdateEvent)) + { + new ActionTask(TaskManager.Token, () => + { + lastLocalAndRemoteBranchListChangedEvent = cacheUpdateEvent; + localAndRemoteBranchListHasUpdate = true; + Redraw(); + }) + { Affinity = TaskAffinity.UI }.Start(); + } + } + private void MaybeUpdateData() { if (localAndRemoteBranchListHasUpdate) From d64f2cd69d9bab5ab75c0a8fe997f81f24b6ce4f Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Mon, 6 Nov 2017 11:26:43 -0500 Subject: [PATCH 226/241] Grouping fields --- .../Assets/Editor/GitHub.Unity/UI/ChangesView.cs | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ChangesView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ChangesView.cs index 823acf93a..270e3fd24 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ChangesView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ChangesView.cs @@ -17,19 +17,17 @@ class ChangesView : Subview private const string OneChangedFileLabel = "1 changed file"; private const string NoChangedFilesLabel = "No changed files"; + [NonSerialized] private bool currentBranchHasUpdate; + [NonSerialized] private bool currentStatusHasUpdate; [NonSerialized] private bool isBusy; [SerializeField] private string commitBody = ""; [SerializeField] private string commitMessage = ""; [SerializeField] private string currentBranch = "[unknown]"; [SerializeField] private Vector2 horizontalScroll; - [SerializeField] private ChangesetTreeView tree = new ChangesetTreeView(); - [SerializeField] private CacheUpdateEvent lastCurrentBranchChangedEvent; - [NonSerialized] private bool currentBranchHasUpdate; - [SerializeField] private CacheUpdateEvent lastStatusChangedEvent; - [NonSerialized] private bool currentStatusHasUpdate; + [SerializeField] private ChangesetTreeView tree = new ChangesetTreeView(); public override void InitializeView(IView parent) { From 04b03fcc8a956ca858e37d94f5f31a4bb811a150 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Mon, 6 Nov 2017 11:27:23 -0500 Subject: [PATCH 227/241] Moving methods --- .../Editor/GitHub.Unity/UI/ChangesView.cs | 125 +++++++++--------- 1 file changed, 62 insertions(+), 63 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ChangesView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ChangesView.cs index 270e3fd24..15032c106 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ChangesView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ChangesView.cs @@ -35,52 +35,6 @@ public override void InitializeView(IView parent) tree.InitializeView(this); } - private void RepositoryOnStatusChanged(CacheUpdateEvent cacheUpdateEvent) - { - if (!lastStatusChangedEvent.Equals(cacheUpdateEvent)) - { - new ActionTask(TaskManager.Token, () => - { - lastStatusChangedEvent = cacheUpdateEvent; - currentStatusHasUpdate = true; - Redraw(); - }) - { Affinity = TaskAffinity.UI }.Start(); - } - } - - private void RepositoryOnCurrentBranchChanged(CacheUpdateEvent cacheUpdateEvent) - { - if (!lastCurrentBranchChangedEvent.Equals(cacheUpdateEvent)) - { - new ActionTask(TaskManager.Token, () => - { - lastCurrentBranchChangedEvent = cacheUpdateEvent; - currentBranchHasUpdate = true; - Redraw(); - }) - { Affinity = TaskAffinity.UI }.Start(); - } - } - - private void AttachHandlers(IRepository repository) - { - if (repository == null) - return; - - repository.CurrentBranchChanged += RepositoryOnCurrentBranchChanged; - repository.StatusChanged += RepositoryOnStatusChanged; - } - - private void DetachHandlers(IRepository repository) - { - if (repository == null) - return; - - repository.CurrentBranchChanged -= RepositoryOnCurrentBranchChanged; - repository.StatusChanged -= RepositoryOnStatusChanged; - } - public override void OnEnable() { base.OnEnable(); @@ -106,22 +60,6 @@ public override void OnDataUpdate() MaybeUpdateData(); } - private void MaybeUpdateData() - { - if (currentBranchHasUpdate) - { - currentBranchHasUpdate = false; - currentBranch = string.Format("[{0}]", Repository.CurrentBranchName); - } - - if (currentStatusHasUpdate) - { - currentStatusHasUpdate = false; - var gitStatus = Repository.CurrentStatus; - tree.UpdateEntries(gitStatus.Entries.Where(x => x.Status != GitFileStatus.Ignored).ToList()); - } - } - public override void OnGUI() { GUILayout.BeginHorizontal(); @@ -160,11 +98,72 @@ public override void OnGUI() GUILayout.EndHorizontal(); GUILayout.EndScrollView(); - // Do the commit details area OnCommitDetailsAreaGUI(); } + private void RepositoryOnStatusChanged(CacheUpdateEvent cacheUpdateEvent) + { + if (!lastStatusChangedEvent.Equals(cacheUpdateEvent)) + { + new ActionTask(TaskManager.Token, () => { + lastStatusChangedEvent = cacheUpdateEvent; + currentStatusHasUpdate = true; + Redraw(); + }) { Affinity = TaskAffinity.UI }.Start(); + } + } + + private void RepositoryOnCurrentBranchChanged(CacheUpdateEvent cacheUpdateEvent) + { + if (!lastCurrentBranchChangedEvent.Equals(cacheUpdateEvent)) + { + new ActionTask(TaskManager.Token, () => { + lastCurrentBranchChangedEvent = cacheUpdateEvent; + currentBranchHasUpdate = true; + Redraw(); + }) { Affinity = TaskAffinity.UI }.Start(); + } + } + + private void AttachHandlers(IRepository repository) + { + if (repository == null) + { + return; + } + + repository.CurrentBranchChanged += RepositoryOnCurrentBranchChanged; + repository.StatusChanged += RepositoryOnStatusChanged; + } + + private void DetachHandlers(IRepository repository) + { + if (repository == null) + { + return; + } + + repository.CurrentBranchChanged -= RepositoryOnCurrentBranchChanged; + repository.StatusChanged -= RepositoryOnStatusChanged; + } + + private void MaybeUpdateData() + { + if (currentBranchHasUpdate) + { + currentBranchHasUpdate = false; + currentBranch = string.Format("[{0}]", Repository.CurrentBranchName); + } + + if (currentStatusHasUpdate) + { + currentStatusHasUpdate = false; + var gitStatus = Repository.CurrentStatus; + tree.UpdateEntries(gitStatus.Entries.Where(x => x.Status != GitFileStatus.Ignored).ToList()); + } + } + private void OnCommitDetailsAreaGUI() { GUILayout.BeginHorizontal(); From 3eb968c1bdb70bc925c492b49678790ace704294 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Mon, 6 Nov 2017 11:27:43 -0500 Subject: [PATCH 228/241] Some code formatting --- .../Assets/Editor/GitHub.Unity/UI/ChangesView.cs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ChangesView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ChangesView.cs index 15032c106..3434bd075 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ChangesView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/ChangesView.cs @@ -83,8 +83,9 @@ public override void OnGUI() GUILayout.Label( tree.Entries.Count == 0 ? NoChangedFilesLabel - : tree.Entries.Count == 1 ? OneChangedFileLabel : String.Format(ChangedFilesLabel, tree.Entries.Count), - EditorStyles.miniLabel); + : tree.Entries.Count == 1 + ? OneChangedFileLabel + : String.Format(ChangedFilesLabel, tree.Entries.Count), EditorStyles.miniLabel); } GUILayout.EndHorizontal(); From 0938eda83918c180abb3bd6150db55a9fbaa6779 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Mon, 6 Nov 2017 11:37:20 -0500 Subject: [PATCH 229/241] Organizing HistoryView --- .../Editor/GitHub.Unity/UI/HistoryView.cs | 290 +++++++++--------- 1 file changed, 143 insertions(+), 147 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/HistoryView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/HistoryView.cs index 96c3a5698..b8fc37400 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/HistoryView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/HistoryView.cs @@ -30,6 +30,9 @@ class HistoryView : Subview private const int HistoryExtraItemCount = 10; private const float MaxChangelistHeightRatio = .2f; + [NonSerialized] private bool currentLogHasUpdate; + [NonSerialized] private bool currentRemoteHasUpdate; + [NonSerialized] private bool currentStatusHasUpdate; [NonSerialized] private int historyStartIndex; [NonSerialized] private int historyStopIndex; [NonSerialized] private int listID; @@ -39,26 +42,19 @@ class HistoryView : Subview [NonSerialized] private int selectionIndex; [NonSerialized] private bool useScrollTime; - [SerializeField] private Vector2 detailsScroll; - [SerializeField] private Vector2 scroll; - [SerializeField] private string selectionID; - [SerializeField] private int statusAhead; - [SerializeField] private int statusBehind; - [SerializeField] private ChangesetTreeView changesetTree = new ChangesetTreeView(); - [SerializeField] private List history = new List(); [SerializeField] private string currentRemoteName; - [SerializeField] private bool hasRemote; + [SerializeField] private Vector2 detailsScroll; [SerializeField] private bool hasItemsToCommit; - + [SerializeField] private bool hasRemote; + [SerializeField] private List history = new List(); [SerializeField] private CacheUpdateEvent lastCurrentRemoteChangedEvent; - [NonSerialized] private bool currentRemoteHasUpdate; - - [SerializeField] private CacheUpdateEvent lastStatusChangedEvent; - [NonSerialized] private bool currentStatusHasUpdate; - [SerializeField] private CacheUpdateEvent lastLogChangedEvent; - [NonSerialized] private bool currentLogHasUpdate; + [SerializeField] private CacheUpdateEvent lastStatusChangedEvent; + [SerializeField] private Vector2 scroll; + [SerializeField] private string selectionID; + [SerializeField] private int statusAhead; + [SerializeField] private int statusBehind; public override void InitializeView(IView parent) { @@ -100,138 +96,6 @@ public override void OnGUI() OnEmbeddedGUI(); } - private void RepositoryOnStatusChanged(CacheUpdateEvent cacheUpdateEvent) - { - if (!lastStatusChangedEvent.Equals(cacheUpdateEvent)) - { - new ActionTask(TaskManager.Token, () => - { - lastStatusChangedEvent = cacheUpdateEvent; - currentStatusHasUpdate = true; - Redraw(); - }) - { Affinity = TaskAffinity.UI }.Start(); - } - } - - private void RepositoryOnLogChanged(CacheUpdateEvent cacheUpdateEvent) - { - if (!lastLogChangedEvent.Equals(cacheUpdateEvent)) - { - new ActionTask(TaskManager.Token, () => - { - lastLogChangedEvent = cacheUpdateEvent; - currentLogHasUpdate = true; - Redraw(); - }) - { Affinity = TaskAffinity.UI }.Start(); - } - } - - private void RepositoryOnCurrentRemoteChanged(CacheUpdateEvent cacheUpdateEvent) - { - if (!lastCurrentRemoteChangedEvent.Equals(cacheUpdateEvent)) - { - new ActionTask(TaskManager.Token, () => - { - lastCurrentRemoteChangedEvent = cacheUpdateEvent; - currentRemoteHasUpdate = true; - Redraw(); - }) - { Affinity = TaskAffinity.UI }.Start(); - } - } - - private void AttachHandlers(IRepository repository) - { - if (repository == null) - return; - - repository.StatusChanged += RepositoryOnStatusChanged; - repository.LogChanged += RepositoryOnLogChanged; - repository.CurrentRemoteChanged += RepositoryOnCurrentRemoteChanged; - } - - private void DetachHandlers(IRepository repository) - { - if (repository == null) - return; - - repository.StatusChanged -= RepositoryOnStatusChanged; - repository.LogChanged -= RepositoryOnLogChanged; - repository.CurrentRemoteChanged -= RepositoryOnCurrentRemoteChanged; - } - - private void MaybeUpdateData() - { - if (Repository == null) - return; - - if (currentRemoteHasUpdate) - { - currentRemoteHasUpdate = false; - - var currentRemote = Repository.CurrentRemote; - hasRemote = currentRemote.HasValue; - currentRemoteName = hasRemote ? currentRemote.Value.Name : "placeholder"; - } - - if (currentStatusHasUpdate) - { - currentStatusHasUpdate = false; - - var currentStatus = Repository.CurrentStatus; - statusAhead = currentStatus.Ahead; - statusBehind = currentStatus.Behind; - hasItemsToCommit = currentStatus.Entries != null && - currentStatus.GetEntriesExcludingIgnoredAndUntracked().Any(); - } - - if (currentLogHasUpdate) - { - currentLogHasUpdate = false; - - history = Repository.CurrentLog; - - if (history.Any()) - { - // Make sure that scroll as much as possible focuses the same time period in the new entry list - if (useScrollTime) - { - var closestIndex = -1; - double closestDifference = Mathf.Infinity; - for (var index = 0; index < history.Count; ++index) - { - var diff = Math.Abs((history[index].Time - scrollTime).TotalSeconds); - if (diff < closestDifference) - { - closestDifference = diff; - closestIndex = index; - } - } - - ScrollTo(closestIndex, scrollOffset); - } - - CullHistory(); - } - - // Restore selection index or clear it - newSelectionIndex = -1; - if (!string.IsNullOrEmpty(selectionID)) - { - selectionIndex = Enumerable.Range(1, history.Count + 1) - .FirstOrDefault( - index => history[index - 1].CommitID.Equals(selectionID)) - 1; - - if (selectionIndex < 0) - { - selectionID = string.Empty; - } - } - } - } - public void OnEmbeddedGUI() { // History toolbar @@ -428,6 +292,138 @@ public void OnEmbeddedGUI() } } + private void RepositoryOnStatusChanged(CacheUpdateEvent cacheUpdateEvent) + { + if (!lastStatusChangedEvent.Equals(cacheUpdateEvent)) + { + new ActionTask(TaskManager.Token, () => { + lastStatusChangedEvent = cacheUpdateEvent; + currentStatusHasUpdate = true; + Redraw(); + }) { Affinity = TaskAffinity.UI }.Start(); + } + } + + private void RepositoryOnLogChanged(CacheUpdateEvent cacheUpdateEvent) + { + if (!lastLogChangedEvent.Equals(cacheUpdateEvent)) + { + new ActionTask(TaskManager.Token, () => { + lastLogChangedEvent = cacheUpdateEvent; + currentLogHasUpdate = true; + Redraw(); + }) { Affinity = TaskAffinity.UI }.Start(); + } + } + + private void RepositoryOnCurrentRemoteChanged(CacheUpdateEvent cacheUpdateEvent) + { + if (!lastCurrentRemoteChangedEvent.Equals(cacheUpdateEvent)) + { + new ActionTask(TaskManager.Token, () => { + lastCurrentRemoteChangedEvent = cacheUpdateEvent; + currentRemoteHasUpdate = true; + Redraw(); + }) { Affinity = TaskAffinity.UI }.Start(); + } + } + + private void AttachHandlers(IRepository repository) + { + if (repository == null) + { + return; + } + + repository.StatusChanged += RepositoryOnStatusChanged; + repository.LogChanged += RepositoryOnLogChanged; + repository.CurrentRemoteChanged += RepositoryOnCurrentRemoteChanged; + } + + private void DetachHandlers(IRepository repository) + { + if (repository == null) + { + return; + } + + repository.StatusChanged -= RepositoryOnStatusChanged; + repository.LogChanged -= RepositoryOnLogChanged; + repository.CurrentRemoteChanged -= RepositoryOnCurrentRemoteChanged; + } + + private void MaybeUpdateData() + { + if (Repository == null) + { + return; + } + + if (currentRemoteHasUpdate) + { + currentRemoteHasUpdate = false; + + var currentRemote = Repository.CurrentRemote; + hasRemote = currentRemote.HasValue; + currentRemoteName = hasRemote ? currentRemote.Value.Name : "placeholder"; + } + + if (currentStatusHasUpdate) + { + currentStatusHasUpdate = false; + + var currentStatus = Repository.CurrentStatus; + statusAhead = currentStatus.Ahead; + statusBehind = currentStatus.Behind; + hasItemsToCommit = currentStatus.Entries != null && + currentStatus.GetEntriesExcludingIgnoredAndUntracked().Any(); + } + + if (currentLogHasUpdate) + { + currentLogHasUpdate = false; + + history = Repository.CurrentLog; + + if (history.Any()) + { + // Make sure that scroll as much as possible focuses the same time period in the new entry list + if (useScrollTime) + { + var closestIndex = -1; + double closestDifference = Mathf.Infinity; + for (var index = 0; index < history.Count; ++index) + { + var diff = Math.Abs((history[index].Time - scrollTime).TotalSeconds); + if (diff < closestDifference) + { + closestDifference = diff; + closestIndex = index; + } + } + + ScrollTo(closestIndex, scrollOffset); + } + + CullHistory(); + } + + // Restore selection index or clear it + newSelectionIndex = -1; + if (!string.IsNullOrEmpty(selectionID)) + { + selectionIndex = Enumerable.Range(1, history.Count + 1) + .FirstOrDefault( + index => history[index - 1].CommitID.Equals(selectionID)) - 1; + + if (selectionIndex < 0) + { + selectionID = string.Empty; + } + } + } + } + private void ScrollTo(int index, float offset = 0f) { scroll.Set(scroll.x, EntryHeight * index + offset); From dbbc878d06a6979dd25c4b602997d0bb9f9ea176 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Mon, 6 Nov 2017 12:00:08 -0500 Subject: [PATCH 230/241] Organizing SettingsView --- .../Editor/GitHub.Unity/UI/SettingsView.cs | 95 +++++++++---------- 1 file changed, 44 insertions(+), 51 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/SettingsView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/SettingsView.cs index 81c239e14..91afd8fe0 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/SettingsView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/SettingsView.cs @@ -1,8 +1,6 @@ using System; using System.Collections.Generic; -using System.IO; using System.Linq; -using System.Threading.Tasks; using UnityEditor; using UnityEngine; @@ -20,30 +18,25 @@ class SettingsView : Subview private const string MetricsOptInLabel = "Help us improve by sending anonymous usage data"; private const string DefaultRepositoryRemoteName = "origin"; + [NonSerialized] private bool currentLocksHasUpdate; + [NonSerialized] private bool currentRemoteHasUpdate; [NonSerialized] private bool isBusy; + [NonSerialized] private bool metricsHasChanged; + [SerializeField] private GitPathView gitPathView = new GitPathView(); + [SerializeField] private bool hasRemote; + [SerializeField] private CacheUpdateEvent lastCurrentRemoteChangedEvent; + [SerializeField] private CacheUpdateEvent lastLocksChangedEvent; [SerializeField] private List lockedFiles = new List(); + [SerializeField] private int lockedFileSelection = -1; [SerializeField] private Vector2 lockScrollPos; + [SerializeField] private bool metricsEnabled; + [SerializeField] private string newRepositoryRemoteUrl; [SerializeField] private string repositoryRemoteName; [SerializeField] private string repositoryRemoteUrl; [SerializeField] private Vector2 scroll; - [SerializeField] private int lockedFileSelection = -1; - [SerializeField] private bool hasRemote; - - [SerializeField] private string newRepositoryRemoteUrl; - - [SerializeField] private bool metricsEnabled; - [NonSerialized] private bool metricsHasChanged; - - [SerializeField] private GitPathView gitPathView = new GitPathView(); [SerializeField] private UserSettingsView userSettingsView = new UserSettingsView(); - [SerializeField] private CacheUpdateEvent lastCurrentRemoteChangedEvent; - [NonSerialized] private bool currentRemoteHasUpdate; - - [SerializeField] private CacheUpdateEvent lastLocksChangedEvent; - [NonSerialized] private bool currentLocksHasUpdate; - public override void InitializeView(IView parent) { base.InitializeView(parent); @@ -91,10 +84,39 @@ public override void Refresh() userSettingsView.Refresh(); } + public override void OnGUI() + { + scroll = GUILayout.BeginScrollView(scroll); + { + userSettingsView.OnGUI(); + + GUILayout.Space(EditorGUIUtility.standardVerticalSpacing); + + if (Repository != null) + { + OnRepositorySettingsGUI(); + + GUILayout.Space(EditorGUIUtility.standardVerticalSpacing); + + OnGitLfsLocksGUI(); + + GUILayout.Space(EditorGUIUtility.standardVerticalSpacing); + } + + gitPathView.OnGUI(); + OnPrivacyGui(); + OnLoggingSettingsGui(); + } + + GUILayout.EndScrollView(); + } + private void AttachHandlers(IRepository repository) { if (repository == null) + { return; + } repository.CurrentRemoteChanged += RepositoryOnCurrentRemoteChanged; repository.LocksChanged += RepositoryOnLocksChanged; @@ -104,13 +126,11 @@ private void RepositoryOnLocksChanged(CacheUpdateEvent cacheUpdateEvent) { if (!lastLocksChangedEvent.Equals(cacheUpdateEvent)) { - new ActionTask(TaskManager.Token, () => - { + new ActionTask(TaskManager.Token, () => { lastLocksChangedEvent = cacheUpdateEvent; currentLocksHasUpdate = true; Redraw(); - }) - { Affinity = TaskAffinity.UI }.Start(); + }) { Affinity = TaskAffinity.UI }.Start(); } } @@ -118,47 +138,20 @@ private void RepositoryOnCurrentRemoteChanged(CacheUpdateEvent cacheUpdateEvent) { if (!lastCurrentRemoteChangedEvent.Equals(cacheUpdateEvent)) { - new ActionTask(TaskManager.Token, () => - { + new ActionTask(TaskManager.Token, () => { lastCurrentRemoteChangedEvent = cacheUpdateEvent; currentRemoteHasUpdate = true; Redraw(); - }) - { Affinity = TaskAffinity.UI }.Start(); + }) { Affinity = TaskAffinity.UI }.Start(); } } private void DetachHandlers(IRepository repository) { if (repository == null) - return; - } - - public override void OnGUI() - { - scroll = GUILayout.BeginScrollView(scroll); { - userSettingsView.OnGUI(); - - GUILayout.Space(EditorGUIUtility.standardVerticalSpacing); - - if (Repository != null) - { - OnRepositorySettingsGUI(); - - GUILayout.Space(EditorGUIUtility.standardVerticalSpacing); - - OnGitLfsLocksGUI(); - - GUILayout.Space(EditorGUIUtility.standardVerticalSpacing); - } - - gitPathView.OnGUI(); - OnPrivacyGui(); - OnLoggingSettingsGui(); + return; } - - GUILayout.EndScrollView(); } private void MaybeUpdateData() From 3ae8c946836f1ce74c470375c88af240e3f60873 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Mon, 6 Nov 2017 13:09:38 -0500 Subject: [PATCH 231/241] Making fields public so they can be serialized --- src/GitHub.Api/Git/GitBranch.cs | 6 +++--- src/GitHub.Api/Git/GitRemote.cs | 14 +++++++------- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/src/GitHub.Api/Git/GitBranch.cs b/src/GitHub.Api/Git/GitBranch.cs index fb0297628..733b845df 100644 --- a/src/GitHub.Api/Git/GitBranch.cs +++ b/src/GitHub.Api/Git/GitBranch.cs @@ -13,9 +13,9 @@ public struct GitBranch : ITreeData { public static GitBranch Default = new GitBranch(); - private string name; - private string tracking; - private bool isActive; + public string name; + public string tracking; + public bool isActive; public string Name { get { return name; } } public string Tracking { get { return tracking; } } diff --git a/src/GitHub.Api/Git/GitRemote.cs b/src/GitHub.Api/Git/GitRemote.cs index bc64c3be6..b91cf2da9 100644 --- a/src/GitHub.Api/Git/GitRemote.cs +++ b/src/GitHub.Api/Git/GitRemote.cs @@ -16,13 +16,13 @@ public struct GitRemote { public static GitRemote Default = new GitRemote(); - private string name; - private string url; - private string login; - private string user; - private string host; - private GitRemoteFunction function; - private readonly string token; + public string name; + public string url; + public string login; + public string user; + public string host; + public GitRemoteFunction function; + public readonly string token; public string Name { From 9e39cb4c937e145ba3e981cd714acc1e8bd16464 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Mon, 6 Nov 2017 13:10:04 -0500 Subject: [PATCH 232/241] Removing readonly on GitRemote.token --- src/GitHub.Api/Git/GitRemote.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/GitHub.Api/Git/GitRemote.cs b/src/GitHub.Api/Git/GitRemote.cs index b91cf2da9..f380db01b 100644 --- a/src/GitHub.Api/Git/GitRemote.cs +++ b/src/GitHub.Api/Git/GitRemote.cs @@ -22,7 +22,7 @@ public struct GitRemote public string user; public string host; public GitRemoteFunction function; - public readonly string token; + public string token; public string Name { From 1528234382cd1ebb1eca7926b4f58342e4633746 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Mon, 6 Nov 2017 13:14:46 -0500 Subject: [PATCH 233/241] Populating name if null --- src/GitHub.Api/Git/Repository.cs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/GitHub.Api/Git/Repository.cs b/src/GitHub.Api/Git/Repository.cs index 1c09d9cfb..f4c3359c9 100644 --- a/src/GitHub.Api/Git/Repository.cs +++ b/src/GitHub.Api/Git/Repository.cs @@ -628,6 +628,10 @@ public string Name { name = url.RepositoryName; } + else + { + name = LocalPath.FileName; + } } return name; } From 0b96c44397ad53e86f4b385f913346bd9fbacedd Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Mon, 6 Nov 2017 13:43:48 -0500 Subject: [PATCH 234/241] Fixes needed after merge --- .../Assets/Editor/GitHub.Unity/UI/BranchesView.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs index c91b4a855..43535e72a 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/BranchesView.cs @@ -56,14 +56,14 @@ public override void InitializeView(IView parent) targetMode = mode; } - private void Repository_BranchCacheUpdated(CacheUpdateEvent cacheUpdateEvent) + private void RepositoryOnLocalAndRemoteBranchListChanged(CacheUpdateEvent cacheUpdateEvent) { - if (!branchUpdateEvent.Equals(cacheUpdateEvent)) + if (!lastLocalAndRemoteBranchListChangedEvent.Equals(cacheUpdateEvent)) { new ActionTask(TaskManager.Token, () => { - branchUpdateEvent = cacheUpdateEvent; - branchCacheHasUpdate = true; + lastLocalAndRemoteBranchListChangedEvent = cacheUpdateEvent; + localAndRemoteBranchListHasUpdate = true; Redraw(); }) { Affinity = TaskAffinity.UI }.Start(); From f15a29552858ef6cf9b9eef3bf23dcfadc92f967 Mon Sep 17 00:00:00 2001 From: Andreia Gaita Date: Mon, 6 Nov 2017 20:18:25 -0800 Subject: [PATCH 235/241] Cleanup GitRemote class --- src/GitHub.Api/Git/GitRemote.cs | 57 +++++++++------------------------ 1 file changed, 15 insertions(+), 42 deletions(-) diff --git a/src/GitHub.Api/Git/GitRemote.cs b/src/GitHub.Api/Git/GitRemote.cs index f380db01b..f8e2c0529 100644 --- a/src/GitHub.Api/Git/GitRemote.cs +++ b/src/GitHub.Api/Git/GitRemote.cs @@ -24,41 +24,6 @@ public struct GitRemote public GitRemoteFunction function; public string token; - public string Name - { - get { return name; } - } - - public string Url - { - get { return url; } - } - - public string Login - { - get { return login; } - } - - public string User - { - get { return user; } - } - - public string Token - { - get { return token; } - } - - public string Host - { - get { return host; } - } - - public GitRemoteFunction Function - { - get { return function; } - } - public GitRemote(string name, string host, string url, GitRemoteFunction function, string user, string login, string token) { this.name = name; @@ -77,8 +42,8 @@ public GitRemote(string name, string host, string url, GitRemoteFunction functio this.host = host; this.function = function; this.user = user; - login = null; - token = null; + this.login = null; + this.token = null; } public GitRemote(string name, string host, string url, GitRemoteFunction function) @@ -96,11 +61,11 @@ public GitRemote(string name, string url) { this.name = name; this.url = url; - login = null; - user = null; - token = null; - host = null; - function = GitRemoteFunction.Unknown; + this.login = null; + this.user = null; + this.token = null; + this.host = null; + this.function = GitRemoteFunction.Unknown; } public override string ToString() @@ -114,5 +79,13 @@ public override string ToString() sb.AppendLine(String.Format("Function: {0}", Function)); return sb.ToString(); } + + public string Name => name; + public string Url => url; + public string Login => login; + public string User => user; + public string Token => token; + public string Host => host; + public GitRemoteFunction Function => function; } } \ No newline at end of file From 08705a7250605a79fbc9a6fd1aa35df7144e2a13 Mon Sep 17 00:00:00 2001 From: Andreia Gaita Date: Mon, 6 Nov 2017 20:28:17 -0800 Subject: [PATCH 236/241] Format SerializableDictionary according to our coding style --- .../GitHub.Unity/SerializableDictionary.cs | 27 ++++++++++--------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/SerializableDictionary.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/SerializableDictionary.cs index 84b69c38e..0efc80e8b 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/SerializableDictionary.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/SerializableDictionary.cs @@ -1,9 +1,7 @@ using System; using System.Collections.Generic; -using System.Linq; using UnityEngine; - namespace GitHub.Unity { //http://answers.unity3d.com/answers/809221/view.html @@ -11,18 +9,15 @@ namespace GitHub.Unity [Serializable] public class SerializableDictionary : Dictionary, ISerializationCallbackReceiver { - [SerializeField] - private List keys = new List(); - - [SerializeField] - private List values = new List(); + [SerializeField] private List keys = new List(); + [SerializeField] private List values = new List(); // save the dictionary to lists public void OnBeforeSerialize() { keys.Clear(); values.Clear(); - foreach (KeyValuePair pair in this) + foreach (var pair in this) { keys.Add(pair.Key); values.Add(pair.Value); @@ -32,13 +27,19 @@ public void OnBeforeSerialize() // load dictionary from lists public void OnAfterDeserialize() { - this.Clear(); + Clear(); if (keys.Count != values.Count) - throw new Exception(string.Format("there are {0} keys and {1} values after deserialization. Make sure that both key and value types are serializable.", keys.Count, values.Count)); + { + throw new Exception( + string.Format("there are {0} keys and {1} values after deserialization. Make sure that both key and value types are serializable.", + keys.Count, values.Count)); + } - for (int i = 0; i < keys.Count; i++) - this.Add(keys[i], values[i]); + for (var i = 0; i < keys.Count; i++) + { + Add(keys[i], values[i]); + } } } -} \ No newline at end of file +} From 76a11f7458e5ca397bc7f4e55b6a071ffda14bc8 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Tue, 7 Nov 2017 12:19:08 -0500 Subject: [PATCH 237/241] Removing UserSettingsView and GitPathView from InitProjectView --- .../Editor/GitHub.Unity/UI/InitProjectView.cs | 16 +--------------- 1 file changed, 1 insertion(+), 15 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs index 401721e72..94412db71 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs @@ -11,9 +11,6 @@ class InitProjectView : Subview private const string NoRepoDescription = "Initialize a Git repository to track changes and collaborate with others."; private const string NoUserOrEmailError = "Name and Email must be configured in Settings"; - [SerializeField] private UserSettingsView userSettingsView = new UserSettingsView(); - [SerializeField] private GitPathView gitPathView = new GitPathView(); - [NonSerialized] private bool isBusy; [NonSerialized] private string errorMessage; @@ -24,9 +21,6 @@ public override void InitializeView(IView parent) { base.InitializeView(parent); - userSettingsView.InitializeView(this); - gitPathView.InitializeView(this); - if (!string.IsNullOrEmpty(Environment.GitExecutablePath)) { CheckForUser(); @@ -36,17 +30,9 @@ public override void InitializeView(IView parent) public override void OnEnable() { base.OnEnable(); - gitPathView.OnEnable(); userDataHasChanged = Environment.GitExecutablePath != null; } - public override void OnDataUpdate() - { - base.OnDataUpdate(); - userSettingsView.OnDataUpdate(); - gitPathView.OnDataUpdate(); - } - public override void OnGUI() { GUILayout.BeginVertical(Styles.GenericBoxStyle); @@ -124,7 +110,7 @@ private void CheckForUser() public override bool IsBusy { - get { return isBusy || userSettingsView.IsBusy || gitPathView.IsBusy; } + get { return isBusy; } } } } From fbd8f994d8fafb6b6f2e123ceb55e49838156b22 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Tue, 7 Nov 2017 12:24:24 -0500 Subject: [PATCH 238/241] Hiding error is user data is present --- .../Assets/Editor/GitHub.Unity/UI/InitProjectView.cs | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs index 94412db71..b31712b92 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs @@ -69,11 +69,13 @@ public override void OnGUI() GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); - EditorGUILayout.Space(); - EditorGUILayout.HelpBox( - "Name and email not set in git. Go into the settings tab and enter the missing information", - MessageType.Error - ); + if (!isUserDataPresent) + { + EditorGUILayout.Space(); + EditorGUILayout.HelpBox( + "Name and email not set in git. Go into the settings tab and enter the missing information", + MessageType.Error); + } GUILayout.FlexibleSpace(); } From 812f97454537733b0fa91c832210d8905c301314 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Tue, 7 Nov 2017 12:26:55 -0500 Subject: [PATCH 239/241] Formatting some code --- .../Editor/GitHub.Unity/UI/InitProjectView.cs | 24 ++++++++++--------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs index b31712b92..1763e7485 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs @@ -52,21 +52,23 @@ public override void OnGUI() GUILayout.Space(4); GUILayout.BeginHorizontal(); - GUILayout.FlexibleSpace(); - - EditorGUI.BeginDisabledGroup(IsBusy || !isUserDataPresent); { - if (GUILayout.Button(Localization.InitializeRepositoryButtonText, "Button")) + GUILayout.FlexibleSpace(); + + EditorGUI.BeginDisabledGroup(IsBusy || !isUserDataPresent); { - isBusy = true; - Manager.InitializeRepository() - .FinallyInUI(() => isBusy = false) - .Start(); + if (GUILayout.Button(Localization.InitializeRepositoryButtonText, "Button")) + { + isBusy = true; + Manager.InitializeRepository() + .FinallyInUI(() => isBusy = false) + .Start(); + } } - } - EditorGUI.EndDisabledGroup(); + EditorGUI.EndDisabledGroup(); - GUILayout.FlexibleSpace(); + GUILayout.FlexibleSpace(); + } GUILayout.EndHorizontal(); if (!isUserDataPresent) From 99ab5428e313ac6d4e419e0f09dc0ac772ae5819 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Tue, 7 Nov 2017 12:32:12 -0500 Subject: [PATCH 240/241] Cleaning up messages --- .../Assets/Editor/GitHub.Unity/UI/InitProjectView.cs | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs index 1763e7485..39de2f269 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs @@ -8,12 +8,10 @@ namespace GitHub.Unity class InitProjectView : Subview { private const string NoRepoTitle = "To begin using GitHub, initialize a git repository"; - private const string NoRepoDescription = "Initialize a Git repository to track changes and collaborate with others."; - private const string NoUserOrEmailError = "Name and Email must be configured in Settings"; + private const string NoUserOrEmailError = "Name and email not set in git. Go into the settings tab and enter the missing information"; [NonSerialized] private bool isBusy; - [NonSerialized] private string errorMessage; [NonSerialized] private bool isUserDataPresent; [NonSerialized] private bool userDataHasChanged; @@ -74,9 +72,7 @@ public override void OnGUI() if (!isUserDataPresent) { EditorGUILayout.Space(); - EditorGUILayout.HelpBox( - "Name and email not set in git. Go into the settings tab and enter the missing information", - MessageType.Error); + EditorGUILayout.HelpBox(NoUserOrEmailError, MessageType.Error); } GUILayout.FlexibleSpace(); @@ -101,10 +97,8 @@ private void CheckForUser() var username = strings[0]; var email = strings[1]; - isBusy = false; isUserDataPresent = success && !String.IsNullOrEmpty(username) && !String.IsNullOrEmpty(email); - errorMessage = isUserDataPresent ? null : NoUserOrEmailError; Logger.Trace("Finally: {0}", isUserDataPresent); From 39eb5dac1b73cac0744b78ae3facb0ca746c6489 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Tue, 7 Nov 2017 12:49:42 -0500 Subject: [PATCH 241/241] Changing how InitProjectView updates itself --- .../Editor/GitHub.Unity/UI/InitProjectView.cs | 30 +++++++++++-------- 1 file changed, 17 insertions(+), 13 deletions(-) diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs index 39de2f269..fa87e3454 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/InitProjectView.cs @@ -11,20 +11,10 @@ class InitProjectView : Subview private const string NoUserOrEmailError = "Name and email not set in git. Go into the settings tab and enter the missing information"; [NonSerialized] private bool isBusy; - [NonSerialized] private bool isUserDataPresent; + [NonSerialized] private bool hasCompletedInitialCheck; [NonSerialized] private bool userDataHasChanged; - public override void InitializeView(IView parent) - { - base.InitializeView(parent); - - if (!string.IsNullOrEmpty(Environment.GitExecutablePath)) - { - CheckForUser(); - } - } - public override void OnEnable() { base.OnEnable(); @@ -69,7 +59,7 @@ public override void OnGUI() } GUILayout.EndHorizontal(); - if (!isUserDataPresent) + if (hasCompletedInitialCheck && !isUserDataPresent) { EditorGUILayout.Space(); EditorGUILayout.HelpBox(NoUserOrEmailError, MessageType.Error); @@ -80,6 +70,12 @@ public override void OnGUI() GUILayout.EndVertical(); } + public override void OnDataUpdate() + { + base.OnDataUpdate(); + MaybeUpdateData(); + } + private void MaybeUpdateData() { if (userDataHasChanged) @@ -91,6 +87,13 @@ private void MaybeUpdateData() private void CheckForUser() { + if (string.IsNullOrEmpty(Environment.GitExecutablePath)) + { + Logger.Warning("No git exec cannot check for user"); + return; + } + + Logger.Trace("Checking for user"); isBusy = true; GitClient.GetConfigUserAndEmail().FinallyInUI((success, ex, strings) => { @@ -99,8 +102,9 @@ private void CheckForUser() isBusy = false; isUserDataPresent = success && !String.IsNullOrEmpty(username) && !String.IsNullOrEmpty(email); + hasCompletedInitialCheck = true; - Logger.Trace("Finally: {0}", isUserDataPresent); + Logger.Trace("User Present: {0}", isUserDataPresent); Redraw(); }).Start();