text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resource_create_ticket(self, token, id, scopes, **kwargs):
""" Create a ticket form permission to resource. https://www.keycloak.org/docs/latest/authorization_services/index.html#_service_protection_permission_api_papi :param str token: user access token :param str id: resource id :param list scopes: scopes access is wanted :param dict claims: (optional) :rtype: dict """ |
data = dict(resource_id=id, resource_scopes=scopes, **kwargs)
return self._realm.client.post(
self.well_known['permission_endpoint'],
data=self._dumps([data]),
headers=self.get_headers(token)
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resource_associate_permission(self, token, id, name, scopes, **kwargs):
""" Associates a permission with a Resource. https://www.keycloak.org/docs/latest/authorization_services/index.html#_service_authorization_uma_policy_api :param str token: client access token :param str id: resource id :param str name: permission name :param list scopes: scopes access is wanted :param str description:optional :param list roles: (optional) :param list groups: (optional) :param list clients: (optional) :param str condition: (optional) :rtype: dict """ |
return self._realm.client.post(
'{}/{}'.format(self.well_known['policy_endpoint'], id),
data=self._get_data(name=name, scopes=scopes, **kwargs),
headers=self.get_headers(token)
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def permission_update(self, token, id, **kwargs):
""" To update an existing permission. https://www.keycloak.org/docs/latest/authorization_services/index.html#_service_authorization_uma_policy_api :param str token: client access token :param str id: permission id :rtype: dict """ |
return self._realm.client.put(
'{}/{}'.format(self.well_known['policy_endpoint'], id),
data=self._dumps(kwargs),
headers=self.get_headers(token)
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def permission_delete(self, token, id):
""" Removing a Permission. https://www.keycloak.org/docs/latest/authorization_services/index.html#removing-a-permission :param str token: client access token :param str id: permission id :rtype: dict """ |
return self._realm.client.delete(
'{}/{}'.format(self.well_known['policy_endpoint'], id),
headers=self.get_headers(token)
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _decode_token(cls, token):
""" Permission information is encoded in an authorization token. """ |
missing_padding = len(token) % 4
if missing_padding != 0:
token += '=' * (4 - missing_padding)
return json.loads(base64.b64decode(token).decode('utf-8')) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_permissions(self, token, resource_scopes_tuples=None, submit_request=False, ticket=None):
""" Request permissions for user from keycloak server. https://www.keycloak.org/docs/latest/authorization_services/index .html#_service_protection_permission_api_papi :param str token: client access token :param Iterable[Tuple[str, str]] resource_scopes_tuples: list of tuples (resource, scope) :param boolean submit_request: submit request if not allowed to access? :param str ticket: Permissions ticket rtype: dict """ |
headers = {
"Authorization": "Bearer %s" % token,
'Content-type': 'application/x-www-form-urlencoded',
}
data = [
('grant_type', 'urn:ietf:params:oauth:grant-type:uma-ticket'),
('audience', self._client_id),
('response_include_resource_name', True),
]
if resource_scopes_tuples:
for atuple in resource_scopes_tuples:
data.append(('permission', '#'.join(atuple)))
data.append(('submit_request', submit_request))
elif ticket:
data.append(('ticket', ticket))
authz_info = {}
try:
response = self._realm.client.post(
self.well_known['token_endpoint'],
data=urlencode(data),
headers=headers,
)
error = response.get('error')
if error:
self.logger.warning(
'%s: %s',
error,
response.get('error_description')
)
else:
token = response.get('refresh_token')
decoded_token = self._decode_token(token.split('.')[1])
authz_info = decoded_token.get('authorization', {})
except KeycloakClientError as error:
self.logger.warning(str(error))
return authz_info |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def eval_permission(self, token, resource, scope, submit_request=False):
""" Evalutes if user has permission for scope on resource. :param str token: client access token :param str resource: resource to access :param str scope: scope on resource :param boolean submit_request: submit request if not allowed to access? rtype: boolean """ |
return self.eval_permissions(
token=token,
resource_scopes_tuples=[(resource, scope)],
submit_request=submit_request
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def eval_permissions(self, token, resource_scopes_tuples=None, submit_request=False):
""" Evaluates if user has permission for all the resource scope combinations. :param str token: client access token :param Iterable[Tuple[str, str]] resource_scopes_tuples: resource to access :param boolean submit_request: submit request if not allowed to access? rtype: boolean """ |
permissions = self.get_permissions(
token=token,
resource_scopes_tuples=resource_scopes_tuples,
submit_request=submit_request
)
res = []
for permission in permissions.get('permissions', []):
for scope in permission.get('scopes', []):
ptuple = (permission.get('rsname'), scope)
if ptuple in resource_scopes_tuples:
res.append(ptuple)
return res == resource_scopes_tuples |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def logout(self, refresh_token):
""" The logout endpoint logs out the authenticated user. :param str refresh_token: """ |
return self._realm.client.post(self.get_url('end_session_endpoint'),
data={
'refresh_token': refresh_token,
'client_id': self._client_id,
'client_secret': self._client_secret
}) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def userinfo(self, token):
""" The UserInfo Endpoint is an OAuth 2.0 Protected Resource that returns Claims about the authenticated End-User. To obtain the requested Claims about the End-User, the Client makes a request to the UserInfo Endpoint using an Access Token obtained through OpenID Connect Authentication. These Claims are normally represented by a JSON object that contains a collection of name and value pairs for the Claims. http://openid.net/specs/openid-connect-core-1_0.html#UserInfo :param str token: :rtype: dict """ |
url = self.well_known['userinfo_endpoint']
return self._realm.client.get(url, headers={
"Authorization": "Bearer {}".format(
token
)
}) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def authorization_url(self, **kwargs):
""" Get authorization URL to redirect the resource owner to. https://tools.ietf.org/html/rfc6749#section-4.1.1 :param str redirect_uri: (optional) Absolute URL of the client where the user-agent will be redirected to. :param str scope: (optional) Space delimited list of strings. :param str state: (optional) An opaque value used by the client to maintain state between the request and callback :return: URL to redirect the resource owner to :rtype: str """ |
payload = {'response_type': 'code', 'client_id': self._client_id}
for key in kwargs.keys():
# Add items in a sorted way for unittest purposes.
payload[key] = kwargs[key]
payload = sorted(payload.items(), key=lambda val: val[0])
params = urlencode(payload)
url = self.get_url('authorization_endpoint')
return '{}?{}'.format(url, params) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def authorization_code(self, code, redirect_uri):
""" Retrieve access token by `authorization_code` grant. https://tools.ietf.org/html/rfc6749#section-4.1.3 :param str code: The authorization code received from the authorization server. :param str redirect_uri: the identical value of the "redirect_uri" parameter in the authorization request. :rtype: dict :return: Access token response """ |
return self._token_request(grant_type='authorization_code', code=code,
redirect_uri=redirect_uri) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def password_credentials(self, username, password, **kwargs):
""" Retrieve access token by 'password credentials' grant. https://tools.ietf.org/html/rfc6749#section-4.3 :param str username: The user name to obtain an access token for :param str password: The user's password :rtype: dict :return: Access token response """ |
return self._token_request(grant_type='password',
username=username, password=password,
**kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def refresh_token(self, refresh_token, **kwargs):
""" Refresh an access token https://tools.ietf.org/html/rfc6749#section-6 :param str refresh_token: :param str scope: (optional) Space delimited list of strings. :rtype: dict :return: Access token response """ |
return self._token_request(grant_type='refresh_token',
refresh_token=refresh_token, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _token_request(self, grant_type, **kwargs):
""" Do the actual call to the token end-point. :param grant_type: :param kwargs: See invoking methods. :return: """ |
payload = {
'grant_type': grant_type,
'client_id': self._client_id,
'client_secret': self._client_secret
}
payload.update(**kwargs)
return self._realm.client.post(self.get_url('token_endpoint'),
data=payload) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create(self, name, **kwargs):
""" Create new role http://www.keycloak.org/docs-api/3.4/rest-api/index.html #_roles_resource :param str name: Name for the role :param str description: (optional) :param str id: (optional) :param bool client_role: (optional) :param bool composite: (optional) :param object composites: (optional) :param str container_id: (optional) :param bool scope_param_required: (optional) """ |
payload = OrderedDict(name=name)
for key in ROLE_KWARGS:
if key in kwargs:
payload[to_camel_case(key)] = kwargs[key]
return self._client.post(
url=self._client.get_full_url(
self.get_path('collection',
realm=self._realm_name,
id=self._client_id)
),
data=json.dumps(payload, sort_keys=True)
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update(self, name, **kwargs):
""" Update existing role. http://www.keycloak.org/docs-api/3.4/rest-api/index.html#_roles_resource :param str name: Name for the role :param str description: (optional) :param str id: (optional) :param bool client_role: (optional) :param bool composite: (optional) :param object composites: (optional) :param str container_id: (optional) :param bool scope_param_required: (optional) """ |
payload = OrderedDict(name=name)
for key in ROLE_KWARGS:
if key in kwargs:
payload[to_camel_case(key)] = kwargs[key]
return self._client.put(
url=self._client.get_full_url(
self.get_path('single',
realm=self._realm_name,
id=self._client_id,
role_name=self._role_name)
),
data=json.dumps(payload, sort_keys=True)
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract_rpm (archive, compression, cmd, verbosity, interactive, outdir):
"""Extract a RPM archive.""" |
# also check cpio
cpio = util.find_program("cpio")
if not cpio:
raise util.PatoolError("cpio(1) is required for rpm2cpio extraction; please install it")
path = util.shell_quote(os.path.abspath(archive))
cmdlist = [util.shell_quote(cmd), path, "|", util.shell_quote(cpio),
'--extract', '--make-directories', '--preserve-modification-time',
'--no-absolute-filenames', '--force-local', '--nonmatching',
r'"*\.\.*"']
if verbosity > 1:
cmdlist.append('-v')
return (cmdlist, {'cwd': outdir, 'shell': True}) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_tar (archive, compression, cmd, verbosity, interactive):
"""List a TAR archive with the tarfile Python module.""" |
try:
with tarfile.open(archive) as tfile:
tfile.list(verbose=verbosity>1)
except Exception as err:
msg = "error listing %s: %s" % (archive, err)
raise util.PatoolError(msg)
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract_tar (archive, compression, cmd, verbosity, interactive, outdir):
"""Extract a TAR archive with the tarfile Python module.""" |
try:
with tarfile.open(archive) as tfile:
tfile.extractall(path=outdir)
except Exception as err:
msg = "error extracting %s: %s" % (archive, err)
raise util.PatoolError(msg)
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_tar (archive, compression, cmd, verbosity, interactive, filenames):
"""Create a TAR archive with the tarfile Python module.""" |
mode = get_tar_mode(compression)
try:
with tarfile.open(archive, mode) as tfile:
for filename in filenames:
tfile.add(filename)
except Exception as err:
msg = "error creating %s: %s" % (archive, err)
raise util.PatoolError(msg)
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_tar_mode (compression):
"""Determine tarfile open mode according to the given compression.""" |
if compression == 'gzip':
return 'w:gz'
if compression == 'bzip2':
return 'w:bz2'
if compression == 'lzma' and py_lzma:
return 'w:xz'
if compression:
msg = 'pytarfile does not support %s for tar compression'
raise util.PatoolError(msg % compression)
# no compression
return 'w' |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract_arj (archive, compression, cmd, verbosity, interactive, outdir):
"""Extract an ARJ archive.""" |
cmdlist = [cmd, 'x', '-r']
if not interactive:
cmdlist.append('-y')
cmdlist.extend([archive, outdir])
return cmdlist |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_arj (archive, compression, cmd, verbosity, interactive):
"""List an ARJ archive.""" |
cmdlist = [cmd]
if verbosity > 1:
cmdlist.append('v')
else:
cmdlist.append('l')
if not interactive:
cmdlist.append('-y')
cmdlist.extend(['-r', archive])
return cmdlist |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_arj (archive, compression, cmd, verbosity, interactive, filenames):
"""Create an ARJ archive.""" |
cmdlist = [cmd, 'a', '-r']
if not interactive:
cmdlist.append('-y')
cmdlist.append(archive)
cmdlist.extend(filenames)
return cmdlist |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_zpaq(archive, compression, cmd, verbosity, interactive, filenames):
"""Create a ZPAQ archive.""" |
cmdlist = [cmd, 'a', archive]
cmdlist.extend(filenames)
cmdlist.extend(['-method', '4'])
return cmdlist |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract_alzip (archive, compression, cmd, verbosity, interactive, outdir):
"""Extract a ALZIP archive.""" |
return [cmd, '-d', outdir, archive] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract_tar (archive, compression, cmd, verbosity, interactive, outdir):
"""Extract a TAR archive.""" |
cmdlist = [cmd, '--extract']
add_tar_opts(cmdlist, compression, verbosity)
cmdlist.extend(["--file", archive, '--directory', outdir])
return cmdlist |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_tar_opts (cmdlist, compression, verbosity):
"""Add tar options to cmdlist.""" |
progname = os.path.basename(cmdlist[0])
if compression == 'gzip':
cmdlist.append('-z')
elif compression == 'compress':
cmdlist.append('-Z')
elif compression == 'bzip2':
cmdlist.append('-j')
elif compression in ('lzma', 'xz') and progname == 'bsdtar':
cmdlist.append('--%s' % compression)
elif compression in ('lzma', 'xz', 'lzip'):
# use the compression name as program name since
# tar is picky which programs it can use
program = compression
# set compression program
cmdlist.extend(['--use-compress-program', program])
if verbosity > 1:
cmdlist.append('--verbose')
if progname == 'tar':
cmdlist.append('--force-local') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_zip(archive, compression, cmd, verbosity, interactive):
"""List member of a ZIP archive with the zipfile Python module.""" |
try:
with zipfile.ZipFile(archive, "r") as zfile:
for name in zfile.namelist():
if verbosity >= 0:
print(name)
except Exception as err:
msg = "error listing %s: %s" % (archive, err)
raise util.PatoolError(msg)
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract_zip(archive, compression, cmd, verbosity, interactive, outdir):
"""Extract a ZIP archive with the zipfile Python module.""" |
try:
with zipfile.ZipFile(archive) as zfile:
zfile.extractall(outdir)
except Exception as err:
msg = "error extracting %s: %s" % (archive, err)
raise util.PatoolError(msg)
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_zip(archive, compression, cmd, verbosity, interactive, filenames):
"""Create a ZIP archive with the zipfile Python module.""" |
try:
with zipfile.ZipFile(archive, 'w') as zfile:
for filename in filenames:
if os.path.isdir(filename):
write_directory(zfile, filename)
else:
zfile.write(filename)
except Exception as err:
msg = "error creating %s: %s" % (archive, err)
raise util.PatoolError(msg)
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write_directory (zfile, directory):
"""Write recursively all directories and filenames to zipfile instance.""" |
for dirpath, dirnames, filenames in os.walk(directory):
zfile.write(dirpath)
for filename in filenames:
zfile.write(os.path.join(dirpath, filename)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract_shn (archive, compression, cmd, verbosity, interactive, outdir):
"""Decompress a SHN archive to a WAV file.""" |
cmdlist = [util.shell_quote(cmd)]
outfile = util.get_single_outfile(outdir, archive, extension=".wav")
cmdlist.extend(['-x', '-', util.shell_quote(outfile), '<',
util.shell_quote(archive)])
return (cmdlist, {'shell': True}) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_shn (archive, compression, cmd, verbosity, interactive, filenames):
"""Compress a WAV file to a SHN archive.""" |
if len(filenames) > 1:
raise util.PatoolError("multiple filenames for shorten not supported")
cmdlist = [util.shell_quote(cmd)]
cmdlist.extend(['-', util.shell_quote(archive), '<',
util.shell_quote(filenames[0])])
return (cmdlist, {'shell': True}) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract_dms (archive, compression, cmd, verbosity, interactive, outdir):
"""Extract a DMS archive.""" |
check_archive_ext(archive)
cmdlist = [cmd, '-d', outdir]
if verbosity > 1:
cmdlist.append('-v')
cmdlist.extend(['u', archive])
return cmdlist |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_dms (archive, compression, cmd, verbosity, interactive):
"""List a DMS archive.""" |
check_archive_ext(archive)
return [cmd, 'v', archive] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_xz (archive, compression, cmd, verbosity, interactive):
"""List a XZ archive.""" |
cmdlist = [cmd]
cmdlist.append('-l')
if verbosity > 1:
cmdlist.append('-v')
cmdlist.append(archive)
return cmdlist |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract_lzma(archive, compression, cmd, verbosity, interactive, outdir):
"""Extract an LZMA archive.""" |
cmdlist = [util.shell_quote(cmd), '--format=lzma']
if verbosity > 1:
cmdlist.append('-v')
outfile = util.get_single_outfile(outdir, archive)
cmdlist.extend(['-c', '-d', '--', util.shell_quote(archive), '>',
util.shell_quote(outfile)])
return (cmdlist, {'shell': True}) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract_ace (archive, compression, cmd, verbosity, interactive, outdir):
"""Extract an ACE archive.""" |
cmdlist = [cmd, 'x']
if not outdir.endswith('/'):
outdir += '/'
cmdlist.extend([archive, outdir])
return cmdlist |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_ace (archive, compression, cmd, verbosity, interactive):
"""List an ACE archive.""" |
cmdlist = [cmd]
if verbosity > 1:
cmdlist.append('v')
else:
cmdlist.append('l')
cmdlist.append(archive)
return cmdlist |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract_bzip2 (archive, compression, cmd, verbosity, interactive, outdir):
"""Extract a BZIP2 archive with the bz2 Python module.""" |
targetname = util.get_single_outfile(outdir, archive)
try:
with bz2.BZ2File(archive) as bz2file:
with open(targetname, 'wb') as targetfile:
data = bz2file.read(READ_SIZE_BYTES)
while data:
targetfile.write(data)
data = bz2file.read(READ_SIZE_BYTES)
except Exception as err:
msg = "error extracting %s to %s: %s" % (archive, targetname, err)
raise util.PatoolError(msg)
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_bzip2 (archive, compression, cmd, verbosity, interactive, filenames):
"""Create a BZIP2 archive with the bz2 Python module.""" |
if len(filenames) > 1:
raise util.PatoolError('multi-file compression not supported in Python bz2')
try:
with bz2.BZ2File(archive, 'wb') as bz2file:
filename = filenames[0]
with open(filename, 'rb') as srcfile:
data = srcfile.read(READ_SIZE_BYTES)
while data:
bz2file.write(data)
data = srcfile.read(READ_SIZE_BYTES)
except Exception as err:
msg = "error creating %s: %s" % (archive, err)
raise util.PatoolError(msg)
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract_lzh (archive, compression, cmd, verbosity, interactive, outdir):
"""Extract a LZH archive.""" |
opts = 'x'
if verbosity > 1:
opts += 'v'
opts += "w=%s" % outdir
return [cmd, opts, archive] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_lzh (archive, compression, cmd, verbosity, interactive):
"""List a LZH archive.""" |
cmdlist = [cmd]
if verbosity > 1:
cmdlist.append('v')
else:
cmdlist.append('l')
cmdlist.append(archive)
return cmdlist |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract_ape (archive, compression, cmd, verbosity, interactive, outdir):
"""Decompress an APE archive to a WAV file.""" |
outfile = util.get_single_outfile(outdir, archive, extension=".wav")
return [cmd, archive, outfile, '-d'] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract_adf (archive, compression, cmd, verbosity, interactive, outdir):
"""Extract an ADF archive.""" |
return [cmd, archive, '-d', outdir] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract_lrzip (archive, compression, cmd, verbosity, interactive, outdir):
"""Extract a LRZIP archive.""" |
cmdlist = [cmd, '-d']
if verbosity > 1:
cmdlist.append('-v')
outfile = util.get_single_outfile(outdir, archive)
cmdlist.extend(["-o", outfile, os.path.abspath(archive)])
return cmdlist |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_bzip2 (archive, compression, cmd, verbosity, interactive):
"""List a BZIP2 archive.""" |
return stripext(cmd, archive, verbosity) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_ape (archive, compression, cmd, verbosity, interactive):
"""List an APE archive.""" |
return stripext(cmd, archive, verbosity, extension=".wav") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stripext (cmd, archive, verbosity, extension=""):
"""Print the name without suffix.""" |
if verbosity >= 0:
print(util.stripext(archive)+extension)
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract_ar (archive, compression, cmd, verbosity, interactive, outdir):
"""Extract a AR archive.""" |
opts = 'x'
if verbosity > 1:
opts += 'v'
cmdlist = [cmd, opts, os.path.abspath(archive)]
return (cmdlist, {'cwd': outdir}) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_ar (archive, compression, cmd, verbosity, interactive):
"""List a AR archive.""" |
opts = 't'
if verbosity > 1:
opts += 'v'
return [cmd, opts, archive] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_ar (archive, compression, cmd, verbosity, interactive, filenames):
"""Create a AR archive.""" |
opts = 'rc'
if verbosity > 1:
opts += 'v'
cmdlist = [cmd, opts, archive]
cmdlist.extend(filenames)
return cmdlist |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract_cab (archive, compression, cmd, verbosity, interactive, outdir):
"""Extract a CAB archive.""" |
cmdlist = [cmd, '-d', outdir]
if verbosity > 0:
cmdlist.append('-v')
cmdlist.append(archive)
return cmdlist |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_cab (archive, compression, cmd, verbosity, interactive):
"""List a CAB archive.""" |
cmdlist = [cmd, '-l']
if verbosity > 0:
cmdlist.append('-v')
cmdlist.append(archive)
return cmdlist |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract_rzip (archive, compression, cmd, verbosity, interactive, outdir):
"""Extract an RZIP archive.""" |
cmdlist = [cmd, '-d', '-k']
if verbosity > 1:
cmdlist.append('-v')
outfile = util.get_single_outfile(outdir, archive)
cmdlist.extend(["-o", outfile, archive])
return cmdlist |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def program_supports_compression (program, compression):
"""Decide if the given program supports the compression natively. @return: True iff the program supports the given compression format natively, else False. """ |
if program in ('tar', ):
return compression in ('gzip', 'bzip2', 'xz', 'lzip', 'compress', 'lzma') + py_lzma
elif program in ('star', 'bsdtar', 'py_tarfile'):
return compression in ('gzip', 'bzip2') + py_lzma
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_archive_format (filename):
"""Detect filename archive format and optional compression.""" |
mime, compression = util.guess_mime(filename)
if not (mime or compression):
raise util.PatoolError("unknown archive format for file `%s'" % filename)
if mime in ArchiveMimetypes:
format = ArchiveMimetypes[mime]
else:
raise util.PatoolError("unknown archive format for file `%s' (mime-type is `%s')" % (filename, mime))
if format == compression:
# file cannot be in same format compressed
compression = None
return format, compression |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_archive_format (format, compression):
"""Make sure format and compression is known.""" |
if format not in ArchiveFormats:
raise util.PatoolError("unknown archive format `%s'" % format)
if compression is not None and compression not in ArchiveCompressions:
raise util.PatoolError("unkonwn archive compression `%s'" % compression) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_archive_program (format, command, program=None):
"""Find suitable archive program for given format and mode.""" |
commands = ArchivePrograms[format]
programs = []
if program is not None:
# try a specific program first
programs.append(program)
# first try the universal programs with key None
for key in (None, command):
if key in commands:
programs.extend(commands[key])
if not programs:
raise util.PatoolError("%s archive format `%s' is not supported" % (command, format))
# return the first existing program
for program in programs:
if program.startswith('py_'):
# it's a Python module and therefore always supported
return program
exe = util.find_program(program)
if exe:
if program == '7z' and format == 'rar' and not util.p7zip_supports_rar():
continue
return exe
# no programs found
raise util.PatoolError("could not find an executable program to %s format %s; candidates are (%s)," % (command, format, ",".join(programs))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_formats ():
"""Print information about available archive formats to stdout.""" |
print("Archive programs of", App)
print("Archive programs are searched in the following directories:")
print(util.system_search_path())
print()
for format in ArchiveFormats:
print(format, "files:")
for command in ArchiveCommands:
programs = ArchivePrograms[format]
if command not in programs and None not in programs:
print(" %8s: - (not supported)" % command)
continue
try:
program = find_archive_program(format, command)
print(" %8s: %s" % (command, program), end=' ')
if format == 'tar':
encs = [x for x in ArchiveCompressions if util.find_program(x)]
if encs:
print("(supported compressions: %s)" % ", ".join(encs), end=' ')
elif format == '7z':
if util.p7zip_supports_rar():
print("(rar archives supported)", end=' ')
else:
print("(rar archives not supported)", end=' ')
print()
except util.PatoolError:
# display information what programs can handle this archive format
handlers = programs.get(None, programs.get(command))
print(" %8s: - (no program found; install %s)" %
(command, util.strlist_with_or(handlers))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_program_compression(archive, command, program, compression):
"""Check if a program supports the given compression.""" |
program = os.path.basename(program)
if compression:
# check if compression is supported
if not program_supports_compression(program, compression):
if command == 'create':
comp_command = command
else:
comp_command = 'extract'
comp_prog = find_archive_program(compression, comp_command)
if not comp_prog:
msg = "cannot %s archive `%s': compression `%s' not supported"
raise util.PatoolError(msg % (command, archive, compression)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run_archive_cmdlist (archive_cmdlist, verbosity=0):
"""Run archive command.""" |
# archive_cmdlist is a command list with optional keyword arguments
if isinstance(archive_cmdlist, tuple):
cmdlist, runkwargs = archive_cmdlist
else:
cmdlist, runkwargs = archive_cmdlist, {}
return util.run_checked(cmdlist, verbosity=verbosity, **runkwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_file_readable (filename):
"""Make file user readable if it is not a link.""" |
if not os.path.islink(filename):
util.set_mode(filename, stat.S_IRUSR) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_user_readable (directory):
"""Make all files in given directory user readable. Also recurse into subdirectories.""" |
for root, dirs, files in os.walk(directory, onerror=util.log_error):
for filename in files:
make_file_readable(os.path.join(root, filename))
for dirname in dirs:
make_dir_readable(os.path.join(root, dirname)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cleanup_outdir (outdir, archive):
"""Cleanup outdir after extraction and return target file name and result string.""" |
make_user_readable(outdir)
# move single directory or file in outdir
(success, msg) = move_outdir_orphan(outdir)
if success:
# msg is a single directory or filename
return msg, "`%s'" % msg
# outdir remains unchanged
# rename it to something more user-friendly (basically the archive
# name without extension)
outdir2 = util.get_single_outfile("", archive)
os.rename(outdir, outdir2)
return outdir2, "`%s' (%s)" % (outdir2, msg) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _extract_archive(archive, verbosity=0, interactive=True, outdir=None, program=None, format=None, compression=None):
"""Extract an archive. @return: output directory if command is 'extract', else None """ |
if format is None:
format, compression = get_archive_format(archive)
check_archive_format(format, compression)
program = find_archive_program(format, 'extract', program=program)
check_program_compression(archive, 'extract', program, compression)
get_archive_cmdlist = get_archive_cmdlist_func(program, 'extract', format)
if outdir is None:
outdir = util.tmpdir(dir=".")
do_cleanup_outdir = True
else:
do_cleanup_outdir = False
try:
cmdlist = get_archive_cmdlist(archive, compression, program, verbosity, interactive, outdir)
if cmdlist:
# an empty command list means the get_archive_cmdlist() function
# already handled the command (eg. when it's a builtin Python
# function)
run_archive_cmdlist(cmdlist, verbosity=verbosity)
if do_cleanup_outdir:
target, msg = cleanup_outdir(outdir, archive)
else:
target, msg = outdir, "`%s'" % outdir
if verbosity >= 0:
util.log_info("... %s extracted to %s." % (archive, msg))
return target
finally:
# try to remove an empty temporary output directory
if do_cleanup_outdir:
try:
os.rmdir(outdir)
except OSError:
pass |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _create_archive(archive, filenames, verbosity=0, interactive=True, program=None, format=None, compression=None):
"""Create an archive.""" |
if format is None:
format, compression = get_archive_format(archive)
check_archive_format(format, compression)
program = find_archive_program(format, 'create', program=program)
check_program_compression(archive, 'create', program, compression)
get_archive_cmdlist = get_archive_cmdlist_func(program, 'create', format)
origarchive = None
if os.path.basename(program) == 'arc' and \
".arc" in archive and not archive.endswith(".arc"):
# the arc program mangles the archive name if it contains ".arc"
origarchive = archive
archive = util.tmpfile(dir=os.path.dirname(archive), suffix=".arc")
cmdlist = get_archive_cmdlist(archive, compression, program, verbosity, interactive, filenames)
if cmdlist:
# an empty command list means the get_archive_cmdlist() function
# already handled the command (eg. when it's a builtin Python
# function)
run_archive_cmdlist(cmdlist, verbosity=verbosity)
if origarchive:
shutil.move(archive, origarchive) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _handle_archive(archive, command, verbosity=0, interactive=True, program=None, format=None, compression=None):
"""Test and list archives.""" |
if format is None:
format, compression = get_archive_format(archive)
check_archive_format(format, compression)
if command not in ('list', 'test'):
raise util.PatoolError("invalid archive command `%s'" % command)
program = find_archive_program(format, command, program=program)
check_program_compression(archive, command, program, compression)
get_archive_cmdlist = get_archive_cmdlist_func(program, command, format)
# prepare keyword arguments for command list
cmdlist = get_archive_cmdlist(archive, compression, program, verbosity, interactive)
if cmdlist:
# an empty command list means the get_archive_cmdlist() function
# already handled the command (eg. when it's a builtin Python
# function)
run_archive_cmdlist(cmdlist, verbosity=verbosity) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_archive_cmdlist_func (program, command, format):
"""Get the Python function that executes the given program.""" |
# get python module for given archive program
key = util.stripext(os.path.basename(program).lower())
modulename = ".programs." + ProgramModules.get(key, key)
# import the module
try:
module = importlib.import_module(modulename, __name__)
except ImportError as msg:
raise util.PatoolError(msg)
# get archive handler function (eg. patoolib.programs.star.extract_tar)
try:
return getattr(module, '%s_%s' % (command, format))
except AttributeError as msg:
raise util.PatoolError(msg) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _diff_archives (archive1, archive2, verbosity=0, interactive=True):
"""Show differences between two archives. @return 0 if archives are the same, else 1 @raises: PatoolError on errors """ |
if util.is_same_file(archive1, archive2):
return 0
diff = util.find_program("diff")
if not diff:
msg = "The diff(1) program is required for showing archive differences, please install it."
raise util.PatoolError(msg)
tmpdir1 = util.tmpdir()
try:
path1 = _extract_archive(archive1, outdir=tmpdir1, verbosity=-1)
tmpdir2 = util.tmpdir()
try:
path2 = _extract_archive(archive2, outdir=tmpdir2, verbosity=-1)
return util.run_checked([diff, "-urN", path1, path2], verbosity=1, ret_ok=(0, 1))
finally:
shutil.rmtree(tmpdir2, onerror=rmtree_log_error)
finally:
shutil.rmtree(tmpdir1, onerror=rmtree_log_error) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _search_archive(pattern, archive, verbosity=0, interactive=True):
"""Search for given pattern in an archive.""" |
grep = util.find_program("grep")
if not grep:
msg = "The grep(1) program is required for searching archive contents, please install it."
raise util.PatoolError(msg)
tmpdir = util.tmpdir()
try:
path = _extract_archive(archive, outdir=tmpdir, verbosity=-1)
return util.run_checked([grep, "-r", "-e", pattern, "."], ret_ok=(0, 1), verbosity=1, cwd=path)
finally:
shutil.rmtree(tmpdir, onerror=rmtree_log_error) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _repack_archive (archive1, archive2, verbosity=0, interactive=True):
"""Repackage an archive to a different format.""" |
format1, compression1 = get_archive_format(archive1)
format2, compression2 = get_archive_format(archive2)
if format1 == format2 and compression1 == compression2:
# same format and compression allows to copy the file
util.link_or_copy(archive1, archive2, verbosity=verbosity)
return
tmpdir = util.tmpdir()
try:
kwargs = dict(verbosity=verbosity, outdir=tmpdir)
same_format = (format1 == format2 and compression1 and compression2)
if same_format:
# only decompress since the format is the same
kwargs['format'] = compression1
path = _extract_archive(archive1, **kwargs)
archive = os.path.abspath(archive2)
files = tuple(os.listdir(path))
olddir = os.getcwd()
os.chdir(path)
try:
kwargs = dict(verbosity=verbosity, interactive=interactive)
if same_format:
# only compress since the format is the same
kwargs['format'] = compression2
_create_archive(archive, files, **kwargs)
finally:
os.chdir(olddir)
finally:
shutil.rmtree(tmpdir, onerror=rmtree_log_error) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _recompress_archive(archive, verbosity=0, interactive=True):
"""Try to recompress an archive to smaller size.""" |
format, compression = get_archive_format(archive)
if compression:
# only recompress the compression itself (eg. for .tar.xz)
format = compression
tmpdir = util.tmpdir()
tmpdir2 = util.tmpdir()
base, ext = os.path.splitext(os.path.basename(archive))
archive2 = util.get_single_outfile(tmpdir2, base, extension=ext)
try:
# extract
kwargs = dict(verbosity=verbosity, format=format, outdir=tmpdir)
path = _extract_archive(archive, **kwargs)
# compress to new file
olddir = os.getcwd()
os.chdir(path)
try:
kwargs = dict(verbosity=verbosity, interactive=interactive, format=format)
files = tuple(os.listdir(path))
_create_archive(archive2, files, **kwargs)
finally:
os.chdir(olddir)
# check file sizes and replace if new file is smaller
filesize = util.get_filesize(archive)
filesize2 = util.get_filesize(archive2)
if filesize2 < filesize:
# replace file
os.remove(archive)
shutil.move(archive2, archive)
diffsize = filesize - filesize2
return "... recompressed file is now %s smaller." % util.strsize(diffsize)
finally:
shutil.rmtree(tmpdir, onerror=rmtree_log_error)
shutil.rmtree(tmpdir2, onerror=rmtree_log_error)
return "... recompressed file is not smaller, leaving archive as is." |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract_archive(archive, verbosity=0, outdir=None, program=None, interactive=True):
"""Extract given archive.""" |
util.check_existing_filename(archive)
if verbosity >= 0:
util.log_info("Extracting %s ..." % archive)
return _extract_archive(archive, verbosity=verbosity, interactive=interactive, outdir=outdir, program=program) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_archive(archive, verbosity=1, program=None, interactive=True):
"""List given archive.""" |
# Set default verbosity to 1 since the listing output should be visible.
util.check_existing_filename(archive)
if verbosity >= 0:
util.log_info("Listing %s ..." % archive)
return _handle_archive(archive, 'list', verbosity=verbosity,
interactive=interactive, program=program) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_archive(archive, filenames, verbosity=0, program=None, interactive=True):
"""Create given archive with given files.""" |
util.check_new_filename(archive)
util.check_archive_filelist(filenames)
if verbosity >= 0:
util.log_info("Creating %s ..." % archive)
res = _create_archive(archive, filenames, verbosity=verbosity,
interactive=interactive, program=program)
if verbosity >= 0:
util.log_info("... %s created." % archive)
return res |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def diff_archives(archive1, archive2, verbosity=0, interactive=True):
"""Print differences between two archives.""" |
util.check_existing_filename(archive1)
util.check_existing_filename(archive2)
if verbosity >= 0:
util.log_info("Comparing %s with %s ..." % (archive1, archive2))
res = _diff_archives(archive1, archive2, verbosity=verbosity, interactive=interactive)
if res == 0 and verbosity >= 0:
util.log_info("... no differences found.") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def search_archive(pattern, archive, verbosity=0, interactive=True):
"""Search pattern in archive members.""" |
if not pattern:
raise util.PatoolError("empty search pattern")
util.check_existing_filename(archive)
if verbosity >= 0:
util.log_info("Searching %r in %s ..." % (pattern, archive))
res = _search_archive(pattern, archive, verbosity=verbosity, interactive=interactive)
if res == 1 and verbosity >= 0:
util.log_info("... %r not found" % pattern)
return res |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def recompress_archive(archive, verbosity=0, interactive=True):
"""Recompress an archive to hopefully smaller size.""" |
util.check_existing_filename(archive)
util.check_writable_filename(archive)
if verbosity >= 0:
util.log_info("Recompressing %s ..." % (archive,))
res = _recompress_archive(archive, verbosity=verbosity, interactive=interactive)
if res and verbosity >= 0:
util.log_info(res)
return 0 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def init_mimedb():
"""Initialize the internal MIME database.""" |
global mimedb
try:
mimedb = mimetypes.MimeTypes(strict=False)
except Exception as msg:
log_error("could not initialize MIME database: %s" % msg)
return
add_mimedb_data(mimedb) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_mimedb_data(mimedb):
"""Add missing encodings and mimetypes to MIME database.""" |
mimedb.encodings_map['.bz2'] = 'bzip2'
mimedb.encodings_map['.lzma'] = 'lzma'
mimedb.encodings_map['.xz'] = 'xz'
mimedb.encodings_map['.lz'] = 'lzip'
mimedb.suffix_map['.tbz2'] = '.tar.bz2'
add_mimetype(mimedb, 'application/x-lzop', '.lzo')
add_mimetype(mimedb, 'application/x-adf', '.adf')
add_mimetype(mimedb, 'application/x-arj', '.arj')
add_mimetype(mimedb, 'application/x-lzma', '.lzma')
add_mimetype(mimedb, 'application/x-xz', '.xz')
add_mimetype(mimedb, 'application/java-archive', '.jar')
add_mimetype(mimedb, 'application/x-rar', '.rar')
add_mimetype(mimedb, 'application/x-rar', '.cbr')
add_mimetype(mimedb, 'application/x-7z-compressed', '.7z')
add_mimetype(mimedb, 'application/x-7z-compressed', '.cb7')
add_mimetype(mimedb, 'application/x-cab', '.cab')
add_mimetype(mimedb, 'application/x-rpm', '.rpm')
add_mimetype(mimedb, 'application/x-debian-package', '.deb')
add_mimetype(mimedb, 'application/x-ace', '.ace')
add_mimetype(mimedb, 'application/x-ace', '.cba')
add_mimetype(mimedb, 'application/x-archive', '.a')
add_mimetype(mimedb, 'application/x-alzip', '.alz')
add_mimetype(mimedb, 'application/x-arc', '.arc')
add_mimetype(mimedb, 'application/x-lrzip', '.lrz')
add_mimetype(mimedb, 'application/x-lha', '.lha')
add_mimetype(mimedb, 'application/x-lzh', '.lzh')
add_mimetype(mimedb, 'application/x-rzip', '.rz')
add_mimetype(mimedb, 'application/x-zoo', '.zoo')
add_mimetype(mimedb, 'application/x-dms', '.dms')
add_mimetype(mimedb, 'application/x-zip-compressed', '.crx')
add_mimetype(mimedb, 'application/x-shar', '.shar')
add_mimetype(mimedb, 'application/x-tar', '.cbt')
add_mimetype(mimedb, 'application/x-vhd', '.vhd')
add_mimetype(mimedb, 'audio/x-ape', '.ape')
add_mimetype(mimedb, 'audio/x-shn', '.shn')
add_mimetype(mimedb, 'audio/flac', '.flac')
add_mimetype(mimedb, 'application/x-chm', '.chm')
add_mimetype(mimedb, 'application/x-iso9660-image', '.iso')
add_mimetype(mimedb, 'application/zip', '.cbz')
add_mimetype(mimedb, 'application/zip', '.epub')
add_mimetype(mimedb, 'application/zip', '.apk')
add_mimetype(mimedb, 'application/zpaq', '.zpaq') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def backtick (cmd, encoding='utf-8'):
"""Return decoded output from command.""" |
data = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]
return data.decode(encoding) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run (cmd, verbosity=0, **kwargs):
"""Run command without error checking. @return: command return code""" |
# Note that shell_quote_nt() result is not suitable for copy-paste
# (especially on Unix systems), but it looks nicer than shell_quote().
if verbosity >= 0:
log_info("running %s" % " ".join(map(shell_quote_nt, cmd)))
if kwargs:
if verbosity >= 0:
log_info(" with %s" % ", ".join("%s=%s" % (k, shell_quote(str(v)))\
for k, v in kwargs.items()))
if kwargs.get("shell"):
# for shell calls the command must be a string
cmd = " ".join(cmd)
if verbosity < 1:
# hide command output on stdout
with open(os.devnull, 'wb') as devnull:
kwargs['stdout'] = devnull
res = subprocess.call(cmd, **kwargs)
else:
res = subprocess.call(cmd, **kwargs)
return res |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run_checked (cmd, ret_ok=(0,), **kwargs):
"""Run command and raise PatoolError on error.""" |
retcode = run(cmd, **kwargs)
if retcode not in ret_ok:
msg = "Command `%s' returned non-zero exit status %d" % (cmd, retcode)
raise PatoolError(msg)
return retcode |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def guess_mime_mimedb (filename):
"""Guess MIME type from given filename. @return: tuple (mime, encoding) """ |
mime, encoding = None, None
if mimedb is not None:
mime, encoding = mimedb.guess_type(filename, strict=False)
if mime not in ArchiveMimetypes and encoding in ArchiveCompressions:
# Files like 't.txt.gz' are recognized with encoding as format, and
# an unsupported mime-type like 'text/plain'. Fix this.
mime = Encoding2Mime[encoding]
encoding = None
return mime, encoding |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_existing_filename (filename, onlyfiles=True):
"""Ensure that given filename is a valid, existing file.""" |
if not os.path.exists(filename):
raise PatoolError("file `%s' was not found" % filename)
if not os.access(filename, os.R_OK):
raise PatoolError("file `%s' is not readable" % filename)
if onlyfiles and not os.path.isfile(filename):
raise PatoolError("`%s' is not a file" % filename) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_archive_filelist (filenames):
"""Check that file list is not empty and contains only existing files.""" |
if not filenames:
raise PatoolError("cannot create archive with empty filelist")
for filename in filenames:
check_existing_filename(filename, onlyfiles=False) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_mode (filename, flags):
"""Set mode flags for given filename if not already set.""" |
try:
mode = os.lstat(filename).st_mode
except OSError:
# ignore
return
if not (mode & flags):
try:
os.chmod(filename, flags | mode)
except OSError as msg:
log_error("could not set mode flags for `%s': %s" % (filename, msg)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tmpfile (dir=None, prefix="temp", suffix=None):
"""Return a temporary file.""" |
return tempfile.mkstemp(suffix=suffix, prefix=prefix, dir=dir)[1] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_single_outfile (directory, archive, extension=""):
"""Get output filename if archive is in a single file format like gzip.""" |
outfile = os.path.join(directory, stripext(archive))
if os.path.exists(outfile + extension):
# prevent overwriting existing files
i = 1
newfile = "%s%d" % (outfile, i)
while os.path.exists(newfile + extension):
newfile = "%s%d" % (outfile, i)
i += 1
outfile = newfile
return outfile + extension |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def print_env_info(key, out=sys.stderr):
"""If given environment key is defined, print it out.""" |
value = os.getenv(key)
if value is not None:
print(key, "=", repr(value), file=out) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def p7zip_supports_rar():
"""Determine if the RAR codec is installed for 7z program.""" |
if os.name == 'nt':
# Assume RAR support is compiled into the binary.
return True
# the subdirectory and codec name
codecname = 'p7zip/Codecs/Rar29.so'
# search canonical user library dirs
for libdir in ('/usr/lib', '/usr/local/lib', '/usr/lib64', '/usr/local/lib64', '/usr/lib/i386-linux-gnu', '/usr/lib/x86_64-linux-gnu'):
fname = os.path.join(libdir, codecname)
if os.path.exists(fname):
return True
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_program (program):
"""Look for program in environment PATH variable.""" |
if os.name == 'nt':
# Add some well-known archiver programs to the search path
path = os.environ['PATH']
path = append_to_path(path, get_nt_7z_dir())
path = append_to_path(path, get_nt_mac_dir())
path = append_to_path(path, get_nt_winrar_dir())
else:
# use default path
path = None
return which(program, path=path) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def append_to_path (path, directory):
"""Add a directory to the PATH environment variable, if it is a valid directory.""" |
if not os.path.isdir(directory) or directory in path:
return path
if not path.endswith(os.pathsep):
path += os.pathsep
return path + directory |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_nt_7z_dir ():
"""Return 7-Zip directory from registry, or an empty string.""" |
# Python 3.x renamed the _winreg module to winreg
try:
import _winreg as winreg
except ImportError:
import winreg
try:
key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\7-Zip")
try:
return winreg.QueryValueEx(key, "Path")[0]
finally:
winreg.CloseKey(key)
except WindowsError:
return "" |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_same_file (filename1, filename2):
"""Check if filename1 and filename2 point to the same file object. There can be false negatives, ie. the result is False, but it is the same file anyway. Reason is that network filesystems can create different paths to the same physical file. """ |
if filename1 == filename2:
return True
if os.name == 'posix':
return os.path.samefile(filename1, filename2)
return is_same_filename(filename1, filename2) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_same_filename (filename1, filename2):
"""Check if filename1 and filename2 are the same filename.""" |
return os.path.realpath(filename1) == os.path.realpath(filename2) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def link_or_copy(src, dst, verbosity=0):
"""Try to make a hard link from src to dst and if that fails copy the file. Hard links save some disk space and linking should fail fast since no copying is involved. """ |
if verbosity > 0:
log_info("Copying %s -> %s" % (src, dst))
try:
os.link(src, dst)
except (AttributeError, OSError):
try:
shutil.copy(src, dst)
except OSError as msg:
raise PatoolError(msg) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.