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 # (This lint-disable is for pylint bug https://github.com/PyCQA/pylint/issues/179
105 # which is fixed in pylint 2.5.)
106 class TarrableSearchPath(SearchPath
, ABC
): # pylint: disable=abstract-method
113 old_git_revision
: str
114 table
: Dict
[str, ChannelTableEntry
]
116 def fetch(self
, v
: Verification
, section
: str,
117 conf
: configparser
.SectionProxy
) -> str:
118 if 'git_repo' not in conf
or 'release_name' not in conf
:
120 'Cannot update unpinned channel "%s" (Run "pin" before "update")' %
123 if 'channel_url' in conf
:
124 return fetch_with_nix_prefetch_url(
125 v
, conf
['tarball_url'], Digest16(
126 conf
['tarball_sha256']))
128 ensure_git_rev_available(v
, self
)
129 return git_get_tarball(v
, self
)
132 class GitSearchPath(TarrableSearchPath
):
133 def pin(self
, v
: Verification
, conf
: configparser
.SectionProxy
) -> None:
134 if hasattr(self
, 'git_revision'):
135 self
.old_git_revision
= self
.git_revision
136 del self
.git_revision
139 conf
['release_name'] = git_revision_name(v
, self
)
140 conf
['git_revision'] = self
.git_revision
143 class ChannelSearchPath(TarrableSearchPath
):
144 def pin(self
, v
: Verification
, conf
: configparser
.SectionProxy
) -> None:
145 if hasattr(self
, 'git_revision'):
146 self
.old_git_revision
= self
.git_revision
147 del self
.git_revision
150 conf
['release_name'] = self
.release_name
151 conf
['tarball_url'] = self
.table
['nixexprs.tar.xz'].absolute_url
152 conf
['tarball_sha256'] = self
.table
['nixexprs.tar.xz'].digest
153 conf
['git_revision'] = self
.git_revision
156 def compare(a
: str, b
: str) -> Tuple
[List
[str], List
[str], List
[str]]:
158 def throw(error
: OSError) -> None:
161 def join(x
: str, y
: str) -> str:
162 return y
if x
== '.' else os
.path
.join(x
, y
)
164 def recursive_files(d
: str) -> Iterable
[str]:
165 all_files
: List
[str] = []
166 for path
, dirs
, files
in os
.walk(d
, onerror
=throw
):
167 rel
= os
.path
.relpath(path
, start
=d
)
168 all_files
.extend(join(rel
, f
) for f
in files
)
169 for dir_or_link
in dirs
:
170 if os
.path
.islink(join(path
, dir_or_link
)):
171 all_files
.append(join(rel
, dir_or_link
))
174 def exclude_dot_git(files
: Iterable
[str]) -> Iterable
[str]:
175 return (f
for f
in files
if not f
.startswith('.git/'))
177 files
= functools
.reduce(
180 recursive_files(x
))) for x
in [a
, b
]))
181 return filecmp
.cmpfiles(a
, b
, files
, shallow
=False)
184 def fetch(v
: Verification
, channel
: TarrableSearchPath
) -> None:
185 v
.status('Fetching channel')
186 request
= urllib
.request
.urlopen(channel
.channel_url
, timeout
=10)
187 channel
.channel_html
= request
.read()
188 channel
.forwarded_url
= request
.geturl()
189 v
.result(request
.status
== 200) # type: ignore # (for old mypy)
190 v
.check('Got forwarded', channel
.channel_url
!= channel
.forwarded_url
)
193 def parse_channel(v
: Verification
, channel
: TarrableSearchPath
) -> None:
194 v
.status('Parsing channel description as XML')
195 d
= xml
.dom
.minidom
.parseString(channel
.channel_html
)
198 v
.status('Extracting release name:')
199 title_name
= d
.getElementsByTagName(
200 'title')[0].firstChild
.nodeValue
.split()[2]
201 h1_name
= d
.getElementsByTagName('h1')[0].firstChild
.nodeValue
.split()[2]
203 v
.result(title_name
== h1_name
)
204 channel
.release_name
= title_name
206 v
.status('Extracting git commit:')
207 git_commit_node
= d
.getElementsByTagName('tt')[0]
208 channel
.git_revision
= git_commit_node
.firstChild
.nodeValue
209 v
.status(channel
.git_revision
)
211 v
.status('Verifying git commit label')
212 v
.result(git_commit_node
.previousSibling
.nodeValue
== 'Git commit ')
214 v
.status('Parsing table')
216 for row
in d
.getElementsByTagName('tr')[1:]:
217 name
= row
.childNodes
[0].firstChild
.firstChild
.nodeValue
218 url
= row
.childNodes
[0].firstChild
.getAttribute('href')
219 size
= int(row
.childNodes
[1].firstChild
.nodeValue
)
220 digest
= Digest16(row
.childNodes
[2].firstChild
.firstChild
.nodeValue
)
221 channel
.table
[name
] = ChannelTableEntry(
222 url
=url
, digest
=digest
, size
=size
)
226 def digest_string(s
: bytes) -> Digest16
:
227 return Digest16(hashlib
.sha256(s
).hexdigest())
230 def digest_file(filename
: str) -> Digest16
:
231 hasher
= hashlib
.sha256()
232 with open(filename
, 'rb') as f
:
233 # pylint: disable=cell-var-from-loop
234 for block
in iter(lambda: f
.read(4096), b
''):
236 return Digest16(hasher
.hexdigest())
239 def to_Digest16(v
: Verification
, digest32
: Digest32
) -> Digest16
:
240 v
.status('Converting digest to base16')
241 process
= subprocess
.run(
242 ['nix', 'to-base16', '--type', 'sha256', digest32
], stdout
=subprocess
.PIPE
)
243 v
.result(process
.returncode
== 0)
244 return Digest16(process
.stdout
.decode().strip())
247 def to_Digest32(v
: Verification
, digest16
: Digest16
) -> Digest32
:
248 v
.status('Converting digest to base32')
249 process
= subprocess
.run(
250 ['nix', 'to-base32', '--type', 'sha256', digest16
], stdout
=subprocess
.PIPE
)
251 v
.result(process
.returncode
== 0)
252 return Digest32(process
.stdout
.decode().strip())
255 def fetch_with_nix_prefetch_url(
258 digest
: Digest16
) -> str:
259 v
.status('Fetching %s' % url
)
260 process
= subprocess
.run(
261 ['nix-prefetch-url', '--print-path', url
, digest
], stdout
=subprocess
.PIPE
)
262 v
.result(process
.returncode
== 0)
263 prefetch_digest
, path
, empty
= process
.stdout
.decode().split('\n')
265 v
.check("Verifying nix-prefetch-url's digest",
266 to_Digest16(v
, Digest32(prefetch_digest
)) == digest
)
267 v
.status("Verifying file digest")
268 file_digest
= digest_file(path
)
269 v
.result(file_digest
== digest
)
270 return path
# type: ignore # (for old mypy)
273 def fetch_resources(v
: Verification
, channel
: TarrableSearchPath
) -> None:
274 for resource
in ['git-revision', 'nixexprs.tar.xz']:
275 fields
= channel
.table
[resource
]
276 fields
.absolute_url
= urllib
.parse
.urljoin(
277 channel
.forwarded_url
, fields
.url
)
278 fields
.file = fetch_with_nix_prefetch_url(
279 v
, fields
.absolute_url
, fields
.digest
)
280 v
.status('Verifying git commit on main page matches git commit in table')
283 channel
.table
['git-revision'].file).read(999) == channel
.git_revision
)
286 def git_cachedir(git_repo
: str) -> str:
290 digest_string(git_repo
.encode()))
293 def tarball_cache_file(channel
: TarrableSearchPath
) -> str:
298 (digest_string(channel
.git_repo
.encode()),
299 channel
.git_revision
,
300 channel
.release_name
))
303 def verify_git_ancestry(v
: Verification
, channel
: TarrableSearchPath
) -> None:
304 cachedir
= git_cachedir(channel
.git_repo
)
305 v
.status('Verifying rev is an ancestor of ref')
306 process
= subprocess
.run(['git',
311 channel
.git_revision
,
313 v
.result(process
.returncode
== 0)
315 if hasattr(channel
, 'old_git_revision'):
317 'Verifying rev is an ancestor of previous rev %s' %
318 channel
.old_git_revision
)
319 process
= subprocess
.run(['git',
324 channel
.old_git_revision
,
325 channel
.git_revision
])
326 v
.result(process
.returncode
== 0)
329 def git_fetch(v
: Verification
, channel
: TarrableSearchPath
) -> None:
330 # It would be nice if we could share the nix git cache, but as of the time
331 # of writing it is transitioning from gitv2 (deprecated) to gitv3 (not ready
332 # yet), and trying to straddle them both is too far into nix implementation
333 # details for my comfort. So we re-implement here half of nix.fetchGit.
336 cachedir
= git_cachedir(channel
.git_repo
)
337 if not os
.path
.exists(cachedir
):
338 v
.status("Initializing git repo")
339 process
= subprocess
.run(
340 ['git', 'init', '--bare', cachedir
])
341 v
.result(process
.returncode
== 0)
343 v
.status('Fetching ref "%s" from %s' % (channel
.git_ref
, channel
.git_repo
))
344 # We don't use --force here because we want to abort and freak out if forced
345 # updates are happening.
346 process
= subprocess
.run(['git',
351 '%s:%s' % (channel
.git_ref
,
353 v
.result(process
.returncode
== 0)
355 if hasattr(channel
, 'git_revision'):
356 v
.status('Verifying that fetch retrieved this rev')
357 process
= subprocess
.run(
358 ['git', '-C', cachedir
, 'cat-file', '-e', channel
.git_revision
])
359 v
.result(process
.returncode
== 0)
361 channel
.git_revision
= open(
366 channel
.git_ref
)).read(999).strip()
368 verify_git_ancestry(v
, channel
)
371 def ensure_git_rev_available(
373 channel
: TarrableSearchPath
) -> None:
374 cachedir
= git_cachedir(channel
.git_repo
)
375 if os
.path
.exists(cachedir
):
376 v
.status('Checking if we already have this rev:')
377 process
= subprocess
.run(
378 ['git', '-C', cachedir
, 'cat-file', '-e', channel
.git_revision
])
379 if process
.returncode
== 0:
381 if process
.returncode
== 1:
383 v
.result(process
.returncode
== 0 or process
.returncode
== 1)
384 if process
.returncode
== 0:
385 verify_git_ancestry(v
, channel
)
387 git_fetch(v
, channel
)
390 def compare_tarball_and_git(
392 channel
: TarrableSearchPath
,
393 channel_contents
: str,
394 git_contents
: str) -> None:
395 v
.status('Comparing channel tarball with git checkout')
396 match
, mismatch
, errors
= compare(os
.path
.join(
397 channel_contents
, channel
.release_name
), git_contents
)
399 v
.check('%d files match' % len(match
), len(match
) > 0)
400 v
.check('%d files differ' % len(mismatch
), len(mismatch
) == 0)
408 for ee
in expected_errors
:
411 benign_errors
.append(ee
)
413 '%d unexpected incomparable files' %
417 '(%d of %d expected incomparable files)' %
419 len(expected_errors
)),
420 len(benign_errors
) == len(expected_errors
))
425 channel
: TarrableSearchPath
,
427 v
.status('Extracting tarball %s' %
428 channel
.table
['nixexprs.tar.xz'].file)
429 shutil
.unpack_archive(
430 channel
.table
['nixexprs.tar.xz'].file,
437 channel
: TarrableSearchPath
,
439 v
.status('Checking out corresponding git revision')
440 git
= subprocess
.Popen(['git',
442 git_cachedir(channel
.git_repo
),
444 channel
.git_revision
],
445 stdout
=subprocess
.PIPE
)
446 tar
= subprocess
.Popen(
447 ['tar', 'x', '-C', dest
, '-f', '-'], stdin
=git
.stdout
)
452 v
.result(git
.returncode
== 0 and tar
.returncode
== 0)
455 def git_get_tarball(v
: Verification
, channel
: TarrableSearchPath
) -> str:
456 cache_file
= tarball_cache_file(channel
)
457 if os
.path
.exists(cache_file
):
458 cached_tarball
= open(cache_file
).read(9999)
459 if os
.path
.exists(cached_tarball
):
460 return cached_tarball
462 with tempfile
.TemporaryDirectory() as output_dir
:
463 output_filename
= os
.path
.join(
464 output_dir
, channel
.release_name
+ '.tar.xz')
465 with open(output_filename
, 'w') as output_file
:
467 'Generating tarball for git revision %s' %
468 channel
.git_revision
)
469 git
= subprocess
.Popen(['git',
471 git_cachedir(channel
.git_repo
),
473 '--prefix=%s/' % channel
.release_name
,
474 channel
.git_revision
],
475 stdout
=subprocess
.PIPE
)
476 xz
= subprocess
.Popen(['xz'], stdin
=git
.stdout
, stdout
=output_file
)
479 v
.result(git
.returncode
== 0 and xz
.returncode
== 0)
481 v
.status('Putting tarball in Nix store')
482 process
= subprocess
.run(
483 ['nix-store', '--add', output_filename
], stdout
=subprocess
.PIPE
)
484 v
.result(process
.returncode
== 0)
485 store_tarball
= process
.stdout
.decode().strip()
487 os
.makedirs(os
.path
.dirname(cache_file
), exist_ok
=True)
488 open(cache_file
, 'w').write(store_tarball
)
489 return store_tarball
# type: ignore # (for old mypy)
492 def check_channel_metadata(
494 channel
: TarrableSearchPath
,
495 channel_contents
: str) -> None:
496 v
.status('Verifying git commit in channel tarball')
501 channel
.release_name
,
502 '.git-revision')).read(999) == channel
.git_revision
)
505 'Verifying version-suffix is a suffix of release name %s:' %
506 channel
.release_name
)
507 version_suffix
= open(
510 channel
.release_name
,
511 '.version-suffix')).read(999)
512 v
.status(version_suffix
)
513 v
.result(channel
.release_name
.endswith(version_suffix
))
516 def check_channel_contents(
518 channel
: TarrableSearchPath
) -> None:
519 with tempfile
.TemporaryDirectory() as channel_contents
, \
520 tempfile
.TemporaryDirectory() as git_contents
:
522 extract_tarball(v
, channel
, channel_contents
)
523 check_channel_metadata(v
, channel
, channel_contents
)
525 git_checkout(v
, channel
, git_contents
)
527 compare_tarball_and_git(v
, channel
, channel_contents
, git_contents
)
529 v
.status('Removing temporary directories')
533 def pin_channel(v
: Verification
, channel
: TarrableSearchPath
) -> None:
535 parse_channel(v
, channel
)
536 fetch_resources(v
, channel
)
537 ensure_git_rev_available(v
, channel
)
538 check_channel_contents(v
, channel
)
541 def git_revision_name(v
: Verification
, channel
: TarrableSearchPath
) -> str:
542 v
.status('Getting commit date')
543 process
= subprocess
.run(['git',
545 git_cachedir(channel
.git_repo
),
550 '--no-show-signature',
551 channel
.git_revision
],
552 stdout
=subprocess
.PIPE
)
553 v
.result(process
.returncode
== 0 and process
.stdout
!= b
'')
554 return '%s-%s' % (os
.path
.basename(channel
.git_repo
),
555 process
.stdout
.decode().strip())
558 def read_search_path(conf
: configparser
.SectionProxy
) -> SearchPath
:
559 if 'alias_of' in conf
:
560 return AliasSearchPath(**dict(conf
.items()))
561 if 'channel_url' in conf
:
562 return ChannelSearchPath(**dict(conf
.items()))
563 return GitSearchPath(**dict(conf
.items()))
566 def read_config(filename
: str) -> configparser
.ConfigParser
:
567 config
= configparser
.ConfigParser()
568 config
.read_file(open(filename
), filename
)
572 def read_config_files(
573 filenames
: Iterable
[str]) -> Dict
[str, configparser
.SectionProxy
]:
574 merged_config
: Dict
[str, configparser
.SectionProxy
] = {}
575 for file in filenames
:
576 config
= read_config(file)
577 for section
in config
.sections():
578 if section
in merged_config
:
579 raise Exception('Duplicate channel "%s"' % section
)
580 merged_config
[section
] = config
[section
]
584 def pin(args
: argparse
.Namespace
) -> None:
586 config
= read_config(args
.channels_file
)
587 for section
in config
.sections():
588 if args
.channels
and section
not in args
.channels
:
591 sp
= read_search_path(config
[section
])
593 sp
.pin(v
, config
[section
])
595 with open(args
.channels_file
, 'w') as configfile
:
596 config
.write(configfile
)
599 def update(args
: argparse
.Namespace
) -> None:
601 exprs
: Dict
[str, str] = {}
602 config
= read_config_files(args
.channels_file
)
603 for section
in config
:
604 sp
= read_search_path(config
[section
])
605 if isinstance(sp
, AliasSearchPath
):
606 assert 'git_repo' not in config
[section
]
608 tarball
= sp
.fetch(v
, section
, config
[section
])
610 'f: f { name = "%s"; channelName = "%%s"; src = builtins.storePath "%s"; }' %
611 (config
[section
]['release_name'], tarball
))
613 for section
in config
:
614 if 'alias_of' in config
[section
]:
615 exprs
[section
] = exprs
[str(config
[section
]['alias_of'])]
620 '/nix/var/nix/profiles/per-user/%s/channels' %
624 '<nix/unpack-channel.nix>',
626 '--from-expression'] + [exprs
[name
] % name
for name
in sorted(exprs
.keys())]
628 print(' '.join(map(shlex
.quote
, command
)))
630 v
.status('Installing channels with nix-env')
631 process
= subprocess
.run(command
)
632 v
.result(process
.returncode
== 0)
636 parser
= argparse
.ArgumentParser(prog
='pinch')
637 subparsers
= parser
.add_subparsers(dest
='mode', required
=True)
638 parser_pin
= subparsers
.add_parser('pin')
639 parser_pin
.add_argument('channels_file', type=str)
640 parser_pin
.add_argument('channels', type=str, nargs
='*')
641 parser_pin
.set_defaults(func
=pin
)
642 parser_update
= subparsers
.add_parser('update')
643 parser_update
.add_argument('--dry-run', action
='store_true')
644 parser_update
.add_argument('channels_file', type=str, nargs
='+')
645 parser_update
.set_defaults(func
=update
)
646 args
= parser
.parse_args()
650 if __name__
== '__main__':