GitLab统计代码量

本文介绍了如何通过GitLabAPI获取个人访问令牌,列举了获取用户可见项目、项目分支以及分支上的Commits的步骤,并展示了如何统计代码增删情况。详细过程包括设置访问令牌、遍历项目和分支、获取Commits以及解析提交的代码统计信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

gitlab官方文档:https://docs.gitlab.com/ee/api/index.html

1、生成密钥

登录gitlab,编辑个人资料,设置访问令牌
在这里插入图片描述

2、获取当前用户所有可见的项目

在这里插入图片描述
接口地址

GET请求
http://gitlab访问地址/api/v4/projects?private_token=xxx 

返回参数

[
	{
		"id": 1,
		"description": "This project is automatically generated and helps monitor this GitLab instance. [Learn more](/help/administration/monitoring/gitlab_self_monitoring_project/index).",
		"name": "Monitoring",
		"name_with_namespace": "GitLab Instance / Monitoring",
		"path": "Monitoring",
		"path_with_namespace": "gitlab-instance-d71d8d97/Monitoring",
		"created_at": "2021-07-12T08:41:01.299Z",
		"default_branch": "main",
		"tag_list": [],
		"topics": [],
		"ssh_url_to_repo": "git@gitlab.example.cn:gitlab-instance-d71d8d97/Monitoring.git",
		"http_url_to_repo": "http://gitlab.example.cn/gitlab-instance-d71d8d97/Monitoring.git",
		"web_url": "http://gitlab.example.cn/gitlab-instance-d71d8d97/Monitoring",
		"readme_url": null,
		"avatar_url": null,
		"forks_count": 0,
		"star_count": 0,
		"last_activity_at": "2021-07-12T08:41:01.299Z",
		"namespace": {
			"id": 2,
			"name": "GitLab Instance",
			"path": "gitlab-instance-d71d8d97",
			"kind": "group",
			"full_path": "gitlab-instance-d71d8d97",
			"parent_id": null,
			"avatar_url": null,
			"web_url": "http://gitlab.example.cn/groups/gitlab-instance-d71d8d97"
		},
		"_links": {
			"self": "http://gitlab.example.cn/api/v4/projects/1",
			"issues": "http://gitlab.example.cn/api/v4/projects/1/issues",
			"merge_requests": "http://gitlab.example.cn/api/v4/projects/1/merge_requests",
			"repo_branches": "http://gitlab.example.cn/api/v4/projects/1/repository/branches",
			"labels": "http://gitlab.example.cn/api/v4/projects/1/labels",
			"events": "http://gitlab.example.cn/api/v4/projects/1/events",
			"members": "http://gitlab.example.cn/api/v4/projects/1/members"
		},
		"packages_enabled": true,
		
		...
		...
		...
	}
]

这里我们只需要关注项目id即可

3、获取当前项目所有分支

接口地址

GET请求
http://gitlab访问地址/api/v4/projects/项目id/repository/branches?private_token=xxx 

返回参数

[
    {
        "name": "main",
        "commit": {
            "id": "2d3e01fbedf088fccb5000303428df35c09ea07d",
            "short_id": "2d3e01fb",
            "created_at": "2023-01-06T02:52:54.000+00:00",
            "parent_ids": null,
            "title": "xxxxxx",
            "message": "xxxxxx",
            "author_name": "xxxx",
            "author_email": "xxxx@example.cn",
            "authored_date": "2023-01-06T02:52:54.000+00:00",
            "committer_name": "xxxx",
            "committer_email": "xxxx@example.cn",
            "committed_date": "2023-01-06T02:52:54.000+00:00",
            "trailers": null,
            "web_url": "http://gitlab.example.cn/example/-/commit/2d3e01fbedf088fccb5000303428df35c09ea07d"
        },
        "merged": false,
        "protected": true,
        "developers_can_push": false,
        "developers_can_merge": false,
        "can_push": true,
        "default": true,
        "web_url": "http://gitlab.example.cn/example/-/tree/main"
    }
]

4、遍历分支,根据分支name获取commits

接口地址

GET请求
http://gitlab访问地址/api/v4/projects/项目id/repository/commits?ref_name=main&private_token=xxx 

返回参数

[
	{
		"id": "8fc81980222370d51c11cd9bc609f10f3b7d9828",
		"short_id": "8fc81980",
		"created_at": "2022-07-21T08:46:35.000+00:00",
		"parent_ids": [],
		"title": "Initial commit",
		"message": "Initial commit",
		"author_name": "xxxx",
		"author_email": "xxxx@example.cn",
		"authored_date": "2022-07-21T08:46:35.000+00:00",
		"committer_name": "xxxx",
		"committer_email": "xxxx@example.cn",
		"committed_date": "2022-07-21T08:46:35.000+00:00",
		"trailers": {},
		"web_url": "http://gitlab.example.cn/example/-/commit/8fc81980222370d51c11cd9bc609f10f3b7d9828"
	}
]

5、根据commit的id获取代码量

接口地址

GET请求
http://gitlab访问地址/api/v4/projects/项目id/repository/commits/commit的id?private_token=xxx 

返回参数

{
    "id": "8fc81980222370d51c11cd9bc609f10f3b7d9828",
    "short_id": "8fc81980",
    "created_at": "2022-07-21T08:46:35.000+00:00",
    "parent_ids": [],
    "title": "Initial commit",
    "message": "Initial commit",
    "author_name": "xxxx",
    "author_email": "xxxx@example.cn",
    "authored_date": "2022-07-21T08:46:35.000+00:00",
    "committer_name": "xxxx",
    "committer_email": "xxxx@example.cn",
    "committed_date": "2022-07-21T08:46:35.000+00:00",
    "trailers": {},
    "web_url": "http://gitlab.example.cn/example/-/commit/8fc81980222370d51c11cd9bc609f10f3b7d9828",
    "stats": {
        "additions": 92,
        "deletions": 0,
        "total": 92
    },
    "status": null,
    "project_id": 1,
    "last_pipeline": null
}

stats节点下参数就是我们本次提交的代码量,additions为新增行数,deletions为删除行数,total为总数。

修改操作实际上是删除之后再新增。

注:通过API获取gitlab项目、分支、commits时,默认只能查到20条数据,可以增加入参指定每页数量,数量最大为50000
在这里插入图片描述
Java代码实现

private void gitLab() throws Exception {
    JSONObject params = new JSONObject();
    params.put("private_token", "xxx");
    params.put("per_page", "50000");

    //项目列表
    String result = WebUtils.doGet("http://gitlab.example.cn/api/v4/projects", params);
    JSONArray projects = JSONArray.parseArray(result);
    for (Object project : projects) {
        JSONObject projectValue = JSONObject.parseObject(project.toString());
        String projectId = projectValue.getString("id");

        //commits列表
        String url = String.format("http://gitlab.example.cn/api/v4/projects/%s/repository/commits", projectId);
        result = WebUtils.doGet(url, params);

        int additions = 0;
        int deletions = 0;
        int total = 0;

        JSONArray commits = JSONArray.parseArray(result);
        for (Object commit : commits) {
            JSONObject commitValue = JSONObject.parseObject(commit.toString());
            String commitId = commitValue.getString("id");

            url = String.format("http://gitlab.example.cn/api/v4/projects/%s/repository/commits/%s", projectId, commitId);

            //提交记录
            result = WebUtils.doGet(url, params);
            JSONObject commitStats = JSONObject.parseObject(result);
            JSONObject stats = commitStats.getJSONObject("stats");

            additions += stats.getIntValue("additions");
            deletions += stats.getIntValue("deletions");
            total += stats.getIntValue("total");
        }

        String name = projectValue.getString("name");
        LoggerUtils.info(String.format("项目:%s ,新增:%d ,删除:%d ,合计:%d", name, additions, deletions, total));
    }
}

以上是按照项目统计,扩展类似按作者统计是相同道理

### 如何在 GitLab 中使用命令行统计代码量 为了实现对 GitLab 项目中的代码量进行统计,可以借助 `git` 和第三方工具如 `cloc` 来完成此操作。以下是具体方法: #### 使用 cloc 工具统计代码量 `cloc` 是一种常用的开源工具,专门用于统计代码行数,包括源码、注释和空白行的数量[^2]。可以通过以下方式安装并运行它来统计 GitLab 项目的代码量。 1. **安装 cloc** 如果尚未安装 `cloc`,可以根据操作系统选择合适的安装方式: - 对于基于 Debian 的 Linux 发行版(如 Ubuntu),可执行以下命令安装: ```bash sudo apt-get install cloc ``` - macOS 用户可通过 Homebrew 安装: ```bash brew install cloc ``` 2. **克隆目标仓库** 需要先通过 `git clone` 将目标 GitLab 仓库拉取到本地环境: ```bash git clone https://your-gitlab-instance.com/group/project.git cd project ``` 3. **运行 cloc 命令** 进入项目目录后,可以直接调用 `cloc` 统计整个项目的代码量: ```bash cloc . ``` 输出的结果会显示各个类型的统计数据,例如总行数 (Total Lines),源代码行数 (Source Code Lines),注释行数 (Comment Lines) 及其对应的百分比等[^1]。 4. **自定义统计范围** 若仅需统计特定分支或部分文件夹的内容,则可以在命令中指定路径或者切换至对应分支后再执行统计: ```bash git checkout main cloc path/to/subdirectory/ ``` #### 自制脚本统计代码量 如果不想依赖外部工具,也可以编写简单的 Shell 脚本来手动计算基本的代码量指标。下面是一个示例脚本片段,能够初步估算某些简单属性的数据: ```bash #!/bin/bash # 设置工作目录为当前所在位置 PROJECT_DIR=$(pwd) echo "正在分析 $PROJECT_DIR..." total_lines=$(find . -type f \( -name "*.java" -o -name "*.py" \) | xargs wc -l | awk 'END {print $1}') source_code_lines=$(grep -v "^$" $(find . -type f \( -name "*.java" -o -name "*.py" \)) | grep -vE "(^\s*//|^\s*/\*)" | wc -l) comment_lines=$(grep -E "(^\s*//|^\s*/\*)" $(find . -type f \( -name "*.java" -o -name "*.py" \)) | wc -l) blank_lines=$(( total_lines - source_code_lines )) percentage_source=$(awk "BEGIN { pc=100*$source_code_lines/$total_lines; i=int(pc); print (pc-i<0.5)?i:i+1 }") percentage_comments=$(awk "BEGIN { pc=100*$comment_lines/$total_lines; i=int(pc); print (pc-i<0.5)?i:i+1 }") percentage_blanks=$(awk "BEGIN { pc=100*$blank_lines/$total_lines; i=int(pc); print (pc-i<0.5)?i:i+1 }") printf "\n总计:\t%d 行\n" "$total_lines" printf "代码:\t%d 行 (%d%%)\n" "$source_code_lines" "$percentage_source" printf "注释:\t%d 行 (%d%%)\n" "$comment_lines" "$percentage_comments" printf "空格:\t%d 行 (%d%%)\n" "$blank_lines" "$percentage_blanks" exit 0 ``` 上述脚本适用于 Java 或 Python 文件扩展名的情况;实际应用时可能还需要调整正则表达式的匹配逻辑以适应更多编程语言特性。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值