From e63a9146deb2d9d2fc8e61e60af9e853b646d5f2 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Wed, 7 Mar 2018 15:51:46 -0500 Subject: [PATCH 1/7] Removing Octorun --- GitHub.Unity.sln | 8 - appveyor.yml | 3 - package.cmd | 3 - package.sh | 1 - src/OctoRun/ApiClient.cs | 56 - src/OctoRun/ApiExceptionExtensions.cs | 25 - src/OctoRun/App.config | 6 - src/OctoRun/AppConfiguration.cs | 26 - src/OctoRun/ApplicationInfo.cs | 27 - src/OctoRun/ConsoleLogAdapter.cs | 47 - src/OctoRun/CredentialStore.cs | 25 - src/OctoRun/Guard.cs | 91 - src/OctoRun/HostAddress.cs | 111 -- src/OctoRun/LoginManager.cs | 297 ---- src/OctoRun/NiceIO.cs | 1470 ----------------- src/OctoRun/OctoRun.csproj | 112 -- src/OctoRun/Program.cs | 116 -- src/OctoRun/Properties/AssemblyInfo.cs | 12 - src/OctoRun/StringEquivalent.cs | 109 -- src/OctoRun/StringExtensions.cs | 160 -- src/OctoRun/UriExtensions.cs | 38 - src/OctoRun/UriString.cs | 285 ---- src/OctoRun/packages.config | 5 - .../Editor/GitHub.Unity/GitHub.Unity.csproj | 12 - 24 files changed, 3045 deletions(-) delete mode 100644 src/OctoRun/ApiClient.cs delete mode 100644 src/OctoRun/ApiExceptionExtensions.cs delete mode 100644 src/OctoRun/App.config delete mode 100644 src/OctoRun/AppConfiguration.cs delete mode 100644 src/OctoRun/ApplicationInfo.cs delete mode 100644 src/OctoRun/ConsoleLogAdapter.cs delete mode 100644 src/OctoRun/CredentialStore.cs delete mode 100644 src/OctoRun/Guard.cs delete mode 100644 src/OctoRun/HostAddress.cs delete mode 100644 src/OctoRun/LoginManager.cs delete mode 100644 src/OctoRun/NiceIO.cs delete mode 100644 src/OctoRun/OctoRun.csproj delete mode 100644 src/OctoRun/Program.cs delete mode 100644 src/OctoRun/Properties/AssemblyInfo.cs delete mode 100644 src/OctoRun/StringEquivalent.cs delete mode 100644 src/OctoRun/StringExtensions.cs delete mode 100644 src/OctoRun/UriExtensions.cs delete mode 100644 src/OctoRun/UriString.cs delete mode 100644 src/OctoRun/packages.config diff --git a/GitHub.Unity.sln b/GitHub.Unity.sln index 64ae234f2..db12af918 100644 --- a/GitHub.Unity.sln +++ b/GitHub.Unity.sln @@ -29,8 +29,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestApp", "src\tests\TestAp EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestWebServer", "src\tests\TestWebServer\TestWebServer.csproj", "{3DD3451C-30FA-4294-A3A9-1E080342F867}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OctoRun", "src\OctoRun\OctoRun.csproj", "{127F84FE-DB89-4543-9A83-74DB4E751061}" -EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -104,12 +102,6 @@ Global {3DD3451C-30FA-4294-A3A9-1E080342F867}.dev|Any CPU.Build.0 = Debug|Any CPU {3DD3451C-30FA-4294-A3A9-1E080342F867}.Release|Any CPU.ActiveCfg = Release|Any CPU {3DD3451C-30FA-4294-A3A9-1E080342F867}.Release|Any CPU.Build.0 = Release|Any CPU - {127F84FE-DB89-4543-9A83-74DB4E751061}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {127F84FE-DB89-4543-9A83-74DB4E751061}.Debug|Any CPU.Build.0 = Debug|Any CPU - {127F84FE-DB89-4543-9A83-74DB4E751061}.dev|Any CPU.ActiveCfg = Debug|Any CPU - {127F84FE-DB89-4543-9A83-74DB4E751061}.dev|Any CPU.Build.0 = Debug|Any CPU - {127F84FE-DB89-4543-9A83-74DB4E751061}.Release|Any CPU.ActiveCfg = Release|Any CPU - {127F84FE-DB89-4543-9A83-74DB4E751061}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/appveyor.yml b/appveyor.yml index 2bcf0501c..a5d0c4580 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -43,9 +43,6 @@ install: nuget restore GitHub.Unity.sln -before_build: - - cmd: msbuild GitHub.Unity.sln /target:OctoRun /property:Configuration=Release - assembly_info: patch: false file: common\SolutionInfo.cs diff --git a/package.cmd b/package.cmd index e71dbbb66..e25ddbd41 100644 --- a/package.cmd +++ b/package.cmd @@ -39,9 +39,6 @@ if not exist "%Unity%" ( cd .. call common\nuget.exe restore GitHub.Unity.sln - echo xbuild GitHub.Unity.sln /target:OctoRun /property:Configuration=%Configuration% - call xbuild GitHub.Unity.sln /target:OctoRun /property:Configuration=%Configuration% - echo xbuild GitHub.Unity.sln /property:Configuration=%Configuration% call xbuild GitHub.Unity.sln /property:Configuration=%Configuration% diff --git a/package.sh b/package.sh index b2ce61ee9..ca09bd5e5 100755 --- a/package.sh +++ b/package.sh @@ -51,7 +51,6 @@ else nuget restore GitHub.Unity.sln fi -xbuild GitHub.Unity.sln /target:OctoRun /property:Configuration=$Configuration xbuild GitHub.Unity.sln /property:Configuration=$Configuration rm -f unity/PackageProject/Assets/Plugins/GitHub/Editor/deleteme* diff --git a/src/OctoRun/ApiClient.cs b/src/OctoRun/ApiClient.cs deleted file mode 100644 index a3bdd5e91..000000000 --- a/src/OctoRun/ApiClient.cs +++ /dev/null @@ -1,56 +0,0 @@ -using System; -using System.Threading.Tasks; -using GitHub.Logging; -using GitHub.Unity; -using Octokit; -using static OctoRun.LoginManager; - -namespace OctoRun -{ - class ApiClient - { - private readonly ILogging logger = LogHelper.GetLogger(); - - private readonly GitHubClient client; - private readonly LoginManager loginManager; - private readonly IKeychain keychain; - - public ApiClient(IKeychain keychain, HostAddress host) - { - this.keychain = keychain; - client = new GitHubClient(AppConfiguration.ProductHeader, keychain as ICredentialStore, host.ApiUri); - loginManager = new LoginManager(keychain, ApplicationInfo.ClientId, ApplicationInfo.ClientSecret); - } - - public LoginResult Login() - { - LoginResultData res = null; - try - { - res = loginManager.Login(client); - } - catch (Exception ex) - { - logger.Warning(ex); - return new LoginResult(new LoginResultData(LoginResultCodes.Failed, ex.Message), null); - } - - return new LoginResult(res); - } - - public LoginResult ContinueLogin() - { - LoginResultData result = null; - try - { - result = loginManager.ContinueLogin(client); - } - catch (Exception ex) - { - return new LoginResult(new LoginResultData(LoginResultCodes.Failed, ex.Message), null); - } - return new LoginResult(result); - } - - } -} \ No newline at end of file diff --git a/src/OctoRun/ApiExceptionExtensions.cs b/src/OctoRun/ApiExceptionExtensions.cs deleted file mode 100644 index 37b272a81..000000000 --- a/src/OctoRun/ApiExceptionExtensions.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System; -using System.Linq; -using Octokit; - -namespace OctoRun -{ - static class ApiExceptionExtensions - { - const string GithubHeader = "X-GitHub-Request-Id"; - public static bool IsGitHubApiException(this Exception ex) - { - var apiex = ex as ApiException; - return apiex?.HttpResponse?.Headers.ContainsKey(GithubHeader) ?? false; - } - - public static string FirstErrorMessageSafe(this ApiError apiError) - { - if (apiError == null) return null; - if (apiError.Errors == null) return apiError.Message; - var firstError = apiError.Errors.FirstOrDefault(); - return firstError == null ? null : firstError.Message; - } - - } -} \ No newline at end of file diff --git a/src/OctoRun/App.config b/src/OctoRun/App.config deleted file mode 100644 index 88fa4027b..000000000 --- a/src/OctoRun/App.config +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/src/OctoRun/AppConfiguration.cs b/src/OctoRun/AppConfiguration.cs deleted file mode 100644 index 918f31f68..000000000 --- a/src/OctoRun/AppConfiguration.cs +++ /dev/null @@ -1,26 +0,0 @@ -using GitHub.Unity; -using Octokit; -using System.Reflection; - -namespace OctoRun -{ - static class AppConfiguration - { - static AppConfiguration() - { - var executingAssembly = typeof(AppConfiguration).Assembly; - AssemblyName = executingAssembly.GetName(); - ProductHeader = new ProductHeaderValue(ApplicationInfo.ApplicationSafeName, AssemblyName.Version.ToString()); - } - - /// - /// The currently executing assembly. - /// - public static AssemblyName AssemblyName { get; private set; } - - /// - /// The product header used in the user agent. - /// - public static ProductHeaderValue ProductHeader { get; private set; } - } -} \ No newline at end of file diff --git a/src/OctoRun/ApplicationInfo.cs b/src/OctoRun/ApplicationInfo.cs deleted file mode 100644 index 7a80e498d..000000000 --- a/src/OctoRun/ApplicationInfo.cs +++ /dev/null @@ -1,27 +0,0 @@ -namespace GitHub.Unity -{ - static partial class ApplicationInfo - { -#if DEBUG - public const string ApplicationName = "GitHubUnityDebug"; - public const string ApplicationProvider = "GitHub"; -#else - public const string ApplicationName = "GitHubUnity"; - public const string ApplicationProvider = "GitHub"; -#endif - public const string ApplicationSafeName = "unity-internal-test"; - public const string ApplicationDescription = "GitHub for Unity"; - - internal static string ClientId { get; private set; } = ""; - internal static string ClientSecret { get; private set; } = ""; - - public static string Version { get { return System.AssemblyVersionInformation.Version; } } - - static partial void SetClientData(); - - static ApplicationInfo() - { - SetClientData(); - } - } -} \ No newline at end of file diff --git a/src/OctoRun/ConsoleLogAdapter.cs b/src/OctoRun/ConsoleLogAdapter.cs deleted file mode 100644 index 44111de52..000000000 --- a/src/OctoRun/ConsoleLogAdapter.cs +++ /dev/null @@ -1,47 +0,0 @@ -using System; -using GitHub.Unity; -using System.Threading; -using GitHub.Logging; - -namespace OctoRun -{ - public class ConsoleLogAdapter : LogAdapterBase - { - private string GetMessage(string level, string context, string message) - { - var time = DateTime.Now.ToString("HH:mm:ss.fff tt"); - var threadId = Thread.CurrentThread.ManagedThreadId; - return string.Format("{0} {1} [{2,2}] {3} {4}", time, level, threadId, context, message); - } - - public override void Info(string context, string message) - { - WriteLine("INFO", context, message); - } - - public override void Debug(string context, string message) - { - WriteLine("DEBUG", context, message); - } - - public override void Trace(string context, string message) - { - WriteLine("TRACE", context, message); - } - - public override void Warning(string context, string message) - { - WriteLine("WARN", context, message); - } - - public override void Error(string context, string message) - { - WriteLine("ERROR", context, message); - } - - private void WriteLine(string level, string context, string message) - { - Console.Error.WriteLine(GetMessage(level, context, message)); - } - } -} \ No newline at end of file diff --git a/src/OctoRun/CredentialStore.cs b/src/OctoRun/CredentialStore.cs deleted file mode 100644 index 5ccf9fd22..000000000 --- a/src/OctoRun/CredentialStore.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System.Threading.Tasks; -using Octokit; - -namespace OctoRun -{ - interface IKeychain - { - string Login { get; set; } - string Token { get; set; } - string Code { get; set; } - } - - - class CredentialStore : ICredentialStore, IKeychain - { - public string Login { get; set; } - public string Token { get; set; } - public string Code { get; set; } - - public Task GetCredentials() - { - return Task.FromResult(new Credentials(Login, Token)); - } - } -} \ No newline at end of file diff --git a/src/OctoRun/Guard.cs b/src/OctoRun/Guard.cs deleted file mode 100644 index 1488f9f67..000000000 --- a/src/OctoRun/Guard.cs +++ /dev/null @@ -1,91 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Linq; - -namespace OctoRun -{ - internal class InstanceNotInitializedException : InvalidOperationException - { - public InstanceNotInitializedException(object the, string property) : - base(String.Format(CultureInfo.InvariantCulture, "{0} is not correctly initialized, {1} is null", the?.GetType().Name, property)) - {} - } - - internal static class Guard - { - public static void NotNull(object the, object value, string propertyName) - { - if (value != null) return; - throw new InstanceNotInitializedException(the, propertyName); - } - - public static void ArgumentNotNull(object value, string name) - { - if (value != null) return; - string message = String.Format(CultureInfo.InvariantCulture, "Failed Null Check on '{0}'", name); - throw new ArgumentNullException(name, message); - } - - public static void ArgumentNotNullOrEmpty(IList value, string name) - { - if (value == null) - { - string message = String.Format(CultureInfo.InvariantCulture, "Failed Null Check on '{0}'", name); - throw new ArgumentNullException(name, message); - } - - if (!value.Any()) - { - string message = String.Format(CultureInfo.InvariantCulture, "Failed Empty Check on '{0}'", name); - throw new ArgumentNullException(name, message); - } - } - - public static void ArgumentNonNegative(int value, string name) - { - if (value > -1) return; - - var message = String.Format(CultureInfo.InvariantCulture, "The value for '{0}' must be non-negative", name); - throw new ArgumentException(message, name); - } - - /// - /// Checks a string argument to ensure it isn't null or empty. - /// - /// The argument value to check. - /// The name of the argument. - public static void ArgumentNotNullOrWhiteSpace(string value, string name) - { - if (value != null && value.Trim().Length > 0) - return; - string message = String.Format(CultureInfo.InvariantCulture, "The value for '{0}' must not be empty", name); - throw new ArgumentException(message, name); - } - - public static void ArgumentInRange(int value, int minValue, string name) - { - if (value >= minValue) return; - string message = String.Format(CultureInfo.InvariantCulture, - "The value '{0}' for '{1}' must be greater than or equal to '{2}'", - value, - name, - minValue); - throw new ArgumentOutOfRangeException(name, message); - } - - public static void ArgumentInRange(int value, int minValue, int maxValue, string name) - { - if (value >= minValue && value <= maxValue) return; - string message = String.Format(CultureInfo.InvariantCulture, - "The value '{0}' for '{1}' must be greater than or equal to '{2}' and less than or equal to '{3}'", - value, - name, - minValue, - maxValue); - throw new ArgumentOutOfRangeException(name, message); - } - - public static bool InUnitTestRunner { get; set; } - } -} \ No newline at end of file diff --git a/src/OctoRun/HostAddress.cs b/src/OctoRun/HostAddress.cs deleted file mode 100644 index 65dfc0b7f..000000000 --- a/src/OctoRun/HostAddress.cs +++ /dev/null @@ -1,111 +0,0 @@ -using System; -using System.Globalization; - -namespace OctoRun -{ - public class HostAddress - { - public static HostAddress GitHubDotComHostAddress = new HostAddress(); - static readonly Uri gistUri = new Uri("https://gist.github.com"); - - /// - /// Creates a host address based on the hostUri based on the expected patterns for GitHub.com and - /// GitHub Enterprise instances. The passed in URI can be any URL to the instance. - /// - /// The URI to a GitHub or GitHub Enterprise instance. - /// - public static HostAddress Create(Uri hostUri) - { - return IsGitHubDotCom(hostUri) - ? GitHubDotComHostAddress - : new HostAddress(hostUri); - } - - /// - /// Creates a host address from a host name or URL as a string. - /// - /// - /// - public static HostAddress Create(string host) - { - Uri uri; - if (Uri.TryCreate(host, UriKind.Absolute, out uri) - || Uri.TryCreate("https://" + host, UriKind.Absolute, out uri)) - { - return Create(uri); - } - throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, - "The host '{0}' is not a valid host", - host)); - } - - private HostAddress(Uri enterpriseUri) - { - WebUri = new Uri(enterpriseUri, new Uri("/", UriKind.Relative)); - ApiUri = new Uri(enterpriseUri, new Uri("/api/v3/", UriKind.Relative)); - CredentialCacheKeyHost = WebUri.ToString(); - } - - public HostAddress() - { - WebUri = new Uri("https://github.com"); - ApiUri = new Uri("https://api.github.com"); - CredentialCacheKeyHost = WebUri.ToString(); - } - - /// - /// The Base URL to the host. For example, "https://github.com" or "https://ghe.io" - /// - public Uri WebUri { get; set; } - - /// - /// The Base Url to the host's API endpoint. For example, "https://api.github.com" or - /// "https://ghe.io/api/v3" - /// - public Uri ApiUri { get; set; } - - // If the host name is "api.github.com" or "gist.github.com", we really only want "github.com", - // since that's the same cache key for all the other github.com operations. - public string CredentialCacheKeyHost { get; private set; } - - public static bool IsGitHubDotCom(Uri hostUri) - { - return hostUri.IsSameHost(GitHubDotComHostAddress.WebUri) - || hostUri.IsSameHost(GitHubDotComHostAddress.ApiUri) - || hostUri.IsSameHost(gistUri); - } - - public static bool IsGitHubDotCom(string url) - { - if (String.IsNullOrEmpty(url)) - return false; - Uri uri = null; - if (!Uri.TryCreate(url, UriKind.Absolute, out uri)) - return false; - return IsGitHubDotCom(uri); - } - - public bool IsGitHubDotCom() - { - return IsGitHubDotCom(ApiUri); - } - - public string Title - { - get { return IsGitHubDotCom() ? "GitHub" : ApiUri.Host; } - } - - public override int GetHashCode() - { - return (WebUri?.GetHashCode() ?? 0) ^ (ApiUri?.GetHashCode() ?? 0); - } - - public override bool Equals(object obj) - { - if (ReferenceEquals(this, obj)) - return true; - var other = obj as HostAddress; - return other != null && WebUri.IsSameHost(other.WebUri) && ApiUri.IsSameHost(other.ApiUri); - } - } -} diff --git a/src/OctoRun/LoginManager.cs b/src/OctoRun/LoginManager.cs deleted file mode 100644 index 808d90b30..000000000 --- a/src/OctoRun/LoginManager.cs +++ /dev/null @@ -1,297 +0,0 @@ -using System; -using System.Net; -using System.Threading.Tasks; -using GitHub.Unity; -using Octokit; -using System.Diagnostics; -using GitHub.Logging; - -namespace OctoRun -{ - class LoginManager - { - private readonly ILogging logger = LogHelper.GetLogger(); - - private readonly string[] scopes = { "user", "repo", "gist", "write:public_key" }; - private readonly string clientId; - private readonly string clientSecret; - private readonly string authorizationNote; - private readonly string fingerprint; - private readonly IKeychain keychain; - - public LoginManager( - IKeychain keychain, - string clientId, - string clientSecret, - string authorizationNote = null, - string fingerprint = null) - { - Guard.ArgumentNotNull(keychain, nameof(keychain)); - Guard.ArgumentNotNullOrWhiteSpace(clientId, nameof(clientId)); - Guard.ArgumentNotNullOrWhiteSpace(clientSecret, nameof(clientSecret)); - - this.keychain = keychain; - this.clientId = clientId; - this.clientSecret = clientSecret; - this.authorizationNote = authorizationNote; - this.fingerprint = fingerprint; - } - - public LoginResultData Login(IGitHubClient client) - { - Guard.ArgumentNotNull(client, nameof(client)); - - var newAuth = new NewAuthorization - { - Scopes = scopes, - Note = authorizationNote, - Fingerprint = fingerprint, - }; - - ApplicationAuthorization auth = null; - - try - { - try - { - logger.Info("Login Username:{0}", keychain.Login); - - auth = CreateAndDeleteExistingApplicationAuthorization(client, newAuth, null).Result; - EnsureNonNullAuthorization(auth); - } - catch (AggregateException ex) - { - throw ex.InnerException; - } - } - catch (TwoFactorAuthorizationException e) - { - LoginResultCodes result; - if (e is TwoFactorRequiredException) - { - result = LoginResultCodes.CodeRequired; - logger.Trace("2FA TwoFactorAuthorizationException: {0} {1}", LoginResultCodes.CodeRequired, "2fa"); - } - else - { - result = LoginResultCodes.CodeFailed; - logger.Error(e, "2FA TwoFactorAuthorizationException: {0} {1}", LoginResultCodes.CodeRequired, "wrong"); - } - - return new LoginResultData(result, e.Message, client, newAuth); - } - catch (LoginAttemptsExceededException e) - { - logger.Warning(e, "Login LoginAttemptsExceededException: {0}", e.Message); - - return new LoginResultData(LoginResultCodes.LockedOut, "locked"); - } - catch (ApiValidationException e) - { - logger.Warning(e, "Login ApiValidationException: {0}", e.Message); - - var message = e.ApiError.FirstErrorMessageSafe(); - return new LoginResultData(LoginResultCodes.Failed, message); - } - catch (Exception e) - { - logger.Warning(e, "Login Exception"); - - // Some enterprise instances don't support OAUTH, so fall back to using the - // supplied password - on instances that don't support OAUTH the user should - // be using a personal access token as the password. - if (EnterpriseWorkaround(client.Connection.BaseAddress.ToUriString(), e)) - { - auth = new ApplicationAuthorization(keychain.Token); - } - else - { - return new LoginResultData(LoginResultCodes.Failed, "failed"); - } - } - - keychain.Token = auth.Token; - - return new LoginResultData(LoginResultCodes.Success, auth.Token); - } - - - public LoginResultData ContinueLogin(IGitHubClient client) - { - var twofacode = keychain.Code; - var newAuth = new NewAuthorization - { - Scopes = scopes, - Note = authorizationNote, - Fingerprint = fingerprint, - }; - - try - { - logger.Trace("2FA Continue"); - - var auth = CreateAndDeleteExistingApplicationAuthorization( - client, - newAuth, - twofacode).Result; - EnsureNonNullAuthorization(auth); - - keychain.Token = auth.Token; - - return new LoginResultData(LoginResultCodes.Success, ""); - } - catch (AggregateException ex) - { - throw ex.InnerException; - } - catch (TwoFactorAuthorizationException e) - { - logger.Trace(e, "2FA TwoFactorAuthorizationException: {0} {1}", LoginResultCodes.CodeFailed, e.Message); - - return new LoginResultData(LoginResultCodes.CodeFailed, "wrong code", client, newAuth); - } - catch (ApiValidationException e) - { - logger.Trace(e, "2FA ApiValidationException: {0}", e.Message); - - var message = e.ApiError.FirstErrorMessageSafe(); - return new LoginResultData(LoginResultCodes.Failed, message); - } - catch (Exception e) - { - logger.Trace(e, "Exception: {0}", e.Message); - - return new LoginResultData(LoginResultCodes.Failed, e.Message); - } - } - - private async Task CreateAndDeleteExistingApplicationAuthorization( - IGitHubClient client, - NewAuthorization newAuth, - string twoFactorAuthenticationCode) - { - ApplicationAuthorization result = null; - var retry = 0; - - do - { - try - { - if (twoFactorAuthenticationCode == null) - { - result = client.Authorization.GetOrCreateApplicationAuthentication( - clientId, - clientSecret, - newAuth).Result; - } - else - { - result = client.Authorization.GetOrCreateApplicationAuthentication( - clientId, - clientSecret, - newAuth, - twoFactorAuthenticationCode).Result; - } - } - catch (AggregateException ex) - { - throw ex.InnerException; - } - catch (Exception ex) - { - throw ex; - } - - if (result.Token == string.Empty) - { - if (twoFactorAuthenticationCode == null) - { - await client.Authorization.Delete(result.Id); - } - else - { - await client.Authorization.Delete(result.Id, twoFactorAuthenticationCode); - } - } - } while (result.Token == string.Empty && retry++ == 0); - - return result; - } - - ApplicationAuthorization EnsureNonNullAuthorization(ApplicationAuthorization auth) - { - // If a mock IGitHubClient is not set up correctly, it can return null from - // IGitHubClient.Authorization.Create - this will cause an infinite loop in Login() - // so prevent that. - if (auth == null) - { - throw new InvalidOperationException("IGitHubClient.Authorization.Create returned null."); - } - - return auth; - } - - bool EnterpriseWorkaround(UriString hostAddress, Exception e) - { - // Older Enterprise hosts either don't have the API end-point to PUT an authorization, or they - // return 422 because they haven't white-listed our client ID. In that case, we just ignore - // the failure, using basic authentication (with username and password) instead of trying - // to get an authorization token. - var apiException = e as ApiException; - return !HostAddress.IsGitHubDotCom(hostAddress) && - (e is NotFoundException || - e is ForbiddenException || - apiException?.StatusCode == (HttpStatusCode)422); - } - - public enum LoginResultCodes - { - Failed, - Success, - CodeRequired, - CodeFailed, - LockedOut - } - - public class LoginResult - { - public bool NeedTwoFA { get { return Data.Code == LoginResultCodes.CodeRequired || Data.Code == LoginResultCodes.CodeFailed; } } - public bool Success { get { return Data.Code == LoginResultCodes.Success; } } - public bool Failed { get { return Data.Code == LoginResultCodes.Failed; } } - public string Message { get { return Data.Message; } } - - internal LoginResultData Data { get; set; } - internal Action Callback { get; set; } - internal Action TwoFACallback { get; set; } - - internal LoginResult(LoginResultData data, Action callback = null, Action twofaCallback = null) - { - this.Data = data; - this.Callback = callback; - this.TwoFACallback = twofaCallback; - } - } - - public class LoginResultData - { - public LoginResultCodes Code; - public string Message; - internal NewAuthorization NewAuth { get; set; } - internal IGitHubClient Client { get; set; } - - internal LoginResultData(LoginResultCodes code, string message, - IGitHubClient client, NewAuthorization newAuth) - { - this.Code = code; - this.Message = message; - this.NewAuth = newAuth; - this.Client = client; - } - - internal LoginResultData(LoginResultCodes code, string message) - : this(code, message, null, null) - { - } - } - } -} \ No newline at end of file diff --git a/src/OctoRun/NiceIO.cs b/src/OctoRun/NiceIO.cs deleted file mode 100644 index 5f41d6b7b..000000000 --- a/src/OctoRun/NiceIO.cs +++ /dev/null @@ -1,1470 +0,0 @@ -// The MIT License(MIT) -// ===================== -// -// Copyright © `2015-2017` `Lucas Meijer` -// -// Permission is hereby granted, free of charge, to any person -// obtaining a copy of this software and associated documentation -// files (the “Software”), to deal in the Software without -// restriction, including without limitation the rights to use, -// copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the -// Software is furnished to do so, subject to the following -// conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -// OTHER DEALINGS IN THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; - -namespace NiceIO -{ - [Serializable] -#if !NICEIO_INTERNAL - public -#endif - struct NPath : IEquatable, IComparable - { - public static NPath Default; - - private readonly string[] _elements; - private readonly bool _isRelative; - private readonly string _driveLetter; - private readonly bool _isInitialized; - - #region construction - - public NPath(string path) - { - if (path == null) - throw new ArgumentNullException("path"); - - _isInitialized = true; - - path = ParseDriveLetter(path, out _driveLetter); - - if (path == "/") - { - _isRelative = false; - _elements = new string[] { }; - } - else - { - var split = path.Split('/', '\\'); - - _isRelative = _driveLetter == null && IsRelativeFromSplitString(split); - - _elements = ParseSplitStringIntoElements(split.Where(s => s.Length > 0).ToArray(), _isRelative); - } - } - - private NPath(string[] elements, bool isRelative, string driveLetter) - { - _elements = elements; - _isRelative = isRelative; - _driveLetter = driveLetter; - _isInitialized = true; - } - - private static string[] ParseSplitStringIntoElements(IEnumerable inputs, bool isRelative) - { - var stack = new List(); - - foreach (var input in inputs.Where(input => input.Length != 0)) - { - if (input == ".") - { - if ((stack.Count > 0) && (stack.Last() != ".")) - continue; - } - else if (input == "..") - { - if (HasNonDotDotLastElement(stack)) - { - stack.RemoveAt(stack.Count - 1); - continue; - } - if (!isRelative) - throw new ArgumentException("You cannot create a path that tries to .. past the root"); - } - stack.Add(input); - } - return stack.ToArray(); - } - - private static bool HasNonDotDotLastElement(List stack) - { - return stack.Count > 0 && stack[stack.Count - 1] != ".."; - } - - private static string ParseDriveLetter(string path, out string driveLetter) - { - if (path.Length >= 2 && path[1] == ':') - { - driveLetter = path[0].ToString(); - return path.Substring(2); - } - - driveLetter = null; - return path; - } - - private static bool IsRelativeFromSplitString(string[] split) - { - if (split.Length < 2) - return true; - - return split[0].Length != 0 || !split.Any(s => s.Length > 0); - } - - public NPath Combine(params string[] append) - { - return Combine(append.Select(a => new NPath(a)).ToArray()); - } - - public NPath Combine(params NPath[] append) - { - ThrowIfNotInitialized(); - - if (!append.All(p => p.IsRelative)) - throw new ArgumentException("You cannot .Combine a non-relative path"); - - return new NPath(ParseSplitStringIntoElements(_elements.Concat(append.SelectMany(p => p._elements)), _isRelative), _isRelative, _driveLetter); - } - - public NPath Parent - { - get - { - ThrowIfNotInitialized(); - - if (_elements.Length == 0) - throw new InvalidOperationException("Parent is called on an empty path"); - - var newElements = _elements.Take(_elements.Length - 1).ToArray(); - - return new NPath(newElements, _isRelative, _driveLetter); - } - } - - public NPath RelativeTo(NPath path) - { - ThrowIfNotInitialized(); - - if (!IsChildOf(path)) - { - if (!IsRelative && !path.IsRelative && _driveLetter != path._driveLetter) - throw new ArgumentException("Path.RelativeTo() was invoked with two paths that are on different volumes. invoked on: " + ToString() + " asked to be made relative to: " + path); - - NPath commonParent = Default; - foreach (var parent in RecursiveParents) - { - commonParent = path.RecursiveParents.FirstOrDefault(otherParent => otherParent == parent); - - if (commonParent.IsInitialized) - break; - } - - if (!commonParent.IsInitialized) - throw new ArgumentException("Path.RelativeTo() was unable to find a common parent between " + ToString() + " and " + path); - - if (IsRelative && path.IsRelative && commonParent.IsEmpty) - throw new ArgumentException("Path.RelativeTo() was invoked with two relative paths that do not share a common parent. Invoked on: " + ToString() + " asked to be made relative to: " + path); - - var depthDiff = path.Depth - commonParent.Depth; - return new NPath(Enumerable.Repeat("..", depthDiff).Concat(_elements.Skip(commonParent.Depth)).ToArray(), true, null); - } - - return new NPath(_elements.Skip(path._elements.Length).ToArray(), true, null); - } - - public NPath GetCommonParent(NPath path) - { - ThrowIfNotInitialized(); - - if (!IsChildOf(path)) - { - if (!IsRelative && !path.IsRelative && _driveLetter != path._driveLetter) - return Default; - - NPath commonParent = Default; - foreach (var parent in new List { this }.Concat(RecursiveParents)) - { - commonParent = path.RecursiveParents.FirstOrDefault(otherParent => otherParent == parent); - if (commonParent.IsInitialized) - break; - } - - if (IsRelative && path.IsRelative && (!commonParent.IsInitialized || commonParent.IsEmpty)) - return Default; - return commonParent; - } - return path; - } - - public NPath ChangeExtension(string extension) - { - ThrowIfNotInitialized(); - ThrowIfRoot(); - - var newElements = (string[])_elements.Clone(); - newElements[newElements.Length - 1] = FileSystem.ChangeExtension(_elements[_elements.Length - 1], WithDot(extension)); - if (extension == string.Empty) - newElements[newElements.Length - 1] = newElements[newElements.Length - 1].TrimEnd('.'); - return new NPath(newElements, _isRelative, _driveLetter); - } - #endregion construction - - #region inspection - - public bool IsRelative - { - get { return _isRelative; } - } - - public string FileName - { - get - { - ThrowIfNotInitialized(); - ThrowIfRoot(); - - return _elements.Last(); - } - } - - public string FileNameWithoutExtension - { - get - { - ThrowIfNotInitialized(); - - return FileSystem.GetFileNameWithoutExtension(FileName); - } - } - - public IEnumerable Elements - { - get - { - ThrowIfNotInitialized(); - return _elements; - } - } - - public int Depth - { - get - { - ThrowIfNotInitialized(); - return _elements.Length; - } - } - - public bool IsInitialized - { - get { return _isInitialized; } - } - - public bool Exists() - { - ThrowIfNotInitialized(); - return FileExists() || DirectoryExists(); - } - - public bool Exists(string append) - { - ThrowIfNotInitialized(); - if (String.IsNullOrEmpty(append)) - { - return Exists(); - } - return Exists(new NPath(append)); - } - - public bool Exists(NPath append) - { - ThrowIfNotInitialized(); - if (!append.IsInitialized) - return Exists(); - return FileExists(append) || DirectoryExists(append); - } - - public bool DirectoryExists() - { - ThrowIfNotInitialized(); - return FileSystem.DirectoryExists(ToString()); - } - - public bool DirectoryExists(string append) - { - ThrowIfNotInitialized(); - if (String.IsNullOrEmpty(append)) - return DirectoryExists(); - return DirectoryExists(new NPath(append)); - } - - public bool DirectoryExists(NPath append) - { - ThrowIfNotInitialized(); - if (!append.IsInitialized) - return DirectoryExists(); - return FileSystem.DirectoryExists(Combine(append).ToString()); - } - - public bool FileExists() - { - ThrowIfNotInitialized(); - return FileSystem.FileExists(ToString()); - } - - public bool FileExists(string append) - { - ThrowIfNotInitialized(); - if (String.IsNullOrEmpty(append)) - return FileExists(); - return FileExists(new NPath(append)); - } - - public bool FileExists(NPath append) - { - ThrowIfNotInitialized(); - if (!append.IsInitialized) - return FileExists(); - return FileSystem.FileExists(Combine(append).ToString()); - } - - public string ExtensionWithDot - { - get - { - ThrowIfNotInitialized(); - if (IsRoot) - throw new ArgumentException("A root directory does not have an extension"); - - var last = _elements.Last(); - var index = last.LastIndexOf("."); - if (index < 0) return String.Empty; - return last.Substring(index); - } - } - - public string InQuotes() - { - return "\"" + ToString() + "\""; - } - - public string InQuotes(SlashMode slashMode) - { - return "\"" + ToString(slashMode) + "\""; - } - - public override string ToString() - { - return ToString(SlashMode.Native); - } - - public string ToString(SlashMode slashMode) - { - if (!_isInitialized) - return null; - - // Check if it's linux root / - if (IsRoot && string.IsNullOrEmpty(_driveLetter)) - return Slash(slashMode).ToString(); - - if (_isRelative && _elements.Length == 0) - return "."; - - var sb = new StringBuilder(); - if (_driveLetter != null) - { - sb.Append(_driveLetter); - sb.Append(":"); - } - if (!_isRelative) - sb.Append(Slash(slashMode)); - var first = true; - foreach (var element in _elements) - { - if (!first) - sb.Append(Slash(slashMode)); - - sb.Append(element); - first = false; - } - return sb.ToString(); - } - - public static implicit operator string(NPath path) - { - return path.ToString(); - } - - static char Slash(SlashMode slashMode) - { - switch (slashMode) - { - case SlashMode.Backward: - return '\\'; - case SlashMode.Forward: - return '/'; - default: - return FileSystem.DirectorySeparatorChar; - } - } - - public override bool Equals(Object other) - { - if (other is NPath) - { - return Equals((NPath)other); - } - return false; - } - - public bool Equals(NPath p) - { - if (p._isInitialized != _isInitialized) - return false; - - // return early if we're comparing two NPath.Default instances - if (!_isInitialized) - return true; - - if (p._isRelative != _isRelative) - return false; - - if (!string.Equals(p._driveLetter, _driveLetter, PathStringComparison)) - return false; - - if (p._elements.Length != _elements.Length) - return false; - - for (var i = 0; i != _elements.Length; i++) - if (!string.Equals(p._elements[i], _elements[i], PathStringComparison)) - return false; - - return true; - } - - public static bool operator ==(NPath lhs, NPath rhs) - { - return lhs.Equals(rhs); - } - - public override int GetHashCode() - { - unchecked - { - int hash = 17; - // Suitable nullity checks etc, of course :) - hash = hash * 23 + _isInitialized.GetHashCode(); - hash = hash * 23 + _isRelative.GetHashCode(); - foreach (var element in _elements) - hash = hash * 23 + (IsLinux ? element : element.ToUpperInvariant()).GetHashCode(); - if (_driveLetter != null) - hash = hash * 23 + (IsLinux ? _driveLetter : _driveLetter.ToUpperInvariant()).GetHashCode(); - return hash; - } - } - - public int CompareTo(object other) - { - if (!(other is NPath)) - return -1; - - return ToString().CompareTo(((NPath)other).ToString()); - } - - public static bool operator !=(NPath lhs, NPath rhs) - { - return !(lhs.Equals(rhs)); - } - - public bool HasExtension(params string[] extensions) - { - ThrowIfNotInitialized(); - var extensionWithDotLower = ExtensionWithDot.ToLower(); - return extensions.Any(e => WithDot(e).ToLower() == extensionWithDotLower); - } - - private static string WithDot(string extension) - { - return extension.StartsWith(".") ? extension : "." + extension; - } - - public bool IsEmpty - { - get - { - ThrowIfNotInitialized(); - return _elements.Length == 0; - } - } - - public bool IsRoot - { - get - { - ThrowIfNotInitialized(); - return _elements.Length == 0 && !_isRelative; - } - } - - #endregion inspection - - #region directory enumeration - - public IEnumerable Files(string filter, bool recurse = false) - { - return FileSystem.GetFiles(ToString(), filter, recurse ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly).Select(s => new NPath(s)); - } - - public IEnumerable Files(bool recurse = false) - { - return Files("*", recurse); - } - - public IEnumerable Contents(string filter, bool recurse = false) - { - return Files(filter, recurse).Concat(Directories(filter, recurse)); - } - - public IEnumerable Contents(bool recurse = false) - { - return Contents("*", recurse); - } - - public IEnumerable Directories(string filter, bool recurse = false) - { - return FileSystem.GetDirectories(ToString(), filter, recurse ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly).Select(s => new NPath(s)); - } - - public IEnumerable Directories(bool recurse = false) - { - return Directories("*", recurse); - } - - #endregion - - #region filesystem writing operations - public NPath CreateFile() - { - ThrowIfNotInitialized(); - ThrowIfRelative(); - ThrowIfRoot(); - EnsureParentDirectoryExists(); - FileSystem.WriteAllBytes(ToString(), new byte[0]); - return this; - } - - public NPath CreateFile(string file) - { - return CreateFile(new NPath(file)); - } - - public NPath CreateFile(NPath file) - { - ThrowIfNotInitialized(); - if (!file.IsRelative) - throw new ArgumentException("You cannot call CreateFile() on an existing path with a non relative argument"); - return Combine(file).CreateFile(); - } - - public NPath CreateDirectory() - { - ThrowIfNotInitialized(); - ThrowIfRelative(); - - if (IsRoot) - throw new NotSupportedException("CreateDirectory is not supported on a root level directory because it would be dangerous:" + ToString()); - - FileSystem.DirectoryCreate(ToString()); - return this; - } - - public NPath CreateDirectory(string directory) - { - return CreateDirectory(new NPath(directory)); - } - - public NPath CreateDirectory(NPath directory) - { - ThrowIfNotInitialized(); - if (!directory.IsRelative) - throw new ArgumentException("Cannot call CreateDirectory with an absolute argument"); - - return Combine(directory).CreateDirectory(); - } - - public NPath Copy(string dest) - { - return Copy(new NPath(dest)); - } - - public NPath Copy(string dest, Func fileFilter) - { - return Copy(new NPath(dest), fileFilter); - } - - public NPath Copy(NPath dest) - { - return Copy(dest, p => true); - } - - public NPath Copy(NPath dest, Func fileFilter) - { - ThrowIfNotInitialized(); - ThrowIfRelative(); - ThrowIfNotInitialized(dest); - - if (dest.IsRelative) - dest = Parent.Combine(dest); - - if (dest.DirectoryExists()) - return CopyWithDeterminedDestination(dest.Combine(FileName), fileFilter); - - return CopyWithDeterminedDestination(dest, fileFilter); - } - - public NPath MakeAbsolute() - { - ThrowIfNotInitialized(); - - if (!IsRelative) - return this; - - return NPath.CurrentDirectory.Combine(this); - } - - NPath CopyWithDeterminedDestination(NPath absoluteDestination, Func fileFilter) - { - if (absoluteDestination.IsRelative) - throw new ArgumentException("absoluteDestination must be absolute"); - - if (FileExists()) - { - if (!fileFilter(absoluteDestination)) - return Default; - - absoluteDestination.EnsureParentDirectoryExists(); - - FileSystem.FileCopy(ToString(), absoluteDestination.ToString(), true); - return absoluteDestination; - } - - if (DirectoryExists()) - { - absoluteDestination.EnsureDirectoryExists(); - foreach (var thing in Contents()) - thing.CopyWithDeterminedDestination(absoluteDestination.Combine(thing.RelativeTo(this)), fileFilter); - return absoluteDestination; - } - - throw new ArgumentException("Copy() called on path that doesnt exist: " + ToString()); - } - - public void Delete(DeleteMode deleteMode = DeleteMode.Normal) - { - ThrowIfNotInitialized(); - ThrowIfRelative(); - - if (IsRoot) - throw new NotSupportedException("Delete is not supported on a root level directory because it would be dangerous:" + ToString()); - - if (FileExists()) - FileSystem.FileDelete(ToString()); - else if (DirectoryExists()) - try - { - FileSystem.DirectoryDelete(ToString(), true); - } - catch (IOException) - { - if (deleteMode == DeleteMode.Normal) - throw; - } - else - throw new InvalidOperationException("Trying to delete a path that does not exist: " + ToString()); - } - - public void DeleteIfExists(DeleteMode deleteMode = DeleteMode.Normal) - { - ThrowIfNotInitialized(); - ThrowIfRelative(); - - if (FileExists() || DirectoryExists()) - Delete(deleteMode); - } - - public NPath DeleteContents() - { - ThrowIfNotInitialized(); - ThrowIfRelative(); - - if (IsRoot) - throw new NotSupportedException("DeleteContents is not supported on a root level directory because it would be dangerous:" + ToString()); - - if (FileExists()) - throw new InvalidOperationException("It is not valid to perform this operation on a file"); - - if (DirectoryExists()) - { - try - { - Files().Delete(); - Directories().Delete(); - } - catch (IOException) - { - if (Files(true).Any()) - throw; - } - - return this; - } - - return EnsureDirectoryExists(); - } - - public static NPath CreateTempDirectory(string myprefix) - { - var random = new Random(); - while (true) - { - var candidate = new NPath(FileSystem.GetTempPath() + "/" + myprefix + "_" + random.Next()); - if (!candidate.Exists()) - return candidate.CreateDirectory(); - } - } - - public static NPath GetTempFilename(string myprefix = "") - { - var random = new Random(); - var prefix = FileSystem.GetTempPath() + "/" + (String.IsNullOrEmpty(myprefix) ? "" : myprefix + "_"); - while (true) - { - var candidate = new NPath(prefix + random.Next()); - if (!candidate.Exists()) - return candidate; - } - } - - public NPath Move(string dest) - { - return Move(new NPath(dest)); - } - - public NPath Move(NPath dest) - { - ThrowIfNotInitialized(); - ThrowIfNotInitialized(dest); - ThrowIfRelative(); - - if (IsRoot) - throw new NotSupportedException("Move is not supported on a root level directory because it would be dangerous:" + ToString()); - - if (dest.IsRelative) - return Move(Parent.Combine(dest)); - - if (dest.DirectoryExists()) - return Move(dest.Combine(FileName)); - - if (FileExists()) - { - dest.EnsureParentDirectoryExists(); - FileSystem.FileMove(ToString(), dest.ToString()); - return dest; - } - - if (DirectoryExists()) - { - FileSystem.DirectoryMove(ToString(), dest.ToString()); - return dest; - } - - throw new ArgumentException("Move() called on a path that doesn't exist: " + ToString()); - } - - public NPath WriteAllText(string contents) - { - ThrowIfNotInitialized(); - ThrowIfRelative(); - EnsureParentDirectoryExists(); - FileSystem.WriteAllText(ToString(), contents); - return this; - } - - public string ReadAllText() - { - ThrowIfNotInitialized(); - ThrowIfRelative(); - return FileSystem.ReadAllText(ToString()); - } - - public NPath WriteAllText(string contents, Encoding encoding) - { - ThrowIfNotInitialized(); - ThrowIfRelative(); - EnsureParentDirectoryExists(); - FileSystem.WriteAllText(ToString(), contents, encoding); - return this; - } - - public string ReadAllText(Encoding encoding) - { - ThrowIfNotInitialized(); - ThrowIfRelative(); - return FileSystem.ReadAllText(ToString(), encoding); - } - - public NPath WriteLines(string[] contents) - { - ThrowIfNotInitialized(); - ThrowIfRelative(); - EnsureParentDirectoryExists(); - FileSystem.WriteLines(ToString(), contents); - return this; - } - - public NPath WriteAllLines(string[] contents) - { - ThrowIfNotInitialized(); - ThrowIfRelative(); - EnsureParentDirectoryExists(); - FileSystem.WriteAllLines(ToString(), contents); - return this; - } - - public string[] ReadAllLines() - { - ThrowIfNotInitialized(); - ThrowIfRelative(); - return FileSystem.ReadAllLines(ToString()); - } - - public NPath WriteAllBytes(byte[] contents) - { - ThrowIfNotInitialized(); - ThrowIfRelative(); - EnsureParentDirectoryExists(); - FileSystem.WriteAllBytes(ToString(), contents); - return this; - } - - public byte[] ReadAllBytes() - { - ThrowIfNotInitialized(); - ThrowIfRelative(); - return FileSystem.ReadAllBytes(ToString()); - } - - - public IEnumerable CopyFiles(NPath destination, bool recurse, Func fileFilter = null) - { - ThrowIfNotInitialized(); - ThrowIfNotInitialized(destination); - - destination.EnsureDirectoryExists(); - var _this = this; - return Files(recurse).Where(fileFilter ?? AlwaysTrue).Select(file => file.Copy(destination.Combine(file.RelativeTo(_this)))).ToArray(); - } - - public IEnumerable MoveFiles(NPath destination, bool recurse, Func fileFilter = null) - { - ThrowIfNotInitialized(); - ThrowIfNotInitialized(destination); - - if (IsRoot) - throw new NotSupportedException("MoveFiles is not supported on this directory because it would be dangerous:" + ToString()); - - destination.EnsureDirectoryExists(); - var _this = this; - return Files(recurse).Where(fileFilter ?? AlwaysTrue).Select(file => file.Move(destination.Combine(file.RelativeTo(_this)))).ToArray(); - } - #endregion - - #region special paths - - public static NPath CurrentDirectory - { - get - { - return new NPath(FileSystem.GetCurrentDirectory()); - } - } - - public static NPath HomeDirectory - { - get - { - if (FileSystem.DirectorySeparatorChar == '\\') - return new NPath(Environment.GetEnvironmentVariable("USERPROFILE")); - return new NPath(Environment.GetEnvironmentVariable("HOME")); - } - } - - private static NPath systemTemp; - public static NPath SystemTemp - { - get - { - if (!systemTemp.IsInitialized) - systemTemp = new NPath(FileSystem.GetTempPath()); - return systemTemp; - } - } - - #endregion - - private void ThrowIfRelative() - { - if (_isRelative) - throw new ArgumentException("You are attempting an operation on a Path that requires an absolute path, but the path is relative"); - } - - private void ThrowIfRoot() - { - if (IsRoot) - throw new ArgumentException("You are attempting an operation that is not valid on a root level directory"); - } - - private void ThrowIfNotInitialized() - { - if (!_isInitialized) - throw new InvalidOperationException("You are attemping an operation on an null path"); - } - - private static void ThrowIfNotInitialized(NPath path) - { - path.ThrowIfNotInitialized(); - } - - public NPath EnsureDirectoryExists(string append = "") - { - ThrowIfNotInitialized(); - - if (String.IsNullOrEmpty(append)) - { - if (DirectoryExists()) - return this; - EnsureParentDirectoryExists(); - CreateDirectory(); - return this; - } - return EnsureDirectoryExists(new NPath(append)); - } - - public NPath EnsureDirectoryExists(NPath append) - { - ThrowIfNotInitialized(); - ThrowIfNotInitialized(append); - - var combined = Combine(append); - if (combined.DirectoryExists()) - return combined; - combined.EnsureParentDirectoryExists(); - combined.CreateDirectory(); - return combined; - } - - public NPath EnsureParentDirectoryExists() - { - ThrowIfNotInitialized(); - - var parent = Parent; - parent.EnsureDirectoryExists(); - return parent; - } - - public NPath FileMustExist() - { - ThrowIfNotInitialized(); - - if (!FileExists()) - throw new FileNotFoundException("File was expected to exist : " + ToString()); - - return this; - } - - public NPath DirectoryMustExist() - { - ThrowIfNotInitialized(); - - if (!DirectoryExists()) - throw new DirectoryNotFoundException("Expected directory to exist : " + ToString()); - - return this; - } - - public bool IsChildOf(string potentialBasePath) - { - return IsChildOf(new NPath(potentialBasePath)); - } - - public bool IsChildOf(NPath potentialBasePath) - { - ThrowIfNotInitialized(); - ThrowIfNotInitialized(potentialBasePath); - - if ((IsRelative && !potentialBasePath.IsRelative) || !IsRelative && potentialBasePath.IsRelative) - throw new ArgumentException("You can only call IsChildOf with two relative paths, or with two absolute paths"); - - // If the other path is the root directory, then anything is a child of it as long as it's not a Windows path - if (potentialBasePath.IsRoot) - { - if (_driveLetter != potentialBasePath._driveLetter) - return false; - return true; - } - - if (IsEmpty) - return false; - - if (Equals(potentialBasePath)) - return true; - - return Parent.IsChildOf(potentialBasePath); - } - - public IEnumerable RecursiveParents - { - get - { - ThrowIfNotInitialized(); - var candidate = this; - while (true) - { - if (candidate.IsEmpty) - yield break; - - candidate = candidate.Parent; - yield return candidate; - } - } - } - - public NPath ParentContaining(string needle) - { - return ParentContaining(new NPath(needle)); - } - - public NPath ParentContaining(NPath needle) - { - ThrowIfNotInitialized(); - ThrowIfNotInitialized(needle); - ThrowIfRelative(); - - return RecursiveParents.FirstOrDefault(p => p.Exists(needle)); - } - - static bool AlwaysTrue(NPath p) - { - return true; - } - - private static IFileSystem _fileSystem; - public static IFileSystem FileSystem - { - get - { - if (_fileSystem == null) -#if UNITY_4 || UNITY_5 || UNITY_5_3_OR_NEWER - _fileSystem = new FileSystem(UnityEngine.Application.dataPath); -#else - _fileSystem = new FileSystem(Directory.GetCurrentDirectory()); -#endif - return _fileSystem; - } - set - { - _fileSystem = value; - } - } - - private static bool? _isLinux; - internal static bool IsLinux - { - get - { - if (!_isLinux.HasValue) - _isLinux = FileSystem.DirectoryExists("/proc"); - return _isLinux.Value; - } - } - - private static StringComparison? _pathStringComparison; - private static StringComparison PathStringComparison - { - get - { - // this is lazily evaluated because IsLinux uses the FileSystem object and that can be set - // after static constructors happen here - if (!_pathStringComparison.HasValue) - _pathStringComparison = IsLinux ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase; - return _pathStringComparison.Value; - } - } - } - -#if !NICEIO_INTERNAL - public -#endif - static class Extensions - { - public static IEnumerable Copy(this IEnumerable self, string dest) - { - return Copy(self, new NPath(dest)); - } - - public static IEnumerable Copy(this IEnumerable self, NPath dest) - { - if (dest.IsRelative) - throw new ArgumentException("When copying multiple files, the destination cannot be a relative path"); - dest.EnsureDirectoryExists(); - return self.Select(p => p.Copy(dest.Combine(p.FileName))).ToArray(); - } - - public static IEnumerable Move(this IEnumerable self, string dest) - { - return Move(self, new NPath(dest)); - } - - public static IEnumerable Move(this IEnumerable self, NPath dest) - { - if (dest.IsRelative) - throw new ArgumentException("When moving multiple files, the destination cannot be a relative path"); - dest.EnsureDirectoryExists(); - return self.Select(p => p.Move(dest.Combine(p.FileName))).ToArray(); - } - - public static IEnumerable Delete(this IEnumerable self) - { - foreach (var p in self) - p.Delete(); - return self; - } - - public static IEnumerable InQuotes(this IEnumerable self, SlashMode forward = SlashMode.Native) - { - return self.Select(p => p.InQuotes(forward)); - } - - public static NPath ToNPath(this string path) - { - if (path == null) - return NPath.Default; - return new NPath(path); - } - - public static NPath Resolve(this NPath path) - { - // Add a reference to Mono.Posix with an .rsp file in the Assets folder with the line "-r:Mono.Posix.dll" for this to work -#if ENABLE_MONO - if (!path.IsInitialized || !NPath.IsLinux /* nothing to resolve on windows */ || path.IsRelative || !path.FileExists()) - return path; - return new NPath(Mono.Unix.UnixPath.GetCompleteRealPath(path.ToString())); -#else - return path; -#endif - } - } - -#if !NICEIO_INTERNAL - public -#endif - enum SlashMode - { - Native, - Forward, - Backward - } - -#if !NICEIO_INTERNAL - public -#endif - enum DeleteMode - { - Normal, - Soft - } - -#if !NICEIO_INTERNAL - public -#endif - interface IFileSystem - { - string ChangeExtension(string path, string extension); - string Combine(string path1, string path2); - string Combine(string path1, string path2, string path3); - void DirectoryCreate(string path); - void DirectoryDelete(string path, bool recursive); - bool DirectoryExists(string path); - void DirectoryMove(string toString, string s); - bool ExistingPathIsDirectory(string path); - void FileCopy(string sourceFileName, string destFileName, bool overwrite); - void FileDelete(string path); - bool FileExists(string path); - void FileMove(string sourceFileName, string s); - string GetCurrentDirectory(); - IEnumerable GetDirectories(string path); - IEnumerable GetDirectories(string path, string pattern); - IEnumerable GetDirectories(string path, string pattern, SearchOption searchOption); - string GetDirectoryName(string path); - string GetFileNameWithoutExtension(string fileName); - IEnumerable GetFiles(string path); - IEnumerable GetFiles(string path, string pattern); - IEnumerable GetFiles(string path, string pattern, SearchOption searchOption); - string GetFullPath(string path); - string GetParentDirectory(string path); - string GetRandomFileName(); - string GetTempPath(); - Stream OpenRead(string path); - Stream OpenWrite(string path, FileMode mode); - byte[] ReadAllBytes(string path); - string[] ReadAllLines(string path); - string ReadAllText(string path); - string ReadAllText(string path, Encoding encoding); - void SetCurrentDirectory(string currentDirectory); - void WriteAllBytes(string path, byte[] bytes); - void WriteAllLines(string path, string[] contents); - void WriteAllText(string path, string contents); - void WriteAllText(string path, string contents, Encoding encoding); - void WriteLines(string path, string[] contents); - - char DirectorySeparatorChar { get; } - } - -#if !NICEIO_INTERNAL - public -#endif - class FileSystem : IFileSystem - { - private string _currentDirectory; - - public FileSystem() - { } - - /// - /// Initialize the filesystem object with the path passed in set as the current directory - /// - /// Current directory - public FileSystem(string directory) - { - _currentDirectory = directory; - } - - public void SetCurrentDirectory(string directory) - { - if (!Path.IsPathRooted(directory)) - throw new ArgumentException("SetCurrentDirectory requires a rooted path", "directory"); - _currentDirectory = directory; - } - - public bool FileExists(string filename) - { - return File.Exists(filename); - } - - public IEnumerable GetDirectories(string path) - { - return Directory.GetDirectories(path); - } - - public string GetTempPath() - { - return Path.GetTempPath(); - } - - public string Combine(string path1, string path2) - { - return Path.Combine(path1, path2); - } - - public string Combine(string path1, string path2, string path3) - { - return Path.Combine(Path.Combine(path1, path2), path3); - } - - public string GetFullPath(string path) - { - return Path.GetFullPath(path); - } - - public string GetDirectoryName(string path) - { - return Path.GetDirectoryName(path); - } - - public bool DirectoryExists(string path) - { - return Directory.Exists(path); - } - - public bool ExistingPathIsDirectory(string path) - { - var attr = File.GetAttributes(path); - return (attr & FileAttributes.Directory) == FileAttributes.Directory; - } - - public string GetParentDirectory(string path) - { - return Directory.GetParent(path).FullName; - } - - public IEnumerable GetDirectories(string path, string pattern) - { - return Directory.GetDirectories(path, pattern); - } - - public IEnumerable GetDirectories(string path, string pattern, SearchOption searchOption) - { - return Directory.GetDirectories(path, pattern, searchOption); - } - - public string ChangeExtension(string path, string extension) - { - return Path.ChangeExtension(path, extension); - } - - public string GetFileNameWithoutExtension(string fileName) - { - return Path.GetFileNameWithoutExtension(fileName); - } - - public IEnumerable GetFiles(string path) - { - return Directory.GetFiles(path); - } - - public IEnumerable GetFiles(string path, string pattern) - { - return Directory.GetFiles(path, pattern); - } - - public IEnumerable GetFiles(string path, string pattern, SearchOption searchOption) - { - return Directory.GetFiles(path, pattern, searchOption); - } - - public byte[] ReadAllBytes(string path) - { - return File.ReadAllBytes(path); - } - - public void WriteAllBytes(string path, byte[] bytes) - { - File.WriteAllBytes(path, bytes); - } - - public void DirectoryCreate(string toString) - { - Directory.CreateDirectory(toString); - } - - public void FileCopy(string sourceFileName, string destFileName, bool overwrite) - { - File.Copy(sourceFileName, destFileName, overwrite); - } - - public void FileDelete(string path) - { - File.Delete(path); - } - - public void DirectoryDelete(string path, bool recursive) - { - Directory.Delete(path, recursive); - } - - public void FileMove(string sourceFileName, string destFileName) - { - File.Move(sourceFileName, destFileName); - } - - public void DirectoryMove(string toString, string s) - { - Directory.Move(toString, s); - } - - public string GetCurrentDirectory() - { - if (_currentDirectory != null) - return _currentDirectory; - return Directory.GetCurrentDirectory(); - } - - public void WriteAllText(string path, string contents) - { - File.WriteAllText(path, contents); - } - - public void WriteAllText(string path, string contents, Encoding encoding) - { - File.WriteAllText(path, contents, encoding); - } - - public string ReadAllText(string path) - { - return File.ReadAllText(path); - } - - public string ReadAllText(string path, Encoding encoding) - { - return File.ReadAllText(path, encoding); - } - - public void WriteAllLines(string path, string[] contents) - { - File.WriteAllLines(path, contents); - } - - public string[] ReadAllLines(string path) - { - return File.ReadAllLines(path); - } - - public void WriteLines(string path, string[] contents) - { - using (var fs = File.AppendText(path)) - { - foreach (var line in contents) - fs.WriteLine(line); - } - } - - public string GetRandomFileName() - { - return Path.GetRandomFileName(); - } - - public Stream OpenRead(string path) - { - return File.OpenRead(path); - } - - public Stream OpenWrite(string path, FileMode mode) - { - return new FileStream(path, mode); - } - - public char DirectorySeparatorChar - { - get { return Path.DirectorySeparatorChar; } - } - } -} diff --git a/src/OctoRun/OctoRun.csproj b/src/OctoRun/OctoRun.csproj deleted file mode 100644 index b72ec6fe6..000000000 --- a/src/OctoRun/OctoRun.csproj +++ /dev/null @@ -1,112 +0,0 @@ - - - - - Debug - AnyCPU - {127F84FE-DB89-4543-9A83-74DB4E751061} - Exe - Properties - OctoRun - octorun - v4.6.1 - 512 - true - Internal - - - AnyCPU - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - AnyCPU - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - ..\..\packages\Mono.Options.5.3.0.1\lib\net4-client\Mono.Options.dll - True - - - ..\..\packages\Octokit.0.29.0\lib\net45\Octokit.dll - True - - - - - - - - - - - - - - - - - - - - - - - - - Properties\SolutionInfo.cs - - - - - - - - - - - Properties\ApplicationInfo_Local.cs - - - - - - - Properties\ApplicationInfo_Local.cs-example - - - Properties\ApplicationInfo_Local.cs - - - - - - - - - - - {bb6a8eda-15d8-471b-a6ed-ee551e0b3ba0} - GitHub.Logging - - - - - \ No newline at end of file diff --git a/src/OctoRun/Program.cs b/src/OctoRun/Program.cs deleted file mode 100644 index c149ba868..000000000 --- a/src/OctoRun/Program.cs +++ /dev/null @@ -1,116 +0,0 @@ -using GitHub.Unity; -using Mono.Options; -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Net; -using System.Threading.Tasks; -using static OctoRun.LoginManager; - -namespace OctoRun -{ - class LoginCommand - { - public Command[] Commands { get; private set; } - private string host; - private bool in2fa; - - public static LoginCommand Initialize() - { - var instance = new LoginCommand(); - instance.Commands = new Command[] - { - new Command("login", "login") - { - Options = new OptionSet { - { "h|host=", host => instance.host = host }, - { "2fa", v => instance.in2fa = v != null } - }, - Run = args => instance.Run(args) - } - }; - return instance; - } - - public void Run(IEnumerable args) - { - DoLogin(); - } - - private void DoLogin() - { - var login = Console.ReadLine(); - var token = Console.ReadLine(); - string twofa = null; - if (in2fa) - twofa = Console.ReadLine(); - var credStore = new CredentialStore { Login = login, Token = token, Code = twofa }; - var hostAddress = HostAddress.Create(host); - var client = new ApiClient(credStore, hostAddress); - - LoginResult result = null; - if (!in2fa) - { - result = client.Login(); - if (result.NeedTwoFA) - { - Console.WriteLine("2fa"); - Console.WriteLine(credStore.Token); - } - else if (result.Success) - { - Console.WriteLine(credStore.Token); - } - else - { - Console.WriteLine("failed"); - Console.WriteLine(result.Message); - } - } - else - { - result = client.ContinueLogin(); - if (result.NeedTwoFA) - { - Console.WriteLine("2fa"); - Console.WriteLine(credStore.Token); - } - else if (result.Success) - { - Console.WriteLine(credStore.Token); - } - else - { - Console.WriteLine("failed"); - Console.WriteLine(result.Message); - } - } - - } - } - - class Program - { - static void Main(string[] args) - { - //Logging.LogAdapter = new ConsoleLogAdapter(); - - ServicePointManager.ServerCertificateValidationCallback = (sender, chain, cert, errors) => true; - ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; - AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; - - var opts = new OptionSet(); - var commands = new CommandSet(""); - foreach (var cmd in LoginCommand.Initialize().Commands) - commands.Add(cmd); - - opts.Parse(args); - commands.Run(args); - } - - private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) - { - Debugger.Break(); - } - } -} diff --git a/src/OctoRun/Properties/AssemblyInfo.cs b/src/OctoRun/Properties/AssemblyInfo.cs deleted file mode 100644 index 7b4846420..000000000 --- a/src/OctoRun/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("OctoRun")] -[assembly: AssemblyDescription("")] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("127f84fe-db89-4543-9a83-74db4e751061")] diff --git a/src/OctoRun/StringEquivalent.cs b/src/OctoRun/StringEquivalent.cs deleted file mode 100644 index 88756fe82..000000000 --- a/src/OctoRun/StringEquivalent.cs +++ /dev/null @@ -1,109 +0,0 @@ -using System; -using System.Diagnostics.CodeAnalysis; -using System.Runtime.Serialization; -using System.Xml; -using System.Xml.Schema; -using System.Xml.Serialization; - -namespace OctoRun -{ - [Serializable] - public abstract class StringEquivalent : ISerializable, IXmlSerializable where T : StringEquivalent - { - protected string Value; - - protected StringEquivalent(string value) - { - Value = value; - } - - protected StringEquivalent() - { - } - - public abstract T Combine(string addition); - - [SuppressMessage("Microsoft.Usage", "CA2225:OperatorOverloadsHaveNamedAlternates", Justification = "Add doesn't make sense in the case of a string equivalent")] - public static T operator +(StringEquivalent a, string b) - { - return a.Combine(b); - } - - public static bool operator ==(StringEquivalent a, StringEquivalent b) - { - // If both are null, or both are same instance, return true. - if (ReferenceEquals(a, b)) - { - return true; - } - - // If one is null, but not both, return false. - if (((object)a == null) || ((object)b == null)) - { - return false; - } - - // Return true if the fields match: - return a.Value.Equals(b.Value, StringComparison.OrdinalIgnoreCase); - } - - public static bool operator !=(StringEquivalent a, StringEquivalent b) - { - return !(a == b); - } - - public override bool Equals(Object obj) - { - return obj != null && Equals(obj as T) || Equals(obj as string); - } - - public virtual bool Equals(T stringEquivalent) - { - return this == stringEquivalent; - } - - public override int GetHashCode() - { - return (Value ?? "").GetHashCode(); - } - - public virtual bool Equals(string other) - { - return other != null && Value == other; - } - - public override string ToString() - { - return Value; - } - - protected StringEquivalent(SerializationInfo info) : this(info.GetValue("Value", typeof(string)) as string) - { - } - - public virtual void GetObjectData(SerializationInfo info, StreamingContext context) - { - info.AddValue("Value", Value); - } - - public XmlSchema GetSchema() - { - return null; - } - - public void ReadXml(XmlReader reader) - { - Value = reader.ReadString(); - } - - public void WriteXml(XmlWriter writer) - { - writer.WriteString(Value); - } - - public int Length - { - get { return Value != null ? Value.Length : 0; } - } - } -} diff --git a/src/OctoRun/StringExtensions.cs b/src/OctoRun/StringExtensions.cs deleted file mode 100644 index ce966542e..000000000 --- a/src/OctoRun/StringExtensions.cs +++ /dev/null @@ -1,160 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Text; - -namespace OctoRun -{ - static class StringExtensions - { - public static bool Contains(this string s, string expectedSubstring, StringComparison comparison) - { - return s.IndexOf(expectedSubstring, comparison) > -1; - } - - public static bool ContainsAny(this string s, IEnumerable characters) - { - return s.IndexOfAny(characters.ToArray()) > -1; - } - - public static string ToNullIfEmpty(this string s) - { - return String.IsNullOrEmpty(s) ? null : s; - } - - public static bool StartsWith(this string s, char c) - { - if (String.IsNullOrEmpty(s)) return false; - return s.First() == c; - } - - public static string RightAfter(this string s, string search) - { - if (s == null) return null; - int lastIndex = s.IndexOf(search, StringComparison.OrdinalIgnoreCase); - if (lastIndex < 0) - return null; - - return s.Substring(lastIndex + search.Length); - } - - public static string RightAfterLast(this string s, string search) - { - if (s == null) return null; - int lastIndex = s.LastIndexOf(search, StringComparison.OrdinalIgnoreCase); - if (lastIndex < 0) - return null; - - return s.Substring(lastIndex + search.Length); - } - - public static string LeftBeforeLast(this string s, string search) - { - if (s == null) return null; - int lastIndex = s.LastIndexOf(search, StringComparison.OrdinalIgnoreCase); - if (lastIndex < 0) - return null; - - return s.Substring(0, lastIndex); - } - - public static string TrimEnd(this string s, string suffix) - { - if (s == null) return null; - if (!s.EndsWith(suffix, StringComparison.OrdinalIgnoreCase)) - return s; - - return s.Substring(0, s.Length - suffix.Length); - } - - /// - /// Pretty much the same things as `String.Join` but used when appending to an already delimited string. If the values passed - /// in are empty, it does not prepend the delimeter. Otherwise, it prepends with the delimiter. - /// - /// The separator character - /// The set values to join - public static string JoinForAppending(string separator, IEnumerable values) - { - return values.Any() - ? separator + String.Join(separator, values.ToArray()) - : string.Empty; - } - - public static string RemoveSurroundingQuotes(this string s) - { - Guard.ArgumentNotNull(s, "string"); - - if (s.Length < 2) - return s; - - var quoteCharacters = new[] { '"', '\'' }; - char firstCharacter = s[0]; - if (!quoteCharacters.Contains(firstCharacter)) - return s; - - if (firstCharacter != s[s.Length - 1]) - return s; - - return s.Substring(1, s.Length - 2); - } - - public static string RightAfter(this string s, char search) - { - if (s == null) return null; - int lastIndex = s.IndexOf(search); - if (lastIndex < 0) - return null; - - return s.Substring(lastIndex + 1); - } - - public static string RightAfterLast(this string s, char search) - { - if (s == null) return null; - int lastIndex = s.LastIndexOf(search); - if (lastIndex < 0) - return null; - - return s.Substring(lastIndex + 1); - } - - public static string LeftBeforeLast(this string s, char search) - { - if (s == null) return null; - int lastIndex = s.LastIndexOf(search); - if (lastIndex < 0) - return null; - - return s.Substring(0, lastIndex); - } - - public static StringResult? NextChunk(this string s, int start, char search) - { - if (s == null) return null; - int index = s.IndexOf(search, start); - if (index < 0) - return null; - - return new StringResult { Chunk = s.Substring(start, index - start), Start = start, End = index }; - } - - public static StringResult? NextChunk(this string s, int start, string search) - { - if (s == null) return null; - int index = s.IndexOf(search, start); - if (index < 0) - return null; - - return new StringResult { Chunk = s.Substring(start, index - start), Start = start, End = index }; - } - } - - public struct StringResult - { - public string Chunk; - public int Start; - public int End; - } -} diff --git a/src/OctoRun/UriExtensions.cs b/src/OctoRun/UriExtensions.cs deleted file mode 100644 index c0e6893bf..000000000 --- a/src/OctoRun/UriExtensions.cs +++ /dev/null @@ -1,38 +0,0 @@ -using System; - -namespace OctoRun -{ - static class UriExtensions - { - /// - /// Appends a relative path to the URL. - /// - /// - /// The Uri constructor for combining relative URLs have a different behavior with URLs that end with / - /// than those that don't. - /// - public static Uri Append(this Uri uri, string relativePath) - { - if (!uri.AbsolutePath.EndsWith("/", StringComparison.Ordinal)) - { - uri = new Uri(uri + "/"); - } - return new Uri(uri, new Uri(relativePath, UriKind.Relative)); - } - - public static bool IsHypertextTransferProtocol(this Uri uri) - { - return uri.Scheme == "http" || uri.Scheme == "https"; - } - - public static bool IsSameHost(this Uri uri, Uri compareUri) - { - return uri.Host.Equals(compareUri.Host, StringComparison.OrdinalIgnoreCase); - } - - public static UriString ToUriString(this Uri uri) - { - return uri == null ? null : new UriString(uri.ToString()); - } - } -} diff --git a/src/OctoRun/UriString.cs b/src/OctoRun/UriString.cs deleted file mode 100644 index da91f50fa..000000000 --- a/src/OctoRun/UriString.cs +++ /dev/null @@ -1,285 +0,0 @@ -using System; -using System.Diagnostics.CodeAnalysis; -using System.Globalization; -using System.Linq; -using System.Runtime.Serialization; -using System.Text.RegularExpressions; - -namespace OctoRun -{ - /// - /// This class represents a URI given to us as a string and is implicitly - /// convertible to and from string. - /// - /// - /// This typically represents a URI from an external source such as user input, a - /// Git Repo Remote, or an API URL. We try to preserve the original form and let - /// downstream clients validate the URL. This class doesn't validate the URL. It just - /// performs a best-effort to parse the URI into bits important to us. For example, - /// we need to know the HOST so we can compare against GitHub.com, GH:E instances, etc. - /// - [SuppressMessage("Microsoft.Usage", "CA2240:ImplementISerializableCorrectly", Justification = "GetObjectData is implemented in the base class")] - [Serializable] - public class UriString : StringEquivalent, IEquatable - { - static readonly Regex sshRegex = new Regex(@"^.+@(?(\[.*?\]|[a-z0-9-.]+?))(:(?.*?))?(/(?.*)(\.git)?)?$", RegexOptions.Compiled | RegexOptions.IgnoreCase); - readonly Uri url; - - public UriString(string uriString) : base(NormalizePath(uriString)) - { - if (uriString == null || uriString.Length == 0) return; - if (Uri.TryCreate(uriString, UriKind.Absolute, out url)) - { - if (!url.IsFile) - SetUri(url); - else - SetFilePath(url); - } - else if (!ParseScpSyntax(uriString)) - { - SetFilePath(uriString); - } - - if (RepositoryName != null) - { - NameWithOwner = Owner != null - ? string.Format(CultureInfo.InvariantCulture, "{0}/{1}", Owner, RepositoryName) - : RepositoryName; - } - } - - public static UriString ToUriString(Uri uri) - { - return uri == null ? null : new UriString(uri.ToString()); - } - - public static UriString TryParse(string uri) - { - if (uri == null || uri.Length == 0) return null; - return new UriString(uri); - } - - public Uri ToUri() - { - if (url == null) - throw new InvalidOperationException("This Uri String is not a valid Uri"); - return url; - } - - void SetUri(Uri uri) - { - Host = uri.Host; - if (uri.Segments.Any()) - { - RepositoryName = GetRepositoryName(uri.Segments.Last()); - } - - if (uri.Segments.Length > 2) - { - Owner = (uri.Segments[uri.Segments.Length - 2] ?? "").TrimEnd('/').ToNullIfEmpty(); - } - - IsHypertextTransferProtocol = uri.IsHypertextTransferProtocol(); - } - - void SetFilePath(Uri uri) - { - Host = ""; - Owner = ""; - RepositoryName = GetRepositoryName(uri.Segments.Last()); - IsFileUri = true; - } - - void SetFilePath(string path) - { - Host = ""; - Owner = ""; - RepositoryName = GetRepositoryName(path.Replace("/", @"\").RightAfterLast(@"\")); - IsFileUri = true; - } - - // For xml serialization - protected UriString() - { - } - - bool ParseScpSyntax(string scpString) - { - var match = sshRegex.Match(scpString); - if (match.Success) - { - Host = match.Groups["host"].Value.ToNullIfEmpty(); - Owner = match.Groups["owner"].Value.ToNullIfEmpty(); - RepositoryName = GetRepositoryName(match.Groups["repo"].Value); - IsScpUri = true; - return true; - } - return false; - } - - public string Host { get; private set; } - - public string Owner { get; private set; } - - public string RepositoryName { get; private set; } - - public string NameWithOwner { get; private set; } - - public bool IsFileUri { get; private set; } - - public bool IsScpUri { get; private set; } - - public bool IsValidUri => url != null; - public string Protocol => url?.Scheme; - - /// - /// Attempts a best-effort to convert the remote origin to a GitHub Repository URL. - /// - /// A converted uri, or the existing one if we can't convert it (which might be null) - public Uri ToRepositoryUri() - { - // we only want to process urls that represent network resources - if (!IsScpUri && (!IsValidUri || IsFileUri)) return url; - - var scheme = url != null && IsHypertextTransferProtocol - ? url.Scheme - : Uri.UriSchemeHttps; - - var port = url?.Port == 80 - ? -1 - : (url?.Port ?? -1); - return new UriBuilder - { - Scheme = scheme, - Host = Host, - Path = NameWithOwner, - Port = port - }.Uri; - } - - /// - /// Attempts a best-effort to convert the remote origin to a GitHub Repository URL. - /// - /// A converted uri, or the existing one if we can't convert it (which might be null) - public UriString ToRepositoryUrl() - { - // we only want to process urls that represent network resources - if (!IsScpUri && (!IsValidUri || IsFileUri)) return this; - - var scheme = url != null && IsHypertextTransferProtocol - ? url.Scheme - : Uri.UriSchemeHttps; - - var port = url?.Port == 80 - ? -1 - : (url?.Port ?? -1); - return new UriString(new UriBuilder - { - Scheme = scheme, - Host = Host, - Path = NameWithOwner, - Port = port - }.Uri.ToString()); - } - - /// - /// True if the URL is HTTP or HTTPS - /// - public bool IsHypertextTransferProtocol { get; private set; } - - [SuppressMessage("Microsoft.Usage", "CA2225:OperatorOverloadsHaveNamedAlternates")] - public static implicit operator UriString(string value) - { - if (value == null) return null; - - return new UriString(value); - } - - [SuppressMessage("Microsoft.Usage", "CA2225:OperatorOverloadsHaveNamedAlternates")] - public static implicit operator string(UriString uriString) - { - return uriString?.Value; - } - - [SuppressMessage("Microsoft.Usage", "CA2234:PassSystemUriObjectsInsteadOfStrings", Justification = "No.")] - public override UriString Combine(string addition) - { - if (url != null) - { - var urlBuilder = new UriBuilder(url); - if (!String.IsNullOrEmpty(urlBuilder.Query)) - { - var query = urlBuilder.Query; - if (query.StartsWith("?", StringComparison.Ordinal)) - { - query = query.Substring(1); - } - - if (!addition.StartsWith("&", StringComparison.Ordinal) && query.Length > 0) - { - addition = "&" + addition; - } - urlBuilder.Query = query + addition; - } - else - { - var path = url.AbsolutePath; - if (path == "/") path = ""; - if (!addition.StartsWith("/", StringComparison.Ordinal)) addition = "/" + addition; - - urlBuilder.Path = path + addition; - } - return ToUriString(urlBuilder.Uri); - } - return String.Concat(Value, addition); - } - - public override string ToString() - { - // Makes this look better in the debugger. - return Value; - } - - protected UriString(SerializationInfo info, StreamingContext context) - : this(GetSerializedValue(info)) - { - } - - static string GetSerializedValue(SerializationInfo info) - { - // First try to get the current way it's serialized, then fall back to the older way it's serialized. - string value; - try - { - value = info.GetValue("Value", typeof(string)) as string; - } - catch (SerializationException) - { - value = info.GetValue("uriString", typeof(string)) as string; - } - - return value; - } - - static string NormalizePath(string path) - { - return path?.Replace('\\', '/'); - } - - static string GetRepositoryName(string repositoryNameSegment) - { - if (String.IsNullOrEmpty(repositoryNameSegment) - || repositoryNameSegment.Equals("/", StringComparison.Ordinal)) - { - return null; - } - - return repositoryNameSegment.TrimEnd('/').TrimEnd(".git"); - } - - bool IEquatable.Equals(UriString other) - { - return other != null && ToString().Equals(other.ToString()); - } - } -} diff --git a/src/OctoRun/packages.config b/src/OctoRun/packages.config deleted file mode 100644 index c98040a1a..000000000 --- a/src/OctoRun/packages.config +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ 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 141cfba6e..0c7b3c03c 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/GitHub.Unity.csproj +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/GitHub.Unity.csproj @@ -195,18 +195,6 @@ - - Tools\octorun.exe - - - Tools\GitHub.Logging.dll - - - Tools\Mono.Options.dll - - - Tools\Octokit.dll - From be899c48af3adc7e0d9f8f99799dc93d3c181074 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Wed, 7 Mar 2018 16:14:35 -0500 Subject: [PATCH 2/7] Removing octokit --- lib/dotnet-httpClient35/DotNetHttp35.dll | 3 --- lib/dotnet-httpClient35/DotNetHttp35.dll.mdb | 3 --- lib/dotnet-httpClient35/md5sums.txt | 2 -- lib/dotnet-httpClient35/version.txt | 1 - lib/octokit.net/Octokit.dll | 3 --- lib/octokit.net/Octokit.dll.mdb | 3 --- lib/octokit.net/md5sums.txt | 2 -- lib/octokit.net/version.txt | 1 - script | 2 +- src/GitHub.Api/Application/ApiClient.cs | 19 ++++++++----------- .../Application/ApplicationConfiguration.cs | 6 ------ .../Application/ApplicationManagerBase.cs | 3 +-- src/GitHub.Api/Application/IApiClient.cs | 5 ++--- .../Editor/GitHub.Unity/UI/PublishView.cs | 6 +----- 14 files changed, 13 insertions(+), 46 deletions(-) delete mode 100644 lib/dotnet-httpClient35/DotNetHttp35.dll delete mode 100644 lib/dotnet-httpClient35/DotNetHttp35.dll.mdb delete mode 100644 lib/dotnet-httpClient35/md5sums.txt delete mode 100644 lib/dotnet-httpClient35/version.txt delete mode 100644 lib/octokit.net/Octokit.dll delete mode 100644 lib/octokit.net/Octokit.dll.mdb delete mode 100644 lib/octokit.net/md5sums.txt delete mode 100644 lib/octokit.net/version.txt diff --git a/lib/dotnet-httpClient35/DotNetHttp35.dll b/lib/dotnet-httpClient35/DotNetHttp35.dll deleted file mode 100644 index 7e68fe5e3..000000000 --- a/lib/dotnet-httpClient35/DotNetHttp35.dll +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:6daaf4e57900d0a092a94dbe10aca3796ad7496f40347112b602a6ff6dcf0275 -size 123392 diff --git a/lib/dotnet-httpClient35/DotNetHttp35.dll.mdb b/lib/dotnet-httpClient35/DotNetHttp35.dll.mdb deleted file mode 100644 index fdd070e10..000000000 --- a/lib/dotnet-httpClient35/DotNetHttp35.dll.mdb +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:be437526dd7332f42ea2c10cf9548e5c8b4f3f0fc735d584294d72ba4d592e81 -size 47000 diff --git a/lib/dotnet-httpClient35/md5sums.txt b/lib/dotnet-httpClient35/md5sums.txt deleted file mode 100644 index 4f97ea53b..000000000 --- a/lib/dotnet-httpClient35/md5sums.txt +++ /dev/null @@ -1,2 +0,0 @@ -0b299a0c541e19a6205f1265da27e540 *DotNetHttp35.dll -4698f765de6671c08befd610eb254013 *DotNetHttp35.dll.mdb diff --git a/lib/dotnet-httpClient35/version.txt b/lib/dotnet-httpClient35/version.txt deleted file mode 100644 index 38dcf35fb..000000000 --- a/lib/dotnet-httpClient35/version.txt +++ /dev/null @@ -1 +0,0 @@ -3.5.0.0 3.5.22000.2-gfu 43d89b670547006521c95fc150d9b79506c208ca \ No newline at end of file diff --git a/lib/octokit.net/Octokit.dll b/lib/octokit.net/Octokit.dll deleted file mode 100644 index fd797251f..000000000 --- a/lib/octokit.net/Octokit.dll +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:cb297646723b439a8755e1b967a9f5850dd9c50f1126f1e6ba9ddd8677188f84 -size 741888 diff --git a/lib/octokit.net/Octokit.dll.mdb b/lib/octokit.net/Octokit.dll.mdb deleted file mode 100644 index ef51d4875..000000000 --- a/lib/octokit.net/Octokit.dll.mdb +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:ebdf240eb57a1154884fdc1ae5962e0d2af5f0c663fe5cb8f1897fa5c82b7218 -size 283050 diff --git a/lib/octokit.net/md5sums.txt b/lib/octokit.net/md5sums.txt deleted file mode 100644 index 33bc5f2df..000000000 --- a/lib/octokit.net/md5sums.txt +++ /dev/null @@ -1,2 +0,0 @@ -352dbd9611f700a9dbde52999752d88d *Octokit.dll -883c04490791e7d4f63c2e918233dc55 *Octokit.dll.mdb diff --git a/lib/octokit.net/version.txt b/lib/octokit.net/version.txt deleted file mode 100644 index 1024bde64..000000000 --- a/lib/octokit.net/version.txt +++ /dev/null @@ -1 +0,0 @@ -0.23.0.1 0.23.0.2-gfu 9784094cdd6192887dc97180918565c036c6b62c \ No newline at end of file diff --git a/script b/script index f00ae1339..5b88bddc0 160000 --- a/script +++ b/script @@ -1 +1 @@ -Subproject commit f00ae13391948f6a2b4b6df54fa7ab86e6886e6e +Subproject commit 5b88bddc0a11c7a5a5455287753c380bc99f27b1 diff --git a/src/GitHub.Api/Application/ApiClient.cs b/src/GitHub.Api/Application/ApiClient.cs index 0668438cc..98c60cf14 100644 --- a/src/GitHub.Api/Application/ApiClient.cs +++ b/src/GitHub.Api/Application/ApiClient.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -using Octokit; using GitHub.Logging; using System.Runtime.Serialization; using System.Text; @@ -19,7 +18,6 @@ public static IApiClient Create(UriString repositoryUrl, IKeychain keychain, IPr var hostAddress = HostAddress.Create(repositoryUrl); return new ApiClient(repositoryUrl, keychain, - new GitHubClient(ApplicationConfiguration.ProductHeader, credentialStore, hostAddress.ApiUri), processManager, taskManager, nodeJsExecutablePath, octorunScriptPath); } @@ -34,11 +32,10 @@ public static IApiClient Create(UriString repositoryUrl, IKeychain keychain, IPr private readonly NPath octorunScriptPath; private readonly ILoginManager loginManager; - public ApiClient(UriString hostUrl, IKeychain keychain, IGitHubClient githubClient, IProcessManager processManager, ITaskManager taskManager, NPath nodeJsExecutablePath, NPath octorunScriptPath) + public ApiClient(UriString hostUrl, IKeychain keychain, IProcessManager processManager, ITaskManager taskManager, NPath nodeJsExecutablePath, NPath octorunScriptPath) { Guard.ArgumentNotNull(hostUrl, nameof(hostUrl)); Guard.ArgumentNotNull(keychain, nameof(keychain)); - Guard.ArgumentNotNull(githubClient, nameof(githubClient)); HostAddress = HostAddress.Create(hostUrl); OriginalUrl = hostUrl; @@ -64,12 +61,12 @@ 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(string name, string description, bool isPrivate, Action callback, string organization = null) { Guard.ArgumentNotNull(callback, "callback"); try { - var repository = await CreateRepositoryInternal(newRepository, organization); + var repository = await CreateRepositoryInternal(name, organization, description, isPrivate); callback(repository, null); } catch (Exception e) @@ -201,7 +198,7 @@ public async Task ContinueLoginAsync(LoginResult loginResult, Func CreateRepositoryInternal(NewRepository newRepository, string organization) + private async Task CreateRepositoryInternal(string repositoryName, string organization, string description, bool isPrivate) { try { @@ -214,12 +211,12 @@ private async Task CreateRepositoryInternal(NewRepository newR var keychainAdapter = await keychain.Load(uriString); var command = new StringBuilder("publish -r "); - command.Append(newRepository.Name); + command.Append(repositoryName); - if (!string.IsNullOrEmpty(newRepository.Description)) + if (!string.IsNullOrEmpty(description)) { command.Append(" -d "); - command.Append(newRepository.Description); + command.Append(description); } if (!string.IsNullOrEmpty(organization)) @@ -228,7 +225,7 @@ private async Task CreateRepositoryInternal(NewRepository newR command.Append(organization); } - if (newRepository.Private ?? false) + if (isPrivate) { command.Append(" -p"); } diff --git a/src/GitHub.Api/Application/ApplicationConfiguration.cs b/src/GitHub.Api/Application/ApplicationConfiguration.cs index 0b4a4d31e..0e1bd84bc 100644 --- a/src/GitHub.Api/Application/ApplicationConfiguration.cs +++ b/src/GitHub.Api/Application/ApplicationConfiguration.cs @@ -11,7 +11,6 @@ static ApplicationConfiguration() { var executingAssembly = typeof(ApplicationConfiguration).Assembly; AssemblyName = executingAssembly.GetName(); - ProductHeader = new ProductHeaderValue(ApplicationInfo.ApplicationSafeName, AssemblyName.Version.ToString()); } /// @@ -19,11 +18,6 @@ static ApplicationConfiguration() /// public static AssemblyName AssemblyName { get; } - /// - /// The product header used in the user agent. - /// - public static ProductHeaderValue ProductHeader { get; private set; } - public static int WebTimeout { get; set; } = DefaultWebTimeout; } } diff --git a/src/GitHub.Api/Application/ApplicationManagerBase.cs b/src/GitHub.Api/Application/ApplicationManagerBase.cs index afb75eb29..01c5ed09e 100644 --- a/src/GitHub.Api/Application/ApplicationManagerBase.cs +++ b/src/GitHub.Api/Application/ApplicationManagerBase.cs @@ -159,8 +159,7 @@ protected void SetupMetrics(string unityVersion, bool firstRun) TaskManager, Environment.FileSystem, Environment.NodeJsExecutablePath, - Environment.OctorunScriptPath, - ApplicationConfiguration.ProductHeader); + Environment.OctorunScriptPath); UsageTracker = new UsageTracker(metricsService, UserSettings, usagePath, id, unityVersion); diff --git a/src/GitHub.Api/Application/IApiClient.cs b/src/GitHub.Api/Application/IApiClient.cs index d4a87e3e2..438e9bbf5 100644 --- a/src/GitHub.Api/Application/IApiClient.cs +++ b/src/GitHub.Api/Application/IApiClient.cs @@ -1,7 +1,5 @@ using System.Threading.Tasks; -using Octokit; using System; -using System.Collections.Generic; namespace GitHub.Unity { @@ -9,7 +7,8 @@ interface IApiClient { HostAddress HostAddress { get; } UriString OriginalUrl { get; } - Task CreateRepository(NewRepository newRepository, Action callback, string organization = null); + Task CreateRepository(string name, string description, bool isPrivate, + 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); diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs index 29d1505cc..0d5280f46 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs @@ -163,11 +163,7 @@ public override void OnGUI() var cleanRepoDescription = repoDescription.Trim(); cleanRepoDescription = string.IsNullOrEmpty(cleanRepoDescription) ? null : cleanRepoDescription; - Client.CreateRepository(new NewRepository(repoName) - { - Private = togglePrivate, - Description = cleanRepoDescription - }, (repository, ex) => + Client.CreateRepository(repoName, cleanRepoDescription, togglePrivate, (repository, ex) => { if (ex != null) { From b45a0f94a3f1350166357169ecff9dc8b1befabf Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Wed, 7 Mar 2018 17:30:13 -0500 Subject: [PATCH 3/7] Removing a lot more octokit --- .../Application/ApplicationConfiguration.cs | 1 - .../Application/OctokitExtensions.cs | 21 ------------------- .../Authentication/ILoginManager.cs | 1 - src/GitHub.Api/Authentication/Keychain.cs | 7 +++---- .../Authentication/KeychainAdapter.cs | 21 ++----------------- src/GitHub.Api/Authentication/LoginManager.cs | 1 - .../Extensions/ExceptionExtensions.cs | 21 ------------------- src/GitHub.Api/Git/RepositoryManager.cs | 3 --- src/GitHub.Api/GitHub.Api.csproj | 1 - 9 files changed, 5 insertions(+), 72 deletions(-) delete mode 100644 src/GitHub.Api/Application/OctokitExtensions.cs diff --git a/src/GitHub.Api/Application/ApplicationConfiguration.cs b/src/GitHub.Api/Application/ApplicationConfiguration.cs index 0e1bd84bc..40d4e7933 100644 --- a/src/GitHub.Api/Application/ApplicationConfiguration.cs +++ b/src/GitHub.Api/Application/ApplicationConfiguration.cs @@ -1,5 +1,4 @@ using System.Reflection; -using Octokit; namespace GitHub.Unity { diff --git a/src/GitHub.Api/Application/OctokitExtensions.cs b/src/GitHub.Api/Application/OctokitExtensions.cs deleted file mode 100644 index c53101c74..000000000 --- a/src/GitHub.Api/Application/OctokitExtensions.cs +++ /dev/null @@ -1,21 +0,0 @@ -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/Authentication/ILoginManager.cs b/src/GitHub.Api/Authentication/ILoginManager.cs index bbacf54a1..32defff79 100644 --- a/src/GitHub.Api/Authentication/ILoginManager.cs +++ b/src/GitHub.Api/Authentication/ILoginManager.cs @@ -1,5 +1,4 @@ using System.Threading.Tasks; -using Octokit; namespace GitHub.Unity { diff --git a/src/GitHub.Api/Authentication/Keychain.cs b/src/GitHub.Api/Authentication/Keychain.cs index 204c80bc6..609966044 100644 --- a/src/GitHub.Api/Authentication/Keychain.cs +++ b/src/GitHub.Api/Authentication/Keychain.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -using Octokit; using GitHub.Logging; namespace GitHub.Unity @@ -220,7 +219,7 @@ public async Task Save(UriString host) throw new ArgumentException($"Host: {host} is not found"); } - if (credentialAdapter.OctokitCredentials == Credentials.Anonymous) + if (string.IsNullOrEmpty(credentialAdapter.Credential.Token)) { throw new InvalidOperationException("Anonymous credentials cannot be stored"); } @@ -229,7 +228,7 @@ public async Task Save(UriString host) if (connectionCache.ContainsKey(host)) connectionCache.Remove(host); - connectionCache.Add(host, new Connection { Host = host, Username = credentialAdapter.OctokitCredentials.Login }); + connectionCache.Add(host, new Connection { Host = host, Username = credentialAdapter.Credential.Username }); // flushes credential cache to disk (host and username only) WriteCacheToDisk(); @@ -275,6 +274,6 @@ public void UpdateToken(UriString host, string token) public bool HasKeys => connectionCache.Any(); - public bool NeedsLoad => HasKeys && FindOrCreateAdapter(connectionCache.First().Value.Host).OctokitCredentials == Credentials.Anonymous; + public bool NeedsLoad => HasKeys && FindOrCreateAdapter(connectionCache.First().Value.Host).Credential.Token != null; } } \ No newline at end of file diff --git a/src/GitHub.Api/Authentication/KeychainAdapter.cs b/src/GitHub.Api/Authentication/KeychainAdapter.cs index f61a80855..3fdde60b3 100644 --- a/src/GitHub.Api/Authentication/KeychainAdapter.cs +++ b/src/GitHub.Api/Authentication/KeychainAdapter.cs @@ -1,44 +1,27 @@ -using System.Threading.Tasks; -using Octokit; - -namespace GitHub.Unity +namespace GitHub.Unity { class KeychainAdapter : IKeychainAdapter { - public Credentials OctokitCredentials { get; private set; } = Credentials.Anonymous; public ICredential Credential { get; private set; } public void Set(ICredential credential) { Credential = credential; - OctokitCredentials = new Credentials(credential.Username, credential.Token); } public void UpdateToken(string token) { Credential.UpdateToken(token); - OctokitCredentials = new Credentials(OctokitCredentials.Login, token); } public void Clear() { - OctokitCredentials = Credentials.Anonymous; Credential = null; } - - /// - /// Implementation for Octokit - /// - /// Octokit credentials - Task ICredentialStore.GetCredentials() - { - return TaskEx.FromResult(OctokitCredentials); - } } - public interface IKeychainAdapter: ICredentialStore + public interface IKeychainAdapter { - Credentials OctokitCredentials { get; } ICredential Credential { get; } } } diff --git a/src/GitHub.Api/Authentication/LoginManager.cs b/src/GitHub.Api/Authentication/LoginManager.cs index 03b8ee6f6..50d71a8a6 100644 --- a/src/GitHub.Api/Authentication/LoginManager.cs +++ b/src/GitHub.Api/Authentication/LoginManager.cs @@ -1,7 +1,6 @@ using System; using System.Net; using System.Threading.Tasks; -using Octokit; using GitHub.Logging; namespace GitHub.Unity diff --git a/src/GitHub.Api/Extensions/ExceptionExtensions.cs b/src/GitHub.Api/Extensions/ExceptionExtensions.cs index 162292d2c..a367bfdfc 100644 --- a/src/GitHub.Api/Extensions/ExceptionExtensions.cs +++ b/src/GitHub.Api/Extensions/ExceptionExtensions.cs @@ -1,29 +1,8 @@ using System; -using System.Linq; -using Octokit; using System.Threading; namespace GitHub.Unity { - static class ApiExceptionExtensions - { - const string GithubHeader = "X-GitHub-Request-Id"; - public static bool IsGitHubApiException(this Exception ex) - { - var apiex = ex as ApiException; - return apiex?.HttpResponse?.Headers.ContainsKey(GithubHeader) ?? false; - } - - public static string FirstErrorMessageSafe(this ApiError apiError) - { - if (apiError == null) return null; - if (apiError.Errors == null) return apiError.Message; - var firstError = apiError.Errors.FirstOrDefault(); - return firstError == null ? null : firstError.Message; - } - - } - static class ExceptionExtensions { /// diff --git a/src/GitHub.Api/Git/RepositoryManager.cs b/src/GitHub.Api/Git/RepositoryManager.cs index e969f7f25..6efe9f4ce 100644 --- a/src/GitHub.Api/Git/RepositoryManager.cs +++ b/src/GitHub.Api/Git/RepositoryManager.cs @@ -1,9 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using Octokit; using GitHub.Logging; namespace GitHub.Unity diff --git a/src/GitHub.Api/GitHub.Api.csproj b/src/GitHub.Api/GitHub.Api.csproj index e83560907..eb2bf6e05 100644 --- a/src/GitHub.Api/GitHub.Api.csproj +++ b/src/GitHub.Api/GitHub.Api.csproj @@ -95,7 +95,6 @@ - From ab6e27fbca1b825f566474614c53a6c2d6d31712 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 8 Mar 2018 11:50:50 -0500 Subject: [PATCH 4/7] Removing more octokit --- src/GitHub.Api/Authentication/LoginManager.cs | 191 +++--------------- .../Editor/GitHub.Unity/UI/PublishView.cs | 1 - .../BasePlatformIntegrationTest.cs | 1 - .../UnitTests/Authentication/KeychainTests.cs | 29 --- 4 files changed, 32 insertions(+), 190 deletions(-) diff --git a/src/GitHub.Api/Authentication/LoginManager.cs b/src/GitHub.Api/Authentication/LoginManager.cs index 50d71a8a6..cb6a77210 100644 --- a/src/GitHub.Api/Authentication/LoginManager.cs +++ b/src/GitHub.Api/Authentication/LoginManager.cs @@ -21,12 +21,9 @@ class LoginManager : ILoginManager { private readonly ILogging logger = LogHelper.GetLogger(); - private readonly string[] scopes = { "user", "repo", "gist", "write:public_key" }; private readonly IKeychain keychain; private readonly string clientId; private readonly string clientSecret; - private readonly string authorizationNote; - private readonly string fingerprint; private readonly IProcessManager processManager; private readonly ITaskManager taskManager; private readonly NPath nodeJsExecutablePath; @@ -38,8 +35,6 @@ class LoginManager : ILoginManager /// /// The application's client API ID. /// The application's client API secret. - /// An note to store with the authorization. - /// The machine fingerprint. /// /// /// @@ -48,8 +43,6 @@ public LoginManager( IKeychain keychain, string clientId, string clientSecret, - string authorizationNote = null, - string fingerprint = null, IProcessManager processManager = null, ITaskManager taskManager = null, NPath nodeJsExecutablePath = null, NPath octorunScript = null) { Guard.ArgumentNotNull(keychain, nameof(keychain)); @@ -59,8 +52,6 @@ public LoginManager( this.keychain = keychain; this.clientId = clientId; this.clientSecret = clientSecret; - this.authorizationNote = authorizationNote; - this.fingerprint = fingerprint; this.processManager = processManager; this.taskManager = taskManager; this.nodeJsExecutablePath = nodeJsExecutablePath; @@ -82,70 +73,32 @@ public async Task Login( keychain.Connect(host); keychain.SetCredentials(new Credential(host, username, password)); - var newAuth = new NewAuthorization - { - Scopes = scopes, - Note = authorizationNote, - Fingerprint = fingerprint, - }; - - ApplicationAuthorization auth = null; - + string token; try { - auth = await TryLogin(host, username, password); - EnsureNonNullAuthorization(auth); - } - catch (TwoFactorAuthorizationException e) - { - LoginResultCodes result; - if (e is TwoFactorRequiredException) + token = await TryLogin(host, username, password); + if (string.IsNullOrEmpty(token)) { - result = LoginResultCodes.CodeRequired; - logger.Trace("2FA TwoFactorAuthorizationException: {0} {1}", LoginResultCodes.CodeRequired, e.Message); + throw new InvalidOperationException("Returned token is null or empty"); } - else - { - result = LoginResultCodes.CodeFailed; - logger.Error(e, "2FA TwoFactorAuthorizationException: {0} {1}", LoginResultCodes.CodeRequired, e.Message); - } - - return new LoginResultData(result, e.Message, host, newAuth); - } - catch(LoginAttemptsExceededException e) - { - logger.Warning(e, "Login LoginAttemptsExceededException: {0}", e.Message); - - await keychain.Clear(host, false); - return new LoginResultData(LoginResultCodes.LockedOut, Localization.LockedOut, host); } - catch (ApiValidationException e) + catch (TwoFactorRequiredException e) { - logger.Warning(e, "Login ApiValidationException: {0}", e.Message); + LoginResultCodes result; + result = LoginResultCodes.CodeRequired; + logger.Trace("2FA TwoFactorAuthorizationException: {0} {1}", LoginResultCodes.CodeRequired, e.Message); - var message = e.ApiError.FirstErrorMessageSafe(); - await keychain.Clear(host, false); - return new LoginResultData(LoginResultCodes.Failed, message, host); + return new LoginResultData(result, e.Message, host, password); } catch (Exception e) { logger.Warning(e, "Login Exception"); - // Some enterprise instances don't support OAUTH, so fall back to using the - // supplied password - on instances that don't support OAUTH the user should - // be using a personal access token as the password. - if (EnterpriseWorkaround(host, e)) - { - auth = new ApplicationAuthorization(password); - } - else - { - await keychain.Clear(host, false); - return new LoginResultData(LoginResultCodes.Failed, Localization.LoginFailed, host); - } + await keychain.Clear(host, false); + return new LoginResultData(LoginResultCodes.Failed, Localization.LoginFailed, host); } - keychain.SetToken(host, auth.Token); + keychain.SetToken(host, token); await keychain.Save(host); return new LoginResultData(LoginResultCodes.Success, "Success", host); @@ -153,7 +106,7 @@ public async Task Login( public async Task ContinueLogin(LoginResultData loginResultData, string twofacode) { - var newAuth = loginResultData.NewAuth; + var token = loginResultData.Token; var host = loginResultData.Host; var keychainAdapter = keychain.Connect(host); var username = keychainAdapter.Credential.Username; @@ -161,29 +114,18 @@ public async Task ContinueLogin(LoginResultData loginResultData try { logger.Trace("2FA Continue"); - var auth = await TryContinueLogin(host, username, password, twofacode); - - EnsureNonNullAuthorization(auth); + token = await TryContinueLogin(host, username, password, twofacode); - keychain.SetToken(host, auth.Token); + if (string.IsNullOrEmpty(token)) + { + throw new InvalidOperationException("Returned token is null or empty"); + } + + keychain.SetToken(host, token); await keychain.Save(host); return new LoginResultData(LoginResultCodes.Success, "", host); } - catch (TwoFactorAuthorizationException e) - { - logger.Trace(e, "2FA TwoFactorAuthorizationException: {0} {1}", LoginResultCodes.CodeFailed, e.Message); - - return new LoginResultData(LoginResultCodes.CodeFailed, Localization.Wrong2faCode, host, newAuth); - } - catch (ApiValidationException e) - { - logger.Trace(e, "2FA ApiValidationException: {0}", e.Message); - - var message = e.ApiError.FirstErrorMessageSafe(); - await keychain.Clear(host, false); - return new LoginResultData(LoginResultCodes.Failed, message, host); - } catch (Exception e) { logger.Trace(e, "Exception: {0}", e.Message); @@ -201,56 +143,12 @@ public async Task Logout(UriString hostAddress) await new ActionTask(keychain.Clear(hostAddress, true)).StartAwait(); } - private async Task CreateAndDeleteExistingApplicationAuthorization( - IGitHubClient client, - NewAuthorization newAuth, - string twoFactorAuthenticationCode) - { - ApplicationAuthorization result; - var retry = 0; - - do - { - if (twoFactorAuthenticationCode == null) - { - - result = await client.Authorization.GetOrCreateApplicationAuthentication( - clientId, - clientSecret, - newAuth); - } - else - { - result = await client.Authorization.GetOrCreateApplicationAuthentication( - clientId, - clientSecret, - newAuth, - twoFactorAuthenticationCode); - } - - if (result.Token == string.Empty) - { - if (twoFactorAuthenticationCode == null) - { - await client.Authorization.Delete(result.Id); - } - else - { - await client.Authorization.Delete(result.Id, twoFactorAuthenticationCode); - } - } - } while (result.Token == string.Empty && retry++ == 0); - - return result; - } - - private async Task TryLogin( + private async Task TryLogin( UriString host, string username, string password ) { - ApplicationAuthorization auth; var loginTask = new OctorunTask(taskManager.Token, nodeJsExecutablePath, octorunScript, "login", ApplicationInfo.ClientId, ApplicationInfo.ClientSecret); loginTask.Configure(processManager, workingDirectory: octorunScript.Parent.Parent, withInput: true); @@ -270,15 +168,14 @@ string password if (ret[0] == "success") { - auth = new ApplicationAuthorization(ret[1]); - return auth; + return ret[1]; } if (ret[0] == "2fa") { keychain.SetToken(host, ret[1]); await keychain.Save(host); - throw new TwoFactorRequiredException(TwoFactorType.Unknown); + throw new TwoFactorRequiredException(); } if (ret.Count > 2) @@ -289,7 +186,7 @@ string password throw new Exception("Authentication failed"); } - private async Task TryContinueLogin( + private async Task TryContinueLogin( UriString host, string username, string password, @@ -298,7 +195,6 @@ string code { logger.Info("Continue Username:{0} {1} {2}", username, password, code); - ApplicationAuthorization auth; var loginTask = new OctorunTask(taskManager.Token, nodeJsExecutablePath, octorunScript, "login --twoFactor", ApplicationInfo.ClientId, ApplicationInfo.ClientSecret); loginTask.Configure(processManager, workingDirectory: octorunScript.Parent.Parent, withInput: true); @@ -321,8 +217,7 @@ string code if (ret[0] == "success") { - auth = new ApplicationAuthorization(ret[1]); - return auth; + return ret[1]; } if (ret.Count > 2) @@ -332,47 +227,21 @@ string code throw new Exception("Authentication failed"); } - - ApplicationAuthorization EnsureNonNullAuthorization(ApplicationAuthorization auth) - { - // If a mock IGitHubClient is not set up correctly, it can return null from - // IGitHubClient.Authorization.Create - this will cause an infinite loop in Login() - // so prevent that. - if (auth == null) - { - throw new InvalidOperationException("IGitHubClient.Authorization.Create returned null."); - } - - return auth; - } - - bool EnterpriseWorkaround(UriString hostAddress, Exception e) - { - // Older Enterprise hosts either don't have the API end-point to PUT an authorization, or they - // return 422 because they haven't white-listed our client ID. In that case, we just ignore - // the failure, using basic authentication (with username and password) instead of trying - // to get an authorization token. - var apiException = e as ApiException; - return !HostAddress.IsGitHubDotCom(hostAddress) && - (e is NotFoundException || - e is ForbiddenException || - apiException?.StatusCode == (HttpStatusCode)422); - } } class LoginResultData { public LoginResultCodes Code; public string Message; - internal NewAuthorization NewAuth { get; set; } + internal string Token { get; set; } internal UriString Host { get; set; } internal LoginResultData(LoginResultCodes code, string message, - UriString host, NewAuthorization newAuth) + UriString host, string token) { this.Code = code; this.Message = message; - this.NewAuth = newAuth; + this.Token = token; this.Host = host; } @@ -382,4 +251,8 @@ internal LoginResultData(LoginResultCodes code, string message, UriString host) } } + class TwoFactorRequiredException : Exception + { + + } } diff --git a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs index 0d5280f46..1258bc54b 100644 --- a/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs +++ b/src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishView.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; -using Octokit; using UnityEditor; using UnityEngine; diff --git a/src/tests/IntegrationTests/BasePlatformIntegrationTest.cs b/src/tests/IntegrationTests/BasePlatformIntegrationTest.cs index 37261448a..d1e3d3f42 100644 --- a/src/tests/IntegrationTests/BasePlatformIntegrationTest.cs +++ b/src/tests/IntegrationTests/BasePlatformIntegrationTest.cs @@ -4,7 +4,6 @@ using System.Threading.Tasks; using GitHub.Unity; using NSubstitute; -using Octokit; namespace IntegrationTests { diff --git a/src/tests/UnitTests/Authentication/KeychainTests.cs b/src/tests/UnitTests/Authentication/KeychainTests.cs index 292a92a4d..c15b6eb15 100644 --- a/src/tests/UnitTests/Authentication/KeychainTests.cs +++ b/src/tests/UnitTests/Authentication/KeychainTests.cs @@ -7,7 +7,6 @@ using NCrunch.Framework; using NSubstitute; using NUnit.Framework; -using Octokit; using TestUtils; namespace UnitTests @@ -183,10 +182,6 @@ public void ShouldLoadFromConnectionManager() keychainAdapter.Credential.Token.Should().Be(token); keychainAdapter.Credential.Host.Should().Be(hostUri); - keychainAdapter.OctokitCredentials.AuthenticationType.Should().Be(AuthenticationType.Basic); - keychainAdapter.OctokitCredentials.Login.Should().Be(username); - keychainAdapter.OctokitCredentials.Password.Should().Be(token); - credentialManager.Received(1).Load(hostUri); credentialManager.DidNotReceive().HasCredentials(); credentialManager.DidNotReceive().Delete(Args.UriString); @@ -231,10 +226,6 @@ public void ShouldDeleteFromCacheWhenLoadReturnsNullFromConnectionManager() var keychainAdapter = keychain.Load(uriString).Result; keychainAdapter.Credential.Should().BeNull(); - keychainAdapter.OctokitCredentials.AuthenticationType.Should().Be(AuthenticationType.Anonymous); - keychainAdapter.OctokitCredentials.Login.Should().BeNull(); - keychainAdapter.OctokitCredentials.Password.Should().BeNull(); - fileSystem.DidNotReceive().FileExists(Args.String); fileSystem.DidNotReceive().ReadAllText(Args.String); fileSystem.DidNotReceive().FileDelete(Args.String); @@ -294,10 +285,6 @@ public void ShouldConnectSetCredentialsTokenAndSave() var keychainAdapter = keychain.Connect(hostUri); keychainAdapter.Credential.Should().BeNull(); - keychainAdapter.OctokitCredentials.Should().NotBeNull(); - keychainAdapter.OctokitCredentials.AuthenticationType.Should().Be(AuthenticationType.Anonymous); - keychainAdapter.OctokitCredentials.Login.Should().BeNull(); - keychainAdapter.OctokitCredentials.Password.Should().BeNull(); keychain.SetCredentials(new Credential(hostUri, username, password)); @@ -305,9 +292,6 @@ public void ShouldConnectSetCredentialsTokenAndSave() keychainAdapter.Credential.Host.Should().Be(hostUri); keychainAdapter.Credential.Username.Should().Be(username); keychainAdapter.Credential.Token.Should().Be(password); - keychainAdapter.OctokitCredentials.AuthenticationType.Should().Be(AuthenticationType.Basic); - keychainAdapter.OctokitCredentials.Login.Should().Be(username); - keychainAdapter.OctokitCredentials.Password.Should().Be(password); keychain.SetToken(hostUri, token); @@ -315,9 +299,6 @@ public void ShouldConnectSetCredentialsTokenAndSave() keychainAdapter.Credential.Host.Should().Be(hostUri); keychainAdapter.Credential.Username.Should().Be(username); keychainAdapter.Credential.Token.Should().Be(token); - keychainAdapter.OctokitCredentials.AuthenticationType.Should().Be(AuthenticationType.Basic); - keychainAdapter.OctokitCredentials.Login.Should().Be(username); - keychainAdapter.OctokitCredentials.Password.Should().Be(token); keychain.Save(hostUri).Wait(); @@ -379,10 +360,6 @@ public void ShouldConnectSetCredentialsAndClear() var keychainAdapter = keychain.Connect(hostUri); keychainAdapter.Credential.Should().BeNull(); - keychainAdapter.OctokitCredentials.Should().NotBeNull(); - keychainAdapter.OctokitCredentials.AuthenticationType.Should().Be(AuthenticationType.Anonymous); - keychainAdapter.OctokitCredentials.Login.Should().BeNull(); - keychainAdapter.OctokitCredentials.Password.Should().BeNull(); keychain.SetCredentials(new Credential(hostUri, username, password)); @@ -390,16 +367,10 @@ public void ShouldConnectSetCredentialsAndClear() keychainAdapter.Credential.Host.Should().Be(hostUri); keychainAdapter.Credential.Username.Should().Be(username); keychainAdapter.Credential.Token.Should().Be(password); - keychainAdapter.OctokitCredentials.AuthenticationType.Should().Be(AuthenticationType.Basic); - keychainAdapter.OctokitCredentials.Login.Should().Be(username); - keychainAdapter.OctokitCredentials.Password.Should().Be(password); keychain.Clear(hostUri, false).Wait(); keychainAdapter.Credential.Should().BeNull(); - keychainAdapter.OctokitCredentials.AuthenticationType.Should().Be(AuthenticationType.Anonymous); - keychainAdapter.OctokitCredentials.Login.Should().BeNull(); - keychainAdapter.OctokitCredentials.Password.Should().BeNull(); fileSystem.DidNotReceive().FileExists(Args.String); fileSystem.DidNotReceive().FileDelete(Args.String); From eb93b0c45b55adf90919693c2ac39a26675f83c4 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 8 Mar 2018 13:13:59 -0500 Subject: [PATCH 5/7] Removing the bits about OctokitDebugging --- GitHub.Unity.OctokitDebugging.sln | 132 ------------------------------ common/build.targets | 25 ------ common/properties.props | 1 - 3 files changed, 158 deletions(-) delete mode 100644 GitHub.Unity.OctokitDebugging.sln diff --git a/GitHub.Unity.OctokitDebugging.sln b/GitHub.Unity.OctokitDebugging.sln deleted file mode 100644 index 8d9cef6c2..000000000 --- a/GitHub.Unity.OctokitDebugging.sln +++ /dev/null @@ -1,132 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 14 -VisualStudioVersion = 14.0.25420.1 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GitHub.Unity", "src\UnityExtension\Assets\Editor\GitHub.Unity\GitHub.Unity.csproj", "{ADD7A18B-DD2A-4C22-A2C1-488964EFF30A}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GitHub.Api", "src\GitHub.Api\GitHub.Api.csproj", "{B389ADAF-62CC-486E-85B4-2D8B078DF763}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GitHub.Logging", "src\GitHub.Logging\GitHub.Logging.csproj", "{BB6A8EDA-15D8-471B-A6ED-EE551E0B3BA0}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CopyLibrariesToDevelopmentFolder", "src\packaging\CopyLibrariesToDevelopmentFolder\CopyLibrariesToDevelopmentFolder.csproj", "{44257C81-EE4A-4817-9AF4-A26C02AA6DD4}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UnitTests", "src\tests\UnitTests\UnitTests.csproj", "{69F13D9D-AD56-4EEC-AE10-D528EE23E1A9}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IntegrationTests", "src\tests\IntegrationTests\IntegrationTests.csproj", "{1AC3F82E-AEAE-4C84-825C-207BB264FCFA}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tests", "Tests", "{D17F1B4C-42DC-4E78-BCEF-9F239A084C4D}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "packaging", "packaging", "{B50B646C-3B86-4BDA-9F2B-766F96608CE0}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CopyLibrariesToPackageProject", "src\packaging\CopyLibrariesToPackageProject\CopyLibrariesToPackageProject.csproj", "{7DEF4226-7740-457F-9199-34174C49A978}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestUtils", "src\tests\TestUtils\TestUtils.csproj", "{66A1D219-F61D-4AE4-9BD7-AAEB97276FFF}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TaskSystem", "src\tests\TaskSystemIntegrationTests\TaskSystem.csproj", "{1A382F40-FD9E-43E1-89C1-320073F35CE9}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestApp", "src\tests\TestApp\TestApp.csproj", "{08B87D2A-8CF1-4211-B7AA-5209F00F72F8}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "dotnet-httpclient35", "dotnet-httpclient35", "{C6854BB9-D594-46B0-9E10-72607CC97E77}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "octokit", "octokit", "{5C9C1D3B-0740-4EF3-A374-CCCD67FB6E48}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Octokit-35", "..\octokit.net\Octokit\Octokit-35.csproj", "{49EF16A2-5ED1-480F-80A1-D1D05D6C1BE4}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "System.Net.Http-net_3_5", "..\dotnet-httpclient35\System.Net.Http\System.Net.Http-net_3_5.csproj", "{9862694D-E4FA-418B-8692-A0280FEDDF36}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - dev|Any CPU = dev|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {ADD7A18B-DD2A-4C22-A2C1-488964EFF30A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {ADD7A18B-DD2A-4C22-A2C1-488964EFF30A}.Debug|Any CPU.Build.0 = Debug|Any CPU - {ADD7A18B-DD2A-4C22-A2C1-488964EFF30A}.dev|Any CPU.ActiveCfg = dev|Any CPU - {ADD7A18B-DD2A-4C22-A2C1-488964EFF30A}.dev|Any CPU.Build.0 = dev|Any CPU - {ADD7A18B-DD2A-4C22-A2C1-488964EFF30A}.Release|Any CPU.ActiveCfg = Release|Any CPU - {ADD7A18B-DD2A-4C22-A2C1-488964EFF30A}.Release|Any CPU.Build.0 = Release|Any CPU - {B389ADAF-62CC-486E-85B4-2D8B078DF763}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {B389ADAF-62CC-486E-85B4-2D8B078DF763}.Debug|Any CPU.Build.0 = Debug|Any CPU - {B389ADAF-62CC-486E-85B4-2D8B078DF763}.dev|Any CPU.ActiveCfg = dev|Any CPU - {B389ADAF-62CC-486E-85B4-2D8B078DF763}.dev|Any CPU.Build.0 = dev|Any CPU - {B389ADAF-62CC-486E-85B4-2D8B078DF763}.Release|Any CPU.ActiveCfg = Release|Any CPU - {B389ADAF-62CC-486E-85B4-2D8B078DF763}.Release|Any CPU.Build.0 = Release|Any CPU - {BB6A8EDA-15D8-471B-A6ED-EE551E0B3BA0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {BB6A8EDA-15D8-471B-A6ED-EE551E0B3BA0}.Debug|Any CPU.Build.0 = Debug|Any CPU - {BB6A8EDA-15D8-471B-A6ED-EE551E0B3BA0}.dev|Any CPU.ActiveCfg = dev|Any CPU - {BB6A8EDA-15D8-471B-A6ED-EE551E0B3BA0}.dev|Any CPU.Build.0 = dev|Any CPU - {BB6A8EDA-15D8-471B-A6ED-EE551E0B3BA0}.Release|Any CPU.ActiveCfg = Release|Any CPU - {BB6A8EDA-15D8-471B-A6ED-EE551E0B3BA0}.Release|Any CPU.Build.0 = Release|Any CPU - {44257C81-EE4A-4817-9AF4-A26C02AA6DD4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {44257C81-EE4A-4817-9AF4-A26C02AA6DD4}.Debug|Any CPU.Build.0 = Debug|Any CPU - {44257C81-EE4A-4817-9AF4-A26C02AA6DD4}.dev|Any CPU.ActiveCfg = Debug|Any CPU - {44257C81-EE4A-4817-9AF4-A26C02AA6DD4}.dev|Any CPU.Build.0 = Debug|Any CPU - {44257C81-EE4A-4817-9AF4-A26C02AA6DD4}.Release|Any CPU.ActiveCfg = Release|Any CPU - {44257C81-EE4A-4817-9AF4-A26C02AA6DD4}.Release|Any CPU.Build.0 = Release|Any CPU - {69F13D9D-AD56-4EEC-AE10-D528EE23E1A9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {69F13D9D-AD56-4EEC-AE10-D528EE23E1A9}.Debug|Any CPU.Build.0 = Debug|Any CPU - {69F13D9D-AD56-4EEC-AE10-D528EE23E1A9}.dev|Any CPU.ActiveCfg = Debug|Any CPU - {69F13D9D-AD56-4EEC-AE10-D528EE23E1A9}.dev|Any CPU.Build.0 = Debug|Any CPU - {69F13D9D-AD56-4EEC-AE10-D528EE23E1A9}.Release|Any CPU.ActiveCfg = Release|Any CPU - {69F13D9D-AD56-4EEC-AE10-D528EE23E1A9}.Release|Any CPU.Build.0 = Release|Any CPU - {1AC3F82E-AEAE-4C84-825C-207BB264FCFA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {1AC3F82E-AEAE-4C84-825C-207BB264FCFA}.Debug|Any CPU.Build.0 = Debug|Any CPU - {1AC3F82E-AEAE-4C84-825C-207BB264FCFA}.dev|Any CPU.ActiveCfg = Debug|Any CPU - {1AC3F82E-AEAE-4C84-825C-207BB264FCFA}.dev|Any CPU.Build.0 = Debug|Any CPU - {1AC3F82E-AEAE-4C84-825C-207BB264FCFA}.Release|Any CPU.ActiveCfg = Release|Any CPU - {1AC3F82E-AEAE-4C84-825C-207BB264FCFA}.Release|Any CPU.Build.0 = Release|Any CPU - {7DEF4226-7740-457F-9199-34174C49A978}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {7DEF4226-7740-457F-9199-34174C49A978}.Debug|Any CPU.Build.0 = Debug|Any CPU - {7DEF4226-7740-457F-9199-34174C49A978}.dev|Any CPU.ActiveCfg = Debug|Any CPU - {7DEF4226-7740-457F-9199-34174C49A978}.dev|Any CPU.Build.0 = Debug|Any CPU - {7DEF4226-7740-457F-9199-34174C49A978}.Release|Any CPU.ActiveCfg = Release|Any CPU - {7DEF4226-7740-457F-9199-34174C49A978}.Release|Any CPU.Build.0 = Release|Any CPU - {66A1D219-F61D-4AE4-9BD7-AAEB97276FFF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {66A1D219-F61D-4AE4-9BD7-AAEB97276FFF}.Debug|Any CPU.Build.0 = Debug|Any CPU - {66A1D219-F61D-4AE4-9BD7-AAEB97276FFF}.dev|Any CPU.ActiveCfg = Debug|Any CPU - {66A1D219-F61D-4AE4-9BD7-AAEB97276FFF}.dev|Any CPU.Build.0 = Debug|Any CPU - {66A1D219-F61D-4AE4-9BD7-AAEB97276FFF}.Release|Any CPU.ActiveCfg = Release|Any CPU - {66A1D219-F61D-4AE4-9BD7-AAEB97276FFF}.Release|Any CPU.Build.0 = Release|Any CPU - {1A382F40-FD9E-43E1-89C1-320073F35CE9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {1A382F40-FD9E-43E1-89C1-320073F35CE9}.Debug|Any CPU.Build.0 = Debug|Any CPU - {1A382F40-FD9E-43E1-89C1-320073F35CE9}.dev|Any CPU.ActiveCfg = Debug|Any CPU - {1A382F40-FD9E-43E1-89C1-320073F35CE9}.dev|Any CPU.Build.0 = Debug|Any CPU - {1A382F40-FD9E-43E1-89C1-320073F35CE9}.Release|Any CPU.ActiveCfg = Release|Any CPU - {1A382F40-FD9E-43E1-89C1-320073F35CE9}.Release|Any CPU.Build.0 = Release|Any CPU - {08B87D2A-8CF1-4211-B7AA-5209F00F72F8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {08B87D2A-8CF1-4211-B7AA-5209F00F72F8}.Debug|Any CPU.Build.0 = Debug|Any CPU - {08B87D2A-8CF1-4211-B7AA-5209F00F72F8}.dev|Any CPU.ActiveCfg = Debug|Any CPU - {08B87D2A-8CF1-4211-B7AA-5209F00F72F8}.dev|Any CPU.Build.0 = Debug|Any CPU - {08B87D2A-8CF1-4211-B7AA-5209F00F72F8}.Release|Any CPU.ActiveCfg = Release|Any CPU - {08B87D2A-8CF1-4211-B7AA-5209F00F72F8}.Release|Any CPU.Build.0 = Release|Any CPU - {49EF16A2-5ED1-480F-80A1-D1D05D6C1BE4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {49EF16A2-5ED1-480F-80A1-D1D05D6C1BE4}.Debug|Any CPU.Build.0 = Debug|Any CPU - {49EF16A2-5ED1-480F-80A1-D1D05D6C1BE4}.dev|Any CPU.ActiveCfg = Debug|Any CPU - {49EF16A2-5ED1-480F-80A1-D1D05D6C1BE4}.dev|Any CPU.Build.0 = Debug|Any CPU - {49EF16A2-5ED1-480F-80A1-D1D05D6C1BE4}.Release|Any CPU.ActiveCfg = Release|Any CPU - {49EF16A2-5ED1-480F-80A1-D1D05D6C1BE4}.Release|Any CPU.Build.0 = Release|Any CPU - {9862694D-E4FA-418B-8692-A0280FEDDF36}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {9862694D-E4FA-418B-8692-A0280FEDDF36}.Debug|Any CPU.Build.0 = Debug|Any CPU - {9862694D-E4FA-418B-8692-A0280FEDDF36}.dev|Any CPU.ActiveCfg = Debug|Any CPU - {9862694D-E4FA-418B-8692-A0280FEDDF36}.dev|Any CPU.Build.0 = Debug|Any CPU - {9862694D-E4FA-418B-8692-A0280FEDDF36}.Release|Any CPU.ActiveCfg = Release|Any CPU - {9862694D-E4FA-418B-8692-A0280FEDDF36}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(NestedProjects) = preSolution - {44257C81-EE4A-4817-9AF4-A26C02AA6DD4} = {B50B646C-3B86-4BDA-9F2B-766F96608CE0} - {69F13D9D-AD56-4EEC-AE10-D528EE23E1A9} = {D17F1B4C-42DC-4E78-BCEF-9F239A084C4D} - {1AC3F82E-AEAE-4C84-825C-207BB264FCFA} = {D17F1B4C-42DC-4E78-BCEF-9F239A084C4D} - {7DEF4226-7740-457F-9199-34174C49A978} = {B50B646C-3B86-4BDA-9F2B-766F96608CE0} - {66A1D219-F61D-4AE4-9BD7-AAEB97276FFF} = {D17F1B4C-42DC-4E78-BCEF-9F239A084C4D} - {1A382F40-FD9E-43E1-89C1-320073F35CE9} = {D17F1B4C-42DC-4E78-BCEF-9F239A084C4D} - {08B87D2A-8CF1-4211-B7AA-5209F00F72F8} = {D17F1B4C-42DC-4E78-BCEF-9F239A084C4D} - {49EF16A2-5ED1-480F-80A1-D1D05D6C1BE4} = {5C9C1D3B-0740-4EF3-A374-CCCD67FB6E48} - {9862694D-E4FA-418B-8692-A0280FEDDF36} = {C6854BB9-D594-46B0-9E10-72607CC97E77} - EndGlobalSection -EndGlobal diff --git a/common/build.targets b/common/build.targets index ca88d77e4..450909d08 100644 --- a/common/build.targets +++ b/common/build.targets @@ -14,31 +14,6 @@ - - - - - {9862694d-e4fa-418b-8692-a0280feddf36} - System.Net.Http-net_3_5 - - - {49ef16a2-5ed1-480f-80a1-d1d05d6c1be4} - Octokit-35 - - - - - - - $(SolutionDir)lib\octokit.net\Octokit.dll - - - $(SolutionDir)lib\dotnet-httpclient35\DotNetHttp35.dll - - - - - Location of Unity dlls is not set. You'll need to install Unity in a known location (the default installation directory for your system), or copy UnityEngine.dll and UnityEditor.dll to the {0}lib folder diff --git a/common/properties.props b/common/properties.props index 441fd006d..30e26a07d 100644 --- a/common/properties.props +++ b/common/properties.props @@ -2,7 +2,6 @@ - OctokitDebugging Internal $(SolutionDir)\script\lib\ From 4d5478fa214908b3a661d0cac30221dc064abf61 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Thu, 8 Mar 2018 13:22:30 -0500 Subject: [PATCH 6/7] Fixing import --- src/GitHub.Api/Git/RepositoryManager.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/GitHub.Api/Git/RepositoryManager.cs b/src/GitHub.Api/Git/RepositoryManager.cs index bdc7cb469..9e3566e7f 100644 --- a/src/GitHub.Api/Git/RepositoryManager.cs +++ b/src/GitHub.Api/Git/RepositoryManager.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Threading; using GitHub.Logging; namespace GitHub.Unity From b422312c31c2032e937d7ccb0995b6b43d639f91 Mon Sep 17 00:00:00 2001 From: Stanley Goldman Date: Fri, 9 Mar 2018 14:01:27 -0500 Subject: [PATCH 7/7] Removing unintentional change --- src/GitHub.Api/Authentication/LoginManager.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/GitHub.Api/Authentication/LoginManager.cs b/src/GitHub.Api/Authentication/LoginManager.cs index b6c81b498..c7b39dd5a 100644 --- a/src/GitHub.Api/Authentication/LoginManager.cs +++ b/src/GitHub.Api/Authentication/LoginManager.cs @@ -1,4 +1,4 @@ -i have using System; +using System; using System.Linq; using System.Net; using System.Threading.Tasks;