The Jenkins client was written by Golang

Gitpod ready-to-code codecov Codacy Badge Contributors

jenkins-client Document

How to get it

go.mod

require github.com/jenkins-zh/jenkins-client

Configuration

Examples of jcli configuration

- name: dev
  url: http://192.168.1.10
  username: admin
  token: 11132c9ae4b20edbe56ac3e09cb5a3c8c2
  proxy: http://192.168.10.10:47586
  proxyAuth: username:password

So when you use jcli-client, you need to configure and read configuration files like this

type Config struct {
	URL      string `yaml:"url"`
	UserName string `yaml:"username"`
	Token    string `yaml:"token"`
}

func GetJenkinsCore() (core client.JenkinsCore, e error) {
	// read configuration files
	jenkinsConfigPath := "./jenkins.yml"
	yamlFile, e := ioutil.ReadFile(jenkinsConfigPath)
	if e != nil {
		return
	}
	// yaml parse
	var config Config
	e = yaml.Unmarshal(yamlFile, &config)
	if e != nil {
		return
	}
	// capsulate JenkinsCore
	core = client.JenkinsCore{
		URL:      config.URL,
		UserName: config.UserName,
		Token:    config.Token,
	}
	crumbIssuer, e := core.GetCrumb()
	if e != nil {
		return
	} else if crumbIssuer != nil {
		core.JenkinsCrumb = *crumbIssuer
	}
	return
}

Job API

More used API

// GetBuild get build information of a job
func (q *JobClient) GetBuild(jobName string, id int) (job *JobBuild, err error){...}

// Build trigger a job
func (q *JobClient) Build(jobName string) (err error) {...}

// BuildWithParams build a job which has params
func (q *JobClient) BuildWithParams(jobName string, parameters []ParameterDefinition) (err error) {...}

// GetHistory returns the build history of a job
func (q *JobClient) GetHistory(name string) (builds []*JobBuild, err error) {...}

// Log get the log of a job
func (q *JobClient) Log(jobName string, history int, start int64) (jobLog JobLog, err error){...}

User API

More used API

// Create will create a user in Jenkins
func (q *UserClient) Create(username, password string) (user *UserForCreate, err error) {...}

// Delete will remove a user from Jenkins
func (q *UserClient) Delete(username string) (err error) {...}

Examples

type JobBuildOptions struct {
	Env       string 
	JobName   string 
	BranchTag string 
}


func BuildJob(jobBuild JobBuildOptions) (e error) {
	core, e := GetJenkinsCore()
	jobClient = client.JobClient{core}
	if e != nil {
		return
	}
	param1 := client.ParameterDefinition{
		Description:           "pre and prd please use tag",
		Name:                  "BRANCH_TAG",
		Type:                  "Branch or Tag",
		Value:                 jobBuild.BranchTag,
		DefaultParameterValue: client.DefaultParameterValue{Value: "origin/master"},
	}
	param2 := client.ParameterDefinition{
		Description:           "choice",
		Name:                  "ENV",
		Type:                  "Choice Parameter",
		Value:                 jobBuild.Env,
		DefaultParameterValue: client.DefaultParameterValue{Value: "qa"},
	}
	param3 := client.ParameterDefinition{
		Description:           "Deploy Type",
		Name:                  "DEPLOY_TYPE",
		Type:                  "Choice Parameter",
		Value:                 "publish",
		DefaultParameterValue: client.DefaultParameterValue{Value: "publish"},
	}
	params := []client.ParameterDefinition{param1, param2, param3}
	e = jobClient.BuildWithParams(jobBuild.JobName, params)
	return
}

Plugin Dependencies

Pay attention to the part of the Jenkins CLI, they need some special plugins. Please read through the following table:

API Plugin
Search Job pipeline-restful-api
Owner
Jenkins Chinese Community
共建开放、包容、活跃的 Jenkins 社区
Jenkins Chinese Community
Comments
  • Request support Blue Ocean API download artifact

    Request support Blue Ocean API download artifact

    Currently, the Blue API only supports getting a list of artifacts: https://github.com/jenkins-zh/jenkins-client/blob/94e2330ce3cc7303ebca41bc0de544d2c33089d5/pkg/artifact/artifacts.go

    Hope to support artifact download

  • Add MarshalJSON method for job.time type

    Add MarshalJSON method for job.time type

    What this PR dose?

    • Add MarshalJSON method for job.time type
    • Make sure that UnMarshalJSON supports to parse time using Jenkins time layout and RFC3339 time layout

    Why we need it

    Before doing this, we cannot deserialize time string which is serialized by job.Time. Because the time layouts used by deserialization and serialization are different. Jenkins time layout is used by deserialization, but RFC3339 time layout is used by serialization by default. So we will get the following error when we trying to deserialize the time string:

    parsing time "2021-09-28T03:40:11.253Z" as "2006-01-02T15:04:05.000-0700": cannot parse "Z" as "-0700"
    

    /kind bug

  • Provide a list API of all steps

    Provide a list API of all steps

    What this PR dose

    Provide a list API of all steps.

    Please see: https://github.com/jenkinsci/blueocean-plugin/tree/master/blueocean-rest#get-pipeline-steps

  • Adapt pipeline nodes API

    Adapt pipeline nodes API

    What this PR dose

    Adapt pipeline nodes API.

    Why we need it

    https://github.com/jenkinsci/blueocean-plugin/tree/master/blueocean-rest#get-pipeline-run-nodes

    /kind feature

    TODO

    • [x] Add tests against GetNodes method
  • Support multi-branch pipeline build and fetching build

    Support multi-branch pipeline build and fetching build

    What this PR dose

    • Support multi-branch pipeline build and fetching build
    • Refactor arguments of method GetBuild

    Why we need it

    In the real scene, we have many multi-branch pipeline to be built.

    /kind feature

  • Wrong type in DurationInMillis

    Wrong type in DurationInMillis

    The type of DurationInMillis in Node struct should also be int64 as in the Step struct. https://github.com/jenkins-zh/jenkins-client/blob/0c9041a612a1bc6047236fc1e3194fc01e33830e/pkg/job/blueocean_type.go#L131

    See also: BluePipelineNode extends BluePipelineSteps and the type of durationInMillis in BulePipelineStep is long.

  • Fix json form in UpdateInFolder

    Fix json form in UpdateInFolder

    change the json payload that in the UpdateInFolder function from

    {
        "credentials":{
            "description":"",
            "DisplayName":"",
            "Fingerprint":null,
            "FullName":"",
            "id":"gitee",
            "TypeName":"",
            "$class":"com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl",
            "stapler-class":"com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl",
            "scope":"GLOBAL",
            "username":"chengleqi",
            "password":"xxx"
        }
    }
    

    to

    {
        "description":"",
        "DisplayName":"",
        "Fingerprint":null,
        "FullName":"",
        "id":"gitee",
        "TypeName":"",
        "$class":"com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl",
        "stapler-class":"com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl",
        "scope":"GLOBAL",
        "username":"chengleqi",
        "password":"xxx"
    }
    
  • Escape special character for branch parameter

    Escape special character for branch parameter

    What this PR dose

    Escape special character for branch parameter while getting steps data.

    Why we need it

    Considering the branch named release%2Fv3.2, Jenkins client will create a request with url /blue/rest/organizations/jenkins/pipelines/pipelineA/branches/release%2Fv3.2/runs/123/steps/(equal to /blue/rest/organizations/jenkins/pipelines/pipelineA/branches/release/v3.2/runs/123/steps/) while getting steps data.

    /blue/rest/organizations/jenkins/pipelines/pipelineA/branches/release%252Fv3.2/runs/123/steps/ is what we expect. See also in BlueOcean Dashboard: image

  • Refine ParameterDefinition definition according upstream source code

    Refine ParameterDefinition definition according upstream source code

    What this PR dose

    Add Choices, ProjectName and Filter to ParameterDefinition type.

    Why we need it

    See also:

    • https://github.com/jenkinsci/jenkins/blob/65b9f1cf51c3b3cf44ecb7d51d3f30d7dbe6b3bd/core/src/main/java/hudson/model/RunParameterDefinition.java#L103-L106
    • https://github.com/jenkinsci/jenkins/blob/65b9f1cf51c3b3cf44ecb7d51d3f30d7dbe6b3bd/core/src/main/java/hudson/model/RunParameterDefinition.java#L103-L106
    • https://github.com/jenkinsci/jenkins/blob/65b9f1cf51c3b3cf44ecb7d51d3f30d7dbe6b3bd/core/src/main/java/hudson/model/RunParameterDefinition.java#L116-L121
  • Refine ParameterDefinition and ParameterValue types

    Refine ParameterDefinition and ParameterValue types

    What this PR dose?

    • Add missing JSON tag for ParameterDefinition and ParameterValue types
    • Correct inner fields of ParameterValue type

    References:

    • https://github.com/jenkinsci/jenkins/blob/master/core/src/main/java/hudson/model/ParameterDefinition.java#L98
    • https://github.com/jenkinsci/jenkins/blob/f23512f2bc97d18cd4f0183a7db4a62bc6b84196/core/src/main/java/hudson/model/ParameterValue.java#L78

    /kind bug

  • Make type of some optional fields as pointer

    Make type of some optional fields as pointer

    What this PR dose?

    Make type of some optional fields as pointer.

    Why we need it?

    It's unnecessary to initialize struct if one field is optional.

    /kind enhancement

  • Can't download artifacts with multi-branch-pipelines

    Can't download artifacts with multi-branch-pipelines

    refactor artifacts.go:41

    for single branch pipeline artifacts downloads URI

    artifactURL := fmt.Sprintf("/job/%s/job/%s/%d/artifact/%s", projectName, pipelineName, buildID, filename)

    multi_branch_pipeline artifacts downloads URI

    artifactURL := fmt.Sprintf("/job/%s/job/%s/job/%s/%d/artifact/%s", projectName, pipelineName, branchName, buildID, filename)

  • Request to resolve error message responded by Blue Ocean API and append it into error

    Request to resolve error message responded by Blue Ocean API and append it into error

    In BlueOcean RESTful API documentation, there contains a Error Message section that describes error details when something goes wrong.

    {
      "message" : "Failed to create Git pipeline: demo",
      "code" : 400,
      "errors" : [ {
        "message" : "demo already exists",
        "code" : "ALREADY_EXISTS",
        "field" : "name"
      } ]
    }
    

    But Jenkins Client don't include the JSON response into error detail or resolve the JSON response.

    Therefore, the only feedback to invoker is unexpected status code: 400 instead of demo already exists.

    At last, if we resolved this the error message responded by Blue Ocean API and append it into error, invoker would know what happended just now.

    Originally posted by @JohnNiang in https://github.com/kubesphere/ks-devops/issues/219#issuecomment-912229863

  • Make Organization of BlueOceanClient be a default value: jenkins

    Make Organization of BlueOceanClient be a default value: jenkins

    The parameter Organization almost is jenkins. Please consider make it be a default value in the Jenkins client library.

    Originally posted by @LinuxSuRen in https://github.com/kubesphere/ks-devops/pull/214#discussion_r700876533

    /assign

A http-relay server/client written in golang to forward requests to a service behind a nat router from web

http-relay This repo is WIP http-relay is a server/client application written in go(lang) to forward http(s) requests to an application behind a nat r

Dec 16, 2021
Prisma Client Go is an auto-generated and fully type-safe database client

Prisma Client Go Typesafe database access for Go Quickstart • Website • Docs • API reference • Blog • Slack • Twitter Prisma Client Go is an auto-gene

Jan 9, 2023
The Dual-Stack Dynamic DNS client, the world's first dynamic DNS client built for IPv6.

dsddns DsDDNS is the Dual-Stack Dynamic DNS client. A dynamic DNS client keeps your DNS records in sync with the IP addresses associated with your hom

Sep 27, 2022
Go Substrate RPC Client (GSRPC)Go Substrate RPC Client (GSRPC)

Go Substrate RPC Client (GSRPC) Substrate RPC client in Go. It provides APIs and types around Polkadot and any Substrate-based chain RPC calls. This c

Nov 11, 2021
Server and client implementation of the grpc go libraries to perform unary, client streaming, server streaming and full duplex RPCs from gRPC go introduction

Description This is an implementation of a gRPC client and server that provides route guidance from gRPC Basics: Go tutorial. It demonstrates how to u

Nov 24, 2021
Tailscale-client-go - A client implementation for the Tailscale HTTP API

tailscale-client-go A client implementation for the Tailscale HTTP API Example p

Sep 8, 2022
Comunicación de envios de archivos entres cliente-servidor, client-client.

Client - Server - Client Estes es un proyecto simple de comunicacion de envios de archivos del cliente al servidor y viceversamente, y de cliente a cl

Jul 16, 2022
httpie-like HTTP client written in Go
httpie-like HTTP client written in Go

httpie-go httpie-go (ht) is a user-friendly HTTP client CLI. Requests can be issued with fewer types compared to curl. Responses are displayed with sy

Dec 9, 2022
GoSNMP is an SNMP client library fully written in Go

GoSNMP is an SNMP client library fully written in Go. It provides Get, GetNext, GetBulk, Walk, BulkWalk, Set and Traps. It supports IPv4 and IPv6, using SNMPv1, SNMPv2c or SNMPv3. Builds are tested against linux/amd64 and linux/386.

Jan 5, 2023
Self-hostable , easy-to-use , lightweight and feature-rich torrent client written in Go
Self-hostable , easy-to-use , lightweight and feature-rich torrent client written in Go

Self-hostable , easy-to-use , lightweight and feature-rich torrent client written in Go . It comes with beautiful Web UI and Optional Multi-User Support . Run Locally or Host in Server . Open/Download/Stream Torrents in Browser Right Away!

Jan 1, 2023
An open source Pusher server implementation compatible with Pusher client libraries written in Go

Try browsing the code on Sourcegraph! IPÊ An open source Pusher server implementation compatible with Pusher client libraries written in Go. Why I wro

Aug 27, 2022
GoSNMP is an SNMP client library fully written in Go.

GoSNMP is an SNMP client library fully written in Go. It provides Get, GetNext, GetBulk, Walk, BulkWalk, Set and Traps. It supports IPv4 and IPv6, using SNMPv1, SNMPv2c or SNMPv3. Builds are tested against linux/amd64 and linux/386.

Oct 28, 2021
Client for the OpenWeather API, written in Go

Weather This is a Go project template, intended for students at the Bitfield Institute of Technology—but everyone's welcome to try it if you're intere

Nov 9, 2021
MPD client inspired by ncmpcpp written in GO with builtin cover art previews.
 MPD client inspired by ncmpcpp written in GO with builtin cover art previews.

goMP MPD client inspired by ncmpcpp written in GO demo.mp4 Roadmap Add Functionality to Sort out most played songs Add a config parser Image Previews

Jan 1, 2023
A Minecraft scanner written in Golang (first Golang project)

__ __/ \__ Gothyc A Minecraft port scanner written in Go. ?? / \__/ \__ \__/ \__/ \ Version 0.3.0 \__/ \__/ Author @toas

Nov 6, 2022
Simple mDNS client/server library in Golang

mdns Simple mDNS client/server library in Golang. mDNS or Multicast DNS can be used to discover services on the local network without the use of an au

Jan 4, 2023
A LWM2M Client and Server implementation (For Go/Golang)

Betwixt - A LWM2M Client and Server in Go Betwixt is a Lightweight M2M implementation written in Go OMA Lightweight M2M is a protocol from the Open Mo

Dec 23, 2022
Golang client for NATS, the cloud native messaging system.

NATS - Go Client A Go client for the NATS messaging system. Installation # Go client go get github.com/nats-io/nats.go/ # Server go get github.com/na

Jan 4, 2023
🤘 The native golang ssh client to execute your commands over ssh connection. 🚀🚀
🤘 The native golang ssh client to execute your commands over ssh connection. 🚀🚀

Golang SSH Client. Fast and easy golang ssh client module. Goph is a lightweight Go SSH client focusing on simplicity! Installation ❘ Features ❘ Usage

Dec 24, 2022