Exemplo n.º 1
0
        private TestHostContext Setup(
            [CallerMemberName] string name = "")
        {
            // Setup the host context.
            TestHostContext hc = new TestHostContext(this, name);

            // Setup the execution context.
            _ec = new Mock <IExecutionContext>();

            GitHubContext githubContext = new GitHubContext();

            _ec.Setup(x => x.GetGitHubContext("repository")).Returns("actions/runner");

            // Store the expected tracking file path.
            _trackingFile = Path.Combine(
                hc.GetDirectory(WellKnownDirectory.Work),
                Constants.Pipeline.Path.PipelineMappingDirectory,
                "actions/runner",
                Constants.Pipeline.Path.TrackingConfigFile);

            _workspaceOptions = new Pipelines.WorkspaceOptions();

            // Setup the tracking manager.
            _trackingManager = new Mock <ITrackingManager>();
            hc.SetSingleton <ITrackingManager>(_trackingManager.Object);

            // Setup the build directory manager.
            _pipelineDirectoryManager = new PipelineDirectoryManager();
            _pipelineDirectoryManager.Initialize(hc);
            return(hc);
        }
 static OpenFromClipboardCommand CreateOpenFromClipboardCommand(
     IGitHubContextService gitHubContextService = null,
     ITeamExplorerContext teamExplorerContext   = null,
     IVSServices vsServices             = null,
     GitHubContext contextFromClipboard = null,
     string repositoryDir   = null,
     string repositoryName  = null,
     string repositoryOwner = null,
     string currentBranch   = null,
     (string, string, string)?resolveBlobResult = null,
Exemplo n.º 3
0
        public void DefaultGitHubDotCom()
        {
            var context = new GitHubContext {
                Host = "github.com", Owner = "github", RepositoryName = "VisualStudio"
            };
            var target = CreateGitHubContextService();

            var uri = target.ToRepositoryUrl(context);

            Assert.That(uri, Is.EqualTo(new Uri("https://github.com/github/VisualStudio")));
        }
        public async Task UnknownLinkType()
        {
            var context = new GitHubContext {
                LinkType = LinkType.Unknown
            };
            var expectMessage       = string.Format(Resources.UnknownLinkTypeMessage, context.Url);
            var activeRepositoryDir = "activeRepositoryDir";
            var vsServices          = Substitute.For <IVSServices>();
            var target = CreateOpenFromClipboardCommand(vsServices: vsServices, contextFromClipboard: context, repositoryDir: activeRepositoryDir);
            await target.Execute(null);

            vsServices.Received(1).ShowMessageBoxInfo(expectMessage);
        }
Exemplo n.º 5
0
        public static PSObject[] GetRepository()
        {
            var repos      = PSRuleOption.TryGetEnvironmentVariableString(GITHUB_REPOSITORY, out string repo) ? new string[] { repo } : null;
            var credential = PSRuleOption.TryGetEnvironmentVariableSecureString(GITHUB_TOKEN, out SecureString token) ? new PSCredential("token", token) : null;

            if (repos == null || repos.Length == 0 || credential == null)
            {
                return(Array.Empty <PSObject>());
            }

            var context = new GitHubContext(repos, credential);
            var helper  = new RepositoryHelper(context);

            return(helper.Get(repo));
        }
Exemplo n.º 6
0
        async Task <bool> TryOpenPullRequest(GitHubContext context)
        {
            var pullRequest = context.PullRequest;

            if (pullRequest == null)
            {
                return(false);
            }

            var host = await gitHubToolWindowManager.Value.ShowGitHubPane();

            await host.ShowPullRequest(context.Owner, context.RepositoryName, pullRequest.Value);

            return(true);
        }
        public static Context ToContext(this ReleaseNotesRequest releaseNotesRequest)
        {
            IIssueTrackerContext issueTrackerContext = null;

            var lowercaseUrl = releaseNotesRequest.IssueTrackerUrl.ToLower();
            if (lowercaseUrl.Contains("bitbucket"))
            {
                issueTrackerContext = new BitBucketContext
                {
                    Url = releaseNotesRequest.IssueTrackerUrl
                };
            }

            if (lowercaseUrl.Contains("atlassian"))
            {
                issueTrackerContext = new JiraContext
                {
                    Url = releaseNotesRequest.IssueTrackerUrl
                };
            }

            if (lowercaseUrl.Contains("github"))
            {
                issueTrackerContext = new GitHubContext
                {
                    Url = releaseNotesRequest.IssueTrackerUrl
                };
            }

            if (lowercaseUrl.Contains("youtrack"))
            {
                issueTrackerContext = new YouTrackContext
                {
                    Url = releaseNotesRequest.IssueTrackerUrl
                };
            }

            var context = new Context(issueTrackerContext);

            context.Repository.Url = releaseNotesRequest.RepositoryUrl;
            context.Repository.Branch = releaseNotesRequest.RepositoryBranch;

            context.IssueTracker.ProjectId = releaseNotesRequest.IssueTrackerProjectId;

            return context;
        }
Exemplo n.º 8
0
        private TestHostContext CreateTestContext([CallerMemberName] String testName = "")
        {
            var hc = new TestHostContext(this, testName);
            Dictionary <string, VariableValue> variablesToCopy = new Dictionary <string, VariableValue>();

            _variables = new Variables(
                hostContext: hc,
                copy: variablesToCopy);
            _env = new Dictionary <string, string>()
            {
                { "env1", "1" },
                { "test", "github_actions" }
            };
            _ec = new Mock <IExecutionContext>();
            _ec.SetupAllProperties();
            _ec.Setup(x => x.Global).Returns(new GlobalContext {
                WriteDebug = true
            });
            _ec.Object.Global.Variables            = _variables;
            _ec.Object.Global.EnvironmentVariables = _env;

            _contexts           = new DictionaryContextData();
            _jobContext         = new JobContext();
            _contexts["github"] = new GitHubContext();
            _contexts["runner"] = new DictionaryContextData();
            _contexts["job"]    = _jobContext;
            _ec.Setup(x => x.ExpressionValues).Returns(_contexts);
            _ec.Setup(x => x.ExpressionFunctions).Returns(new List <IFunctionInfo>());
            _ec.Setup(x => x.JobContext).Returns(_jobContext);

            _stepContext = new StepsContext();
            _ec.Object.Global.StepsContext = _stepContext;

            _ec.Setup(x => x.PostJobSteps).Returns(new Stack <IStep>());

            var trace = hc.GetTrace();

            _ec.Setup(x => x.Write(It.IsAny <string>(), It.IsAny <string>())).Callback((string tag, string message) => { trace.Info($"[{tag}]{message}"); });

            _stepsRunner = new StepsRunner();
            _stepsRunner.Initialize(hc);
            return(hc);
        }
Exemplo n.º 9
0
        public TestHostContext Setup([CallerMemberName] string name = "")
        {
            // Setup the host context.
            TestHostContext hc = new TestHostContext(this, name);

            // Create a random work path.
            _workFolder = hc.GetDirectory(WellKnownDirectory.Work);

            // Setup the execution context.
            _ec = new Mock <IExecutionContext>();
            GitHubContext githubContext = new GitHubContext();

            _ec.Setup(x => x.GetGitHubContext("repository")).Returns("actions/runner");

            // Setup the tracking manager.
            _trackingManager = new TrackingManager();
            _trackingManager.Initialize(hc);

            return(hc);
        }
        private void Setup([CallerMemberName] string name = "")
        {
            _ecTokenSource?.Dispose();
            _ecTokenSource = new CancellationTokenSource();

            // Test host context.
            _hc = new TestHostContext(this, name);

            var actionInputs = new MappingToken(null, null, null);

            actionInputs.Add(new StringToken(null, null, null, "input1"), new StringToken(null, null, null, "input1"));
            actionInputs.Add(new StringToken(null, null, null, "input2"), new StringToken(null, null, null, ""));
            actionInputs.Add(new StringToken(null, null, null, "input3"), new StringToken(null, null, null, "github"));
            var actionDefinition = new Definition()
            {
                Directory = _hc.GetDirectory(WellKnownDirectory.Work),
                Data      = new ActionDefinitionData()
                {
                    Name        = name,
                    Description = name,
                    Inputs      = actionInputs,
                    Execution   = new ScriptActionExecutionData()
                }
            };

            // Mocks.
            _actionManager = new Mock <IActionManager>();
            _actionManager.Setup(x => x.LoadAction(It.IsAny <IExecutionContext>(), It.IsAny <ActionStep>())).Returns(actionDefinition);

            _handlerFactory        = new Mock <IHandlerFactory>();
            _defaultStepHost       = new Mock <IDefaultStepHost>();
            _actionManifestManager = new ActionManifestManager();
            _actionManifestManager.Initialize(_hc);

            var githubContext = new GitHubContext();

            githubContext.Add("event", JToken.Parse("{\"foo\":\"bar\"}").ToPipelineContextData());
            _context.Add("github", githubContext);

#if OS_WINDOWS
            _context["env"] = new DictionaryContextData();
#else
            _context["env"] = new CaseSensitiveDictionaryContextData();
#endif

            _ec = new Mock <IExecutionContext>();
            _ec.Setup(x => x.ExpressionValues).Returns(_context);
            _ec.Setup(x => x.ExpressionFunctions).Returns(new List <IFunctionInfo>());
            _ec.Setup(x => x.IntraActionState).Returns(new Dictionary <string, string>());
            _ec.Setup(x => x.EnvironmentVariables).Returns(new Dictionary <string, string>());
            _ec.Setup(x => x.FileTable).Returns(new List <String>());
            _ec.Setup(x => x.SetGitHubContext(It.IsAny <string>(), It.IsAny <string>()));
            _ec.Setup(x => x.GetGitHubContext(It.IsAny <string>())).Returns("{\"foo\":\"bar\"}");
            _ec.Setup(x => x.CancellationToken).Returns(_ecTokenSource.Token);
            _ec.Setup(x => x.Variables).Returns(new Variables(_hc, new Dictionary <string, VariableValue>()));
            _ec.Setup(x => x.Write(It.IsAny <string>(), It.IsAny <string>())).Callback((string tag, string message) => { _hc.GetTrace().Info($"[{tag}]{message}"); });
            _ec.Setup(x => x.AddIssue(It.IsAny <Issue>(), It.IsAny <string>())).Callback((Issue issue, string message) => { _hc.GetTrace().Info($"[{issue.Type}]{issue.Message ?? message}"); });

            _hc.SetSingleton <IActionManager>(_actionManager.Object);
            _hc.SetSingleton <IHandlerFactory>(_handlerFactory.Object);
            _hc.SetSingleton <IActionManifestManager>(_actionManifestManager);

            _hc.EnqueueInstance <IDefaultStepHost>(_defaultStepHost.Object);

            // Instance to test.
            _actionRunner = new ActionRunner();
            _actionRunner.Initialize(_hc);
            _actionRunner.ExecutionContext = _ec.Object;
        }
Exemplo n.º 11
0
        private TestHostContext CreateTestContext([CallerMemberName] String testName = "")
        {
            var hc = new TestHostContext(this, testName);

            _jobEc                = new Runner.Worker.ExecutionContext();
            _actionManager        = new Mock <IActionManager>();
            _jobServerQueue       = new Mock <IJobServerQueue>();
            _config               = new Mock <IConfigurationStore>();
            _logger               = new Mock <IPagingLogger>();
            _containerProvider    = new Mock <IContainerOperationProvider>();
            _diagnosticLogManager = new Mock <IDiagnosticLogManager>();
            _directoryManager     = new Mock <IPipelineDirectoryManager>();
            _directoryManager.Setup(x => x.PrepareDirectory(It.IsAny <IExecutionContext>(), It.IsAny <Pipelines.WorkspaceOptions>()))
            .Returns(new TrackingConfig()
            {
                PipelineDirectory = "runner", WorkspaceDirectory = "runner/runner"
            });

            IActionRunner step1 = new ActionRunner();
            IActionRunner step2 = new ActionRunner();
            IActionRunner step3 = new ActionRunner();
            IActionRunner step4 = new ActionRunner();
            IActionRunner step5 = new ActionRunner();

            _logger.Setup(x => x.Setup(It.IsAny <Guid>(), It.IsAny <Guid>()));
            var settings = new RunnerSettings
            {
                AgentId    = 1,
                AgentName  = "runner",
                ServerUrl  = "https://pipelines.actions.githubusercontent.com/abcd",
                WorkFolder = "_work",
            };

            _config.Setup(x => x.GetSettings())
            .Returns(settings);

            if (_tokenSource != null)
            {
                _tokenSource.Dispose();
                _tokenSource = null;
            }

            _tokenSource = new CancellationTokenSource();
            TaskOrchestrationPlanReference plan = new TaskOrchestrationPlanReference();
            TimelineReference timeline          = new Timeline(Guid.NewGuid());

            List <Pipelines.ActionStep> steps = new List <Pipelines.ActionStep>()
            {
                new Pipelines.ActionStep()
                {
                    Id          = Guid.NewGuid(),
                    DisplayName = "action1",
                },
                new Pipelines.ActionStep()
                {
                    Id          = Guid.NewGuid(),
                    DisplayName = "action2",
                },
                new Pipelines.ActionStep()
                {
                    Id          = Guid.NewGuid(),
                    DisplayName = "action3",
                },
                new Pipelines.ActionStep()
                {
                    Id          = Guid.NewGuid(),
                    DisplayName = "action4",
                },
                new Pipelines.ActionStep()
                {
                    Id          = Guid.NewGuid(),
                    DisplayName = "action5",
                }
            };

            Guid jobId = Guid.NewGuid();

            _message = new Pipelines.AgentJobRequestMessage(plan, timeline, jobId, "test", "test", null, null, null, new Dictionary <string, VariableValue>(), new List <MaskHint>(), new Pipelines.JobResources(), new Pipelines.ContextData.DictionaryContextData(), new Pipelines.WorkspaceOptions(), steps, null, null, null, null);
            GitHubContext github = new GitHubContext();

            github["repository"]    = new Pipelines.ContextData.StringContextData("actions/runner");
            github["secret_source"] = new Pipelines.ContextData.StringContextData("Actions");
            _message.ContextData.Add("github", github);

            hc.SetSingleton(_actionManager.Object);
            hc.SetSingleton(_config.Object);
            hc.SetSingleton(_jobServerQueue.Object);
            hc.SetSingleton(_containerProvider.Object);
            hc.SetSingleton(_directoryManager.Object);
            hc.SetSingleton(_diagnosticLogManager.Object);
            hc.EnqueueInstance <IPagingLogger>(_logger.Object); // JobExecutionContext
            hc.EnqueueInstance <IPagingLogger>(_logger.Object); // Initial Job
            hc.EnqueueInstance <IPagingLogger>(_logger.Object); // step1
            hc.EnqueueInstance <IPagingLogger>(_logger.Object); // step2
            hc.EnqueueInstance <IPagingLogger>(_logger.Object); // step3
            hc.EnqueueInstance <IPagingLogger>(_logger.Object); // step4
            hc.EnqueueInstance <IPagingLogger>(_logger.Object); // step5
            hc.EnqueueInstance <IPagingLogger>(_logger.Object); // prepare1
            hc.EnqueueInstance <IPagingLogger>(_logger.Object); // prepare2

            hc.EnqueueInstance <IActionRunner>(step1);
            hc.EnqueueInstance <IActionRunner>(step2);
            hc.EnqueueInstance <IActionRunner>(step3);
            hc.EnqueueInstance <IActionRunner>(step4);
            hc.EnqueueInstance <IActionRunner>(step5);

            _jobEc.Initialize(hc);
            _jobEc.InitializeJob(_message, _tokenSource.Token);
            return(hc);
        }
 public RepositoriosController(GitHubContext context)
 {
     _context = context;
 }
Exemplo n.º 13
0
 public UserRepository(GitHubContext gitHubContext)
 {
     _gitHubContext = gitHubContext;
 }
Exemplo n.º 14
0
 public RepoRepository(GitHubContext gitHubContext)
 {
     _gitHubContext = gitHubContext;
 }