Debian Codegraph @

R/github.R

raw
1 #' Get the tags of GitHub releases of a repository
2 #'
3 #' Use the GitHub API ([github_api()]) to obtain the tags of the
4 #' releases.
5 #' @param repo The repository name of the form `user/repo`, e.g.,
6 #' `"yihui/xfun"`.
7 #' @param tag A tag as a character string. If provided, it will be returned if
8 #' the tag exists. If `tag = "latest"`, the tag of the latest release is
9 #' returned.
10 #' @param pattern A regular expression to match the tags.
11 #' @param use_jsonlite Whether to use \pkg{jsonlite} to parse the releases info.
12 #' @export
13 #' @return A character vector of (GIT) tags.
14 #' @examplesIf interactive()
15 #' xfun::github_releases('yihui/litedown')
16 #' xfun::github_releases('gohugoio/hugo', 'latest')
17 github_releases = function(
18 repo, tag = '', pattern = 'v[0-9.]+', use_jsonlite = loadable('jsonlite')
19 ) {
20 if (tag != '') return(github_releases2(repo, tag, pattern))
21
22 i = 1; v = character()
23 repeat {
24 res = github_api(
25 sprintf('/repos/%s/tags', repo), NULL, list(per_page = 100, page = i),
26 raw = !use_jsonlite
27 )
28 v2 = unlist(if (use_jsonlite) {
29 lapply(res, `[[`, 'name')
30 } else {
31 reg_match('\\{"name":"([^"]+)",', res)
32 })
33 if (length(v2) == 0) break
34 v = c(v, v2)
35 if (length(v2) < 100) break # not enough items for the next page
36 i = i + 1
37 }
38 grep(sprintf('^%s$', pattern), unique(v), value = TRUE)
39 }
40
41 # extract the matched elements in the n-th pair of () in the regex
42 reg_match = function(p, x, n = 1, ...) {
43 # TODO: gregexec was added in R 4.1.0; remove this workaround when we don't
44 # need to support R < 4.1.0
45 v = 'gregexec' %in% ls(baseenv())
46 m = (if (v) base::gregexec else base::gregexpr)(p, x, ...)
47 lapply(regmatches(x, m), function(x) {
48 if (v) x[n + 1, ] else gsub(p, paste0('\\', n), x)
49 })
50 }
51
52 # the fallback method to retrieve release tags (read HTML source)
53 github_releases2 = function(repo, tag = '', pattern = '[^"&]+') {
54 read = function() suppressWarnings(
55 read_utf8(sprintf('https://github.com/%s/releases/%s', repo, tag))
56 )
57 h = if (tag == '') read() else tryCatch(read(), error = function(e) '')
58 r = sprintf('^.*?%s/releases/tag/(%s)".*', repo, pattern)
59 v = unique(grep_sub(r, '\\1', h))
60 # if a tag is specified, use the 1st value because other tags may be mentioned
61 # in the current tag page
62 if (tag == '') v else head(v, 1)
63 }
64
65 #' @details `github_api()` is a wrapper function based on
66 #' `rest_api_raw()` to obtain data from the GitHub API:
67 #' <https://docs.github.com/en/rest>. You can provide a personal access
68 #' token (PAT) via the `token` argument, or via one of the environment
69 #' variables \var{GITHUB_PAT}, \var{GITHUB_TOKEN}, \var{GH_TOKEN}. A PAT
70 #' allows for a much higher rate limit in API calls. Without a token, you can
71 #' only make 60 calls in an hour.
72 #' @param raw Whether to return the raw response or parse the response with
73 #' \pkg{jsonlite}.
74 #' @rdname rest_api
75 #' @export
76 github_api = function(
77 endpoint, token = '', params = list(), headers = NULL, raw = !loadable('jsonlite')
78 ) {
79 token = c(token, github_token())
80 token = if (length(token <- token[token != ''])) token[1] else ''
81 names(token) = 'token'
82 error = TRUE
83 on.exit(if (error) github_token(NA, token))
84 res = rest_api_raw('https://api.github.com', endpoint, token, params, headers)
85 error = FALSE
86 if (raw) res else jsonlite::fromJSON(res, FALSE)
87 }
88
89 # the environment variables to check for a GitHub personal access token
90 github_envs = c('GITHUB_PAT', 'GITHUB_TOKEN', 'GH_TOKEN')
91
92 github_token = function(error = FALSE, token = unname(Sys.getenv(github_envs))) {
93 if (length(token <- token[token != ''])) return(token[1])
94 msg = c(
95 'You may need to save a GitHub personal access token in one of the ',
96 'environment variables: ', paste(github_envs, collapse = ', ')
97 )
98 if (is.na(error)) message(msg) else if (error) stop(msg)
99 ''
100 }
101
102 git = function(...) {
103 if (Sys.which('git') == '') stop('git is not available')
104 # R's HOME var is different from the system's HOME on Windows:
105 # https://github.com/yihui/crandalf/issues/24
106 if (is_windows()) {
107 env = set_envvar(c(HOME = Sys.getenv('USERPROFILE')))
108 on.exit(set_envvar(env), add = TRUE)
109 }
110 system3('git', ...)
111 }
112
113 git_co = function(args = NULL, ...) {
114 git(c('checkout', args), ...)
115 }
116
117 git_test_branch = function() {
118 if (length(d <- git(c('diff', '--name-only'), stdout = TRUE))) stop(
119 'The current branch has changes not stated for commit:\n',
120 paste(d, collapse = '\n')
121 )
122 }
123
124 # pull from the current branch if it is a git repository and has a current branch
125 git_pull_current <- function() {
126 is_repo = git(c('rev-parse', '--is-inside-work-tree'), stdout = FALSE, stderr = FALSE)
127 if (is_repo == 0) {
128 branch = git(c('branch', '--show-current'), stdout = TRUE)
129 if (length(branch) == 1 && branch != '') {
130 if (length(git('diff', stdout = TRUE))) {
131 git('stash'); on.exit(git(c('stash', 'pop')), add = TRUE)
132 }
133 git(c('pull', 'origin', branch))
134 }
135 }
136 }
137
138 gh = function(...) {
139 if (Sys.which('gh') == '') stop('GitHub CLI not found: https://cli.github.com')
140 system3('gh', ...)
141 }
142
143 gh_run = function(..., repo = NA) {
144 gh(c(if (!is.na(repo)) c('-R', repo), 'run', ...), stdout = TRUE)
145 }
146
147 # Detect the sprintf template for NEWS.md headers from existing content.
148 # Falls back to '# CHANGES IN %s VERSION %s' when format cannot be inferred.
149 news_tpl = function(news, pkg, ver) {
150 h1 = grep('^# ', news, value = TRUE)[1]
151 tpl = sub(sprintf('\\b%s\\b', ver), '%s', sub(sprintf('\\b%s\\b', pkg), '%s', h1))
152 if (grepl('%s.*%s', tpl)) tpl else '# CHANGES IN %s VERSION %s'
153 }
154
155 #' Perform post-CRAN-release routine tasks
156 #'
157 #' After a CRAN release is accepted, commit and tag the release, bump the
158 #' package version to the next patch dev version, prepend a new header to
159 #' \file{NEWS.md}, push to the remote repository, and create a GitHub release
160 #' with the news items of this version.
161 #'
162 #' The version number `X.Y` or `X.Y.0` is extracted from the `Version` field in
163 #' \file{DESCRIPTION}. For example, if the current version is `0.58` (or
164 #' `0.58.0`), the repo will be tagged as `v0.58` (or `v0.58.0`). The patch
165 #' version is then bumped to `0.58.1`, and a new header for the next minor
166 #' version `0.59` (or `0.59.0`) is prepended to \file{NEWS.md}.
167 #' @export
168 post_release = function() {
169 desc = read.dcf('DESCRIPTION')
170 pkg = desc[, 'Package']
171 ver = desc[, 'Version']
172
173 vers = release_versions(ver)
174 ver_next = vers$next_ver
175 ver_patch = vers$patch
176
177 # Step 1: commit all current changes (only if Version was modified)
178 ver_in_head = system3(
179 'git', c('show', 'HEAD:DESCRIPTION'), stdout = TRUE, stderr = FALSE
180 )
181 ver_in_head = trimws(grep_sub('^Version:\\s+(.*)', '\\1', ver_in_head))
182 if (!identical(ver_in_head, ver)) {
183 message('Committing CRAN release v', ver, ' ...')
184 git(c('commit', '-a', '-m', sprintf('CRAN release v%s', ver)))
185 }
186
187 # Step 2: tag
188 message('Tagging v', ver, ' ...')
189 git(c('tag', sprintf('v%s', ver)))
190
191 # Step 3: bump patch version and prepend NEWS.md
192 process_file('DESCRIPTION', function(x) {
193 ver_line = grep('^Version:\\s+', x)
194 x[ver_line] = sprintf('Version: %s', ver_patch)
195 x
196 })
197
198 news = trimws(read_utf8('NEWS.md'))
199 tpl = news_tpl(news, pkg, ver)
200 news_hdr = function(v) sprintf(tpl, pkg, v)
201
202 process_file('NEWS.md', function(x) c(paste0(news_hdr(ver_next), '\n\n'), x))
203
204 hdr = news_hdr(ver)
205 i = which(hdr == news)
206 if (length(i) == 0) stop('Cannot find the header "', hdr, '" in NEWS.md')
207
208 message('Committing the start of the next version ...')
209 git(c('commit', '-a', '-m', 'start the next version'))
210
211 # Step 4: push with tags
212 message('Pushing to remote ...')
213 git(c('push', '--tags', 'origin', 'HEAD'))
214
215 # Step 5: create GitHub release
216 github_token(TRUE)
217 j = grep('^# ', news)
218 j = j[j > i]
219 end = if (length(j) > 0) j[1] - 1 else length(news)
220 items = strip_blank(news[(i + 1):end])
221
222 f = tempfile()
223 writeLines(items, f)
224 on.exit(unlink(f), add = TRUE)
225
226 gh(c(
227 'release', 'create', sprintf('v%s', ver),
228 '--title', sprintf('%s %s', pkg, ver), '--notes-file', f)
229 )
230
231 invisible()
232 }