Giter Site home page Giter Site logo

qualisystems / fluenttc Goto Github PK

View Code? Open in Web Editor NEW
44.0 15.0 35.0 1.07 MB

:ocean: :two_men_holding_hands: :office: Integrate with TeamCity fluently

Home Page: https://www.nuget.org/packages/fluenttc

License: Apache License 2.0

C# 37.77% Rich Text Format 62.23%
csharp fluent-interface dotnet dot-net ci devops library teamcity nuget continuous-integration

fluenttc's Introduction

FluentTc

Easy-to-use, readable and comprehensive library for consuming TeamCity REST API. Written using real scenarios in mind, enables variuos range of queries and operation on TeamCity

Installation

Run from NuGet Package Manager console:

PM > Install-Package FluentTc

Usage

Get TeamCity builds with branches, status, start and finish date and paging

IList<IBuild> builds =
    new RemoteTc()
        .Connect(connect => connect
            .ToHost("teamcity.jetbrains.com")
            .AsGuest())
        .GetBuilds(
            having => having
                .BuildConfiguration(
                    buildConfiguration => buildConfiguration
                        .Id("FluentTc"))
                .Branch(branch => branch.Branched()),
            include => include
                .IncludeStatusText()
                .IncludeStartDate()
                .IncludeFinishDate(), 
            paging => paging
                .Start(30)
                .Count(10));

Run build on build configuration FluentTc on agent Agent1 with parameters on branch develop, with comment 'personal build on develop', as a personal build, queue on top, rebuild all dependencies on change 123456

IBuild build = new RemoteTc()
    .Connect(connect => connect
        .ToHost("teamcity.jetbrains.com")
        .AsGuest())
    .RunBuildConfiguration(
         buildConfiguration => buildConfiguration.Id("FluentTc"), 
         agent => agent.Name("Agent1"),
         parameters => parameters
                     .Parameter("param1", "value1")
                     .Parameter("param2", "value2"),
         options => options.OnBranch("develop")
                    .WithComment("personal build on develop")
                    .AsPersonal()
                    .QueueAtTop()
                    .RebuildAllDependencies()
                    .WithCleanSources()
                    .OnChange(change => change.Id(123456)));

Interact with TeamCity from within a build step without authentication

ILocalTc localTc = new LocalTc();

// Gets the current checkout directory
string agentWorkDir = localTc.TeamcityBuildCheckoutDir;

// Gets the current parameter value 
int param1 = localTc.GetBuildParameter<int>("param1");

// Sets parameter value of the current build
localTc.SetBuildParameter("parameter.name", "value1");

// Gets list of files changed in the current build
IList<IChangedFile> changedFiles = localTc.ChangedFiles;

// Determines whether the build is personal
bool isPersonal = localTc.IsPersonal;

// Change status of the current build 
localTc.ChangeBuildStatus(BuildStatus.Success);

Quick Links

Project status

  • Continuous Integration: build status
  • Code Coverage: code coverage
  • Downloads: NuGet

Contribute

The best way to contribute is by spreading the word about the library:

  • Blog it
  • Comment it
  • Fork it
  • Star it
  • Share it

A HUGE THANKS for your help.

Contributors

FluentTc keeps growing with the support of of contributors

License

Apache License 2.0

fluenttc's People

Contributors

3breadt avatar abugov avatar bezysoftware avatar borismod avatar davidgilady avatar derrickgwood avatar evolvedlight avatar gibbone avatar gralin avatar igoro1975 avatar nahumtimerman avatar raelyard avatar sokolovsv90 avatar waffle-iron avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

fluenttc's Issues

Artifact dependencies are missing information on the referenced build configuration

The ArtifactDependency object currently does not contain information about the build configuration from which artifacts are referenced. An artifact dependency's ID property does not identify the referenced build config as it does with the snapshot dependency object.

The "source-buildType" element of the REST response needs to be parsed and provided in the ArtifactDependency object, so that the information is available.

This issue is addressed by pull request #91

Add GetProject() method to RemoteTc that accepts lambda Id() and Name()

Feature Request

As a user of FluentTc I would like to be able retrieve a project by Id or Name using fluent API, i.e. using lambda

From TeamCity REST API documentation: https://confluence.jetbrains.com/display/TCD10/REST+API#RESTAPI-ProjectsandBuildConfiguration/TemplatesLists

Project details: GET http://teamcity:8111/app/rest/projects/projectLocator, where projectLocator can be id:internal_project_id or name:project%20name

Test to reproduce

[Test]
public void GetProject_ById()
{
  var project = new RemoteTc(c=>c.ToHost("HOST").AsGuest())
     .GetProject(project => project.Id("FluentTc") );
}

[Test]
public void GetProject_ByName()
{
  var project = new RemoteTc(c=>c.ToHost("HOST").AsGuest())
     .GetProject(project => project.Name("FluentTc") );
}

The encoding requested does not have a corresponding decoder

Hello, whenever I try to use any of your library methods I get this Easyhttp error :( , do you have any idea why?

The encoding requested does not have a corresponding decoder
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: JsonFx.Serialization.SerializationException: The encoding requested does not have a corresponding decoder:

Source Error:

Line 15: public void GetLatestBuildForConfig(string configId)
Line 16: {
Line 17: var buildConfiguration =
Line 18: remoteTc.Connect( => _.ToHost(teamCitySettings).AsGuest())
Line 19: .GetBuilds(
=> _.BuildConfiguration(x => x.Id(configId)));

Stack Trace:

[SerializationException: The encoding requested does not have a corresponding decoder]
EasyHttp.Codecs.DefaultDecoder.ObtainDeserializer(String contentType) in d:\BuildAgent-03\work\48c24454c251185c\src\EasyHttp\Codecs\DefaultDecoder.cs:43
EasyHttp.Codecs.DefaultDecoder.DecodeToStatic(String input, String contentType) in d:\BuildAgent-03\work\48c24454c251185c\src\EasyHttp\Codecs\DefaultDecoder.cs:22
EasyHttp.Http.HttpResponse.StaticBody(String overrideContentType) in d:\BuildAgent-03\work\48c24454c251185c\src\EasyHttp\Http\HttpResponse.cs:111
FluentTc.Engine.TeamCityCaller.Get(String urlPart) +118
FluentTc.Engine.TeamCityCaller.GetFormat(String urlPart, Object[] parts) +124
FluentTc.Engine.BuildsRetriever.GetBuildWrapper(BuildHavingBuilder buildHavingBuilder, CountBuilder countBuilder, BuildIncludeBuilder buildIncludeBuilder) +247
FluentTc.Engine.BuildsRetriever.GetBuilds(Action1 having, Action1 count, Action1 include) +186 FluentTc.ConnectedTc.GetBuilds(Action1 having) +255
MyBachelor.Services.TeamCityDataService.GetLatestBuildForConfig(String configId)

Allow publishing artifacts

FluentTc has a LocalTc class which interacts with TeamCity from within the same process. It can be used in a console application executed from TeamCity build step. It exposes the context of the current build, its properties and allows to interact back with TeamCity via TeamCity service messages.

It would be nice to allow also publishing artifacts from within the context of the current build execution.

new LocalTc().PublishArtifacts("some.zip")

Maybe some additional fluent API would be nice for supporting complex artifact publishing rules, like:

dir*.dll => Binaries.zip

References

Allow fluent branch specification on VCS creation

Feature Request

As a user I would like to be able to fluently specify what branches to include and exclude when defining a VCS root.

Test to reproduce

[Test]
public void CreateVcsRoot_FluentVcsBranchSpec_VcsRootCreated()
{
   var vcsRoot = new RemoteTc(c => c.ToHost("HOST").AsGuest()).
          CreateVcsRoot(project => project.Id("ProjectId"),
                 vcsRoot => vcsRoot
                    .Id("VcsRootId")
                    .Name("VcsRootName")
                    .Password("Password")
                    .Branch("refs/head/develop")
                    .BranchSpec(spec => spec.IncludeFeatureBranches()
                                                               .IncludeMasterBranch()
                                                               .ExcludeBugFixBranches())
}

Add XML documentation to public APIs

Feature Request

As a user I would like to be able to learn about FluentTc API from XML documentation

Definition of done

  • All public types/methods/properties are properly documented
  • XML documentation is part of the nuget package
  • There are no warnings on missing XML documentation

Add build canceling

Build Canceling/Stopping
POST the item to the URL of a running or queued build.
Example of cancelling a running build: click to expand
Note: Readding of builds into the queue is supported for running builds only.
Example of cancelling a queued build: click to expand
Expose cancelled build details:
See the canceledInfo element of the build item (available via GET http://teamcity:8111/httpAuth/app/rest/builds/)

wrong nuget package dependency

As of 4/4/2016, project depends on EasyHttp 1.6.85, but nuget package states that project is dependent on EasyHttp 1.6.67.0, which leads to System.TypeLoadException bugginess

Allow to attach a VCS root to a build configuration and also change checkout rules

From the TeamCity REST API documentation:

Attach VCS root to a build configuration: POST http://teamcity:8111/httpAuth/app/rest/buildTypes//vcs-root-entries. The XML/JSON posted is the same as retrieved by GET request to http://teamcity:8111/httpAuth/app/rest/buildTypes//vcs-root-entries/ except for the secure settings like password: these are not included into responses and should be supplied before POSTing back.

See the full TeamCity REST API documentation

Cancelled and NotCancelled are spelt incorrect in BuildHavingBuilder

Bug

The results produced by the BuildHavingBuilder when asking for a Cancelled or NotCancelled build return an error from TeamCity:

Unhandled Exception: EasyHttp.Infrastructure.HttpException: BadRequest Error: Bad Request
HTTP: BadRequest
URL: https://REDACTED/httpAuth/app/rest/builds?locator=cancelled:False,count:1,&fields=count,build(buildTypeId,href,id,number,state,status,webUrl)
Error has occurred during request processing (Bad Request).
Error: jetbrains.buildServer.server.rest.errors.LocatorProcessException: Locator dimension [cancelled] is unknown. Supported dimensions are: [id, taskId, project, affectedProject, buildType, branch, agent, user, personal, state, tag, property, compatibleAgent, number, status, canceled, pinned, sinceBuild, sinceDate, untilBuild, untilDate, failedToStart, snapshotDependency, defaultFilter, lookupLimit, single value, start, count]
Invalid request. Check locator is specified correctly.
   at FluentTc.Engine.TeamCityCaller.ThrowIfHttpError(HttpResponse response, String url)
   at FluentTc.Engine.TeamCityCaller.GetResponseByFullUrl(String url)
   at FluentTc.Engine.TeamCityCaller.Get[T](String urlPart)
   at FluentTc.Engine.BuildsRetriever.GetBuilds(Action`1 having, Action`1 count, Action`1 include)
   at FluentTc.ConnectedTc.GetLastBuild(Action`1 having, Action`1 include)

The core of it is this:

Error: jetbrains.buildServer.server.rest.errors.LocatorProcessException: Locator dimension [cancelled] is unknown. Supported dimensions are: [id, taskId, project, affectedProject, buildType, branch, agent, user, personal, state, tag, property, compatibleAgent, number, status, canceled, pinned, sinceBuild, sinceDate, untilBuild, untilDate, failedToStart, snapshotDependency, defaultFilter, lookupLimit, single value, start, count]

Test to reproduce

        [Test]
        public void Cancelled()
        {
            // Arrange
            var fixture = Auto.Fixture();
            var buildHavingBuilder = fixture.Create<BuildHavingBuilder>();

            // Act
            buildHavingBuilder.Cancelled();

            // Assert
            buildHavingBuilder.GetLocator().Should().Be("canceled:True");
        }

Affected versions

Product Version
FluentTc latest (0.0.0.213)
TeamCity Enterprise 9.1.6 (build 37459)
Autofac 3.5.0
EasyHttp 1.6.85
SharpZipLib 0.86.0
System.IO.Abstractions 2.0.0.124
TeamCity.ServiceMessages 3.0.5.1

Allow windows authentication

Feature Request

FluentTc allows currently to login as a specified user or use a guest login. It would be nice to add Windows authentication, i.e. to authenticate against TeamCity REST API with the credentials of the current user of the process.

new RemoteTc().Connect(_ => _.ToHost().AsCurrentUser())

Start build with parameters and options

Bug/Feature Request

I would like to start a build with custom parameters at the top of the build queue. I can do either or these, not both.

Happy to create a PR if you think this is valuable

Test to reproduce

_Please provide necessary steps for reproduction of this issue_.
[Test]
public void Test_To_Reproduce_The_Issue()
{
   client.RunBuildConfiguration(_ => _.Id(someBuildConfig.Id),
                    _ => _.Parameter("testParam1", testParam1Value).Parameter("testParam2", testParam2Value), _ => _.QueueAtTop());
}

Affected versions

Product Version
FluentTc latest
TeamCity any
Autofac
EasyHttp
SharpZipLib
System.IO.Abstractions
TeamCity.ServiceMessages

Assign investigation

As a developer I would like to be able to assign investigation on build or test

Test to reproduce

[Test]
public void AssignInvestigation_FluentBuildConfigurationAndUser_InvestigationAssigned()
{
   new RemoteTc(c => c.ToHost("HOST").AsGuest()).
          AssignInvestigation(
             buildConfiguration => buildConfiguration.Id("FluentTc"),
             user => user.Username("borismod")
}

Implementation tip

For TeamCity version prior to 2017.2 use the workaround as stated by @yaegor:

by tracing the browser requests on performing the action.
For me this gives:
POST /buildTypeInvestigationDialog.html?investigation-bt=&do-investigate=true&investigate=ASSIGN&investigator=&remove-investigation=<0 for "when fixed", 1 for "manually">&comment=<comment+text>

For TeamCity version starting with 2017.2 use the REST API as @yaegor wrote

Implemented POST to .../app/rest/investigations (accepts single investigation) and (as an experiment) to .../app/rest/investigations/multiple (accepts list of investigations). Also PUT allows to replace an investigation

For more details see related issue in TeamCity YouTrack: https://youtrack.jetbrains.com/issue/TW-24354

Custom implementation of IBuildIncludeBuilder

Hi,

I would like to have more fields fetched when getting a list of builds, but the API only allows me to add these 4:

  public interface IBuildIncludeBuilder
  {
    IBuildIncludeBuilder IncludeStartDate();

    IBuildIncludeBuilder IncludeFinishDate();

    IBuildIncludeBuilder IncludeStatusText();

    IBuildIncludeBuilder IncludeDefaults();
  }

I would like to, for example, modify the defaults (or even better, have a method which would have name of the field as input).

I thought about having custom implementation of IBuildIncludeBuilder but I don't know how I would give that to the ConnectedTc.

Question about getting running builds

Running builds

First of all, great work, love FluentTc!

I have created a monitor screen displaying status of latest build of all buildTypes of a Project. Green for success and red for failure. Now I want to add yellow for currently running builds, but I can't figure out how to get that info.

So the question is basically how do I acecss data about any currently running builds and their states?

Missing parameters in LocalTc

Please add the parameter is.Personal:
private static bool IsPersonal(ILocalTc localTc)
{
bool isPersonal = false;
try
{
bool.TryParse(localTc.GetBuildParameter("build.is.personal"), out isPersonal);
}
catch (MissingBuildParameterException)
{
}
return isPersonal;
}

Add DownloadArtifacts() method to RemoteTc that accepts lambda

Feature Request

As a user I would like to be able to download artifacts using fluent API with build locators

Test to reproduce

_Please provide necessary steps for reproduction of this issue_.
[Test]
public void DownloadArtifacts_ByBuildConfiguration_Status()
{
    IList<string> downloadedFiles = new RemoteTc(c => c.ToHost("HOST").AsGuest())
        .DownloadArtifacts(build => build
                .BuildConfiguration(with => with.Id("FluentTc"))
                .Status(BuildStatus.Success),  
            @"C:\DownloadedArtifacts");
}

[Test]
public void DownloadArtifacts_ByBuildId()
{
    IList<string> downloadedFiles = new RemoteTc(c => c.ToHost("HOST").AsGuest())
        .DownloadArtifacts(build => build.Id(12345), @"C:\DownloadedArtifacts");
}

Add Properties to Build

TeamCity api provides Properties for build(/app/rest/builds/id:{id}).
Need to add Properties to Build class.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.