Click “Front-end Small Garden” above, select “Top public account”

High-quality technical articles, the first time hot information delivery

This article will introduce the process of using the GitLab API by implementing the update log of the front-end component library.

The cause of

The update log of our team component library is always manually maintained. Every time there is an update, the tag is created after merging into the master and then manually updated in the wiki. This is very inconvenient, I wanted to find a way to create a tag can automatically generate update log, and then, found today’s protagonist GitLab API.

Gitlab API is introduced

Gitlab API is a very complete set of restful apis provided by GitLab. Almost all manual operations can be automated by calling these apis.

The full API documentation can be found at Help.

To see what these apis can do, take a look at the following chart :(this chart only combs through some of the apis that I think are important.)

As you can see, the GitLab API is quite powerful, so let’s take a look at how to use it.

Gitlab API to use

The goal is to create an update log like the one below (element UI update log screenshot).

The update log content contains the version number (tag), update date, update content description, and code submitter.

The Tags API of GitLab provides this data, and we just need to follow a certain rule to add updates every time we create a tag. Then, all the tag information of the current project is obtained through tags API, sorted in descending order by time, and mapped to the data format required by the front-end log page. In this way, the log update is completed.

Here are the specific uses of the GitLab API in this process:

Obtain private_token

Gitlab’s API requires a private_token for authentication. An invalid private_token responds to 401. Private_token can be obtained in two ways:

1. View the User Settings

2. Obtain the IP address from the Session API

By calling the Session API, you can obtain private_token by taking the username/mailbox and password as arguments. The following is an example using the cURL command:

curl --request POST "https://gitlab.example.com/api/v4/session?login=yushihu&password=xxxxx"

Copy the code

Screenshot of response Result

Get the project ID

As you can see by looking at the Tags API, to get all the tags information for a project, you also need the project ID as a parameter. There are two ways to get a project ID.

1. View project Setting

2. Get it through the Projects API

curl --header "PRIVATE-TOKEN: 9koXcdsepg98eAheJpvtK" https://gitlab.example.com/api/v4/projects?search=projectnameCopy the code

Screenshot of response Result

3. Obtain all tag information

One thing to note here is that the interface that retrieves the tag list does not return all of the data. By default, the data is paginated, and only the default 20 entries on the first page are returned without passing any paging parameters.

The per_page parameter is used to control the number of data items per page. The default value is 20 and the maximum value is 100. Therefore, if the number of tags exceeds 100 and you want to obtain all the tag information at one time, you need to obtain the tag information of each page based on the total number of pages. Here is the implementation code (nodeJS implementation) :

let request = require('request')Const PER_PAGE = 60 // Number of pages per pageconst PRIVATE_TOKEN = 'yushihubiubiubiu' // private_tokenconst PROJECT_ID = 666666 // project idConst BASE_URL = 'http://git.feinn-yushihu.com' // Git service domain name// Get the total number of pagesasync function getTotalPages(){    return new Promise((resolve, reject) => {        const options = {url: `${BASE_URL}/api/v4/projects/${PROJECT_ID}/repository/tags? per_page=${PER_PAGE}`,            headers: {                'PRIVATE-TOKEN': PRIVATE_TOKEN            }        }        request.head(options, function (error, response, body) {if (! error && response.statusCode == 200) {              let total_pages = response.caseless.dict['x-total-pages']               resolve(total_pages)          }        })    })}// Get the tag data at the bottom of each pageasync function getPerPageTags(currentPage){    return new Promise((resolve, reject) => {        const options = {url: `${BASE_URL}/api/v4/projects/${PROJECT_ID}/repository/tags? per_page=${PER_PAGE}&page=${currentPage}`,            headers: {                'PRIVATE-TOKEN': PRIVATE_TOKEN            }        }        request.get(options, function (error, response, body) {if (! error && response.statusCode == 200) {            let res = JSON.parse(body)            resolve(res)          }        })    })    } // Iterate to get all the tag dataasync function getTotalTags(){    let re = await getTotalPages()    const promiseArr = []    for(let i=0; i<re; i++){        promiseArr.push(getPerPageTags(i+1))    }    return Promise.all(promiseArr)}Copy the code

Gitlab API usage scenarios

In addition to generating the update log described above, you can do the following:

1. Obtain the version of the deployed code

Sometimes in a project, you need to know the version of the code currently deployed (the COMMIT ID).

For example, when sentry is used to collect error information, if the version information is not configured, it is difficult to know which version of the code reported error is, and it is difficult to find the corresponding code to troubleshoot errors. Using the COMMIT ID as version information makes it easy to find the commit code and locate the source where the error was reported.

2. Automatically filter some issues

An open source project may have many Issues in a day, some Issues may be duplicated, some may be of poor quality and unfriendly, and if all Issues are handled manually, it will take a long time. Specific Issues can then be modified or removed using the Issues API.

More usage scenarios need to be explored in the work