示例#1
0
def get_config(defaults, section):
    """This reads the key-value pairs from the specified section in the
       config file and from the common section.  It then places those
       appearing in the defaults into a dict, which is then returned.

       @type defaults: dict
       @param defaults: dict of name-value pairs derived from the
          defaults list for this application (see defaultargs.py).
          Only the names in the name-value pairs are used.  get_config
          only reads variables from the config file with matching names.
       @type section: str
       @param section: in the configuration from which to read options.
          So far, the sections have been named after applications, e.g.,
          bittorrent, bittorrent-console, etc.
       @return: a dict containing option-value pairs.
       """
    assert type(defaults)==dict
    assert type(section)==str

    configdir = get_dot_dir()

    if configdir is None:
        return {}

    if not os.path.isdir(configdir):
        try:
            os.mkdir(configdir, 0700)
        except:
            pass

    p = _read_config(os.path.join(configdir, 'config'))  # returns parser.

    if p.has_section('format'):
        encoding = p.get('format', 'encoding')
    else:
        encoding = old_broken_config_subencoding

    values = {}
    if p.has_section(section):
        for name, value in p.items(section):
            if name in defaults:
                values[name] = value
    if p.has_section('common'):
        for name, value in p.items('common'):
            if name in defaults and name not in values:
                values[name] = value
    if defaults.get('data_dir') == '' and \
           'data_dir' not in values and os.path.isdir(configdir):
        datadir = os.path.join(configdir, 'data')
        values['data_dir'] = decode_from_filesystem(datadir)

    parseargs.parse_options(defaults, values, encoding)
    return values
示例#2
0
 def to_utf8(name):
     if isinstance(name, unicode):
         u = name
     else:
         try:
             u = decode_from_filesystem(name)
         except Exception, e:
             s = str_exc(e)
             raise BTFailure(_('Could not convert file/directory name %r to '
                               'Unicode (%s). Either the assumed filesystem '
                               'encoding "%s" is wrong or the filename contains '
                               'illegal bytes.') % (name, s, get_filesystem_encoding()))
示例#3
0
    return defaults_tuplelist


if __name__ == '__main__':
    uiname = 'launchmany-console'
    defaults = get_defaults(uiname)
    try:
        if len(sys.argv) < 2:
            printHelp(uiname, defaults)
            sys.exit(1)

        # Modifying default values from get_defaults is annoying...
        # Implementing specific default values for each uiname in
        # defaultargs.py is even more annoying.  --Dave
        ddir = os.path.join( platform.get_dot_dir(), "launchmany-console" )
        ddir = decode_from_filesystem(ddir)
        modify_default(defaults, 'data_dir', ddir)
        config, args = configfile.parse_configuration_and_args(defaults,
                                      uiname, sys.argv[1:], 0, 1)

        # returned from here config['save_in'] is /home/dave/Desktop/...
        if args:
            torrent_dir = args[0]
            config['torrent_dir'] = decode_from_filesystem(torrent_dir)
        else:
            torrent_dir = config['torrent_dir']
            torrent_dir,bad = encode_for_filesystem(torrent_dir)
            if bad:
              raise BTFailure(_("Warning: ")+config['torrent_dir']+
                              _(" is not a directory"))
示例#4
0
    defaults = get_defaults('bittorrent-tracker')   # hard-coded defaults.
    try:
        config, files = parse_configuration_and_args(defaults,
           'bittorrent-tracker', args, 0, 0 )
    except ValueError, e:
        print _("error: ") + str_exc(e)
        print _("run with -? for parameter explanations")
        return
    except BTFailure, e:
        print _("error: ") + str_exc(e)
        print _("run with -? for parameter explanations")
        return

    if config['dfile']=="":
        config['dfile'] = decode_from_filesystem(
            os.path.join(platform.get_temp_dir(), efs2(u"dfile") +
            str(os.getpid())))

    config = Preferences().initWithDict(config)
    ef = lambda e: errorfunc(logging.WARNING, e)
    platform.write_pid_file(config['pid'], ef)

    t = None
    try:
        r = RawServer(config)
        t = Tracker(config, r)
        try:
            #DEBUG
            print "track: create_serversocket, port=", config['port']
            #END
            s = r.create_serversocket(config['port'], config['bind'])
示例#5
0
def parse_configuration_and_args(defaults, uiname, arglist=[], minargs=None,
                                 maxargs=None):
    """Given the default option settings and overrides these defaults
       from values read from the config file, and again overrides the
       config file with the arguments that appear in the arglist.

       'defaults' is a list of tuples of the form (optname, value,
       desc) where 'optname' is a string containing the option's name,
       value is the option's default value, and desc is the option's
       description.

       'uiname' is a string specifying the user interface that has been
       created by the caller.  Ex: bittorrent, maketorrent.

       arglist is usually argv[1:], i.e., excluding the name used to
       execute the program.

       minargs specifies the minimum number of arguments that must appear in
       arglist.  If the number of arguments is less than the minimum then
       a BTFailure exception is raised.

       maxargs specifies the maximum number of arguments that can appear
       in arglist.  If the number of arguments exceeds the maximum then
       a BTFailure exception is raised.

       This returns the tuple (config,args) where config is
       a dictionary of (option, value) pairs, and args is the list
       of arguments in arglist after the command-line arguments have
       been removed.

       For example:

          bittorrent-curses.py --save_as lx-2.6.rpm lx-2.6.rpm.torrent --max_upload_rate 0

          returns a (config,args) pair where the
          config dictionary contains many defaults plus
          the mappings
            'save_as': 'linux-2.6.15.tar.gz'
          and
            'max_upload_rate': 0

          The args in the returned pair is
            args= ['linux-2.6.15.tar.gz.torrent']
    """
    assert type(defaults)==list
    assert type(uiname)==str
    assert type(arglist)==list
    assert minargs is None or type(minargs) in (int,long) and minargs>=0
    assert maxargs is None or type(maxargs) in (int,long) and maxargs>=minargs

    # remap shortform arguments to their long-forms.
    arglist = convert_from_shortforms(arglist)

    defconfig = dict([(name, value) for (name, value, doc) in defaults])
    if arglist[0:] == ['--version']:
        print version
        sys.exit(0)

    if arglist[0:] == '--help':
        parseargs.printHelp(uiname, defaults)
        sys.exit(0)

    if "--use_factory_defaults" not in arglist:
        presets = get_config(defconfig, uiname)  # read from .bittorrent dir.

    # run as if fresh install using temporary directories.
    else:
        presets = {}
        temp_dir = get_temp_subdir()
        #set_config_dir(temp_dir)  # is already set in platform.py.
        save_in = encode_for_filesystem( u"save_in" )[0]
        presets["save_in"] = \
            decode_from_filesystem(os.path.join(temp_dir,save_in))
        data = encode_for_filesystem( u"data" )[0]
        presets["data_dir"] = \
            decode_from_filesystem(os.path.join(temp_dir,data))
        incomplete = encode_for_filesystem( u"incomplete" )[0]
        presets["save_incomplete_in"] = \
            decode_from_filesystem(os.path.join(temp_dir,incomplete))
        presets["one_connection_per_ip"] = False

    config = args = None
    try:
        config, args = parseargs.parseargs(arglist, defaults, minargs, maxargs,
                                           presets)
    except parseargs.UsageException, e:
        print e
        parseargs.printHelp(uiname, defaults)
        sys.exit(0)
示例#6
0
        smart_gettext_and_install('bittorrent', locale_root,
                                  languages=[config['language']])

    if config.has_key('bind') and config['bind'] != '':
        bind_tracker_connection(config['bind'])

    if config.has_key('launch_on_startup'):
        enforce_shortcut(config, log_func=sys.stderr.write)

    if os.name == 'nt' and config.has_key('enforce_association'):
        enforce_association()

    if config.has_key('save_in') and config['save_in'] == '' and \
       (not config.has_key("save_as") or config['save_as'] == '' ) \
       and uiname != 'bittorrent':
        config['save_in'] = decode_from_filesystem(get_save_dir())

    incomplete = decode_from_filesystem(get_incomplete_data_dir())
    if config.get('save_incomplete_in') == '':
        config['save_incomplete_in'] = incomplete
    if config.get('save_incomplete_in') == get_old_incomplete_data_dir():
        config['save_incomplete_in'] = incomplete

    if uiname == "test-client" or (uiname.startswith("bittorrent")
                                   and uiname != 'bittorrent-tracker'):
        if not config.get('ask_for_save'):
            # we check for existance, so things like "D:\" don't trip us up.
            if (config['save_in'] and
                not os.path.exists(config['save_in'])):
                try:
                    os.makedirs(config['save_in'])
示例#7
0
def expanduser(path):
    user_path = os.path.expanduser(path)
    print "expanduser: user_path=", user_path
    print "str?",  isinstance(user_path,str)
    print "unicode?", isinstance(user_path,unicode)
    return decode_from_filesystem(user_path)
    return defaults_tuplelist
    

if __name__ == '__main__':
    uiname = 'launchmany-console'
    defaults = get_defaults(uiname)
    try:
        if len(sys.argv) < 2:
            printHelp(uiname, defaults)
            sys.exit(1)

        # Modifying default values from get_defaults is annoying...
        # Implementing specific default values for each uiname in
        # defaultargs.py is even more annoying.  --Dave
        ddir = os.path.join( platform.get_dot_dir(), "launchmany-console" )
        ddir = decode_from_filesystem(ddir)
        modify_default(defaults, 'data_dir', ddir)
        config, args = configfile.parse_configuration_and_args(defaults,
                                      uiname, sys.argv[1:], 0, 1)

        # returned from here config['save_in'] is /home/dave/Desktop/...
        if args:
            torrent_dir = args[0]
            config['torrent_dir'] = \
                platform.decode_from_filesystem(torrent_dir)
        else:
            torrent_dir = config['torrent_dir']
            torrent_dir,bad = platform.encode_for_filesystem(torrent_dir)
            if bad:
              raise BTFailure(_("Warning: ")+config['torrent_dir']+
                              _(" is not a directory"))
示例#9
0
def commonprefx(pathlist):
    fslist = [efs2(path) for path in pathlist]
    return decode_from_filesystem(os.path.commonprefix(fslist))
示例#10
0
def realpath(path):
    fspath = efs2(path)
    return decode_from_filesystem(os.path.realpath(fspath))
示例#11
0
def normpath(path):
    fspath = efs2(path)
    return decode_from_filesystem(os.path.normpath(fspath))
示例#12
0
def basename(path):
    fspath = efs2(path)
    return decode_from_filesystem(os.path.basename(fspath))
示例#13
0
def split(path):
    fspath, fsname = os.path.split(path)
    return decode_from_filesystem(fspath), decode_from_filesystem(fsname)