简体   繁体   English

如何获得在 Gitlab 中花费的总时间?

[英]How to get total time spend in Gitlab?

Is there a way to get the total time spend on all issues that a user have spend with the time tracking /spend slash command ?有没有办法获得用户使用时间跟踪/spend slash 命令花费在所有问题上的总时间?

Time tracking stats with the API gets just a small amount of data: https://docs.gitlab.com/ce/api/issues.html#get-time-tracking-stats使用 API 的时间跟踪统计信息仅获得少量数据: https://docs.gitlab.com/ce/api/issues.html#get-time

Gitlab CE 9.1.4 Gitlab CE 9.1.4

As I see it is possible to parse comments from API v3 and calculate total. 我认为可以从API v3解析注释并计算总数。

For example, 例如,

https://gitlab.com/api/v3/projects/:id/issues/:issue_id/notes?private_token=your_token

{
  id: 73113225,
  body: "added 1h of time spent at 2018-05-15",
  attachment: null,
  author: {
    ...
    username: "mnvxxx",
  },
  ...
}

More info: https://docs.gitlab.com/ee/api/notes.html 更多信息: https//docs.gitlab.com/ee/api/notes.html

UPDATE UPDATE

Currently I has created instrument for calculating spent time by every contributor. 目前,我已经创建了用于计算每个贡献者的花费时间的工具。 I hope it will be helpful: 我希望它会有所帮助:

https://github.com/zubroide/gitpab https://github.com/zubroide/gitpab

Here is a very simple Python script that works with API v4: 这是一个非常简单的Python脚本,适用于API v4:

import requests

API_KEY = ""  # Enter your API key here
BASE_URL = "https://{{enter gitlab url here}}/api/v4/"

item_counter = 0
total_seconds = 0

for i in range(1, 57):  # manually set range of issues here. All issues doesn't work well.
    issue = requests.get(BASE_URL + 'projects/2/issues/' + str(i) + '/time_stats')
    total_seconds += issue.json()['total_time_spent']
    item_counter += 1

print("Hours on all issues: %.2f" % float((total_seconds / 60) / 60))
print("Total issues: " + str(item_counter))

I'm posting to this thread because this is the first answer that comes up on Google, and there isn't really any other ready-made solutions to be found. 我发帖到这个主题,因为这是Google上出现的第一个答案,并没有真正找到任何其他现成的解决方案。

Building on top of what @josh-harkema has provided, this is a version that lists all closed issues that were assigned to a specific username that have been updated in a given time period (and do not have the label 'paid' set): 在@ josh-harkema提供的基础上,这个版本列出了分配给在给定时间段内更新的特定username所有closed问题(并且没有设置标签'付费'):

import requests
import os

username = os.environ.get('GITLAB_REPORTING_USERNAME')
project_id = os.environ.get('GITLAB_REPORTING_PROJECTID') # in the top of your project page
access_token = os.environ.get('GITLAB_REPORTING_TOKEN')  # https://gitlab.com/profile/personal_access_tokens
base_url = "https://gitlab.com/api/v4"

updated_after = "2019-06-01T00:00:00.00Z"
updated_before = "2019-07-01T00:00:00.00Z"

item_counter = 0
total_seconds = 0

headers = { 'Private-Token': access_token }
url_template = "{base_url}/projects/{project_id}/issues?" \
               "state=closed&assignee_username={username}&updated_after={updated_after}&updated_before={updated_before}"
url = url_template.format(base_url=base_url, project_id=project_id, username=username,
                          updated_after=updated_after, updated_before=updated_before)

# call API
issues = requests.get(url, headers = headers)

total_seconds = 0
issues_to_pay = []
line_template = "id: {id}    closed: {closed_at}    time spent: {time}\ttitle: {title}\turl: {url}"
print("Issue statistics for {u} from {f} to {t}:\n".format(u=username,f=updated_after, t=updated_before))

for issue in issues.json():

    time_val = issue['time_stats']['human_total_time_spent']
    already_paid = u'paid' in issue['labels'] # you can put a label 'paid' to exclude an issue
    if already_paid:
        time_val = time_val + " *"
    else:
        # if the issue has been paid, already, don't add the time, and don't list as to be paid
        total_seconds += issue['time_stats']['total_time_spent']
        issues_to_pay.append(str(issue['id']))

    line = line_template.format(
        id=issue['id'],
        closed_at=issue['closed_at'],
        title=issue['title'],
        time=time_val,
        url=issue['web_url']
    )
    print(line)
print("")
print("Hours to pay on all issues: %.2f" % float((float(total_seconds) / 60) / 60))
print("")
print("* = issue has been paid for, already")
print("All issue to pay: {issues}".format(issues=",".join(issues_to_pay)))

Note: You need to have environment variables set for the GITLAB_REPORTING_USERNAME , the GITLAB_REPORTING_PROJECTID , as well as the GITLAB_REPORTING_TOKEN . 注意:您必须对设置环境变量GITLAB_REPORTING_USERNAMEGITLAB_REPORTING_PROJECTID ,还有GITLAB_REPORTING_TOKEN

We use this to pay contractors. 我们用它来支付承包商。 Hope this helps! 希望这可以帮助!

I was myself looking for the same and after more searching, I found this excellent CLI tool called gitlab-time-tracker .我自己也在寻找相同的东西,经过更多的搜索,我找到了这个名为gitlab-time-tracker 的优秀 CLI 工具。 It generates comprehensive reports of tracked-time that you can customise by multiple options and can print them even as PDFs !它生成全面的跟踪时间报告,您可以通过多个选项对其进行自定义, 甚至可以将它们打印为 PDF

For keeping this answer relevant to OP's question, you can print (in your terminal) total time spent by a user using following command**:为了使这个答案与 OP 的问题相关,您可以使用以下命令打印(在您的终端中)用户花费的总时间**:

gtt report "namespace/project" --user username --closed --from="2017-03-01" --to="2017-04-01"

** This assumes that you've installed this tool (gtt) and setup your Gitlab PAT (with "api" scope activated) in its config file. ** 这假设你已经安装了这个工具 (gtt) 并在它的配置文件中设置了你的 Gitlab PAT(激活了“api”范围)。

Because I like the speed of Go:因为我喜欢Go的速度:

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
)

type AutoGeneratedStuff struct {
    TimeEstimate        int         `json:"time_estimate"`
    TotalTimeSpent      int         `json:"total_time_spent"`
    HumanTimeEstimate   interface{} `json:"human_time_estimate"`
    HumanTotalTimeSpent interface{} `json:"human_total_time_spent"`
}

func main() {
    //for performance, specify the range of issues (i)
    for i := 1; i <= 5; i++ {

        var url string = "https://{{Your_URL_here }}/api/v4/projects/{{ proj_id_here }}/issues/" + fmt.Sprint(i) + "/time_stats"
        var timestuff AutoGeneratedStuff
        var bearer = "Bearer " + "{{your_API_token_here}}"

        // Create a new request using http
        req, err := http.NewRequest("GET", url, nil)

        // add authorization header to the req
        req.Header.Add("Authorization", bearer)

        // Send req using http Client
        client := &http.Client{}
        resp, err := client.Do(req)
        if err != nil {
            log.Println("Error on response.\n[ERROR] -", err)
        }
        defer resp.Body.Close()

        body, err := ioutil.ReadAll(resp.Body)
        if err != nil {
            log.Println("Error while reading the response bytes:", err)
        }
        Data := []byte(body)

        err2 := json.Unmarshal(Data, &timestuff)

        if err2 != nil {

            fmt.Println(err)
        }
        fmt.Println("Time estimate is:", timestuff.TimeEstimate)
        fmt.Println("Human time estimate is:", timestuff.HumanTimeEstimate)
        fmt.Println("Total time is:", timestuff.TotalTimeSpent)
        fmt.Println("Human total time is:", timestuff.HumanTotalTimeSpent)

    }
}

Example response:示例响应:

Time estimate is: 86400
Human time estimate is: 3d
Total time is: 300
Human total time is: 5m

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM