vpac / src / build_repo.v
300 lines · 286 sloc · 12.31 KB · 3609dfbd82867dc1034a443f8f9ced529ddbbedd
Raw
1module main
2
3import crypto.sha256
4import vmakepkg
5import os
6
7fn C.mkdtemp(template &char) &char
8
9// A package is pulled from an arbitrary repo — a directory or a git url —
10// under the config's pkgbuild build dir, reviewed whole, built with the
11// system's makepkg and installed. A bash PKGBUILD runs makepkg exactly as the
12// original spells it; a PKGBUILD.lip gets a generated PKGBUILD whose phases
13// run as blip through this very binary.
14struct ConfigBuild {
15pub mut:
16 show_help bool @[long: help; short: h]
17 noconfirm bool @[long: noconfirm]
18 no_pkgbuild_confirm bool @[long: nopkgbuildconfirm]
19 query []string @[tail]
20}
21
22// generated_review is the review of a generated package: the source (the
23// lip or the .vsh) and the PKGBUILD plus .install it produced, so the user
24// agrees with everything makepkg will execute
25fn generated_review(package string, source_name string, source_text string, pkg_text string, install_name string, install_text string) ReviewEvent {
26 mut parts := [ReviewFile{
27 name: source_name
28 text: source_text
29 }, ReviewFile{
30 name: 'PKGBUILD'
31 text: pkg_text
32 generated: true
33 }]
34 if install_text != '' {
35 parts << ReviewFile{
36 name: install_name
37 text: install_text
38 generated: true
39 }
40 }
41 return ReviewEvent{
42 package: package
43 files: parts
44 }
45}
46
47// install_name_of reads the install file a generated PKGBUILD's head names,
48// spelled the way makepkg accepts one: '=' with spaces, quotes of either
49// kind; '' when it names none. it names a file beside the PKGBUILD: anything
50// that leaves the build dir already (an absolute path, a '..' climb) is not a
51// name this reader agrees to read. makepkg reads the line through bash, so a
52// name spelled with a variable or followed by a comment comes back as
53// written, naming no file here — review_the_rest covers that
54fn install_name_of(pkg_text string) !string {
55 mut name := ''
56 for line in pkg_text.split('\n') {
57 s := line.trim_space()
58 if !s.starts_with('install') {
59 continue
60 }
61 rest := s[7..].trim_space()
62 if !rest.starts_with('=') {
63 continue
64 }
65 val := rest[1..].trim_space().trim('\'"')
66 if val == '' {
67 continue
68 }
69 if val.starts_with('/') || val in ['.', '..'] || val.starts_with('../')
70 || val.contains('/../') || val.ends_with('/..') {
71 return error('b: the install file name "${val}" is not a plain name beside the PKGBUILD')
72 }
73 name = val
74 }
75 return name
76}
77
78// review_the_rest completes a generated PKGBUILD's review the way read_review
79// shows a plain one's: every .install file of the build dir, not only the
80// one install_name_of could resolve, and the build dir's files. the install
81// scriptlet runs as root at install time, so one makepkg packs under a name
82// this reader could not resolve must not get there unseen; such a name is
83// said, beside the files that may be it
84fn review_the_rest(mut review ReviewEvent, work_dir string, install_name string, resolved bool) ! {
85 mut names := os.ls(work_dir)!
86 names.sort()
87 on_view := review.files.map(it.name)
88 for f in names {
89 if f == '.git' {
90 continue
91 }
92 review.listing << f
93 if f.ends_with('.install') && f !in on_view && os.is_file('${work_dir}/${f}') {
94 review.files << ReviewFile{
95 name: f
96 text: os.read_file('${work_dir}/${f}')!
97 }
98 }
99 }
100 if install_name != '' && !resolved {
101 review.warnings << 'the install file "${install_name}" could not be resolved: every .install file is shown'
102 }
103}
104
105// pull_dir copies a local repo into its build dir as the building user: a
106// root-owned copy would stop makepkg from touching anything
107fn pull_dir(user string, src string, dst string) ! {
108 run_as_user(user, ['mkdir', '-p', os.dir(dst)])!
109 run_as_user(user, ['rm', '-rf', dst])!
110 run_as_user(user, ['cp', '-R', src, dst])!
111}
112
113// write_as_user lays a generated file (a PKGBUILD or a .install out of a
114// PKGBUILD.lip) into the work dir with the building user's ownership, the way
115// pull_dir gives the clone theirs: a file that belongs to the root process
116// would make makepkg's reads and the cleanups beside it trip. the text goes
117// into a read-only temp file of the root process, and install copies it over.
118// the temp file lives in a directory mkdtemp made for this one write: its
119// name cannot be guessed and nobody else may write in it, so no link can be
120// planted where the root process is about to write
121fn write_as_user(user string, path string, text string) ! {
122 template := os.join_path(os.temp_dir(), 'vpac.XXXXXX').clone()
123 if C.mkdtemp(&char(template.str)) == unsafe { nil } {
124 return error('could not make a temp dir: ${os.posix_get_error_msg(C.errno)}')
125 }
126 defer {
127 os.rmdir_all(template) or { went_on('remove the temp dir ${template}', err) }
128 }
129 // the building user reads the file through it, and writes nothing in it
130 os.chmod(template, 0o755)!
131 tmp := os.join_path(template, 'text')
132 os.write_file(tmp, text)!
133 os.chmod(tmp, 0o444)!
134 run_as_user(user, ['install', '-m', '644', tmp, path])!
135}
136
137// repo_name is the name a repo goes by: the last part of its path or url,
138// without a .git suffix. an scp-style git address (user@host:path) counts
139// from after the colon. empty when the target names nothing, like / or .
140fn repo_name(source string) string {
141 name := os.base(source.trim_right('/')).all_after_last(':').trim_string_right('.git')
142 return if name in ['', '.', '..', '/'] { '' } else { name }
143}
144
145// is_scp_remote reports scp-style git remotes (user@host:path): a colon that
146// comes before the first slash, where the colon of a host:port transfer url
147// or of a plain path with a colon in it would not. git itself accepts both
148// spellings of that, so the clone does not need the target spelled further
149fn is_scp_remote(target string) bool {
150 colon := target.index(':') or { return false }
151 // no slash: the colon splits the host from the path
152 slash := target.index('/') or { return true }
153 return colon < slash
154}
155
156// is_git_url reports whether git clone can fetch the target: a transfer url,
157// a name ending in .git, or an scp-style remote
158fn is_git_url(target string) bool {
159 return target.ends_with('.git') || target.contains('://') || is_scp_remote(target)
160}
161
162// repo_work_dir is where a b target is pulled and built, and the name the
163// repo goes by. the dir is the name and a hash of the source, so two repos
164// of one name (a fork, a mirror, two checkouts) and a pkgbuild package of
165// that name never share it, and the same repo always lands in the same dir.
166// a directory is keyed on its real path, so ./x and /abs/x are one repo
167fn repo_work_dir(user string, target string) !(string, string) {
168 source := if os.is_dir(target) { os.real_path(target) } else { target.trim_right('/') }
169 name := repo_name(source)
170 if name == '' {
171 return error('b: "${target}" names no repo to build')
172 }
173 return name, pkgbuild_build_dir(user, '${name}-${sha256.hexhash(source)[..8]}')!
174}
175
176// build_repo_target pulls one target, reviews it, builds and installs it.
177// a target is an existing directory (a checkout, taken as the repo stands)
178// or a git url to clone; bare names belong to the pkgbuild repos, which the
179// --pkgbuild installs already cover, so the error points there
180fn build_repo_target(config ConfigBuild, target string, mut ui TransUI) ! {
181 user := invoker_user()!
182 base, work_dir := repo_work_dir(user, target)!
183 // with --nopkgbuildconfirm nothing is asked, and the review is still
184 // shown: the record of what was built stays in the output
185 ask := !config.no_pkgbuild_confirm
186 ui.pause()
187 run_as_user(user, ['mkdir', '-p', os.dir(work_dir)])!
188 defer { ui.sync() }
189 if os.is_dir(target) {
190 pull_dir(user, target, work_dir)!
191 } else if is_git_url(target) {
192 // git is the one tool a clone cannot happen without: an absent one is
193 // said plainly, below user's name, before anything pulls
194 run_as_user(user, ['sh', '-c', 'git --version >/dev/null']) or {
195 return error('git is needed to clone ${target} as user ${user}, but it was not found (or failed): ${err.msg()}')
196 }
197 run_as_user(user, ['rm', '-rf', work_dir])!
198 run_as_user(user, ['git', 'clone', '--depth', '${pkgbuild_depth}', target, work_dir])!
199 } else {
200 return error('b: "${target}" is neither a directory nor a git url; pkgbuild repos are covered by vpac i --pkgbuild ${target}')
201 }
202 // makepkg builds either spelling; a bash PKGBUILD keeps the
203 // plain makepkg flow, the lip one generates its PKGBUILD through this
204 // binary's blip runner, and a PKGBUILD.vsh asks its own script to write
205 // the PKGBUILD through v
206 work_lip := '${work_dir}/PKGBUILD.lip'
207 mut work_vsh := '${work_dir}/PKGBUILD.vsh'
208 if os.exists(work_lip) {
209 bb := vmakepkg.lip_make(work_lip, os.executable())!
210 install_name := if bb.install != '' { '${bb.base}.install' } else { '' }
211 review := generated_review(base, os.base(work_lip), os.read_file(work_lip)!,
212 bb.text, install_name, bb.install)
213 show_review(review, '')
214 if ask && !ui.noyes('build and install ${base}?') {
215 return
216 }
217 write_as_user(user, '${work_dir}/PKGBUILD', bb.text)!
218 if bb.install != '' {
219 write_as_user(user, '${work_dir}/${bb.base}.install', bb.install)!
220 }
221 } else if os.exists(work_vsh) {
222 // v run compiles its temp to the script's own name inside the work
223 // dir, right on top of the PKGBUILD the script writes, so the script
224 // hides before anything runs
225 hsh := '${work_dir}/.vsh'
226 run_as_user(user, ['mv', work_vsh, hsh])!
227 work_vsh = hsh
228 // v lives where every tool of this project lives, and runuser's
229 // sanitized path may not carry it, so the script runs by full path
230 vbin := if os.getenv(env_v) != '' {
231 os.getenv(env_v)
232 } else {
233 os.find_abs_path_of_executable('v') or {
234 return error('the v compiler is not in the path; it is needed to run a PKGBUILD.vsh')
235 }
236 }
237 // the temp compile goes to the side of the PKGBUILD the script writes.
238 // the compiled runner is only for the generation: it is gone before
239 // the review lists the dir and before makepkg could pack it, whether
240 // the generation went through or not
241 generated := run_as_user(user, ['sh', '-c',
242 'export VPAC_VSH_PATH=${vmakepkg.shell_quote(work_vsh)}; cd ${vmakepkg.shell_quote(work_dir)} && ${vmakepkg.shell_quote(vbin)} -o ${vmakepkg.shell_quote('${work_dir}/.vshgen')} run ${vmakepkg.shell_quote(work_vsh)} generate'])
243 run_as_user(user, ['rm', '-f', '${work_dir}/.vshgen']) or {
244 warn('could not remove the generator ${work_dir}/.vshgen: ${err.msg()}')
245 }
246 generated!
247 if !os.exists('${work_dir}/PKGBUILD') {
248 return error('${work_vsh} wrote no PKGBUILD')
249 }
250 pkg_text := os.read_file('${work_dir}/PKGBUILD')!
251 install_name := install_name_of(pkg_text)!
252 install_path := '${work_dir}/${install_name}'
253 resolved := install_name != '' && os.is_file(install_path)
254 install_text := if resolved { os.read_file(install_path)! } else { '' }
255 mut review := generated_review(base, 'PKGBUILD.vsh', os.read_file(work_vsh)!, pkg_text,
256 install_name, install_text)
257 review_the_rest(mut review, work_dir, install_name, resolved)!
258 show_review(review, '')
259 if ask && !ui.noyes('build and install ${base}?') {
260 return
261 }
262 } else if os.exists('${work_dir}/PKGBUILD') {
263 show_review(read_review(base, work_dir)!, 'review ${base}')
264 if ask && !ui.noyes('build and install ${base}?') {
265 return
266 }
267 } else {
268 return error('${work_dir} holds neither PKGBUILD, PKGBUILD.lip nor PKGBUILD.vsh')
269 }
270 build_phase(base, 'start')
271 run_as_user(user, ['sh', '-c', makepkg_line(work_dir)])!
272 build_phase(base, 'done')
273 // everything makepkg produced goes into one install: a split package's
274 // set lands with one transaction, one listing and one go-ahead, the way
275 // the pkgbuild installs batch their own
276 archives := built_packages(user, work_dir)!
277 if archives.len == 0 {
278 return error('b: makepkg built nothing for ${base} that its --packagelist names')
279 }
280 install(ConfigInstall{
281 query: archives
282 noconfirm: config.noconfirm
283 })!
284}
285
286// build_repo is the mode's entry: every query is one repo to build
287fn build_repo(config ConfigBuild) ! {
288 need_query(config.query, 'repo (a directory or a git url)')!
289 // --noconfirm would take the build question's preset, which is no, and
290 // build nothing with a clean exit: the refusal says so first, as the
291 // pkgbuild installs' does
292 if config.noconfirm && !config.no_pkgbuild_confirm {
293 return error('a build is asked about: drop --noconfirm, or pass --nopkgbuildconfirm, to build ${config.query.join(', ')}')
294 }
295 mut ui := new_trans_ui(noconfirm: config.noconfirm)
296 defer { ui.stop() }
297 for target in config.query {
298 build_repo_target(config, target, mut ui)!
299 }
300}
301