Commit Graph

35 Commits

Author SHA1 Message Date
Mark Thomas
1575ac85e1 httpconnection: remove old-style progress bar
Summary:
httpconnection uses old-style progress bars in a way that isn't easy to
replicate using new-style progress bars.  Remove it for now, it can be added
back in later in the right place.

Reviewed By: quark-zju

Differential Revision: D7329486

fbshipit-source-id: 814c55d7a5bb5c97fc6b3967510ed656110038c8
2018-04-13 21:51:33 -07:00
Jun Wu
2946a1c198 codemod: use single blank line
Summary: This makes test-check-code cleaner.

Reviewed By: ryanmce

Differential Revision: D6937934

fbshipit-source-id: 8f92bc32f75b9792ac67db77bb3a8756b37fa941
2018-04-13 21:51:08 -07:00
Pulkit Goyal
90a31fc989 py3: handle keyword arguments correctly in httpconnection.py
Differential Revision: https://phab.mercurial-scm.org/D1634
2017-12-10 04:47:04 +05:30
Augie Fackler
321287c10b cleanup: use urllibcompat for renamed methods on urllib request objects
Differential Revision: https://phab.mercurial-scm.org/D891
2017-10-01 12:14:21 -04:00
Jun Wu
e47f7dc2fa codemod: register core configitems using a script
This is done by a script [2] using RedBaron [1], a tool designed for doing
code refactoring. All "default" values are decided by the script and are
strongly consistent with the existing code.

There are 2 changes done manually to fix tests:

  [warn] mercurial/exchange.py: experimental.bundle2-output-capture: default needs manual removal
  [warn] mercurial/localrepo.py: experimental.hook-track-tags: default needs manual removal

Since RedBaron is not confident about how to indent things [2].

[1]: https://github.com/PyCQA/redbaron
[2]: https://github.com/PyCQA/redbaron/issues/100
[3]:

#!/usr/bin/env python
# codemod_configitems.py - codemod tool to fill configitems
#
# Copyright 2017 Facebook, Inc.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.
from __future__ import absolute_import, print_function

import os
import sys

import redbaron

def readpath(path):
    with open(path) as f:
        return f.read()

def writepath(path, content):
    with open(path, 'w') as f:
        f.write(content)

_configmethods = {'config', 'configbool', 'configint', 'configbytes',
                  'configlist', 'configdate'}

def extractstring(rnode):
    """get the string from a RedBaron string or call_argument node"""
    while rnode.type != 'string':
        rnode = rnode.value
    return rnode.value[1:-1]  # unquote, "'str'" -> "str"

def uiconfigitems(red):
    """match *.ui.config* pattern, yield (node, method, args, section, name)"""
    for node in red.find_all('atomtrailers'):
        entry = None
        try:
            obj = node[-3].value
            method = node[-2].value
            args = node[-1]
            section = args[0].value
            name = args[1].value
            if (obj in ('ui', 'self') and method in _configmethods
                and section.type == 'string' and name.type == 'string'):
                entry = (node, method, args, extractstring(section),
                         extractstring(name))
        except Exception:
            pass
        else:
            if entry:
                yield entry

def coreconfigitems(red):
    """match coreconfigitem(...) pattern, yield (node, args, section, name)"""
    for node in red.find_all('atomtrailers'):
        entry = None
        try:
            args = node[1]
            section = args[0].value
            name = args[1].value
            if (node[0].value == 'coreconfigitem' and section.type == 'string'
                and name.type == 'string'):
                entry = (node, args, extractstring(section),
                         extractstring(name))
        except Exception:
            pass
        else:
            if entry:
                yield entry

def registercoreconfig(cfgred, section, name, defaultrepr):
    """insert coreconfigitem to cfgred AST

    section and name are plain string, defaultrepr is a string
    """
    # find a place to insert the "coreconfigitem" item
    entries = list(coreconfigitems(cfgred))
    for node, args, nodesection, nodename in reversed(entries):
        if (nodesection, nodename) < (section, name):
            # insert after this entry
            node.insert_after(
                'coreconfigitem(%r, %r,\n'
                '    default=%s,\n'
                ')' % (section, name, defaultrepr))
            return

def main(argv):
    if not argv:
        print('Usage: codemod_configitems.py FILES\n'
              'For example, FILES could be "{hgext,mercurial}/*/**.py"')
    dirname = os.path.dirname
    reporoot = dirname(dirname(dirname(os.path.abspath(__file__))))

    # register configitems to this destination
    cfgpath = os.path.join(reporoot, 'mercurial', 'configitems.py')
    cfgred = redbaron.RedBaron(readpath(cfgpath))

    # state about what to do
    registered = set((s, n) for n, a, s, n in coreconfigitems(cfgred))
    toregister = {} # {(section, name): defaultrepr}
    coreconfigs = set() # {(section, name)}, whether it's used in core

    # first loop: scan all files before taking any action
    for i, path in enumerate(argv):
        print('(%d/%d) scanning %s' % (i + 1, len(argv), path))
        iscore = ('mercurial' in path) and ('hgext' not in path)
        red = redbaron.RedBaron(readpath(path))
        # find all repo.ui.config* and ui.config* calls, and collect their
        # section, name and default value information.
        for node, method, args, section, name in uiconfigitems(red):
            if section == 'web':
                # [web] section has some weirdness, ignore them for now
                continue
            defaultrepr = None
            key = (section, name)
            if len(args) == 2:
                if key in registered:
                    continue
                if method == 'configlist':
                    defaultrepr = 'list'
                elif method == 'configbool':
                    defaultrepr = 'False'
                else:
                    defaultrepr = 'None'
            elif len(args) >= 3 and (args[2].target is None or
                                     args[2].target.value == 'default'):
                # try to understand the "default" value
                dnode = args[2].value
                if dnode.type == 'name':
                    if dnode.value in {'None', 'True', 'False'}:
                        defaultrepr = dnode.value
                elif dnode.type == 'string':
                    defaultrepr = repr(dnode.value[1:-1])
                elif dnode.type in ('int', 'float'):
                    defaultrepr = dnode.value
            # inconsistent default
            if key in toregister and toregister[key] != defaultrepr:
                defaultrepr = None
            # interesting to rewrite
            if key not in registered:
                if defaultrepr is None:
                    print('[note] %s: %s.%s: unsupported default'
                          % (path, section, name))
                    registered.add(key) # skip checking it again
                else:
                    toregister[key] = defaultrepr
                    if iscore:
                        coreconfigs.add(key)

    # second loop: rewrite files given "toregister" result
    for path in argv:
        # reconstruct redbaron - trade CPU for memory
        red = redbaron.RedBaron(readpath(path))
        changed = False
        for node, method, args, section, name in uiconfigitems(red):
            key = (section, name)
            defaultrepr = toregister.get(key)
            if defaultrepr is None or key not in coreconfigs:
                continue
            if len(args) >= 3 and (args[2].target is None or
                                   args[2].target.value == 'default'):
                try:
                    del args[2]
                    changed = True
                except Exception:
                    # redbaron fails to do the rewrite due to indentation
                    # see https://github.com/PyCQA/redbaron/issues/100
                    print('[warn] %s: %s.%s: default needs manual removal'
                          % (path, section, name))
            if key not in registered:
                print('registering %s.%s' % (section, name))
                registercoreconfig(cfgred, section, name, defaultrepr)
                registered.add(key)
        if changed:
            print('updating %s' % path)
            writepath(path, red.dumps())

    if toregister:
        print('updating configitems.py')
        writepath(cfgpath, cfgred.dumps())

if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
2017-07-14 14:22:40 -07:00
Gregory Szorc
bd7f2afe30 httpconnection: allow a global auth.cookiefile config entry
This foreshadows support for defining a cookies file.
2017-03-09 22:35:10 -08:00
Yuya Nishihara
e780f7677e httpconnection: make sure to clear progress of httpsendfile at EOF
read() should never raise EOFError. If it did, UnboundLocalError would occur
due to unassigned 'ret' variable.

This issue was originally reported to TortoiseHg:
https://bitbucket.org/tortoisehg/thg/issues/4707/
2017-03-18 16:02:14 +09:00
Gregory Szorc
97e218b123 httpconnection: rename config to groups
Because that is what it is.
2017-03-09 20:53:14 -08:00
Gregory Szorc
6ef9cb88f5 httpconnection: don't use dict()
Not sure the history here. But we don't do this elsewhere.
2017-03-09 20:51:57 -08:00
Mads Kiilerich
7afa73604d largefiles: use context for file closing
Make the code slightly smaller and safer (and more deeply indented).
2016-10-08 00:59:41 +02:00
Gregory Szorc
d65469e1c2 httpconnection: remove use of sslkwargs
It now does nothing.
2016-05-25 19:54:06 -07:00
Gregory Szorc
548b4e9e2c sslutil: remove ui from sslkwargs (API)
Arguments to sslutil.wrapsocket() are partially determined by
calling sslutil.sslkwargs(). This function receives a ui and
a hostname and determines what settings, if any, need to be
applied when the socket is wrapped.

Both the ui and hostname are passed into wrapsocket(). The
other arguments to wrapsocket() provided by sslkwargs() (ca_certs
and cert_reqs) are not looked at or modified anywhere outside
of sslutil.py. So, sslkwargs() doesn't need to exist as a
separate public API called before wrapsocket().

This commit starts the process of removing external consumers of
sslkwargs() by removing the "ui" key/argument from its return.
All callers now pass the ui argument explicitly.
2016-05-25 19:43:22 -07:00
Gregory Szorc
6fd76860b1 sslutil: convert socket validation from a class to a function (API)
Now that the socket validator doesn't have any instance state,
we can make it a generic function.

The "validator" class has been converted into the "validatesocket"
function and all consumers have been updated.
2016-05-15 11:38:38 -07:00
timeless
109fcbc79e pycompat: switch to util.urlreq/util.urlerr for py3 compat 2016-04-06 23:22:12 +00:00
Martin von Zweigbergk
ede6d3a6dd httpconnection: remove obsolete comment about open()
When httpsendfile was moved from url.py into httpconnection.py in
aec6dba8c673 (url: use new http support if requested by the user,
2011-05-06), the comment about not being able to just call open()
became obsolete.
2016-03-14 14:08:28 -07:00
Gregory Szorc
2a56f0283f httpconnection: use absolute_import 2015-12-21 21:52:58 -08:00
Pierre-Yves David
2dc338dc47 httpconnection: remove a mutable default argument
Mutable default arguments are know to the state of California to cause bugs.
2015-09-24 00:54:30 -07:00
Matt Mackall
3e2882b908 http2: mark experimental and developer options 2015-06-25 17:48:43 -05:00
Gregory Szorc
5380dea2a7 global: mass rewrite to use modern exception syntax
Python 2.6 introduced the "except type as instance" syntax, replacing
the "except type, instance" syntax that came before. Python 3 dropped
support for the latter syntax. Since we no longer support Python 2.4 or
2.5, we have no need to continue supporting the "except type, instance".

This patch mass rewrites the exception syntax to be Python 2.6+ and
Python 3 compatible.

This patch was produced by running `2to3 -f except -w -n .`.
2015-06-23 22:20:08 -07:00
Yuya Nishihara
d3afea0260 ssl: rename ssl_wrap_socket() to conform to our naming convention
I've removed ssl_ prefix because the module name contains ssl.
2015-06-05 21:25:28 +09:00
Pierre-Yves David
ca946c595d httpconnection: drop Python 2.4 specify hack
Python 2.4.1 doesn't provide the full URI, good for it.
2015-05-18 16:47:26 -05:00
Augie Fackler
3c989f7606 httpconnection: properly inject ssl_wrap_socket into httpclient (issue4038)
This causes httpclient to use the same SSL settings as the rest of
Mercurial, and adds an easy extension point for later modifications to
our ssl handling.
2013-09-20 09:16:07 -04:00
Matt Mackall
22317edb2f httpclient: fix calling convention violation 2012-10-18 23:55:15 -05:00
Augie Fackler
05dca2a258 http2: make it possible to connect w/o ssl on port 443
The fix is just to make sure we always pass use_ssl=False to non-SSL
connections.
2012-10-16 18:05:33 -05:00
Mads Kiilerich
5e3dc3e383 avoid using abbreviations that look like spelling errors 2012-08-27 23:14:27 +02:00
Martin Geisler
ba8731035e Use explicit integer division
Found by running the test suite with the -3 flag to show places where
we have int / int division that can be replaced with int // int.
2012-01-08 18:15:54 +01:00
Matt Mackall
9dea83bdb8 auth: fix realm handling with Python < 2.4.3 (issue2739) 2011-10-17 13:42:42 -05:00
Mads Kiilerich
35dbb9abb2 http: handle push of bundles > 2 GB again (issue3017)
It was very elegant that httpsendfile implemented __len__ like a string. It was
however also dangerous because that protocol can't handle sizes bigger than 2 GB.
Mercurial tried to work around that, but it turned out to be too easy to
introduce new errors in this area.

With this change __len__ is no longer implemented at all and the code will work
the same way for short and long posts.
2011-09-21 22:52:00 +02:00
Patrick Mezard
107949ab73 http: pass user to readauthforuri() (fix f7ae45a69fcd)
urllib2 never handles URIs with credentials, we have to extract them and store
them in the password manager before handing the stripped URI. Half of the
changes deducing the username from the URI in f7ae45a69fcd were incorrect.
Instead, we retrieve the username from the password manager before passing to
readauthforuri().

test-hgweb-auth.py was passing because the test itself was flawed: it was
passing URIs with credentials to find_password(), which never happens.
2011-08-05 21:05:41 +02:00
Patrick Mezard
8028e79c02 hgweb: do not ignore [auth] if url has a username (issue2822)
The [auth] section was ignored when handling URLs like:

  http://user@example.com/foo

Instead, we look in [auth] for an entry matching the URL and supplied user
name. Entries without username can match URL with a username. Prefix length
ties are resolved in favor of entries matching the username. With:

  foo.prefix = http://example.org
  foo.username = user
  foo.password = password
  bar.prefix = http://example.org/bar

and the input URL:

  http://user@example.org/bar

the 'bar' entry will be selected because of prefix length, therefore prompting
for a password. This behaviour ensure that entries selection is consistent when
looking for credentials or for certificates, and that certificates can be
picked even if their entries do no define usernames while the URL does.
Additionally, entries without a username matched against a username are
returned as if they did have requested username set to avoid prompting again
for a username if the password is not set.

v2: reparse the URL in readauthforuri() to handle HTTP and HTTPS similarly.
v3: allow unset usernames to match URL usernames to pick certificates. Resolve
prefix length ties in favor of entries with usernames.
2011-08-01 23:58:50 +02:00
Matt Mackall
a8dec32fed httprepo: handle large lengths by bypassing the len() operator 2011-05-24 17:30:00 -05:00
Augie Fackler
640a6e5b0b httpconnection: improved logging formatting
I had to use this debugging output for the first time recently when
looking for a problem, and the lack of good formatting made things
difficult.
2011-05-16 16:59:45 -05:00
Augie Fackler
d61478c8ef httpconnection: correctly handle redirects from http to https
Previously the connection cache for keepalives didn't keep track of
ssl. This meant that when we connected to an https server after that
same server via http, both on the default port, we'd incorrectly reuse
the non-https connection as the default port meant the connection
cache key was the same.
2011-05-16 16:59:45 -05:00
Augie Fackler
93b91bd721 httpconnection: fix debug logging option for httpclient 2011-05-11 08:07:51 -05:00
Augie Fackler
33ebd50b83 url: use new http support if requested by the user
The new http library is wired in via an extra module
(httpconnection.py), as it requires similar but different plumbing to
connect the library to Mercurial's internals and urllib2. Eventualy we
should be able to remove all of keepalive.py and its associated tangle
in url.py and replace it all with the code in httpconnection.py.

To use the new library, set 'ui.usehttp2' to true. The underlying http
library uses the logging module liberally, so if things break you can
use 'ui.http2debuglevel' to set the log level to INFO or DEBUG to get
that logging information (for example, ui.http2debuglevel=info.)
2011-05-06 10:22:08 -05:00