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

21

1
GitLab 13.12(2021年5月)中的新时间跟踪报告可能会引起您的兴趣:请参见我的答案 - VonC
5个回答

8

据我所见,从 API v3 中解析注释并计算总数是可行的。

例如:

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",
  },
  ...
}

更多信息请参考:https://docs.gitlab.com/ee/api/notes.html

更新

我已经创建了一款工具,可以计算每个贡献者花费的时间。希望它能有所帮助:

https://github.com/zubroide/gitpab


7

这是一个非常简单的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))

我在这个帖子中留言,因为这是Google上出现的第一个答案,而且实际上没有其他现成的解决方案可以找到。


看起来我们可以使用GitLab的全局搜索API来搜索问题,以便限制返回哪些问题:https://docs.gitlab.com/ee/api/search.html#global-search-api - carlin.scott

4

在 @josh-harkema 提供的基础上,这是一个列出所有已关闭问题的版本,这些问题被分配给特定的用户名,并在给定时间段内更新(且没有设置标签 'paid'):

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)))

注意: 您需要设置环境变量 GITLAB_REPORTING_USERNAMEGITLAB_REPORTING_PROJECTIDGITLAB_REPORTING_TOKEN。我们使用这些变量来支付承包商。希望这能帮到你!

谢谢,非常有用。 - ladrua
你知道如何获取每个用户每个问题的工时吗?因此,如果多个用户跟踪同一问题的时间,您可以提取每个用户的工时。 - ladrua

4
我本人也在寻找这个,经过更多搜索,我发现了这个优秀的 CLI 工具,叫做 gitlab-time-tracker。它可以生成全面的跟踪时间报告,你可以通过多种选项进行自定义,并且可以将它们打印成 PDF 格式
为了让这个答案与提问者的问题相关,你可以使用以下命令(在终端中)打印用户所花费的总时间**:
gtt report "namespace/project" --user username --closed --from="2017-03-01" --to="2017-04-01"

这假设你已经安装了这个工具(gtt),并在其配置文件中设置了你的Gitlab PAT(激活了“api”范围)。

0

你需要同时使用Gitlab Commits API和GraphQL API来实现它。以下是一些为了简洁而缩短的代码。

你需要指定一个Gitlab实例标志和你的个人令牌。

假设你有一个用于捕获Gitlab实例中所有用户的函数,名为"GetUsers":

package main

    import (
        "bytes"
        "encoding/json"
        "fmt"
        "net/http"
        "time"

    "github.com/sirupsen/logrus"
    "github.com/xanzy/go-gitlab"
    "gopkg.in/alecthomas/kingpin.v2"
)

var (

address = kingpin.Flag("address", "The Gitlab URL to use").Required().String()
token   = kingpin.Flag("token", "Project token").String()
)


func main () {

timeTracker()

}

func timeTracker(git *gitlab.Client) {

names := GetUsers(git)

for _, name := range names {

jsonData := map[string]interface{}{
    "query": `
query($user: String!) {
    timelogs(username: $user ) {
        edges {
            node {
            id
    user {
        id
        username
    }
            timeSpent
            issue{
                labels{
                nodes{
                    title
            }
            }
        }
        }
    }
    }
}
`, "variables": fmt.Sprintf(`{"user":"%s"}`, name),
}
jsonValue, _ := json.Marshal(jsonData)
    request, err := http.NewRequest("POST", "https://" +*address + "/api/graphql", bytes.NewBuffer(jsonValue))
    if err != nil {
        logrus.Error(err)
    }
    request.Header.Set("Authorization", "Bearer "+*token)
    request.Header.Set("Content-Type", "application/json")
    client := &http.Client{Timeout: time.Second * 10}
    response, err := client.Do(request)
    response.Body.Close()
    if err != nil {
        fmt.Printf("The HTTP request failed with error %s\n", err)
    }
    logrus.Print(ioutil.ReadAll(response.Body))

结果(使用JSONDecoder解码时):

INFO[0000] User: user1, Time spent: 300 (s)
INFO[0000] User: user2, Time spent: 120 (s)

你可以将这些数据解码成一个结构体(为了方便,我建议复制粘贴post请求到自动生成器中),然后按照你的意愿处理它。或者,如果你对特定项目下的用户更感兴趣,可以更改POST请求以按项目捕获用户。
来源:https://docs.gitlab.com/ee/api/graphql/getting_started.html

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接