GitHub 推出新特性:展示单个文件所有者

2,929 阅读3分钟

本文由 yanglbme 原创,首发于公众号“Doocs开源社区”,禁止未授权转载。

近期,GitHub 推出一个新的特性 Show the CODEOWNERS for a single file,也即是在 GitHub 上展示某个特定文件的所有者,具体效果是怎样的呢?来,跟我一起看看吧。

激活新特性

目前,这个特性需要手动激活,操作很简单,只需要点击 GitHub 个人主页右上角的头像,选中 Feature Preview,并在 File Codeowners 弹框中点击 Enable 即可激活。

声明文件所有者

首先,你需要为你的 GitHub 项目添加一个名为 CODEOWNERS 文件,用于声明代码文件或文档文件对应的所有者。该文件可以放置在项目根目录或者 docs.github 目录下。

CODEOWNERS 文件内容的书写格式与 .gitignore 一致,GitHub 官方给出了一个细致的示例:

# This is a comment.
# Each line is a file pattern followed by one or more owners.

# These owners will be the default owners for everything in
# the repo. Unless a later match takes precedence,
# @global-owner1 and @global-owner2 will be requested for
# review when someone opens a pull request.
*       @global-owner1 @global-owner2

# Order is important; the last matching pattern takes the most
# precedence. When someone opens a pull request that only
# modifies JS files, only @js-owner and not the global
# owner(s) will be requested for a review.
*.js    @js-owner

# You can also use email addresses if you prefer. They'll be
# used to look up users just like we do for commit author
# emails.
*.go docs@example.com

# In this example, @doctocat owns any files in the build/logs
# directory at the root of the repository and any of its
# subdirectories.
/build/logs/ @doctocat

# The `docs/*` pattern will match files like
# `docs/getting-started.md` but not further nested files like
# `docs/build-app/troubleshooting.md`.
docs/*  docs@example.com

# In this example, @octocat owns any file in an apps directory
# anywhere in your repository.
apps/ @octocat

# In this example, @doctocat owns any file in the `/docs`
# directory in the root of your repository.
/docs/ @doctocat

依据上面 GitHub 官方示例,我简单为我的项目添加一个 CODEOWNERS 文件,放置在项目根目录下,文件内容如下:

*.py        @yanglbme
*.java      @yanglbme

docs/       @yanglbme
java/       @yanglbme
python/     @yanglbme

这样写其实就是告诉 GitHub,在本项目中,所有以 .py 或者 .java 后缀命名的文件,以及 docsjavapython 文件夹下的所有文件,都归 GitHub 用户 yanglbme 所有。

特性效果

点击 GitHub 项目 AutoComplete.java 文件,可以看到代码行数左侧有个 Owner 的 logo,光标移动到 logo,可以看到显示 You own this file,说明特性已生效。

当然,如果是非 Owner,会看到这个文件是显示 Owned by yanglbme

注意:无论是否是文件的 Owner,都能看到特性效果,前提是你需要先 Enable 激活才行。

不止于此

CODEOWNERS 文件其实还有另外的用途,就是用在代码的 Review 上。如果你是项目的所有者,那么你可以在 Settings 中设置分支保护,设置提交需要经过代码所有者 Code Owners 审查。

一旦有其他用户对你的文件做出修改,GitHub 便会自动发起 review 请求,请求文件 Owner 进行 review。

怎么样,是不是又 Get 了一个新技巧?关注我公众号“Doocs开源社区”,原创技术类文章第一时间推送。