Debian Codegraph @

unittests/subprojectscommandtests.py

raw
1 # SPDX-License-Identifier: Apache-2.0
2 # Copyright 2016-2021 The Meson development team
3
4 import subprocess
5 import tempfile
6 import textwrap
7 import os
8 from pathlib import Path
9 import typing as T
10
11 from mesonbuild.mesonlib import (
12 version_compare, git, search_version
13 )
14
15
16
17 from .baseplatformtests import BasePlatformTests
18 from .helpers import *
19
20 class SubprojectsCommandTests(BasePlatformTests):
21 def setUp(self):
22 super().setUp()
23 self.root_dir = Path(self.builddir)
24
25 self.project_dir = self.root_dir / 'src'
26 self._create_project(self.project_dir)
27
28 self.subprojects_dir = self.project_dir / 'subprojects'
29 os.makedirs(str(self.subprojects_dir))
30 self.packagecache_dir = self.subprojects_dir / 'packagecache'
31 os.makedirs(str(self.packagecache_dir))
32
33 def _create_project(self, path, project_name='dummy'):
34 os.makedirs(str(path), exist_ok=True)
35 with open(str(path / 'meson.build'), 'w', encoding='utf-8') as f:
36 f.write(f"project('{project_name}')")
37
38 def _git(self, cmd, workdir):
39 return git(cmd, str(workdir), check=True)[1].strip()
40
41 def _git_config(self, workdir):
42 self._git(['config', 'user.name', 'Meson Test'], workdir)
43 self._git(['config', 'user.email', '[email protected]'], workdir)
44
45 def _git_remote(self, cmd, name):
46 return self._git(cmd, self.root_dir / name)
47
48 def _git_local(self, cmd, name):
49 return self._git(cmd, self.subprojects_dir / name)
50
51 def _git_local_branch(self, name):
52 # Same as `git branch --show-current` but compatible with older git version
53 branch = self._git_local(['rev-parse', '--abbrev-ref', 'HEAD'], name)
54 return branch if branch != 'HEAD' else ''
55
56 def _git_local_commit(self, name, ref='HEAD'):
57 return self._git_local(['rev-parse', ref], name)
58
59 def _git_remote_commit(self, name, ref='HEAD'):
60 return self._git_remote(['rev-parse', ref], name)
61
62 def _git_create_repo(self, path):
63 # If a user has git configuration init.defaultBranch set we want to override that
64 with tempfile.TemporaryDirectory() as d:
65 out = git(['--version'], str(d))[1]
66 if version_compare(search_version(out), '>= 2.28'):
67 extra_cmd = ['--initial-branch', 'master']
68 else:
69 extra_cmd = []
70
71 self._create_project(path)
72 self._git(['init'] + extra_cmd, path)
73 self._git_config(path)
74 self._git(['add', '.'], path)
75 self._git(['commit', '--no-gpg-sign', '-m', 'Initial commit'], path)
76
77 def _git_create_remote_repo(self, name):
78 self._git_create_repo(self.root_dir / name)
79
80 def _git_create_local_repo(self, name):
81 self._git_create_repo(self.subprojects_dir / name)
82
83 def _git_create_remote_commit(self, name, branch):
84 self._git_remote(['checkout', branch], name)
85 self._git_remote(['commit', '--no-gpg-sign', '--allow-empty', '-m', f'initial {branch} commit'], name)
86
87 def _git_create_remote_branch(self, name, branch):
88 self._git_remote(['checkout', '-b', branch], name)
89 self._git_remote(['commit', '--no-gpg-sign', '--allow-empty', '-m', f'initial {branch} commit'], name)
90
91 def _git_create_remote_tag(self, name, tag):
92 self._git_remote(['commit', '--no-gpg-sign', '--allow-empty', '-m', f'tag {tag} commit'], name)
93 self._git_remote(['tag', '--no-sign', tag], name)
94
95 def _wrap_create_git(self, name, revision='master', depth=None):
96 path = self.root_dir / name
97 with open(str((self.subprojects_dir / name).with_suffix('.wrap')), 'w', encoding='utf-8') as f:
98 if depth is None:
99 depth_line = ''
100 else:
101 depth_line = 'depth = {}'.format(depth)
102 f.write(textwrap.dedent(
103 '''
104 [wrap-git]
105 url={}
106 revision={}
107 {}
108 '''.format(os.path.abspath(str(path)), revision, depth_line)))
109
110 def _wrap_create_file(self, name, tarball='dummy.tar.gz'):
111 path = self.root_dir / tarball
112 with open(str((self.subprojects_dir / name).with_suffix('.wrap')), 'w', encoding='utf-8') as f:
113 f.write(textwrap.dedent(
114 f'''
115 [wrap-file]
116 source_url={os.path.abspath(str(path))}
117 source_filename={tarball}
118 '''))
119 Path(self.packagecache_dir / tarball).touch()
120
121 def _subprojects_cmd(self, args):
122 return self._run(self.meson_command + ['subprojects'] + args, workdir=str(self.project_dir))
123
124 def test_git_update(self):
125 subp_name = 'sub1'
126
127 # Create a fake remote git repository and a wrap file. Checks that
128 # "meson subprojects download" works.
129 self._git_create_remote_repo(subp_name)
130 self._wrap_create_git(subp_name)
131 self._subprojects_cmd(['download'])
132 self.assertPathExists(str(self.subprojects_dir / subp_name))
133 self._git_config(self.subprojects_dir / subp_name)
134
135 # Create a new remote branch and update the wrap file. Checks that
136 # "meson subprojects update --reset" checkout the new branch.
137 self._git_create_remote_branch(subp_name, 'newbranch')
138 self._wrap_create_git(subp_name, 'newbranch')
139 self._subprojects_cmd(['update', '--reset'])
140 self.assertEqual(self._git_local_branch(subp_name), 'newbranch')
141 self.assertEqual(self._git_local_commit(subp_name), self._git_remote_commit(subp_name, 'newbranch'))
142
143 # Update remote newbranch. Checks the new commit is pulled into existing
144 # local newbranch. Make sure it does not print spurious 'git stash' message.
145 self._git_create_remote_commit(subp_name, 'newbranch')
146 out = self._subprojects_cmd(['update', '--reset'])
147 self.assertNotIn('No local changes to save', out)
148 self.assertEqual(self._git_local_branch(subp_name), 'newbranch')
149 self.assertEqual(self._git_local_commit(subp_name), self._git_remote_commit(subp_name, 'newbranch'))
150
151 # Update remote newbranch and switch to another branch. Checks that it
152 # switch current branch to newbranch and pull latest commit.
153 self._git_local(['checkout', 'master'], subp_name)
154 self._git_create_remote_commit(subp_name, 'newbranch')
155 self._subprojects_cmd(['update', '--reset'])
156 self.assertEqual(self._git_local_branch(subp_name), 'newbranch')
157 self.assertEqual(self._git_local_commit(subp_name), self._git_remote_commit(subp_name, 'newbranch'))
158
159 # Stage some local changes then update. Checks that local changes got
160 # stashed.
161 self._create_project(self.subprojects_dir / subp_name, 'new_project_name')
162 self._git_local(['add', '.'], subp_name)
163 self._git_create_remote_commit(subp_name, 'newbranch')
164 self._subprojects_cmd(['update', '--reset'])
165 self.assertEqual(self._git_local_branch(subp_name), 'newbranch')
166 self.assertEqual(self._git_local_commit(subp_name), self._git_remote_commit(subp_name, 'newbranch'))
167 self.assertTrue(self._git_local(['stash', 'list'], subp_name))
168
169 # Untracked files need to be stashed too, or (re-)applying a patch
170 # creating one of those untracked files will fail.
171 untracked = self.subprojects_dir / subp_name / 'untracked.c'
172 untracked.write_bytes(b'int main(void) { return 0; }')
173 self._subprojects_cmd(['update', '--reset'])
174 self.assertTrue(self._git_local(['stash', 'list'], subp_name))
175 assert not untracked.exists()
176 # Ensure it was indeed stashed, and we can get it back.
177 self.assertTrue(self._git_local(['stash', 'pop'], subp_name))
178 assert untracked.exists()
179
180 # Create a new remote tag and update the wrap file. Checks that
181 # "meson subprojects update --reset" checkout the new tag in detached mode.
182 self._git_create_remote_tag(subp_name, 'newtag')
183 self._wrap_create_git(subp_name, 'newtag')
184 self._subprojects_cmd(['update', '--reset'])
185 self.assertEqual(self._git_local_branch(subp_name), '')
186 self.assertEqual(self._git_local_commit(subp_name), self._git_remote_commit(subp_name, 'newtag'))
187
188 # Create a new remote commit and update the wrap file with the commit id.
189 # Checks that "meson subprojects update --reset" checkout the new commit
190 # in detached mode.
191 self._git_local(['checkout', 'master'], subp_name)
192 self._git_create_remote_commit(subp_name, 'newbranch')
193 new_commit = self._git_remote(['rev-parse', 'HEAD'], subp_name)
194 self._wrap_create_git(subp_name, new_commit)
195 self._subprojects_cmd(['update', '--reset'])
196 self.assertEqual(self._git_local_branch(subp_name), '')
197 self.assertEqual(self._git_local_commit(subp_name), new_commit)
198
199 # Create a local project not in a git repository, then update it with
200 # a git wrap. Without --reset it should print error message and return
201 # failure. With --reset it should delete existing project and clone the
202 # new project.
203 subp_name = 'sub2'
204 self._create_project(self.subprojects_dir / subp_name)
205 self._git_create_remote_repo(subp_name)
206 self._wrap_create_git(subp_name)
207 with self.assertRaises(subprocess.CalledProcessError) as cm:
208 self._subprojects_cmd(['update'])
209 self.assertIn('Not a git repository', cm.exception.output)
210 self._subprojects_cmd(['update', '--reset'])
211 self.assertEqual(self._git_local_commit(subp_name), self._git_remote_commit(subp_name))
212
213 # Create a fake remote git repository and a wrap file targeting
214 # HEAD and depth = 1. Checks that "meson subprojects download" works.
215 subp_name = 'sub3'
216 self._git_create_remote_repo(subp_name)
217 self._wrap_create_git(subp_name, revision='head', depth='1')
218 self._subprojects_cmd(['download'])
219 self.assertPathExists(str(self.subprojects_dir / subp_name))
220 self._git_config(self.subprojects_dir / subp_name)
221
222 @skipIfNoExecutable('true')
223 def test_foreach(self):
224 self._create_project(self.subprojects_dir / 'sub_file')
225 self._wrap_create_file('sub_file')
226 self._git_create_local_repo('sub_git')
227 self._wrap_create_git('sub_git')
228 self._git_create_local_repo('sub_git_no_wrap')
229
230 def ran_in(s):
231 ret = []
232 prefix = 'Executing command in '
233 for l in s.splitlines():
234 if l.startswith(prefix):
235 ret.append(l[len(prefix):])
236 return sorted(ret)
237
238 dummy_cmd = ['true']
239 out = self._subprojects_cmd(['foreach'] + dummy_cmd)
240 self.assertEqual(ran_in(out), sorted(['subprojects/sub_file', 'subprojects/sub_git', 'subprojects/sub_git_no_wrap']))
241 out = self._subprojects_cmd(['foreach', '--types', 'git,file'] + dummy_cmd)
242 self.assertEqual(ran_in(out), sorted(['subprojects/sub_file', 'subprojects/sub_git']))
243 out = self._subprojects_cmd(['foreach', '--types', 'file'] + dummy_cmd)
244 self.assertEqual(ran_in(out), ['subprojects/sub_file'])
245 out = self._subprojects_cmd(['foreach', '--types', 'git'] + dummy_cmd)
246 self.assertEqual(ran_in(out), ['subprojects/sub_git'])
247
248 def test_purge(self):
249 self._create_project(self.subprojects_dir / 'sub_file')
250 self._wrap_create_file('sub_file')
251 self._git_create_local_repo('sub_git')
252 self._wrap_create_git('sub_git')
253
254 sub_file_subprojects_dir = self.subprojects_dir / 'sub_file' / 'subprojects'
255 sub_file_subprojects_dir.mkdir(exist_ok=True, parents=True)
256 real_dir = Path('sub_file') / 'subprojects' / 'real'
257
258 self._wrap_create_file(real_dir, tarball='dummy2.tar.gz')
259
260 with open(str((self.subprojects_dir / 'redirect').with_suffix('.wrap')), 'w', encoding='utf-8') as f:
261 f.write(textwrap.dedent(
262 f'''
263 [wrap-redirect]
264 filename = {real_dir}.wrap
265 '''))
266
267 def deleting(s: str) -> T.List[str]:
268 ret = []
269 prefix = 'Deleting '
270 for l in s.splitlines():
271 if l.startswith(prefix):
272 ret.append(l[len(prefix):])
273 return sorted(ret)
274
275 out = self._subprojects_cmd(['purge'])
276 self.assertEqual(deleting(out), sorted([
277 str(self.subprojects_dir / 'redirect.wrap'),
278 str(self.subprojects_dir / 'sub_file'),
279 str(self.subprojects_dir / 'sub_git'),
280 ]))
281 out = self._subprojects_cmd(['purge', '--include-cache'])
282 self.assertEqual(deleting(out), sorted([
283 str(self.subprojects_dir / 'sub_git'),
284 str(self.subprojects_dir / 'redirect.wrap'),
285 str(self.subprojects_dir / 'packagecache' / 'dummy.tar.gz'),
286 str(self.subprojects_dir / 'packagecache' / 'dummy2.tar.gz'),
287 str(self.subprojects_dir / 'sub_file'),
288 ]))
289 out = self._subprojects_cmd(['purge', '--include-cache', '--confirm'])
290 self.assertEqual(deleting(out), sorted([
291 str(self.subprojects_dir / 'sub_git'),
292 str(self.subprojects_dir / 'redirect.wrap'),
293 str(self.subprojects_dir / 'packagecache' / 'dummy.tar.gz'),
294 str(self.subprojects_dir / 'packagecache' / 'dummy2.tar.gz'),
295 str(self.subprojects_dir / 'sub_file'),
296 ]))
297 self.assertFalse(Path(self.subprojects_dir / 'packagecache' / 'dummy.tar.gz').exists())
298 self.assertFalse(Path(self.subprojects_dir / 'sub_file').exists())
299 self.assertFalse(Path(self.subprojects_dir / 'sub_git').exists())
300 self.assertFalse(Path(self.subprojects_dir / 'redirect.wrap').exists())