1 from abc
import ABC
, abstractmethod
19 import xml
.dom
.minidom
33 # Use xdg module when it's less painful to have as a dependency
36 class XDG(types
.SimpleNamespace
):
41 XDG_CACHE_HOME
=os
.getenv(
43 os
.path
.expanduser('~/.cache')))
46 class VerificationError(Exception):
52 def __init__(self
) -> None:
55 def status(self
, s
: str) -> None:
56 print(s
, end
=' ', file=sys
.stderr
, flush
=True)
57 self
.line_length
+= 1 + len(s
) # Unicode??
60 def _color(s
: str, c
: int) -> str:
61 return '\033[%2dm%s\033[00m' % (c
, s
)
63 def result(self
, r
: bool) -> None:
64 message
, color
= {True: ('OK ', 92), False: ('FAIL', 91)}
[r
]
66 cols
= shutil
.get_terminal_size().columns
or 80
67 pad
= (cols
- (self
.line_length
+ length
)) % cols
68 print(' ' * pad
+ self
._color
(message
, color
), file=sys
.stderr
)
71 raise VerificationError()
73 def check(self
, s
: str, r
: bool) -> None:
81 Digest16
= NewType('Digest16', str)
82 Digest32
= NewType('Digest32', str)
85 class ChannelTableEntry(types
.SimpleNamespace
):
93 class AliasPin(NamedTuple
):
97 class GitPin(NamedTuple
):
102 class ChannelPin(NamedTuple
):
109 Pin
= Union
[AliasPin
, GitPin
, ChannelPin
]
112 class SearchPath(types
.SimpleNamespace
, ABC
):
115 def pin(self
, v
: Verification
) -> Pin
:
119 class AliasSearchPath(SearchPath
):
122 def pin(self
, v
: Verification
) -> AliasPin
:
123 assert not hasattr(self
, 'git_repo')
127 # (This lint-disable is for pylint bug https://github.com/PyCQA/pylint/issues/179
128 # which is fixed in pylint 2.5.)
129 class TarrableSearchPath(SearchPath
, ABC
): # pylint: disable=abstract-method
135 old_git_revision
: str
136 table
: Dict
[str, ChannelTableEntry
]
139 class GitSearchPath(TarrableSearchPath
):
140 def pin(self
, v
: Verification
) -> GitPin
:
141 if hasattr(self
, 'git_revision'):
142 self
.old_git_revision
= self
.git_revision
143 del self
.git_revision
146 return GitPin(release_name
=git_revision_name(v
, self
),
147 git_revision
=self
.git_revision
)
149 def fetch(self
, v
: Verification
, section
: str,
150 conf
: configparser
.SectionProxy
) -> str:
151 if 'git_revision' not in conf
or 'release_name' not in conf
:
153 'Cannot update unpinned channel "%s" (Run "pin" before "update")' %
156 release_name
=conf
['release_name'],
157 git_revision
=conf
['git_revision'])
159 ensure_git_rev_available(v
, self
, the_pin
)
160 return git_get_tarball(v
, self
, the_pin
)
163 class ChannelSearchPath(TarrableSearchPath
):
164 def pin(self
, v
: Verification
) -> ChannelPin
:
165 if hasattr(self
, 'git_revision'):
166 self
.old_git_revision
= self
.git_revision
167 del self
.git_revision
170 new_gitpin
= parse_channel(v
, self
)
171 fetch_resources(v
, self
, new_gitpin
)
172 ensure_git_rev_available(v
, self
, new_gitpin
)
173 check_channel_contents(v
, self
)
175 release_name
=self
.release_name
,
176 tarball_url
=self
.table
['nixexprs.tar.xz'].absolute_url
,
177 tarball_sha256
=self
.table
['nixexprs.tar.xz'].digest
,
178 git_revision
=self
.git_revision
)
180 # Lint TODO: Put tarball_url and tarball_sha256 in ChannelSearchPath
181 # pylint: disable=no-self-use
182 def fetch(self
, v
: Verification
, section
: str,
183 conf
: configparser
.SectionProxy
) -> str:
184 if 'git_repo' not in conf
or 'release_name' not in conf
:
186 'Cannot update unpinned channel "%s" (Run "pin" before "update")' %
189 return fetch_with_nix_prefetch_url(
190 v
, conf
['tarball_url'], Digest16(
191 conf
['tarball_sha256']))
194 def compare(a
: str, b
: str) -> Tuple
[List
[str], List
[str], List
[str]]:
196 def throw(error
: OSError) -> None:
199 def join(x
: str, y
: str) -> str:
200 return y
if x
== '.' else os
.path
.join(x
, y
)
202 def recursive_files(d
: str) -> Iterable
[str]:
203 all_files
: List
[str] = []
204 for path
, dirs
, files
in os
.walk(d
, onerror
=throw
):
205 rel
= os
.path
.relpath(path
, start
=d
)
206 all_files
.extend(join(rel
, f
) for f
in files
)
207 for dir_or_link
in dirs
:
208 if os
.path
.islink(join(path
, dir_or_link
)):
209 all_files
.append(join(rel
, dir_or_link
))
212 def exclude_dot_git(files
: Iterable
[str]) -> Iterable
[str]:
213 return (f
for f
in files
if not f
.startswith('.git/'))
215 files
= functools
.reduce(
218 recursive_files(x
))) for x
in [a
, b
]))
219 return filecmp
.cmpfiles(a
, b
, files
, shallow
=False)
222 def fetch(v
: Verification
, channel
: TarrableSearchPath
) -> None:
223 v
.status('Fetching channel')
224 request
= urllib
.request
.urlopen(channel
.channel_url
, timeout
=10)
225 channel
.channel_html
= request
.read()
226 channel
.forwarded_url
= request
.geturl()
227 v
.result(request
.status
== 200) # type: ignore # (for old mypy)
228 v
.check('Got forwarded', channel
.channel_url
!= channel
.forwarded_url
)
231 def parse_channel(v
: Verification
, channel
: TarrableSearchPath
) -> GitPin
:
232 v
.status('Parsing channel description as XML')
233 d
= xml
.dom
.minidom
.parseString(channel
.channel_html
)
236 v
.status('Extracting release name:')
237 title_name
= d
.getElementsByTagName(
238 'title')[0].firstChild
.nodeValue
.split()[2]
239 h1_name
= d
.getElementsByTagName('h1')[0].firstChild
.nodeValue
.split()[2]
241 v
.result(title_name
== h1_name
)
242 channel
.release_name
= title_name
244 v
.status('Extracting git commit:')
245 git_commit_node
= d
.getElementsByTagName('tt')[0]
246 channel
.git_revision
= git_commit_node
.firstChild
.nodeValue
247 v
.status(channel
.git_revision
)
249 v
.status('Verifying git commit label')
250 v
.result(git_commit_node
.previousSibling
.nodeValue
== 'Git commit ')
252 v
.status('Parsing table')
254 for row
in d
.getElementsByTagName('tr')[1:]:
255 name
= row
.childNodes
[0].firstChild
.firstChild
.nodeValue
256 url
= row
.childNodes
[0].firstChild
.getAttribute('href')
257 size
= int(row
.childNodes
[1].firstChild
.nodeValue
)
258 digest
= Digest16(row
.childNodes
[2].firstChild
.firstChild
.nodeValue
)
259 channel
.table
[name
] = ChannelTableEntry(
260 url
=url
, digest
=digest
, size
=size
)
262 return GitPin(release_name
=title_name
, git_revision
=channel
.git_revision
)
265 def digest_string(s
: bytes) -> Digest16
:
266 return Digest16(hashlib
.sha256(s
).hexdigest())
269 def digest_file(filename
: str) -> Digest16
:
270 hasher
= hashlib
.sha256()
271 with open(filename
, 'rb') as f
:
272 # pylint: disable=cell-var-from-loop
273 for block
in iter(lambda: f
.read(4096), b
''):
275 return Digest16(hasher
.hexdigest())
278 def to_Digest16(v
: Verification
, digest32
: Digest32
) -> Digest16
:
279 v
.status('Converting digest to base16')
280 process
= subprocess
.run(
281 ['nix', 'to-base16', '--type', 'sha256', digest32
], stdout
=subprocess
.PIPE
)
282 v
.result(process
.returncode
== 0)
283 return Digest16(process
.stdout
.decode().strip())
286 def to_Digest32(v
: Verification
, digest16
: Digest16
) -> Digest32
:
287 v
.status('Converting digest to base32')
288 process
= subprocess
.run(
289 ['nix', 'to-base32', '--type', 'sha256', digest16
], stdout
=subprocess
.PIPE
)
290 v
.result(process
.returncode
== 0)
291 return Digest32(process
.stdout
.decode().strip())
294 def fetch_with_nix_prefetch_url(
297 digest
: Digest16
) -> str:
298 v
.status('Fetching %s' % url
)
299 process
= subprocess
.run(
300 ['nix-prefetch-url', '--print-path', url
, digest
], stdout
=subprocess
.PIPE
)
301 v
.result(process
.returncode
== 0)
302 prefetch_digest
, path
, empty
= process
.stdout
.decode().split('\n')
304 v
.check("Verifying nix-prefetch-url's digest",
305 to_Digest16(v
, Digest32(prefetch_digest
)) == digest
)
306 v
.status("Verifying file digest")
307 file_digest
= digest_file(path
)
308 v
.result(file_digest
== digest
)
309 return path
# type: ignore # (for old mypy)
314 channel
: ChannelSearchPath
,
315 pin
: GitPin
) -> None:
316 for resource
in ['git-revision', 'nixexprs.tar.xz']:
317 fields
= channel
.table
[resource
]
318 fields
.absolute_url
= urllib
.parse
.urljoin(
319 channel
.forwarded_url
, fields
.url
)
320 fields
.file = fetch_with_nix_prefetch_url(
321 v
, fields
.absolute_url
, fields
.digest
)
322 v
.status('Verifying git commit on main page matches git commit in table')
325 channel
.table
['git-revision'].file).read(999) == pin
.git_revision
)
328 def git_cachedir(git_repo
: str) -> str:
332 digest_string(git_repo
.encode()))
335 def tarball_cache_file(channel
: TarrableSearchPath
) -> str:
340 (digest_string(channel
.git_repo
.encode()),
341 channel
.git_revision
,
342 channel
.release_name
))
345 def verify_git_ancestry(v
: Verification
, channel
: TarrableSearchPath
) -> None:
346 cachedir
= git_cachedir(channel
.git_repo
)
347 v
.status('Verifying rev is an ancestor of ref')
348 process
= subprocess
.run(['git',
353 channel
.git_revision
,
355 v
.result(process
.returncode
== 0)
357 if hasattr(channel
, 'old_git_revision'):
359 'Verifying rev is an ancestor of previous rev %s' %
360 channel
.old_git_revision
)
361 process
= subprocess
.run(['git',
366 channel
.old_git_revision
,
367 channel
.git_revision
])
368 v
.result(process
.returncode
== 0)
371 def git_fetch(v
: Verification
, channel
: TarrableSearchPath
) -> None:
372 # It would be nice if we could share the nix git cache, but as of the time
373 # of writing it is transitioning from gitv2 (deprecated) to gitv3 (not ready
374 # yet), and trying to straddle them both is too far into nix implementation
375 # details for my comfort. So we re-implement here half of nix.fetchGit.
378 cachedir
= git_cachedir(channel
.git_repo
)
379 if not os
.path
.exists(cachedir
):
380 v
.status("Initializing git repo")
381 process
= subprocess
.run(
382 ['git', 'init', '--bare', cachedir
])
383 v
.result(process
.returncode
== 0)
385 v
.status('Fetching ref "%s" from %s' % (channel
.git_ref
, channel
.git_repo
))
386 # We don't use --force here because we want to abort and freak out if forced
387 # updates are happening.
388 process
= subprocess
.run(['git',
393 '%s:%s' % (channel
.git_ref
,
395 v
.result(process
.returncode
== 0)
397 if hasattr(channel
, 'git_revision'):
398 v
.status('Verifying that fetch retrieved this rev')
399 process
= subprocess
.run(
400 ['git', '-C', cachedir
, 'cat-file', '-e', channel
.git_revision
])
401 v
.result(process
.returncode
== 0)
403 channel
.git_revision
= open(
408 channel
.git_ref
)).read(999).strip()
410 verify_git_ancestry(v
, channel
)
413 def ensure_git_rev_available(
415 channel
: TarrableSearchPath
,
416 pin
: GitPin
) -> None:
417 cachedir
= git_cachedir(channel
.git_repo
)
418 if os
.path
.exists(cachedir
):
419 v
.status('Checking if we already have this rev:')
420 process
= subprocess
.run(
421 ['git', '-C', cachedir
, 'cat-file', '-e', pin
.git_revision
])
422 if process
.returncode
== 0:
424 if process
.returncode
== 1:
426 v
.result(process
.returncode
== 0 or process
.returncode
== 1)
427 if process
.returncode
== 0:
428 verify_git_ancestry(v
, channel
)
430 git_fetch(v
, channel
)
433 def compare_tarball_and_git(
435 channel
: TarrableSearchPath
,
436 channel_contents
: str,
437 git_contents
: str) -> None:
438 v
.status('Comparing channel tarball with git checkout')
439 match
, mismatch
, errors
= compare(os
.path
.join(
440 channel_contents
, channel
.release_name
), git_contents
)
442 v
.check('%d files match' % len(match
), len(match
) > 0)
443 v
.check('%d files differ' % len(mismatch
), len(mismatch
) == 0)
451 for ee
in expected_errors
:
454 benign_errors
.append(ee
)
456 '%d unexpected incomparable files' %
460 '(%d of %d expected incomparable files)' %
462 len(expected_errors
)),
463 len(benign_errors
) == len(expected_errors
))
468 channel
: TarrableSearchPath
,
470 v
.status('Extracting tarball %s' %
471 channel
.table
['nixexprs.tar.xz'].file)
472 shutil
.unpack_archive(
473 channel
.table
['nixexprs.tar.xz'].file,
480 channel
: TarrableSearchPath
,
482 v
.status('Checking out corresponding git revision')
483 git
= subprocess
.Popen(['git',
485 git_cachedir(channel
.git_repo
),
487 channel
.git_revision
],
488 stdout
=subprocess
.PIPE
)
489 tar
= subprocess
.Popen(
490 ['tar', 'x', '-C', dest
, '-f', '-'], stdin
=git
.stdout
)
495 v
.result(git
.returncode
== 0 and tar
.returncode
== 0)
500 channel
: TarrableSearchPath
,
502 cache_file
= tarball_cache_file(channel
)
503 if os
.path
.exists(cache_file
):
504 cached_tarball
= open(cache_file
).read(9999)
505 if os
.path
.exists(cached_tarball
):
506 return cached_tarball
508 with tempfile
.TemporaryDirectory() as output_dir
:
509 output_filename
= os
.path
.join(
510 output_dir
, pin
.release_name
+ '.tar.xz')
511 with open(output_filename
, 'w') as output_file
:
513 'Generating tarball for git revision %s' %
515 git
= subprocess
.Popen(['git',
517 git_cachedir(channel
.git_repo
),
519 '--prefix=%s/' % pin
.release_name
,
521 stdout
=subprocess
.PIPE
)
522 xz
= subprocess
.Popen(['xz'], stdin
=git
.stdout
, stdout
=output_file
)
525 v
.result(git
.returncode
== 0 and xz
.returncode
== 0)
527 v
.status('Putting tarball in Nix store')
528 process
= subprocess
.run(
529 ['nix-store', '--add', output_filename
], stdout
=subprocess
.PIPE
)
530 v
.result(process
.returncode
== 0)
531 store_tarball
= process
.stdout
.decode().strip()
533 os
.makedirs(os
.path
.dirname(cache_file
), exist_ok
=True)
534 open(cache_file
, 'w').write(store_tarball
)
535 return store_tarball
# type: ignore # (for old mypy)
538 def check_channel_metadata(
540 channel
: TarrableSearchPath
,
541 channel_contents
: str) -> None:
542 v
.status('Verifying git commit in channel tarball')
547 channel
.release_name
,
548 '.git-revision')).read(999) == channel
.git_revision
)
551 'Verifying version-suffix is a suffix of release name %s:' %
552 channel
.release_name
)
553 version_suffix
= open(
556 channel
.release_name
,
557 '.version-suffix')).read(999)
558 v
.status(version_suffix
)
559 v
.result(channel
.release_name
.endswith(version_suffix
))
562 def check_channel_contents(
564 channel
: TarrableSearchPath
) -> None:
565 with tempfile
.TemporaryDirectory() as channel_contents
, \
566 tempfile
.TemporaryDirectory() as git_contents
:
568 extract_tarball(v
, channel
, channel_contents
)
569 check_channel_metadata(v
, channel
, channel_contents
)
571 git_checkout(v
, channel
, git_contents
)
573 compare_tarball_and_git(v
, channel
, channel_contents
, git_contents
)
575 v
.status('Removing temporary directories')
579 def git_revision_name(v
: Verification
, channel
: TarrableSearchPath
) -> str:
580 v
.status('Getting commit date')
581 process
= subprocess
.run(['git',
583 git_cachedir(channel
.git_repo
),
588 '--no-show-signature',
589 channel
.git_revision
],
590 stdout
=subprocess
.PIPE
)
591 v
.result(process
.returncode
== 0 and process
.stdout
!= b
'')
592 return '%s-%s' % (os
.path
.basename(channel
.git_repo
),
593 process
.stdout
.decode().strip())
596 def read_search_path(conf
: configparser
.SectionProxy
) -> SearchPath
:
597 mapping
: Mapping
[str, Type
[SearchPath
]] = {
598 'alias': AliasSearchPath
,
599 'channel': ChannelSearchPath
,
600 'git': GitSearchPath
,
602 return mapping
[conf
['type']](**dict(conf
.items()))
605 def read_config(filename
: str) -> configparser
.ConfigParser
:
606 config
= configparser
.ConfigParser()
607 config
.read_file(open(filename
), filename
)
611 def read_config_files(
612 filenames
: Iterable
[str]) -> Dict
[str, configparser
.SectionProxy
]:
613 merged_config
: Dict
[str, configparser
.SectionProxy
] = {}
614 for file in filenames
:
615 config
= read_config(file)
616 for section
in config
.sections():
617 if section
in merged_config
:
618 raise Exception('Duplicate channel "%s"' % section
)
619 merged_config
[section
] = config
[section
]
623 def pinCommand(args
: argparse
.Namespace
) -> None:
625 config
= read_config(args
.channels_file
)
626 for section
in config
.sections():
627 if args
.channels
and section
not in args
.channels
:
630 sp
= read_search_path(config
[section
])
632 config
[section
].update(sp
.pin(v
)._asdict
())
634 with open(args
.channels_file
, 'w') as configfile
:
635 config
.write(configfile
)
638 def updateCommand(args
: argparse
.Namespace
) -> None:
640 exprs
: Dict
[str, str] = {}
641 config
= read_config_files(args
.channels_file
)
642 for section
in config
:
643 sp
= read_search_path(config
[section
])
644 if isinstance(sp
, AliasSearchPath
):
645 assert 'git_repo' not in config
[section
]
647 tarball
= sp
.fetch(v
, section
, config
[section
])
649 'f: f { name = "%s"; channelName = "%%s"; src = builtins.storePath "%s"; }' %
650 (config
[section
]['release_name'], tarball
))
652 for section
in config
:
653 if 'alias_of' in config
[section
]:
654 exprs
[section
] = exprs
[str(config
[section
]['alias_of'])]
659 '/nix/var/nix/profiles/per-user/%s/channels' %
663 '<nix/unpack-channel.nix>',
665 '--from-expression'] + [exprs
[name
] % name
for name
in sorted(exprs
.keys())]
667 print(' '.join(map(shlex
.quote
, command
)))
669 v
.status('Installing channels with nix-env')
670 process
= subprocess
.run(command
)
671 v
.result(process
.returncode
== 0)
675 parser
= argparse
.ArgumentParser(prog
='pinch')
676 subparsers
= parser
.add_subparsers(dest
='mode', required
=True)
677 parser_pin
= subparsers
.add_parser('pin')
678 parser_pin
.add_argument('channels_file', type=str)
679 parser_pin
.add_argument('channels', type=str, nargs
='*')
680 parser_pin
.set_defaults(func
=pinCommand
)
681 parser_update
= subparsers
.add_parser('update')
682 parser_update
.add_argument('--dry-run', action
='store_true')
683 parser_update
.add_argument('channels_file', type=str, nargs
='+')
684 parser_update
.set_defaults(func
=updateCommand
)
685 args
= parser
.parse_args()
689 if __name__
== '__main__':