private static void Go(Repository repository, Commit commit) { Workspace workspace = null; WorkingFolder folder = null; string tempPath = null; try { workspace = CreateWorkspace(); tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); Directory.CreateDirectory(tempPath); Console.WriteLine("Creating scratch TFS enlistment"); folder = AddMapping(workspace, tempPath); Console.WriteLine("Building Git Tree"); var workspaceTree = GitUtils.CreateTreeFromWorkspace(workspace, tempPath, repository.ObjectDatabase); Console.WriteLine("Calculating diff"); var treeChanges = repository.Diff.Compare <TreeChanges>(workspaceTree, commit.Tree, compareOptions: new LibGit2Sharp.CompareOptions() { Similarity = SimilarityOptions.Renames }); Console.WriteLine("Applying commit to workspace"); var commitPortUtil = new CommitPortUtil(repository, workspace, tempPath); commitPortUtil.ApplyGitChangeToWorkspace(treeChanges); var shelvesetName = string.Format("shelve-commit-{0}", commit.Sha); Console.WriteLine("Shelving to {0}", shelvesetName); ShelveChanges(workspace, shelvesetName, commit); } finally { if (workspace != null) { Console.WriteLine("Cleaning up TFS enlistment"); if (folder != null) { workspace.DeleteMapping(folder); } workspace.Delete(); } if (tempPath != null && Directory.Exists(tempPath)) { Console.WriteLine("Cleaning up temp files"); try { Directory.Delete(tempPath, recursive: true); } catch (Exception ex) { Console.WriteLine("Error: {0}", ex.Message); } } } }
private void UpdateVersionFile() { string timeStamp = DateTime.Now.ToString("yyMMddHHmm", CultureInfo.InvariantCulture); string commitShortHash = GitUtils.GetCurrentCommitShortHash(); string[] versionFileLines = File.ReadAllLines(versionFile); for (int i = 0; i < versionFileLines.Length; i++) { string line = versionFileLines[i]; if (line.StartsWith(versionPropertyName, true, CultureInfo.InvariantCulture)) { versionFileLines[i] = $"{versionPropertyName} = {PlayerSettings.bundleVersion}"; } if (line.StartsWith(timeStampPropertyName, true, CultureInfo.InvariantCulture)) { versionFileLines[i] = $"{timeStampPropertyName} = {timeStamp}"; } if (line.StartsWith(commitShortHashPropertyName, true, CultureInfo.InvariantCulture)) { versionFileLines[i] = $"{commitShortHashPropertyName} = {commitShortHash}"; } } File.WriteAllLines(versionFile, versionFileLines); // Unity needs a hint that this asset has changed. AssetDatabase.ImportAsset(versionFile); }
public static async Task <Func <Slide, string> > BuildGetGitEditLinkFunc(string userId, Course course, ICourseRolesRepo courseRolesRepo, ICoursesRepo coursesRepo) { var courseRole = await courseRolesRepo.GetRoleAsync(userId, course.Id); var canEditGit = courseRole <= CourseRoleType.CourseAdmin; if (!canEditGit) { return(s => null); } var publishedCourseVersion = await coursesRepo.GetPublishedCourseVersionAsync(course.Id); if (publishedCourseVersion == null) { return(s => null); } var repoUrl = publishedCourseVersion.RepoUrl; var pathToCourseXml = publishedCourseVersion.PathToCourseXml; if (repoUrl == null || pathToCourseXml == null) { return(s => null); } var courseXmlDirectory = course.CourseXmlDirectory; return(slide => { var pathRelative2CourseXml = slide.Info.SlideFile.FullName.Substring(courseXmlDirectory.FullName.Length + 1); return GitUtils.GetSlideEditLink(repoUrl, pathToCourseXml, pathRelative2CourseXml); }); }
protected FixableRuleBase(ILogger <FixableRuleBase <T> > logger, GitUtils gitUtils, string ruleName, string pullRequestTitle) { RuleName = ruleName; _logger = logger; _gitUtils = gitUtils; _pullRequestTitle = pullRequestTitle; }
/// <summary> /// タイトルに表示する文字列を返します /// </summary> private static string GetTitle() { // https://github.com/Unity-Technologies/UnityCsReference/blob/master/Editor/Mono/EditorApplication.cs var activeSceneName = L10n.Tr("Untitled"); if (!string.IsNullOrEmpty(SceneManager.GetActiveScene().path)) { activeSceneName = Path.GetFileNameWithoutExtension(SceneManager.GetActiveScene().path); } //var projectName = PlayerSettings.productName; var projectName = Path.GetFileName(Path.GetDirectoryName(Application.dataPath)); var targetName = GetBuildTargetGroupDisplayName(BuildPipeline.GetBuildTargetGroup(EditorUserBuildSettings.activeBuildTarget)); var version = Application.unityVersion; var licenseType = InternalEditorUtility.HasPro() ? "" : "Personal"; var branchName = GitUtils.LoadBranchName(); var title = $"{projectName} - {activeSceneName} - {targetName} - Unity {version} {licenseType}"; if (!string.IsNullOrWhiteSpace(branchName)) { title += $" - {branchName}"; } return(title); }
private void FetchUpdate() { try { Release latestRelease = GitUtils.GetLatestVersion(); int[] latestVersion = GitUtils.DecomposeVersion(latestRelease); int[] currentVersion = GitUtils.DecomposeVersion(MapBuilder.Program.Version); if (GitUtils.CompareVersion(latestVersion, currentVersion)) { DialogResult choice = MessageBox.Show("A new version is available ! (Current : " + MapBuilder.Program.Version + " | Latest : " + latestRelease.TagName + ") \n Would you like to go to the downloads page ?", "Updater", MessageBoxButtons.YesNo, MessageBoxIcon.Information); if (choice == DialogResult.Yes) { System.Diagnostics.Process.Start("https://github.com/EdwinMindcraft/PelicamonTools/releases"); } } else { Console.Out.WriteLine("Current version matches latest release"); } OnUpdateFinish.Invoke(); } catch (Exception ex) { MessageBox.Show("Seems like an error occured, please verify your connection and try again. \n If the problem still occurs, please contact EdwinMindcraft or Edern via Discord with the following error report attached. \n \n" + ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); OnUpdateFinish.Invoke(); return; } }
public List <string> FindRecentChanges() { var fromDate = DateTime.Today.AddDays(-30); var commits = GitUtils.FindCommitsWithChanges("master", fromDate, null); return(commits); }
private static void UpdateVersionFile() { string bundleVersion = GetPlayerSettingsFileBundleVersion(); string timeStamp = DateTime.Now.ToString("yyMMddHHmm", CultureInfo.InvariantCulture); string commitShortHash = GitUtils.GetCurrentCommitShortHash(); Dictionary <string, string> propertyNameToValueMap = new(); propertyNameToValueMap.Add(versionPropertyName, bundleVersion); propertyNameToValueMap.Add(timeStampPropertyName, timeStamp); propertyNameToValueMap.Add(commitShortHashPropertyName, commitShortHash); Debug.Log($"Updating {versionFile} with {JsonConverter.ToJson(propertyNameToValueMap)}"); string[] versionFileLines = File.ReadAllLines(versionFile); for (int i = 0; i < versionFileLines.Length; i++) { string line = versionFileLines[i]; propertyNameToValueMap.ForEach(entry => { string propertyName = entry.Key; string propertyValue = entry.Value; if (line.StartsWith(entry.Key, true, CultureInfo.InvariantCulture)) { versionFileLines[i] = $"{propertyName} = {propertyValue}"; } }); } File.WriteAllLines(versionFile, versionFileLines); Debug.Log($"New contents of {versionFile}:\n{versionFileLines.ToCsv(", ")}"); // Unity needs a hint that this asset has changed. AssetDatabase.ImportAsset(versionFile); }
public static BuildTargetResult GenerateVersions(BuildTargetContext c) { var commitCount = GitUtils.GetCommitCount(); var commitHash = GitUtils.GetCommitHash(); var branchInfo = new BranchInfo(Dirs.RepoRoot); var hostVersion = new HostVersion() { ReleaseSuffix = branchInfo.Entries["RELEASE_SUFFIX"], CommitCount = commitCount }; var buildVersion = new BuildVersion() { Major = int.Parse(branchInfo.Entries["MAJOR_VERSION"]), Minor = int.Parse(branchInfo.Entries["MINOR_VERSION"]), Patch = int.Parse(branchInfo.Entries["PATCH_VERSION"]), ReleaseSuffix = branchInfo.Entries["RELEASE_SUFFIX"], CommitCount = commitCount }; c.BuildContext["BuildVersion"] = buildVersion; c.BuildContext["HostVersion"] = hostVersion; c.BuildContext["CommitHash"] = commitHash; c.BuildContext["SharedFrameworkNugetVersion"] = buildVersion.NetCoreAppVersion; c.Info($"Building Version: {hostVersion.LatestHostVersion.WithoutSuffix} (NuGet Packages: {hostVersion.LatestHostVersion})"); c.Info($"From Commit: {commitHash}"); return(c.Success()); }
/// <summary> /// 获取git路径,可能是github或gitee /// https格式正则表达式:https://(.*).git /// ssh格式正则表达式:git@(.*).git /// /// 例: /// 本地插件的packageId:com.chino.upmtool@file:F:\Unity3D\UPM-Tool-Develop\Assets\_package_ /// git插件的packageId:com.chino.testpackage@ssh://[email protected]/Chino66/UPM-Tool-Develop.git#upm /// http://gitlab.wd.com/cyj/Game_AI_Develop.git#upm /// </summary> /// <param name="packageId">插件包的来源路径</param> /// <returns></returns> private static string GetGitUrl(string packageId) { if (string.IsNullOrEmpty(packageId)) { Debug.LogError("packageId is null"); return(""); } Debug.Log(packageId); var pattern = "(https://(.*).git)|(git@(.*).git)|(http://(.*).git)"; Match match = Regex.Match(packageId, pattern); if (match.Success == false) { Debug.LogWarning("packageId is not git url, packageId is :" + packageId); return(""); } var url = match.Value; url = GitUtils.UnityPackagePathConvertGitPath(url); return(url); }
/// <summary> /// Clones a git repository. Only HTTP remote supported /// </summary> /// <param name="remote"></param> /// <param name="dstdir"></param> /// <param name="options"></param> public void GitClone(string remote, string dstdir, string branch = null, CloneOptions options = null) { options = options ?? new CloneOptions(); options.BranchName = branch ?? options.BranchName; GitUtils.Clone(remote, dstdir, options, this); }
public static BuildTargetResult GenerateVersions(BuildTargetContext c) { var commitCount = GitUtils.GetCommitCount(); var commitHash = GitUtils.GetCommitHash(); var branchInfo = new BranchInfo(Dirs.RepoRoot); // Read details from branchinfo.txt for our build configuration int iMajor = int.Parse(branchInfo.Entries["MAJOR_VERSION"]); int iMinor = int.Parse(branchInfo.Entries["MINOR_VERSION"]); int iPatch = int.Parse(branchInfo.Entries["PATCH_VERSION"]); string sReleaseSuffix = branchInfo.Entries["RELEASE_SUFFIX"]; bool fStabilizePackageVersion = bool.Parse(branchInfo.Entries["STABILIZE_PACKAGE_VERSION"]); bool fValidateHostPackages = bool.Parse(branchInfo.Entries["VALIDATE_HOST_PACKAGES"]); bool fLockHostVersion = bool.Parse(branchInfo.Entries["LOCK_HOST_VERSION"]); var hostVersion = new HostVersion() { Major = iMajor, Minor = iMinor, Patch = iPatch, ReleaseSuffix = sReleaseSuffix, EnsureStableVersion = fStabilizePackageVersion, IsLocked = fLockHostVersion, CommitCount = commitCount }; var buildVersion = new BuildVersion() { Major = iMajor, Minor = iMinor, Patch = iPatch, ReleaseSuffix = sReleaseSuffix, CommitCount = commitCount }; c.BuildContext["ValidateHostPackages"] = fValidateHostPackages; c.BuildContext["BuildVersion"] = buildVersion; c.BuildContext["HostVersion"] = hostVersion; c.BuildContext["CommitHash"] = commitHash; c.BuildContext["BranchName"] = branchInfo.Entries["BRANCH_NAME"]; // Define the version string to be used based upon whether we are stabilizing the versions or not. if (!fStabilizePackageVersion) { c.BuildContext["SharedFrameworkNugetVersion"] = buildVersion.NetCoreAppVersion; } else { c.BuildContext["SharedFrameworkNugetVersion"] = buildVersion.ProductionVersion; } c.Info($"Building Version: {hostVersion.LatestHostVersion.WithoutSuffix} (NuGet Packages: {hostVersion.LatestHostVersion})"); c.Info($"From Commit: {commitHash}"); return(c.Success()); }
public List <string> FindChangesWithFilter(string repoName, DateTime?fromDate, int?daysToRetrospect) { if (fromDate.HasValue && daysToRetrospect.HasValue) { throw new ArgumentException("Must choose 'From Date' OR 'Days To Retrospect', cannot filter by both"); } var commits = GitUtils.FindCommitsWithChanges(repoName, fromDate ?? DateTime.MinValue, daysToRetrospect); return(commits); }
public static Task getCommit(Match match, CommandContext context) { string repo = GitUtils.get_repo(match.Groups[1].Value); if (repo == null) { return(context.Channel.SendMessageAsync("Invalid prefix")); } return(context.Channel.SendMessageAsync(embed: GitUtils.embed_commit(match.Groups[2].Value, repo))); }
/// <inheritdoc /> public bool Refresh() { if (!RepositoryReferenceValid()) { return(false); } if (string.IsNullOrEmpty(LocalRepositoryFolder)) { return(false); } if (Repository.IsValid(LocalRepositoryFolder)) { GitRepository = GitUtils.Synchronize( LocalRepositoryFolder, new FetchOptions { CertificateCheck = CertificateCheck, CredentialsProvider = CredentialsProvider, CustomHeaders = CustomHeaders }, caller: this ); } else { GitRepository = GitUtils.Clone( Url, LocalRepositoryFolder, new CloneOptions { CertificateCheck = CertificateCheck, CredentialsProvider = CredentialsProvider, FetchOptions = { CertificateCheck = CertificateCheck, CredentialsProvider = CredentialsProvider, CustomHeaders = CustomHeaders } }, this ); } if (GitRepository != null) { Synchronized = true; var res = this.GatherPackageReferencesFromFolder(LocalRepositoryFolder, _packages); OnRefreshed?.Invoke(this, EventArgs.Empty); Ready = true; return(res); } return(false); }
/// <summary> /// 获取git仓库的tags /// </summary> public void GetGitTags(List <string> choices, Action <List <string> > action) { GitUtils.GetTags(_gitUrl, tags => { choices.Clear(); choices.AddRange(tags); choices.Sort((a, b) => { var sa = a.Split('.'); var sb = b.Split('.'); if (sa.Length != 3 || sb.Length != 3) { return(0); } for (var i = 0; i < 3; i++) { try { var ia = int.Parse(sa[i]); var ib = int.Parse(sb[i]); if (ia == ib) { continue; } if (ia > ib) { return(-1); } if (ia < ib) { return(1); } } catch (Exception e) { Console.WriteLine(e); return(0); } } return(0); }); if (choices.Count > 0) { action(choices); } }); }
public void SetUp() { var mockLogger = Substitute.For <ILogger <GitUtils> >(); _gitUtils = new GitUtils(mockLogger); _mockClient = Substitute.For <IGitHubClient>(); _mockRepositoryBranchesClient = Substitute.For <IRepositoryBranchesClient>(); _mockPullRequestsClient = Substitute.For <IPullRequestsClient>(); _mockClient.Repository.Branch.Returns(_mockRepositoryBranchesClient); _mockClient.Repository.PullRequest.Returns(_mockPullRequestsClient); }
/// <summary> /// load post or reload posts /// </summary> private void LoadPosts() { // make sure directory exists GitUtils.MakeDirectory(CommonData.config.PostDirectory); // clear selected if (selectedItem != null) { selectedItem.RemoveHandlers(); selectedItem = null; } inputTbx.Text = string.Empty; articleListPanel.Children.Clear(); // get markdown files var files = Directory.GetFiles(CommonData.config.PostDirectory) .Where(f => f.EndsWith(Suffix)); var targetBackground = new SolidColorBrush(Color.FromRgb(199, 80, 73)); var targetForeground = new SolidColorBrush(Colors.White); var otherBackground = new SolidColorBrush(Color.FromRgb(49, 47, 47)); var otherForeground = new SolidColorBrush(Colors.Silver); // deal with each post foreach (var file in files) { var current = new PostItemControl(file, this.inputTbx); current.Register((sender, e) => { foreach (var control in cacheControls) { control.Background = otherBackground; control.Foreground = otherForeground; control.RemoveHandlers(); } // current current.Background = targetBackground; current.Foreground = targetForeground; selectedItem = current; current.ConfigTimer(); }); articleListPanel.Children.Add(current); } // bake in cache var array = new PostItemControl[articleListPanel.Children.Count]; articleListPanel.Children.CopyTo(array, 0); // add cache cacheControls.Clear(); cacheControls.AddRange(array); }
public Dictionary <string, IEnumerable <string> > ReadGitRepository() { var dictionary = new Dictionary <string, IEnumerable <string> >(); //var comparers = GitUtils.ReadRepository().ToList(); var comparer = GitUtils.GetTwoFiles(); var differences = comparer.GetDifferences(); dictionary.Add("Element", differences.Select(d => d.ElementName).ToList()); dictionary.Add("Feature", differences.Select(d => d.Feature).ToList()); dictionary.Add("Source Value", differences.Select(d => d.SourceValue).ToList()); dictionary.Add("Target Value", differences.Select(d => d.TargetValue).ToList()); return(dictionary); }
public void Setup() { _diskManager = Substitute.For <IStaticAbstraction>(); _pathManager = Substitute.For <IPath>(); _pathManager.Combine(Arg.Any <string>(), Arg.Any <string>()).Returns(x => { var data = x.Arg <string[]>(); return(data[0].TrimEnd('\\') + "\\" + data[1].TrimStart('\\')); }); _diskManager.Path.Returns(_pathManager); _cacheManager = Substitute.For <ICacheContainer>(); _gitUtils = new GitUtils(_diskManager, _cacheManager); }
public async override Task <GitStatus> Run() { return(await Task.Run <GitStatus>(() => { // save config _form.UpdateStatus(AppStatus.SavingConfig); ConfigUtils.Save(_form.Config); string wowPath = _form.Config.WowPath; // check wow directory _form.UpdateStatus(AppStatus.CheckingWow); if (!FileUtils.IsValidWowDirectory(wowPath)) { _form.UpdateStatus(AppStatus.InvalidWow); return GitStatus.Failed; } // check appdata folder _form.UpdateStatus(AppStatus.CheckingDataFolder); if (!FileUtils.CheckAppDataFolder()) { _form.UpdateStatus(AppStatus.InvalidDataFolder); return GitStatus.Failed; } // clone (or pull) into appdata folder _form.UpdateStatus(AppStatus.Pulling); GitStatus cloneResult = GitUtils.CloneRepo(); // bail out if we failed if (cloneResult == GitStatus.Failed) { _form.UpdateStatus(AppStatus.GitPullFailed); return GitStatus.Failed; } // check existing elvui installation _form.UpdateStatus(AppStatus.CheckingElvUI); if (!FileUtils.CheckElvUIInstallation(wowPath)) { Debug.WriteLine($"Need to reinstall!"); // need to copy new files! _form.UpdateStatus(AppStatus.Copying); GitUtils.Install(wowPath); } return cloneResult; })); }
private static string AppendUrlToPath(string path, string url) { if (!string.IsNullOrWhiteSpace(url)) { try { path = Path.Combine(path, GitUtils.GetHumanishName(url)); } catch (Exception exc) when(!exc.IsCritical()) { } } return(path); }
protected override bool OnStepStart() { var commit = GitUtils.GetCommit(Repository, CommitSearch); if (commit == null) { RockLog.WriteLine(this, LogTier.Error, "Commit not found!"); return(false); } Repository.ApplyTag(TagName, commit.Sha); return(true); }
private static string AppendUrlToPath(string path, string url) { if (url.Length != 0) { try { path = System.IO.Path.Combine(path, GitUtils.GetHumanishName(url)); } catch (Exception exc) when(!exc.IsCritical()) { } } return(path); }
private async Task GetIssueAndCreateBranch(string[] args) { try { var issueKey = args.First(a => !a.Contains('c')).ToString(); Issue issue = await GetIssueByKey(issueKey); GitUtils.CreateBranch(GetSuggestedBranchName(issue)); } catch (Exception) { HandleUnknownParam(); } }
private string GetPackageIdByNewGitUrl() { if (_selectPackageInfo == null) { return(""); } var url = GitUtils.GitPathConvertUnityPackagePath(_gitUrl); // url实例: // "ssh://[email protected]/chinochan66/UPM-Tool-Test.git"; // 真实路径: // "com.chino.upmtool@ssh://[email protected]/chino66/UPM-Tool-Test.git#upm" return($"{_selectPackageInfo.name}@{url}#{_selectVersion}"); }
private static SymbolicReferenceData Parse(string value) { if (value != null && value.Length >= 17 && value.StartsWith(refPrefix + GitConstants.LocalBranchPrefix)) { return(new SymbolicReferenceData(value.Substring(16), ReferenceType.LocalBranch)); } else { if (GitUtils.IsValidSHA1(value)) { return(new SymbolicReferenceData(value, ReferenceType.Revision)); } } return(new SymbolicReferenceData(null, ReferenceType.None)); }
public static Task getIssue(string prefix, string issueid, CommandContext context) { string repo = GitUtils.get_repo(prefix); if (repo == null) { return(context.Channel.SendMessageAsync("Invalid prefix")); } dynamic obj = GitUtils.get_json(GitUtils.github_url($"/repos/{repo}/issues/{issueid}")); if (obj == null) { return(context.Channel.SendMessageAsync("Issue not found")); } return(context.Channel.SendMessageAsync(embed: GitUtils.embed_issue(obj, repo))); }
// returns null if user can't edit git private string GetGitEditLink(Course course, FileInfo pageFile) { var courseRole = User.GetCourseRole(course.Id); var canEditGit = courseRole != null && courseRole <= CourseRole.CourseAdmin; var publishedCourseVersion = coursesRepo.GetPublishedCourseVersion(course.Id); if (!canEditGit || publishedCourseVersion.RepoUrl == null) { return(null); } var pathRelative2CourseXml = pageFile.FullName.Substring(course.CourseXmlDirectory.FullName.Length + 1); if (publishedCourseVersion.PathToCourseXml == null) { return(null); } return(GitUtils.GetSlideEditLink(publishedCourseVersion.RepoUrl, publishedCourseVersion.PathToCourseXml, pathRelative2CourseXml)); }
public static BuildTargetResult GenerateVersions(BuildTargetContext c) { var commitCount = GitUtils.GetCommitCount(); var commitHash = GitUtils.GetCommitHash(); var hostVersion = new HostVersion() { CommitCount = commitCount }; c.BuildContext["HostVersion"] = hostVersion; c.BuildContext["CommitHash"] = commitHash; c.Info($"Building Version: {hostVersion.LatestHostVersionNoSuffix} (NuGet Packages: {hostVersion.LatestHostVersion})"); c.Info($"From Commit: {commitHash}"); return(c.Success()); }