def set(self, clock, ignorehash, notefiles): if clock is None: self.invalidate() return # Read the identity from the file on disk rather than from the open file # pointer below, because the latter is actually a brand new file. identity = util.filestat.frompath(self._vfs.join(b'fsmonitor.state')) if identity != self._identity: self._ui.debug( b'skip updating fsmonitor.state: identity mismatch\n') return try: file = self._vfs(b'fsmonitor.state', b'wb', atomictemp=True, checkambig=True) except (IOError, OSError): self._ui.warn(_(b"warning: unable to write out fsmonitor state\n")) return with file: file.write(struct.pack(_versionformat, _version)) file.write(encoding.strtolocal(socket.gethostname()) + b'\0') file.write(clock + b'\0') file.write(ignorehash + b'\0') if notefiles: file.write(b'\0'.join(notefiles)) file.write(b'\0')
def log(self, event, *msg, **opts): global lastui super(blackboxui, self).log(event, *msg, **opts) if not '*' in self.track and not event in self.track: return if self._bbvfs: ui = self else: # certain ui instances exist outside the context of # a repo, so just default to the last blackbox that # was seen. ui = lastui if not ui: return vfs = ui._bbvfs if not vfs: return repo = getattr(ui, '_bbrepo', None) if not lastui or repo: lastui = ui if getattr(ui, '_bbinlog', False): # recursion and failure guard return ui._bbinlog = True default = self.configdate('devel', 'default-date') date = dateutil.datestr(default, '%Y/%m/%d %H:%M:%S') user = procutil.getuser() pid = '%d' % procutil.getpid() formattedmsg = msg[0] % msg[1:] rev = '(unknown)' changed = '' if repo: ctx = repo[None] parents = ctx.parents() rev = ('+'.join([hex(p.node()) for p in parents])) if (ui.configbool('blackbox', 'dirty') and ctx.dirty( missing=True, merge=False, branch=False)): changed = '+' if ui.configbool('blackbox', 'logsource'): src = ' [%s]' % event else: src = '' try: fmt = '%s %s @%s%s (%s)%s> %s' args = (date, user, rev, changed, pid, src, formattedmsg) with _openlogfile(ui, vfs) as fp: fp.write(fmt % args) except (IOError, OSError) as err: self.debug('warning: cannot write to blackbox.log: %s\n' % encoding.strtolocal(err.strerror)) # do not restore _bbinlog intentionally to avoid failed # logging again else: ui._bbinlog = False
def __setitem__(self, key, value): if self.fp is None: try: self.fp = open(self.path, 'a') except IOError as err: raise error.Abort( _('could not open map file %r: %s') % (self.path, encoding.strtolocal(err.strerror))) self.fp.write('%s %s\n' % (key, value)) self.fp.flush() super(mapfile, self).__setitem__(key, value)
def getrepophid(repo): """given callsign, return repository PHID or None""" # developer config: phabricator.repophid repophid = repo.ui.config(b'phabricator', b'repophid') if repophid: return repophid callsign = repo.ui.config(b'phabricator', b'callsign') if not callsign: return None query = callconduit(repo, b'diffusion.repository.search', {b'constraints': {b'callsigns': [callsign]}}) if len(query[r'data']) == 0: return None repophid = encoding.strtolocal(query[r'data'][0][r'phid']) repo.ui.setconfig(b'phabricator', b'repophid', repophid) return repophid
def getrepophid(repo): """given callsign, return repository PHID or None""" # developer config: phabricator.repophid repophid = repo.ui.config(b'phabricator', b'repophid') if repophid: return repophid callsign = repo.ui.config(b'phabricator', b'callsign') if not callsign: return None query = callconduit(repo, b'diffusion.repository.search', {b'constraints': {b'callsigns': [callsign]}}) if len(query[r'data']) == 0: return None repophid = encoding.strtolocal(query[r'data'][0][r'phid']) repo.ui.setconfig(b'phabricator', b'repophid', repophid) return repophid
def clonenarrowcmd(orig, ui, repo, *args, **opts): """Wraps clone command, so 'hg clone' first wraps localrepo.clone().""" opts = pycompat.byteskwargs(opts) wrappedextraprepare = util.nullcontextmanager() narrowspecfile = opts[b'narrowspec'] if narrowspecfile: filepath = os.path.join(encoding.getcwd(), narrowspecfile) ui.status(_(b"reading narrowspec from '%s'\n") % filepath) try: fdata = util.readfile(filepath) except IOError as inst: raise error.Abort( _(b"cannot read narrowspecs from '%s': %s") % (filepath, encoding.strtolocal(inst.strerror))) includes, excludes, profiles = sparse.parseconfig(ui, fdata, b'narrow') if profiles: raise error.Abort( _(b"cannot specify other files using '%include' in" b" narrowspec")) narrowspec.validatepatterns(includes) narrowspec.validatepatterns(excludes) # narrowspec is passed so we should assume that user wants narrow clone opts[b'narrow'] = True opts[b'include'].extend(includes) opts[b'exclude'].extend(excludes) if opts[b'narrow']: def pullbundle2extraprepare_widen(orig, pullop, kwargs): orig(pullop, kwargs) if opts.get(b'depth'): kwargs[b'depth'] = opts[b'depth'] wrappedextraprepare = extensions.wrappedfunction( exchange, b'_pullbundle2extraprepare', pullbundle2extraprepare_widen) with wrappedextraprepare: return orig(ui, repo, *args, **pycompat.strkwargs(opts))
def messageid(ctx, domain, messageidseed): if domain and messageidseed: host = domain else: host = encoding.strtolocal(socket.getfqdn()) if messageidseed: messagehash = hashlib.sha512(ctx.hex() + messageidseed) messageid = b'<hg.%s@%s>' % ( pycompat.sysbytes(messagehash.hexdigest()[:64]), host, ) else: messageid = b'<hg.%s.%d.%d@%s>' % ( ctx, int(time.time()), hash(ctx.repo().root), host, ) return encoding.strfromlocal(messageid)
def _urlerrorreason(urlerror): '''Create a friendly message for the given URLError to be used in an LfsRemoteError message. ''' inst = urlerror if isinstance(urlerror.reason, Exception): inst = urlerror.reason if util.safehasattr(inst, b'reason'): try: # usually it is in the form (errno, strerror) reason = inst.reason.args[1] except (AttributeError, IndexError): # it might be anything, for example a string reason = inst.reason if isinstance(reason, pycompat.unicode): # SSLError of Python 2.7.9 contains a unicode reason = encoding.unitolocal(reason) return reason elif getattr(inst, "strerror", None): return encoding.strtolocal(inst.strerror) else: return stringutil.forcebytestr(urlerror)
def _log(self, ui, event, msg, opts): default = ui.configdate(b'devel', b'default-date') date = dateutil.datestr(default, ui.config(b'blackbox', b'date-format')) user = procutil.getuser() pid = b'%d' % procutil.getpid() changed = b'' ctx = self._repo[None] parents = ctx.parents() rev = b'+'.join([hex(p.node()) for p in parents]) if ui.configbool(b'blackbox', b'dirty') and ctx.dirty( missing=True, merge=False, branch=False ): changed = b'+' if ui.configbool(b'blackbox', b'logsource'): src = b' [%s]' % event else: src = b'' try: fmt = b'%s %s @%s%s (%s)%s> %s' args = (date, user, rev, changed, pid, src, msg) with loggingutil.openlogfile( ui, self._repo.vfs, name=b'blackbox.log', maxfiles=self._maxfiles, maxsize=self._maxsize, ) as fp: fp.write(fmt % args) except (IOError, OSError) as err: # deactivate this to avoid failed logging again self._trackedevents.clear() ui.debug( b'warning: cannot write to blackbox.log: %s\n' % encoding.strtolocal(err.strerror) ) return _lastlogger.logger = self
def trackedcmd(ui, repo, remotepath=None, *pats, **opts): """show or change the current narrowspec With no argument, shows the current narrowspec entries, one per line. Each line will be prefixed with 'I' or 'X' for included or excluded patterns, respectively. The narrowspec is comprised of expressions to match remote files and/or directories that should be pulled into your client. The narrowspec has *include* and *exclude* expressions, with excludes always trumping includes: that is, if a file matches an exclude expression, it will be excluded even if it also matches an include expression. Excluding files that were never included has no effect. Each included or excluded entry is in the format described by 'hg help patterns'. The options allow you to add or remove included and excluded expressions. If --clear is specified, then all previous includes and excludes are DROPPED and replaced by the new ones specified to --addinclude and --addexclude. If --clear is specified without any further options, the narrowspec will be empty and will not match any files. """ opts = pycompat.byteskwargs(opts) if repository.NARROW_REQUIREMENT not in repo.requirements: ui.warn(_('The narrow command is only supported on respositories cloned' ' with --narrow.\n')) return 1 # Before supporting, decide whether it "hg tracked --clear" should mean # tracking no paths or all paths. if opts['clear']: ui.warn(_('The --clear option is not yet supported.\n')) return 1 # import rules from a file newrules = opts.get('import_rules') if newrules: try: filepath = os.path.join(encoding.getcwd(), newrules) fdata = util.readfile(filepath) except IOError as inst: raise error.Abort(_("cannot read narrowspecs from '%s': %s") % (filepath, encoding.strtolocal(inst.strerror))) includepats, excludepats, profiles = sparse.parseconfig(ui, fdata, 'narrow') if profiles: raise error.Abort(_("including other spec files using '%include' " "is not supported in narrowspec")) opts['addinclude'].extend(includepats) opts['addexclude'].extend(excludepats) addedincludes = narrowspec.parsepatterns(opts['addinclude']) removedincludes = narrowspec.parsepatterns(opts['removeinclude']) addedexcludes = narrowspec.parsepatterns(opts['addexclude']) removedexcludes = narrowspec.parsepatterns(opts['removeexclude']) only_show = not (addedincludes or removedincludes or addedexcludes or removedexcludes or newrules) oldincludes, oldexcludes = repo.narrowpats # filter the user passed additions and deletions into actual additions and # deletions of excludes and includes addedincludes -= oldincludes removedincludes &= oldincludes addedexcludes -= oldexcludes removedexcludes &= oldexcludes widening = addedincludes or removedexcludes narrowing = removedincludes or addedexcludes # Only print the current narrowspec. if only_show: ui.pager('tracked') fm = ui.formatter('narrow', opts) for i in sorted(oldincludes): fm.startitem() fm.write('status', '%s ', 'I', label='narrow.included') fm.write('pat', '%s\n', i, label='narrow.included') for i in sorted(oldexcludes): fm.startitem() fm.write('status', '%s ', 'X', label='narrow.excluded') fm.write('pat', '%s\n', i, label='narrow.excluded') fm.end() return 0 if not widening and not narrowing: ui.status(_("nothing to widen or narrow\n")) return 0 with repo.wlock(), repo.lock(): cmdutil.bailifchanged(repo) # Find the revisions we have in common with the remote. These will # be used for finding local-only changes for narrowing. They will # also define the set of revisions to update for widening. remotepath = ui.expandpath(remotepath or 'default') url, branches = hg.parseurl(remotepath) ui.status(_('comparing with %s\n') % util.hidepassword(url)) remote = hg.peer(repo, opts, url) # check narrow support before doing anything if widening needs to be # performed. In future we should also abort if client is ellipses and # server does not support ellipses if widening and wireprototypes.NARROWCAP not in remote.capabilities(): raise error.Abort(_("server does not support narrow clones")) commoninc = discovery.findcommonincoming(repo, remote) if narrowing: newincludes = oldincludes - removedincludes newexcludes = oldexcludes | addedexcludes _narrow(ui, repo, remote, commoninc, oldincludes, oldexcludes, newincludes, newexcludes, opts['force_delete_local_changes']) # _narrow() updated the narrowspec and _widen() below needs to # use the updated values as its base (otherwise removed includes # and addedexcludes will be lost in the resulting narrowspec) oldincludes = newincludes oldexcludes = newexcludes if widening: newincludes = oldincludes | addedincludes newexcludes = oldexcludes - removedexcludes _widen(ui, repo, remote, commoninc, oldincludes, oldexcludes, newincludes, newexcludes) return 0
def trackedcmd(ui, repo, remotepath=None, *pats, **opts): """show or change the current narrowspec With no argument, shows the current narrowspec entries, one per line. Each line will be prefixed with 'I' or 'X' for included or excluded patterns, respectively. The narrowspec is comprised of expressions to match remote files and/or directories that should be pulled into your client. The narrowspec has *include* and *exclude* expressions, with excludes always trumping includes: that is, if a file matches an exclude expression, it will be excluded even if it also matches an include expression. Excluding files that were never included has no effect. Each included or excluded entry is in the format described by 'hg help patterns'. The options allow you to add or remove included and excluded expressions. If --clear is specified, then all previous includes and excludes are DROPPED and replaced by the new ones specified to --addinclude and --addexclude. If --clear is specified without any further options, the narrowspec will be empty and will not match any files. If --auto-remove-includes is specified, then those includes that don't match any files modified by currently visible local commits (those not shared by the remote) will be added to the set of explicitly specified includes to remove. --import-rules accepts a path to a file containing rules, allowing you to add --addinclude, --addexclude rules in bulk. Like the other include and exclude switches, the changes are applied immediately. """ opts = pycompat.byteskwargs(opts) if repository.NARROW_REQUIREMENT not in repo.requirements: raise error.Abort( _(b'the tracked command is only supported on ' b'repositories cloned with --narrow')) # Before supporting, decide whether it "hg tracked --clear" should mean # tracking no paths or all paths. if opts[b'clear']: raise error.Abort(_(b'the --clear option is not yet supported')) # import rules from a file newrules = opts.get(b'import_rules') if newrules: try: filepath = os.path.join(encoding.getcwd(), newrules) fdata = util.readfile(filepath) except IOError as inst: raise error.Abort( _(b"cannot read narrowspecs from '%s': %s") % (filepath, encoding.strtolocal(inst.strerror))) includepats, excludepats, profiles = sparse.parseconfig( ui, fdata, b'narrow') if profiles: raise error.Abort( _(b"including other spec files using '%include' " b"is not supported in narrowspec")) opts[b'addinclude'].extend(includepats) opts[b'addexclude'].extend(excludepats) addedincludes = narrowspec.parsepatterns(opts[b'addinclude']) removedincludes = narrowspec.parsepatterns(opts[b'removeinclude']) addedexcludes = narrowspec.parsepatterns(opts[b'addexclude']) removedexcludes = narrowspec.parsepatterns(opts[b'removeexclude']) autoremoveincludes = opts[b'auto_remove_includes'] update_working_copy = opts[b'update_working_copy'] only_show = not (addedincludes or removedincludes or addedexcludes or removedexcludes or newrules or autoremoveincludes or update_working_copy) oldincludes, oldexcludes = repo.narrowpats # filter the user passed additions and deletions into actual additions and # deletions of excludes and includes addedincludes -= oldincludes removedincludes &= oldincludes addedexcludes -= oldexcludes removedexcludes &= oldexcludes widening = addedincludes or removedexcludes narrowing = removedincludes or addedexcludes # Only print the current narrowspec. if only_show: ui.pager(b'tracked') fm = ui.formatter(b'narrow', opts) for i in sorted(oldincludes): fm.startitem() fm.write(b'status', b'%s ', b'I', label=b'narrow.included') fm.write(b'pat', b'%s\n', i, label=b'narrow.included') for i in sorted(oldexcludes): fm.startitem() fm.write(b'status', b'%s ', b'X', label=b'narrow.excluded') fm.write(b'pat', b'%s\n', i, label=b'narrow.excluded') fm.end() return 0 if update_working_copy: with repo.wlock(), repo.lock(), repo.transaction(b'narrow-wc'): narrowspec.updateworkingcopy(repo) narrowspec.copytoworkingcopy(repo) return 0 if not (widening or narrowing or autoremoveincludes): ui.status(_(b"nothing to widen or narrow\n")) return 0 with repo.wlock(), repo.lock(): cmdutil.bailifchanged(repo) # Find the revisions we have in common with the remote. These will # be used for finding local-only changes for narrowing. They will # also define the set of revisions to update for widening. remotepath = ui.expandpath(remotepath or b'default') url, branches = hg.parseurl(remotepath) ui.status(_(b'comparing with %s\n') % util.hidepassword(url)) remote = hg.peer(repo, opts, url) # check narrow support before doing anything if widening needs to be # performed. In future we should also abort if client is ellipses and # server does not support ellipses if widening and wireprototypes.NARROWCAP not in remote.capabilities(): raise error.Abort(_(b"server does not support narrow clones")) commoninc = discovery.findcommonincoming(repo, remote) if autoremoveincludes: outgoing = discovery.findcommonoutgoing(repo, remote, commoninc=commoninc) ui.status(_(b'looking for unused includes to remove\n')) localfiles = set() for n in itertools.chain(outgoing.missing, outgoing.excluded): localfiles.update(repo[n].files()) suggestedremovals = [] for include in sorted(oldincludes): match = narrowspec.match(repo.root, [include], oldexcludes) if not any(match(f) for f in localfiles): suggestedremovals.append(include) if suggestedremovals: for s in suggestedremovals: ui.status(b'%s\n' % s) if (ui.promptchoice( _(b'remove these unused includes (yn)?' b'$$ &Yes $$ &No')) == 0): removedincludes.update(suggestedremovals) narrowing = True else: ui.status(_(b'found no unused includes\n')) if narrowing: newincludes = oldincludes - removedincludes newexcludes = oldexcludes | addedexcludes _narrow( ui, repo, remote, commoninc, oldincludes, oldexcludes, newincludes, newexcludes, opts[b'force_delete_local_changes'], ) # _narrow() updated the narrowspec and _widen() below needs to # use the updated values as its base (otherwise removed includes # and addedexcludes will be lost in the resulting narrowspec) oldincludes = newincludes oldexcludes = newexcludes if widening: newincludes = oldincludes | addedincludes newexcludes = oldexcludes - removedexcludes _widen( ui, repo, remote, commoninc, oldincludes, oldexcludes, newincludes, newexcludes, ) return 0
def getkey(ctx): t, tz = ctx.date() date = datetime.datetime(*time.gmtime(float(t) - tz)[:6]) return encoding.strtolocal( date.strftime(encoding.strfromlocal(opts[b'dateformat'])) )
def send(self, ctx, count, data): '''send message.''' # Select subscribers by revset subs = set() for sub, spec in self.subs: if spec is None: subs.add(sub) continue revs = self.repo.revs('%r and %d:', spec, ctx.rev()) if len(revs): subs.add(sub) continue if len(subs) == 0: self.ui.debug('notify: no subscribers to selected repo ' 'and revset\n') return p = emailparser.Parser() try: msg = p.parsestr(encoding.strfromlocal(data)) except emailerrors.MessageParseError as inst: raise error.Abort(inst) # store sender and subject sender = msg[r'From'] subject = msg[r'Subject'] if sender is not None: sender = encoding.strtolocal(sender) if subject is not None: subject = encoding.strtolocal(subject) del msg[r'From'], msg[r'Subject'] if not msg.is_multipart(): # create fresh mime message from scratch # (multipart templates must take care of this themselves) headers = msg.items() payload = msg.get_payload() # for notification prefer readability over data precision msg = mail.mimeencode(self.ui, payload, self.charsets, self.test) # reinstate custom headers for k, v in headers: msg[k] = v msg[r'Date'] = encoding.strfromlocal( dateutil.datestr(format="%a, %d %b %Y %H:%M:%S %1%2")) # try to make subject line exist and be useful if not subject: if count > 1: subject = _('%s: %d new changesets') % (self.root, count) else: s = ctx.description().lstrip().split('\n', 1)[0].rstrip() subject = '%s: %s' % (self.root, s) maxsubject = int(self.ui.config('notify', 'maxsubject')) if maxsubject: subject = stringutil.ellipsis(subject, maxsubject) msg[r'Subject'] = encoding.strfromlocal( mail.headencode(self.ui, subject, self.charsets, self.test)) # try to make message have proper sender if not sender: sender = self.ui.config('email', 'from') or self.ui.username() if '@' not in sender or '@localhost' in sender: sender = self.fixmail(sender) msg[r'From'] = encoding.strfromlocal( mail.addressencode(self.ui, sender, self.charsets, self.test)) msg[r'X-Hg-Notification'] = r'changeset %s' % ctx if not msg[r'Message-Id']: msg[r'Message-Id'] = encoding.strfromlocal( '<hg.%s.%d.%d@%s>' % (ctx, int(time.time()), hash(self.repo.root), encoding.strtolocal(socket.getfqdn()))) msg[r'To'] = encoding.strfromlocal(', '.join(sorted(subs))) msgtext = encoding.strtolocal(msg.as_string()) if self.test: self.ui.write(msgtext) if not msgtext.endswith('\n'): self.ui.write('\n') else: self.ui.status(_('notify: sending %d subscribers %d changes\n') % (len(subs), count)) mail.sendmail(self.ui, stringutil.email(msg[r'From']), subs, msgtext, mbox=self.mbox)
def genmsgid(id): return '<%s.%d@%s>' % (id[:20], int( start_time[0]), encoding.strtolocal(socket.getfqdn()))
def _msgid(node, timestamp): hostname = encoding.strtolocal(socket.getfqdn()) hostname = encoding.environ.get(b'HGHOSTNAME', hostname) return b'<%s.%d@%s>' % (node, timestamp, hostname)
def get(self): try: file = self._vfs(b'fsmonitor.state', b'rb') except IOError as inst: self._identity = util.filestat(None) if inst.errno != errno.ENOENT: raise return None, None, None self._identity = util.filestat.fromfp(file) versionbytes = file.read(4) if len(versionbytes) < 4: self._ui.log( b'fsmonitor', b'fsmonitor: state file only has %d bytes, ' b'nuking state\n' % len(versionbytes), ) self.invalidate() return None, None, None try: diskversion = struct.unpack(_versionformat, versionbytes)[0] if diskversion != _version: # different version, nuke state and start over self._ui.log( b'fsmonitor', b'fsmonitor: version switch from %d to ' b'%d, nuking state\n' % (diskversion, _version), ) self.invalidate() return None, None, None state = file.read().split(b'\0') # state = hostname\0clock\0ignorehash\0 + list of files, each # followed by a \0 if len(state) < 3: self._ui.log( b'fsmonitor', b'fsmonitor: state file truncated (expected ' b'3 chunks, found %d), nuking state\n', len(state), ) self.invalidate() return None, None, None diskhostname = state[0] hostname = encoding.strtolocal(socket.gethostname()) if diskhostname != hostname: # file got moved to a different host self._ui.log( b'fsmonitor', b'fsmonitor: stored hostname "%s" ' b'different from current "%s", nuking state\n' % (diskhostname, hostname), ) self.invalidate() return None, None, None clock = state[1] ignorehash = state[2] # discard the value after the last \0 notefiles = state[3:-1] finally: file.close() return clock, ignorehash, notefiles