1 from abc
import ABC
, abstractmethod
19 import xml
.dom
.minidom
29 # Use xdg module when it's less painful to have as a dependency
32 class XDG(types
.SimpleNamespace
):
37 XDG_CACHE_HOME
=os
.getenv(
39 os
.path
.expanduser('~/.cache')))
42 class VerificationError(Exception):
48 def __init__(self
) -> None:
51 def status(self
, s
: str) -> None:
52 print(s
, end
=' ', file=sys
.stderr
, flush
=True)
53 self
.line_length
+= 1 + len(s
) # Unicode??
56 def _color(s
: str, c
: int) -> str:
57 return '\033[%2dm%s\033[00m' % (c
, s
)
59 def result(self
, r
: bool) -> None:
60 message
, color
= {True: ('OK ', 92), False: ('FAIL', 91)}
[r
]
62 cols
= shutil
.get_terminal_size().columns
or 80
63 pad
= (cols
- (self
.line_length
+ length
)) % cols
64 print(' ' * pad
+ self
._color
(message
, color
), file=sys
.stderr
)
67 raise VerificationError()
69 def check(self
, s
: str, r
: bool) -> None:
77 Digest16
= NewType('Digest16', str)
78 Digest32
= NewType('Digest32', str)
81 class ChannelTableEntry(types
.SimpleNamespace
):
89 class SearchPath(types
.SimpleNamespace
, ABC
):
93 def pin(self
, v
: Verification
, conf
: configparser
.SectionProxy
) -> None:
97 class AliasSearchPath(SearchPath
):
100 def pin(self
, v
: Verification
, conf
: configparser
.SectionProxy
) -> None:
101 assert not hasattr(self
, 'git_repo')
104 class Channel(SearchPath
):
111 old_git_revision
: str
112 table
: Dict
[str, ChannelTableEntry
]
114 def pin(self
, v
: Verification
, conf
: configparser
.SectionProxy
) -> None:
115 if hasattr(self
, 'git_revision'):
116 self
.old_git_revision
= self
.git_revision
117 del self
.git_revision
119 if 'channel_url' in conf
:
121 conf
['release_name'] = self
.release_name
122 conf
['tarball_url'] = self
.table
['nixexprs.tar.xz'].absolute_url
123 conf
['tarball_sha256'] = self
.table
['nixexprs.tar.xz'].digest
126 conf
['release_name'] = git_revision_name(v
, self
)
127 conf
['git_revision'] = self
.git_revision
129 def fetch(self
, v
: Verification
, section
: str,
130 conf
: configparser
.SectionProxy
) -> str:
131 if 'git_repo' not in conf
or 'release_name' not in conf
:
133 'Cannot update unpinned channel "%s" (Run "pin" before "update")' %
136 if 'channel_url' in conf
:
137 return fetch_with_nix_prefetch_url(
138 v
, conf
['tarball_url'], Digest16(
139 conf
['tarball_sha256']))
141 ensure_git_rev_available(v
, self
)
142 return git_get_tarball(v
, self
)
145 def compare(a
: str, b
: str) -> Tuple
[List
[str], List
[str], List
[str]]:
147 def throw(error
: OSError) -> None:
150 def join(x
: str, y
: str) -> str:
151 return y
if x
== '.' else os
.path
.join(x
, y
)
153 def recursive_files(d
: str) -> Iterable
[str]:
154 all_files
: List
[str] = []
155 for path
, dirs
, files
in os
.walk(d
, onerror
=throw
):
156 rel
= os
.path
.relpath(path
, start
=d
)
157 all_files
.extend(join(rel
, f
) for f
in files
)
158 for dir_or_link
in dirs
:
159 if os
.path
.islink(join(path
, dir_or_link
)):
160 all_files
.append(join(rel
, dir_or_link
))
163 def exclude_dot_git(files
: Iterable
[str]) -> Iterable
[str]:
164 return (f
for f
in files
if not f
.startswith('.git/'))
166 files
= functools
.reduce(
169 recursive_files(x
))) for x
in [a
, b
]))
170 return filecmp
.cmpfiles(a
, b
, files
, shallow
=False)
173 def fetch(v
: Verification
, channel
: Channel
) -> None:
174 v
.status('Fetching channel')
175 request
= urllib
.request
.urlopen(channel
.channel_url
, timeout
=10)
176 channel
.channel_html
= request
.read()
177 channel
.forwarded_url
= request
.geturl()
178 v
.result(request
.status
== 200) # type: ignore # (for old mypy)
179 v
.check('Got forwarded', channel
.channel_url
!= channel
.forwarded_url
)
182 def parse_channel(v
: Verification
, channel
: Channel
) -> None:
183 v
.status('Parsing channel description as XML')
184 d
= xml
.dom
.minidom
.parseString(channel
.channel_html
)
187 v
.status('Extracting release name:')
188 title_name
= d
.getElementsByTagName(
189 'title')[0].firstChild
.nodeValue
.split()[2]
190 h1_name
= d
.getElementsByTagName('h1')[0].firstChild
.nodeValue
.split()[2]
192 v
.result(title_name
== h1_name
)
193 channel
.release_name
= title_name
195 v
.status('Extracting git commit:')
196 git_commit_node
= d
.getElementsByTagName('tt')[0]
197 channel
.git_revision
= git_commit_node
.firstChild
.nodeValue
198 v
.status(channel
.git_revision
)
200 v
.status('Verifying git commit label')
201 v
.result(git_commit_node
.previousSibling
.nodeValue
== 'Git commit ')
203 v
.status('Parsing table')
205 for row
in d
.getElementsByTagName('tr')[1:]:
206 name
= row
.childNodes
[0].firstChild
.firstChild
.nodeValue
207 url
= row
.childNodes
[0].firstChild
.getAttribute('href')
208 size
= int(row
.childNodes
[1].firstChild
.nodeValue
)
209 digest
= Digest16(row
.childNodes
[2].firstChild
.firstChild
.nodeValue
)
210 channel
.table
[name
] = ChannelTableEntry(
211 url
=url
, digest
=digest
, size
=size
)
215 def digest_string(s
: bytes) -> Digest16
:
216 return Digest16(hashlib
.sha256(s
).hexdigest())
219 def digest_file(filename
: str) -> Digest16
:
220 hasher
= hashlib
.sha256()
221 with open(filename
, 'rb') as f
:
222 # pylint: disable=cell-var-from-loop
223 for block
in iter(lambda: f
.read(4096), b
''):
225 return Digest16(hasher
.hexdigest())
228 def to_Digest16(v
: Verification
, digest32
: Digest32
) -> Digest16
:
229 v
.status('Converting digest to base16')
230 process
= subprocess
.run(
231 ['nix', 'to-base16', '--type', 'sha256', digest32
], stdout
=subprocess
.PIPE
)
232 v
.result(process
.returncode
== 0)
233 return Digest16(process
.stdout
.decode().strip())
236 def to_Digest32(v
: Verification
, digest16
: Digest16
) -> Digest32
:
237 v
.status('Converting digest to base32')
238 process
= subprocess
.run(
239 ['nix', 'to-base32', '--type', 'sha256', digest16
], stdout
=subprocess
.PIPE
)
240 v
.result(process
.returncode
== 0)
241 return Digest32(process
.stdout
.decode().strip())
244 def fetch_with_nix_prefetch_url(
247 digest
: Digest16
) -> str:
248 v
.status('Fetching %s' % url
)
249 process
= subprocess
.run(
250 ['nix-prefetch-url', '--print-path', url
, digest
], stdout
=subprocess
.PIPE
)
251 v
.result(process
.returncode
== 0)
252 prefetch_digest
, path
, empty
= process
.stdout
.decode().split('\n')
254 v
.check("Verifying nix-prefetch-url's digest",
255 to_Digest16(v
, Digest32(prefetch_digest
)) == digest
)
256 v
.status("Verifying file digest")
257 file_digest
= digest_file(path
)
258 v
.result(file_digest
== digest
)
259 return path
# type: ignore # (for old mypy)
262 def fetch_resources(v
: Verification
, channel
: Channel
) -> None:
263 for resource
in ['git-revision', 'nixexprs.tar.xz']:
264 fields
= channel
.table
[resource
]
265 fields
.absolute_url
= urllib
.parse
.urljoin(
266 channel
.forwarded_url
, fields
.url
)
267 fields
.file = fetch_with_nix_prefetch_url(
268 v
, fields
.absolute_url
, fields
.digest
)
269 v
.status('Verifying git commit on main page matches git commit in table')
272 channel
.table
['git-revision'].file).read(999) == channel
.git_revision
)
275 def git_cachedir(git_repo
: str) -> str:
279 digest_string(git_repo
.encode()))
282 def tarball_cache_file(channel
: Channel
) -> str:
287 (digest_string(channel
.git_repo
.encode()),
288 channel
.git_revision
,
289 channel
.release_name
))
292 def verify_git_ancestry(v
: Verification
, channel
: Channel
) -> None:
293 cachedir
= git_cachedir(channel
.git_repo
)
294 v
.status('Verifying rev is an ancestor of ref')
295 process
= subprocess
.run(['git',
300 channel
.git_revision
,
302 v
.result(process
.returncode
== 0)
304 if hasattr(channel
, 'old_git_revision'):
306 'Verifying rev is an ancestor of previous rev %s' %
307 channel
.old_git_revision
)
308 process
= subprocess
.run(['git',
313 channel
.old_git_revision
,
314 channel
.git_revision
])
315 v
.result(process
.returncode
== 0)
318 def git_fetch(v
: Verification
, channel
: Channel
) -> None:
319 # It would be nice if we could share the nix git cache, but as of the time
320 # of writing it is transitioning from gitv2 (deprecated) to gitv3 (not ready
321 # yet), and trying to straddle them both is too far into nix implementation
322 # details for my comfort. So we re-implement here half of nix.fetchGit.
325 cachedir
= git_cachedir(channel
.git_repo
)
326 if not os
.path
.exists(cachedir
):
327 v
.status("Initializing git repo")
328 process
= subprocess
.run(
329 ['git', 'init', '--bare', cachedir
])
330 v
.result(process
.returncode
== 0)
332 v
.status('Fetching ref "%s" from %s' % (channel
.git_ref
, channel
.git_repo
))
333 # We don't use --force here because we want to abort and freak out if forced
334 # updates are happening.
335 process
= subprocess
.run(['git',
340 '%s:%s' % (channel
.git_ref
,
342 v
.result(process
.returncode
== 0)
344 if hasattr(channel
, 'git_revision'):
345 v
.status('Verifying that fetch retrieved this rev')
346 process
= subprocess
.run(
347 ['git', '-C', cachedir
, 'cat-file', '-e', channel
.git_revision
])
348 v
.result(process
.returncode
== 0)
350 channel
.git_revision
= open(
355 channel
.git_ref
)).read(999).strip()
357 verify_git_ancestry(v
, channel
)
360 def ensure_git_rev_available(v
: Verification
, channel
: Channel
) -> None:
361 cachedir
= git_cachedir(channel
.git_repo
)
362 if os
.path
.exists(cachedir
):
363 v
.status('Checking if we already have this rev:')
364 process
= subprocess
.run(
365 ['git', '-C', cachedir
, 'cat-file', '-e', channel
.git_revision
])
366 if process
.returncode
== 0:
368 if process
.returncode
== 1:
370 v
.result(process
.returncode
== 0 or process
.returncode
== 1)
371 if process
.returncode
== 0:
372 verify_git_ancestry(v
, channel
)
374 git_fetch(v
, channel
)
377 def compare_tarball_and_git(
380 channel_contents
: str,
381 git_contents
: str) -> None:
382 v
.status('Comparing channel tarball with git checkout')
383 match
, mismatch
, errors
= compare(os
.path
.join(
384 channel_contents
, channel
.release_name
), git_contents
)
386 v
.check('%d files match' % len(match
), len(match
) > 0)
387 v
.check('%d files differ' % len(mismatch
), len(mismatch
) == 0)
395 for ee
in expected_errors
:
398 benign_errors
.append(ee
)
400 '%d unexpected incomparable files' %
404 '(%d of %d expected incomparable files)' %
406 len(expected_errors
)),
407 len(benign_errors
) == len(expected_errors
))
410 def extract_tarball(v
: Verification
, channel
: Channel
, dest
: str) -> None:
411 v
.status('Extracting tarball %s' %
412 channel
.table
['nixexprs.tar.xz'].file)
413 shutil
.unpack_archive(
414 channel
.table
['nixexprs.tar.xz'].file,
419 def git_checkout(v
: Verification
, channel
: Channel
, dest
: str) -> None:
420 v
.status('Checking out corresponding git revision')
421 git
= subprocess
.Popen(['git',
423 git_cachedir(channel
.git_repo
),
425 channel
.git_revision
],
426 stdout
=subprocess
.PIPE
)
427 tar
= subprocess
.Popen(
428 ['tar', 'x', '-C', dest
, '-f', '-'], stdin
=git
.stdout
)
433 v
.result(git
.returncode
== 0 and tar
.returncode
== 0)
436 def git_get_tarball(v
: Verification
, channel
: Channel
) -> str:
437 cache_file
= tarball_cache_file(channel
)
438 if os
.path
.exists(cache_file
):
439 cached_tarball
= open(cache_file
).read(9999)
440 if os
.path
.exists(cached_tarball
):
441 return cached_tarball
443 with tempfile
.TemporaryDirectory() as output_dir
:
444 output_filename
= os
.path
.join(
445 output_dir
, channel
.release_name
+ '.tar.xz')
446 with open(output_filename
, 'w') as output_file
:
448 'Generating tarball for git revision %s' %
449 channel
.git_revision
)
450 git
= subprocess
.Popen(['git',
452 git_cachedir(channel
.git_repo
),
454 '--prefix=%s/' % channel
.release_name
,
455 channel
.git_revision
],
456 stdout
=subprocess
.PIPE
)
457 xz
= subprocess
.Popen(['xz'], stdin
=git
.stdout
, stdout
=output_file
)
460 v
.result(git
.returncode
== 0 and xz
.returncode
== 0)
462 v
.status('Putting tarball in Nix store')
463 process
= subprocess
.run(
464 ['nix-store', '--add', output_filename
], stdout
=subprocess
.PIPE
)
465 v
.result(process
.returncode
== 0)
466 store_tarball
= process
.stdout
.decode().strip()
468 os
.makedirs(os
.path
.dirname(cache_file
), exist_ok
=True)
469 open(cache_file
, 'w').write(store_tarball
)
470 return store_tarball
# type: ignore # (for old mypy)
473 def check_channel_metadata(
476 channel_contents
: str) -> None:
477 v
.status('Verifying git commit in channel tarball')
482 channel
.release_name
,
483 '.git-revision')).read(999) == channel
.git_revision
)
486 'Verifying version-suffix is a suffix of release name %s:' %
487 channel
.release_name
)
488 version_suffix
= open(
491 channel
.release_name
,
492 '.version-suffix')).read(999)
493 v
.status(version_suffix
)
494 v
.result(channel
.release_name
.endswith(version_suffix
))
497 def check_channel_contents(v
: Verification
, channel
: Channel
) -> None:
498 with tempfile
.TemporaryDirectory() as channel_contents
, \
499 tempfile
.TemporaryDirectory() as git_contents
:
501 extract_tarball(v
, channel
, channel_contents
)
502 check_channel_metadata(v
, channel
, channel_contents
)
504 git_checkout(v
, channel
, git_contents
)
506 compare_tarball_and_git(v
, channel
, channel_contents
, git_contents
)
508 v
.status('Removing temporary directories')
512 def pin_channel(v
: Verification
, channel
: Channel
) -> None:
514 parse_channel(v
, channel
)
515 fetch_resources(v
, channel
)
516 ensure_git_rev_available(v
, channel
)
517 check_channel_contents(v
, channel
)
520 def git_revision_name(v
: Verification
, channel
: Channel
) -> str:
521 v
.status('Getting commit date')
522 process
= subprocess
.run(['git',
524 git_cachedir(channel
.git_repo
),
529 '--no-show-signature',
530 channel
.git_revision
],
531 stdout
=subprocess
.PIPE
)
532 v
.result(process
.returncode
== 0 and process
.stdout
!= b
'')
533 return '%s-%s' % (os
.path
.basename(channel
.git_repo
),
534 process
.stdout
.decode().strip())
537 def read_search_path(conf
: configparser
.SectionProxy
) -> SearchPath
:
538 if 'alias_of' in conf
:
539 return AliasSearchPath(**dict(conf
.items()))
540 return Channel(**dict(conf
.items()))
543 def read_config(filename
: str) -> configparser
.ConfigParser
:
544 config
= configparser
.ConfigParser()
545 config
.read_file(open(filename
), filename
)
549 def read_config_files(
550 filenames
: Iterable
[str]) -> Dict
[str, configparser
.SectionProxy
]:
551 merged_config
: Dict
[str, configparser
.SectionProxy
] = {}
552 for file in filenames
:
553 config
= read_config(file)
554 for section
in config
.sections():
555 if section
in merged_config
:
556 raise Exception('Duplicate channel "%s"' % section
)
557 merged_config
[section
] = config
[section
]
561 def pin(args
: argparse
.Namespace
) -> None:
563 config
= read_config(args
.channels_file
)
564 for section
in config
.sections():
565 if args
.channels
and section
not in args
.channels
:
568 sp
= read_search_path(config
[section
])
570 sp
.pin(v
, config
[section
])
572 with open(args
.channels_file
, 'w') as configfile
:
573 config
.write(configfile
)
576 def update(args
: argparse
.Namespace
) -> None:
578 exprs
: Dict
[str, str] = {}
579 config
= read_config_files(args
.channels_file
)
580 for section
in config
:
581 if 'alias_of' in config
[section
]:
582 assert 'git_repo' not in config
[section
]
584 sp
= read_search_path(config
[section
])
585 tarball
= sp
.fetch(v
, section
, config
[section
])
587 'f: f { name = "%s"; channelName = "%%s"; src = builtins.storePath "%s"; }' %
588 (config
[section
]['release_name'], tarball
))
590 for section
in config
:
591 if 'alias_of' in config
[section
]:
592 exprs
[section
] = exprs
[str(config
[section
]['alias_of'])]
597 '/nix/var/nix/profiles/per-user/%s/channels' %
601 '<nix/unpack-channel.nix>',
603 '--from-expression'] + [exprs
[name
] % name
for name
in sorted(exprs
.keys())]
605 print(' '.join(map(shlex
.quote
, command
)))
607 v
.status('Installing channels with nix-env')
608 process
= subprocess
.run(command
)
609 v
.result(process
.returncode
== 0)
613 parser
= argparse
.ArgumentParser(prog
='pinch')
614 subparsers
= parser
.add_subparsers(dest
='mode', required
=True)
615 parser_pin
= subparsers
.add_parser('pin')
616 parser_pin
.add_argument('channels_file', type=str)
617 parser_pin
.add_argument('channels', type=str, nargs
='*')
618 parser_pin
.set_defaults(func
=pin
)
619 parser_update
= subparsers
.add_parser('update')
620 parser_update
.add_argument('--dry-run', action
='store_true')
621 parser_update
.add_argument('channels_file', type=str, nargs
='+')
622 parser_update
.set_defaults(func
=update
)
623 args
= parser
.parse_args()
627 if __name__
== '__main__':