Пример #1
0
        /// <summary>
        /// Clone existing build definition
        /// </summary>
        /// <param name="TeamProjectName"></param>
        private static void CloneStandardBuild(string TeamProjectName)
        {
            int    SourceBuildId  = 22; // id of existing build definition
            string NewName        = "ClonedBuildDef";
            string NewPath        = "Cloned";
            string GitRepoName    = "Second";
            string GitRepoFormat  = @"https://<org>@dev.azure.com/<org>/{0}/_git/{1}"; // link to clone a git repo
            string NewBranch      = null;                                              // example for branch dev: refs/heads/dev
            string NewProjectPath = null;                                              // example: "New Folder/New project.sln";

            var bld = BuildClient.GetDefinitionAsync(TeamProjectName, SourceBuildId).Result;

            var clonedBuild = bld;

            clonedBuild.Repository.Url  = new Uri(String.Format(GitRepoFormat, TeamProjectName, GitRepoName));
            clonedBuild.Repository.Name = GitRepoName;
            clonedBuild.Repository.Id   = null;
            if (NewBranch != null)
            {
                clonedBuild.Repository.DefaultBranch = NewBranch;
            }
            clonedBuild.Path = NewPath;
            clonedBuild.Name = NewName;

            if (NewProjectPath != null && clonedBuild.ProcessParameters.Inputs.Count == 1)
            {
                clonedBuild.ProcessParameters.Inputs[0].DefaultValue = NewProjectPath;
            }

            clonedBuild = BuildClient.CreateDefinitionAsync(clonedBuild, TeamProjectName).Result;

            Console.WriteLine("The build definition has been created");
            Console.WriteLine("Build Id: {0}\nBuild Name: {1}\n Build Path: {2}", clonedBuild.Id, clonedBuild.Name, clonedBuild.Path);
        }
        public async Task <BuildDefinition> CloneABuildAsync(int definitionToCloneId, string projectName)
        {
            // Get a build client instance
            VssConnection   connection  = Context.Connection;
            BuildHttpClient buildClient = connection.GetClient <BuildHttpClient>();

            var buildToClone = await buildClient.GetDefinitionAsync(
                projectName,
                definitionToCloneId);

            var x = await buildClient.CreateDefinitionAsync(new BuildDefinition { Name = "Fred", Process = buildToClone.Process, Project = buildToClone.Project, Repository = buildToClone.Repository }, definitionToCloneId);

            return(x);
        }
Пример #3
0
        /// <summary>
        /// create or update build definition
        ///
        /// definition result
        /// </summary>
        /// <param name="buildClient">build client instance</param>
        /// <param name="definition">build definition to process</param>
        /// <param name="targetProjectId">target project to scope search for</param>
        /// <returns>definition instance</returns>
        public static async Task <BuildDefinition> CreateOrUpdateDefinition(this BuildHttpClient buildClient, BuildDefinition definition, string targetProjectId)
        {
            //check whether fork build definition already exists
            var vstsBuildDefinition = (await buildClient.GetFullDefinitionsAsync(targetProjectId, name: definition.Name)).FirstOrDefault();

            if (vstsBuildDefinition != null)
            {
                definition.Id       = vstsBuildDefinition.Id;
                definition.Url      = vstsBuildDefinition.Url;
                definition.Uri      = vstsBuildDefinition.Uri;
                definition.Revision = vstsBuildDefinition.Revision;

                return(await buildClient.UpdateDefinitionAsync(definition, targetProjectId, vstsBuildDefinition.Id));
            }

            return(await buildClient.CreateDefinitionAsync(definition));
        }
Пример #4
0
        public async Task <Build> Handle(RunSetup request, CancellationToken cancellationToken)
        {
            BuildHttpClient c = await clients.GetAppClient <BuildHttpClient>();

            BuildDefinition definition = new BuildDefinition
            {
                Name       = "new name" + Guid.NewGuid().ToString(),
                Repository = new BuildRepository
                {
                    Id   = settings.RepositoryId,
                    Type = "TfsGit"
                },
                Process = new YamlProcess
                {
                    YamlFilename = settings.YamlFilename
                },
                Type  = DefinitionType.Build,
                Queue = new AgentPoolQueue {
                    Id = settings.AgentPoolQueueId.Value
                },
            };

            foreach ((string key, string value) in request.Parameters)
            {
                definition.Variables.Add(key, new BuildDefinitionVariable
                {
                    Value         = value,
                    AllowOverride = false
                });
            }

            BuildDefinition result = await c.CreateDefinitionAsync(
                definition : definition,
                definitionToCloneId : settings.DefinitionToCloneId,
                project : settings.ProjectName);

            Build build = await c.QueueBuildAsync(
                build : new Build {
                Definition = new DefinitionReference {
                    Id = result.Id
                }
            },
                project : settings.ProjectName);

            return(build);
        }
        public void CloneBuildDefinitionIfNeeded()
        {
            var definitions = buildClient.GetDefinitionsAsync(project: SelectedProject.Name).Result;
            var firstDef    = definitions.First();

            DummyBuildDef = definitions.FirstOrDefault(b => b.Name == DummyDefName);

            if (DummyBuildDef == null) // clone needs to be created
            {
                var cloneDef = buildClient.GetDefinitionAsync(SelectedProject.Id, firstDef.Id).Result;
                cloneDef.Name = DummyDefName;
                var cloneResult = buildClient.CreateDefinitionAsync(cloneDef, SelectedProject.Id, firstDef.Id).Result;

                var newDefinitions = buildClient.GetDefinitionsAsync(project: SelectedProject.Name).Result;
                DummyBuildDef = newDefinitions.First(b => b.Name == DummyDefName);
            }
        }
 public static Task <BuildDefinition> AddDefinitionAsync(this BuildHttpClient source, BuildDefinition definition, CancellationToken cancellationToken)
 => source.CreateDefinitionAsync(definition, cancellationToken: cancellationToken);
Пример #7
0
        static void Main(string[] args)
        {
            OptionSet option_set = new OptionSet()
                                   .Add("?|help|h", "Prints out the options.", option => { help = option != null; })
                                   .Add("su|source-url=", "Set the source VSTS account URL (https://[sourcerepo].visualstudio.com)", option => sourceUrl = option)
                                   .Add("sp|source-project=", "Set the source VSTS project", option => sourceProject = option)
                                   .Add("sr|source-repository=", "Set the source VSTS repository path. (ex: $/SourceRepo)", option => sourceRepo = option)
                                   .Add("du|destination-url=", "Set the destination VSTS account URL (https://[destrepo].visualstudio.com)", option => destinationUrl = option)
                                   .Add("dp|destination-project=", "Set the destination VSTS project", option => destinationProject = option)
                                   .Add("dr|destination-repository=", "Set the destination VSTS repository path. (ex: $/DestinationRepo)", option => destinationRepo = option);

            try
            {
                option_set.Parse(args);
            }
            catch (Exception ex)
            {
                LogGenericException(ex, "Error on commandline parse");
            }
            if (help)
            {
                ShowHelp(usage, option_set);
            }

            if (string.IsNullOrEmpty(sourceUrl))
            {
                Console.Write("Enter the source account url (https://<<account>>.visualstudio.com/): ");
                sourceUrl = Console.ReadLine();
            }
            if (string.IsNullOrEmpty(sourceProject))
            {
                Console.Write("Enter the source project: ");
                sourceProject = Console.ReadLine();
            }
            if (string.IsNullOrEmpty(sourceRepo))
            {
                Console.Write("Enter the source repository ($/MYSOURCEREPO): ");
                sourceRepo = Console.ReadLine();
            }

            if (string.IsNullOrEmpty(destinationUrl))
            {
                Console.Write("Enter the destination account url (https://<<account>>.visualstudio.com/): ");
                destinationUrl = Console.ReadLine();
            }
            if (string.IsNullOrEmpty(destinationProject))
            {
                Console.Write("Enter the destination project: ");
                destinationProject = Console.ReadLine();
            }
            if (string.IsNullOrEmpty(destinationRepo))
            {
                Console.Write("Enter the source repository ($/MYDESTREPO): ");
                destinationRepo = Console.ReadLine();
            }

            string sourceAccount      = $"{sourceUrl}DefaultCollection";
            string destinationAccount = $"{destinationUrl}DefaultCollection";

            // Interactively ask the user for credentials

            VssCredentials sourceCredentials = new VssClientCredentials();

            sourceCredentials.Storage = new VssClientCredentialStorage();

            VssCredentials destinationCredentials = new VssClientCredentials();

            destinationCredentials.Storage = new VssClientCredentialStorage();

            BuildHttpClient     sourceBuildClient          = null;
            BuildHttpClient     destinationBuildClient     = null;
            ProjectHttpClient   destinationProjectClient   = null;
            TaskAgentHttpClient destinationTaskAgentClient = null;
            TfvcHttpClient      destinationTfvcClient      = null;

            try
            {
                Console.WriteLine($"Creating VSTS connections and clients.");
                Console.WriteLine();
                // Connect to VSTS Source and Destination
                VssConnection sourceConnection = new VssConnection(new Uri(sourceAccount), sourceCredentials);
                Console.WriteLine($"Authorized acccount {sourceUrl} as {sourceConnection.AuthorizedIdentity.DisplayName} <{sourceConnection.AuthorizedIdentity.Descriptor.Identifier}>");
                VssConnection destinationConnection = new VssConnection(new Uri(destinationAccount), destinationCredentials);
                Console.WriteLine($"Authorized acccount {destinationUrl} as {destinationConnection.AuthorizedIdentity.DisplayName} <{sourceConnection.AuthorizedIdentity.Descriptor.Identifier}>");
                Console.WriteLine();
                // Get a number of HttpClients to read and write data
                Console.WriteLine("Creating source build client.");
                sourceBuildClient = sourceConnection.GetClient <BuildHttpClient>();
                Console.WriteLine("Creating destination build client.");
                destinationBuildClient = destinationConnection.GetClient <BuildHttpClient>();
                Console.WriteLine("Creating destination project client.");
                destinationProjectClient = destinationConnection.GetClient <ProjectHttpClient>();
                Console.WriteLine("Creating destination task agent client.");
                destinationTaskAgentClient = destinationConnection.GetClient <TaskAgentHttpClient>();
                Console.WriteLine("Creating destination TFVC client.");
                destinationTfvcClient = destinationConnection.GetClient <TfvcHttpClient>();
                Console.WriteLine();
            }
            catch (AggregateException ex)
            {
                string message = "Error creating connections.";
                LogAggregateException(ex, message);
            }
            catch (Exception ex)
            {
                string message = "Error creating connections.";
                LogGenericException(ex, message);
            }

            List <BuildDefinition> sourceBuildDefs              = null;
            TeamProject            destinationProjectObject     = null;
            Dictionary <string, TaskAgentQueue> agentDictionary = null;

            try
            {
                sourceBuildDefs = sourceBuildClient.GetFullDefinitionsAsync(project: sourceProject).Result;
            }
            catch (AggregateException ex)
            {
                string message = "Error retreiving objects from source.";
                LogAggregateException(ex, message);
            }
            catch (Exception ex)
            {
                string message = "Error retreiving objects from source.";
                LogGenericException(ex, message);
            }

            try
            {
                destinationProjectObject = destinationProjectClient.GetProject(destinationProject).Result;
                var projectAgentQueues = destinationTaskAgentClient.GetAgentQueuesAsync(project: destinationProject).Result;
                agentDictionary = projectAgentQueues.ToDictionary(k => k.Name);
            }
            catch (AggregateException ex)
            {
                string message = "Error retreiving objects from destination.";
                LogAggregateException(ex, message);
            }
            catch (Exception ex)
            {
                string message = "Error retreiving objects from destination.";
                LogGenericException(ex, message);
            }

            foreach (var item in sourceBuildDefs)
            {
                if (System.Diagnostics.Debugger.IsAttached)
                {
                    item.Name = item.Name + DateTime.Now.ToUnixEpochTime();
                }

                item.Project    = destinationProjectObject;
                item.AuthoredBy = null; // Remove any author to avoid errors in transfer

                FixTriggerRepositories(item);
                UpdateAgentPool(agentDictionary, item);
                ConvertRepositoryPath(item);

                try
                {
                    Console.WriteLine($"Adding build definition: {item.Name}");
                    var itemOut = destinationBuildClient.CreateDefinitionAsync(item).Result;
                }
                catch (AggregateException ex)
                {
                    LogAggregateException(ex, $"Error creating build {item.Name} on {destinationAccount}");
                }
                catch (Exception ex)
                {
                    LogGenericException(ex, $"Error creating build {item.Name} on {destinationAccount}");
                }
            }
            if (hasErrors)
            {
                ExitWithErrors();
            }
            ExitSuccess();
        }