id
int64 0
843k
| repository_name
stringlengths 7
55
| file_path
stringlengths 9
332
| class_name
stringlengths 3
290
| human_written_code
stringlengths 12
4.36M
| class_skeleton
stringlengths 19
2.2M
| total_program_units
int64 1
9.57k
| total_doc_str
int64 0
4.2k
| AvgCountLine
float64 0
7.89k
| AvgCountLineBlank
float64 0
300
| AvgCountLineCode
float64 0
7.89k
| AvgCountLineComment
float64 0
7.89k
| AvgCyclomatic
float64 0
130
| CommentToCodeRatio
float64 0
176
| CountClassBase
float64 0
48
| CountClassCoupled
float64 0
589
| CountClassCoupledModified
float64 0
581
| CountClassDerived
float64 0
5.37k
| CountDeclInstanceMethod
float64 0
4.2k
| CountDeclInstanceVariable
float64 0
299
| CountDeclMethod
float64 0
4.2k
| CountDeclMethodAll
float64 0
4.2k
| CountLine
float64 1
115k
| CountLineBlank
float64 0
9.01k
| CountLineCode
float64 0
94.4k
| CountLineCodeDecl
float64 0
46.1k
| CountLineCodeExe
float64 0
91.3k
| CountLineComment
float64 0
27k
| CountStmt
float64 1
93.2k
| CountStmtDecl
float64 0
46.1k
| CountStmtExe
float64 0
90.2k
| MaxCyclomatic
float64 0
759
| MaxInheritanceTree
float64 0
16
| MaxNesting
float64 0
34
| SumCyclomatic
float64 0
6k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4,500 |
AmesCornish/buttersink
|
AmesCornish_buttersink/buttersink/ButterStore.py
|
buttersink.ButterStore.ButterStore
|
class ButterStore(Store.Store):
""" A local btrfs synchronization source or sink. """
def __init__(self, host, path, mode, dryrun):
""" Initialize.
host is ignored.
path is the file system location of the read-only subvolumes.
"""
# Don't lose a trailing slash -- it's significant
path = os.path.abspath(path) + ("/" if path.endswith("/") else "")
super(ButterStore, self).__init__(host, path, mode, dryrun)
if not os.path.isdir(self.userPath):
raise Exception("'%s' is not an existing directory" % (self.userPath))
self.isDiffStore = True
self.butter = Butter.Butter(dryrun) # subprocess command-line interface
self.btrfs = btrfs.FileSystem(self.userPath) # ioctl interface
# Dict of {uuid: <btrfs.Volume>}
self.butterVolumes = {}
# Volumes to be deleted using the '--delete' option.
# Initialized to hold all volumes inside destination directory,
# Then volumes in source are "kept", and removed from extraVolumes.
self.extraVolumes = {}
def _btrfsVol2StoreVol(self, bvol):
if bvol.received_uuid is not None:
uuid = bvol.received_uuid
gen = bvol.sent_gen
else:
uuid = bvol.uuid
gen = bvol.current_gen
if uuid is None:
return None
return Store.Volume(uuid, gen, bvol.totalSize, bvol.exclusiveSize)
def _fillVolumesAndPaths(self, paths):
""" Fill in paths.
:arg paths: = { Store.Volume: ["linux path",]}
"""
with self.btrfs as mount:
for bv in mount.subvolumes:
if not bv.readOnly:
continue
vol = self._btrfsVol2StoreVol(bv)
if vol is None:
continue
path = bv.fullPath
if path is None:
logger.info("Skipping deleted volume %s", bv.uuid)
continue
relPath = None
for path in bv.linuxPaths:
path = self._relativePath(path)
if path is None:
continue # path is outside store scope
paths[vol].append(path)
infoPath = self._fullPath(path + Store.theInfoExtension)
if os.path.exists(infoPath):
logger.debug("Reading %s", infoPath)
with open(infoPath) as info:
Store.Volume.readInfo(info)
if not path.startswith("/"):
relPath = path
if vol not in paths:
continue
logger.debug("%s", vol.display(sink=self, detail='phrase'))
if vol.uuid in self.butterVolumes:
logger.warn(
"Duplicate effective uuid %s in '%s' and '%s'",
vol.uuid, path, self.butterVolumes[vol.uuid].fullPath
)
self.butterVolumes[vol.uuid] = bv
if relPath is not None:
# vol is inside Store directory
self.extraVolumes[vol] = relPath
def _fileSystemSync(self):
with self.btrfs as mount:
mount.SYNC()
time.sleep(2)
def __unicode__(self):
""" English description of self. """
return u"btrfs %s" % (self.userPath)
def __str__(self):
""" English description of self. """
return unicode(self).encode('utf-8')
def getEdges(self, fromVol):
""" Return the edges available from fromVol. """
if fromVol is None:
for toVol in self.paths:
yield Store.Diff(self, toVol, fromVol, toVol.size)
return
if fromVol not in self.paths:
return
fromBVol = self.butterVolumes[fromVol.uuid]
parentUUID = fromBVol.parent_uuid
butterDir = os.path.dirname(fromBVol.fullPath)
vols = [vol for vol in self.butterVolumes.values()
if vol.parent_uuid == parentUUID or
os.path.dirname(vol.fullPath) == butterDir
]
changeRate = self._calcChangeRate(vols)
for toBVol in vols:
if toBVol == fromBVol:
continue
# This gives a conservative estimate of the size of the diff
estimatedSize = self._estimateSize(toBVol, fromBVol, changeRate)
toVol = self._btrfsVol2StoreVol(toBVol)
yield Store.Diff(self, toVol, fromVol, estimatedSize, sizeIsEstimated=True)
def hasEdge(self, diff):
""" True if Store already contains this edge. """
return diff.toUUID in self.butterVolumes
def receive(self, diff, paths):
""" Return Context Manager for a file-like (stream) object to store a diff. """
if not self.dryrun:
self._fileSystemSync()
path = self.selectReceivePath(paths)
if os.path.exists(path):
raise Exception(
"Path %s exists, can't receive %s" % (path, diff.toUUID)
)
return self.butter.receive(path, diff, self.showProgress is True)
def receiveVolumeInfo(self, paths):
""" Return Context Manager for a file-like (stream) object to store volume info. """
path = self.selectReceivePath(paths)
path = path + Store.theInfoExtension
if Store.skipDryRun(logger, self.dryrun)("receive info to %s", path):
return None
return open(path, "w")
def _estimateSize(self, toBVol, fromBVol, changeRate):
fromGen = fromBVol.current_gen
genDiff = abs(toBVol.current_gen - fromGen)
estimatedSize = max(0, toBVol.totalSize - fromBVol.totalSize)
estimatedSize += toBVol.totalSize * (1 - math.exp(-changeRate * genDiff))
estimatedSize = max(toBVol.exclusiveSize, estimatedSize)
return estimatedSize
def measureSize(self, diff, chunkSize):
""" Spend some time to get an accurate size. """
self._fileSystemSync()
sendContext = self.butter.send(
self.getSendPath(diff.toVol),
self.getSendPath(diff.fromVol),
diff,
showProgress=self.showProgress is not False,
allowDryRun=False,
)
class _Measure(io.RawIOBase):
def __init__(self, estimatedSize, showProgress):
self.totalSize = None
self.progress = progress.DisplayProgress(estimatedSize) if showProgress else None
def __enter__(self):
self.totalSize = 0
if self.progress:
self.progress.__enter__()
return self
def __exit__(self, exceptionType, exceptionValue, traceback):
if self.progress:
self.progress.__exit__(exceptionType, exceptionValue, traceback)
return False # Don't supress exception
def writable(self):
return True
def write(self, bytes):
self.totalSize += len(bytes)
if self.progress:
self.progress.update(self.totalSize)
logger.info("Measuring %s", diff)
measure = _Measure(diff.size, self.showProgress is not False)
Store.transfer(sendContext, measure, chunkSize)
diff.setSize(measure.totalSize, False)
for path in self.getPaths(diff.toVol):
path = self._fullPath(path) + Store.theInfoExtension
with open(path, "a") as infoFile:
diff.toVol.writeInfoLine(infoFile, diff.fromUUID, measure.totalSize)
def _calcChangeRate(self, bvols):
total = 0
diffs = 0
minGen = bvols[0].current_gen
maxGen = minGen
minSize = bvols[0].totalSize
maxSize = minSize
for vol in bvols:
total += vol.totalSize
diffs += vol.exclusiveSize
minGen = min(minGen, vol.current_gen)
maxGen = max(maxGen, vol.current_gen)
minSize = min(minSize, vol.totalSize)
maxSize = max(maxSize, vol.totalSize)
try:
# exclusiveSize is often useless,
# because data may be shared with read-write volumes not usable for send operations
diffs = max(diffs, maxSize - minSize)
rate = - math.log(1 - diffs / total) * (len(bvols) - 1) / (maxGen - minGen)
rate /= 10 # Fudge
except (ZeroDivisionError, ValueError):
# logger.debug("Using minimum change rate.")
rate = theMinimumChangeRate
# logger.debug("Change rate: %f", rate)
return rate
def send(self, diff):
""" Write the diff (toVol from fromVol) to the stream context manager. """
if not self.dryrun:
self._fileSystemSync()
return self.butter.send(
self.getSendPath(diff.toVol),
self.getSendPath(diff.fromVol),
diff,
self.showProgress is True,
)
def keep(self, diff):
""" Mark this diff (or volume) to be kept in path. """
self._keepVol(diff.toVol)
self._keepVol(diff.fromVol)
def _keepVol(self, vol):
""" Mark this volume to be kept in path. """
if vol is None:
return
if vol in self.extraVolumes:
del self.extraVolumes[vol]
return
if vol not in self.paths:
raise Exception("%s not in %s" % (vol, self))
paths = [os.path.basename(path) for path in self.paths[vol]]
newPath = self.selectReceivePath(paths)
if self._skipDryRun(logger, 'INFO')("Copy %s to %s", vol, newPath):
return
self.butterVolumes[vol.uuid].copy(newPath)
def deleteUnused(self, dryrun=False):
""" Delete any old snapshots in path, if not kept. """
for (vol, path) in self.extraVolumes.items():
if self._skipDryRun(logger, 'INFO', dryrun=dryrun)("Delete subvolume %s", path):
continue
self.butterVolumes[vol.uuid].destroy()
def deletePartials(self, dryrun=False):
""" Delete any old partial uploads/downloads in path. """
for (vol, path) in self.extraVolumes.items():
if not path.endswith(".part"):
continue
if self._skipDryRun(logger, 'INFO', dryrun=dryrun)("Delete subvolume %s", path):
continue
self.butterVolumes[vol.uuid].destroy()
|
class ButterStore(Store.Store):
''' A local btrfs synchronization source or sink. '''
def __init__(self, host, path, mode, dryrun):
''' Initialize.
host is ignored.
path is the file system location of the read-only subvolumes.
'''
pass
def _btrfsVol2StoreVol(self, bvol):
pass
def _fillVolumesAndPaths(self, paths):
''' Fill in paths.
:arg paths: = { Store.Volume: ["linux path",]}
'''
pass
def _fileSystemSync(self):
pass
def __unicode__(self):
''' English description of self. '''
pass
def __str__(self):
''' English description of self. '''
pass
def getEdges(self, fromVol):
''' Return the edges available from fromVol. '''
pass
def hasEdge(self, diff):
''' True if Store already contains this edge. '''
pass
def receive(self, diff, paths):
''' Return Context Manager for a file-like (stream) object to store a diff. '''
pass
def receiveVolumeInfo(self, paths):
''' Return Context Manager for a file-like (stream) object to store volume info. '''
pass
def _estimateSize(self, toBVol, fromBVol, changeRate):
pass
def measureSize(self, diff, chunkSize):
''' Spend some time to get an accurate size. '''
pass
class _Measure(io.RawIOBase):
def __init__(self, host, path, mode, dryrun):
pass
def __enter__(self):
pass
def __exit__(self, exceptionType, exceptionValue, traceback):
pass
def writable(self):
pass
def write(self, bytes):
pass
def _calcChangeRate(self, bvols):
pass
def send(self, diff):
''' Write the diff (toVol from fromVol) to the stream context manager. '''
pass
def keep(self, diff):
''' Mark this diff (or volume) to be kept in path. '''
pass
def _keepVol(self, vol):
''' Mark this volume to be kept in path. '''
pass
def deleteUnused(self, dryrun=False):
''' Delete any old snapshots in path, if not kept. '''
pass
def deletePartials(self, dryrun=False):
''' Delete any old partial uploads/downloads in path. '''
pass
| 25 | 15 | 14 | 3 | 10 | 2 | 3 | 0.18 | 1 | 8 | 4 | 0 | 18 | 5 | 18 | 42 | 317 | 82 | 204 | 71 | 179 | 36 | 184 | 67 | 159 | 12 | 2 | 5 | 63 |
4,501 |
AmesCornish/buttersink
|
AmesCornish_buttersink/buttersink/Butter.py
|
buttersink.Butter._Writer
|
class _Writer(io.RawIOBase):
""" Context Manager to write a snapshot. """
def __init__(self, process, stream, path, diff, showProgress):
self.process = process
self.stream = stream
self.path = path
self.diff = diff
self.bytesWritten = None
self.progress = DisplayProgress(diff.size) if showProgress else None
def __enter__(self):
self.bytesWritten = 0
if self.progress is not None:
self.progress.open()
return self
def __exit__(self, exceptionType, exception, trace):
self.stream.close()
if self.progress is not None:
self.progress.close()
if self.process is None:
return
logger.debug("Waiting for receive process to finish...")
self.process.wait()
if exception is None and self.process.returncode == 0:
# Fixup with SET_RECEIVED_SUBVOL
if FIXUP_AFTER_RECEIVE:
received = btrfs.SnapShot(self.path)
received.SET_RECEIVED_SUBVOL(
uuid=self.diff.toUUID,
stransid=self.diff.toGen,
)
return
if self.process.returncode != 0:
logger.error("btrfs receive errors")
for line in self.process.stderr:
sys.stderr.write(line)
if os.path.exists(self.path):
# This tries to mark partial (failed) transfers.
partial = self.path + ".part"
if os.path.exists(partial):
partial = self.path + "_" + datetime.datetime.now().isoformat() + ".part"
os.rename(self.path, partial)
logger.debug("Renamed %s to %s", self.path, partial)
if exception is None:
raise Exception(
"receive %s returned error %d."
% (self.path, self.process.returncode, )
)
def write(self, data):
# If it's the first big chunk (header)
# Tweak the volume information to match what we expect.
if FIXUP_DURING_RECEIVE and self.bytesWritten == 0:
data = send.replaceIDs(
data,
self.diff.toUUID,
self.diff.toGen,
self.diff.fromUUID,
self.diff.fromGen,
)
self.stream.write(data)
self.bytesWritten += len(data)
if self.progress is not None:
self.progress.update(self.bytesWritten)
|
class _Writer(io.RawIOBase):
''' Context Manager to write a snapshot. '''
def __init__(self, process, stream, path, diff, showProgress):
pass
def __enter__(self):
pass
def __exit__(self, exceptionType, exception, trace):
pass
def write(self, data):
pass
| 5 | 1 | 18 | 3 | 14 | 1 | 4 | 0.09 | 1 | 4 | 2 | 0 | 4 | 6 | 4 | 24 | 77 | 15 | 57 | 14 | 52 | 5 | 45 | 14 | 40 | 10 | 5 | 2 | 17 |
4,502 |
AmesCornish/buttersink
|
AmesCornish_buttersink/buttersink/Butter.py
|
buttersink.Butter._Reader
|
class _Reader(io.RawIOBase):
""" Context Manager to read a snapshot. """
def __init__(self, process, stream, path, diff, showProgress):
self.process = process
self.stream = stream
self.path = path
self.diff = diff
self.bytesRead = None
self.progress = DisplayProgress() if showProgress else None
def __enter__(self):
self.bytesRead = 0
if self.progress is not None:
self.progress.open()
return self
def __exit__(self, exceptionType, exception, trace):
self.stream.close()
if self.progress is not None:
self.progress.close()
if self.process is None:
return
logger.debug("Waiting for send process to finish...")
self.process.wait()
if self.process.returncode != 0:
logger.error("btrfs send errors")
for line in self.process.stderr:
sys.stderr.write(line)
if exception is None and self.process.returncode != 0:
raise Exception(
"send returned error %d. %s may be corrupt."
% (self.process.returncode, self.path)
)
def read(self, size):
# If it's the first big chunk (header)
# Tweak the volume information to match what we expect.
data = self.stream.read(size)
if FIXUP_DURING_SEND and self.bytesRead == 0:
data = send.replaceIDs(
data,
self.diff.toUUID,
self.diff.toGen,
self.diff.fromUUID,
self.diff.fromGen,
)
self.bytesRead += len(data)
if self.progress is not None:
self.progress.update(self.bytesRead)
return data
def seek(self, offset, whence):
self.stream.seek(offset, offset, whence)
if whence == io.SEEK_SET:
self.bytesRead = offset
elif whence == io.SEEK_CUR:
pass
elif whence == io.SEEK_END:
self.bytesRead = None
|
class _Reader(io.RawIOBase):
''' Context Manager to read a snapshot. '''
def __init__(self, process, stream, path, diff, showProgress):
pass
def __enter__(self):
pass
def __exit__(self, exceptionType, exception, trace):
pass
def read(self, size):
pass
def seek(self, offset, whence):
pass
| 6 | 1 | 12 | 1 | 10 | 0 | 3 | 0.06 | 1 | 2 | 1 | 0 | 5 | 6 | 5 | 25 | 66 | 11 | 52 | 14 | 46 | 3 | 41 | 14 | 35 | 6 | 5 | 2 | 17 |
4,503 |
AmesCornish/buttersink
|
AmesCornish_buttersink/buttersink/Butter.py
|
buttersink.Butter.Butter
|
class Butter:
""" Interface to local btrfs file system snapshots. """
def __init__(self, dryrun):
""" Initialize. """
self.btrfsVersion = self._getVersion([3, 14])
self.dryrun = dryrun
def _getVersion(self, minVersion):
btrfsVersionString = subprocess.check_output(
["btrfs", "--version"], stderr=sys.stderr
).decode("utf-8").strip()
versionPattern = re.compile("[0-9]+(\.[0-9]+)*")
version = versionPattern.search(btrfsVersionString)
try:
version = [int(num) for num in version.group(0).split(".")]
except AttributeError:
version = None
if version < [3, 14]:
logger.error(
"%s is not supported. Please upgrade your btrfs to at least 3.14",
btrfsVersionString
)
else:
logger.debug("%s", btrfsVersionString)
return btrfsVersionString
def receive(self, path, diff, showProgress=True):
""" Return a context manager for stream that will store a diff. """
directory = os.path.dirname(path)
cmd = ["btrfs", "receive", "-e", directory]
if Store.skipDryRun(logger, self.dryrun)("Command: %s", cmd):
return None
if not os.path.exists(directory):
os.makedirs(directory)
process = subprocess.Popen(
cmd,
stdin=subprocess.PIPE,
stderr=subprocess.PIPE,
stdout=DEVNULL,
)
_makeNice(process)
return _Writer(process, process.stdin, path, diff, showProgress)
def send(self, targetPath, parent, diff, showProgress=True, allowDryRun=True):
""" Return context manager for stream to send a (incremental) snapshot. """
if parent is not None:
cmd = ["btrfs", "send", "-p", parent, targetPath]
else:
cmd = ["btrfs", "send", targetPath]
if Store.skipDryRun(logger, self.dryrun and allowDryRun)("Command: %s", cmd):
return None
process = subprocess.Popen(
cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=DEVNULL)
_makeNice(process)
return _Reader(process, process.stdout, targetPath, diff, showProgress)
|
class Butter:
''' Interface to local btrfs file system snapshots. '''
def __init__(self, dryrun):
''' Initialize. '''
pass
def _getVersion(self, minVersion):
pass
def receive(self, path, diff, showProgress=True):
''' Return a context manager for stream that will store a diff. '''
pass
def send(self, targetPath, parent, diff, showProgress=True, allowDryRun=True):
''' Return context manager for stream to send a (incremental) snapshot. '''
pass
| 5 | 4 | 16 | 3 | 12 | 1 | 3 | 0.08 | 0 | 5 | 2 | 0 | 4 | 2 | 4 | 4 | 69 | 17 | 48 | 15 | 43 | 4 | 35 | 15 | 30 | 3 | 0 | 1 | 10 |
4,504 |
AmesCornish/buttersink
|
AmesCornish_buttersink/buttersink/BestDiffs.py
|
buttersink.BestDiffs._Node
|
class _Node:
def __init__(self, volume, intermediate=False):
self.volume = volume
self.intermediate = intermediate
self.diff = None
self.height = None
@property
def diffSize(self):
return self.diff.size if self.diff is not None else None
@property
def previous(self):
return self.diff.fromVol if self.diff else None
@property
def sink(self):
return self.diff.sink if self.diff else None
def __unicode__(self):
return self.display()
def display(self, sink=None):
if self.height is not None:
ancestors = " (%d ancestors)" % (self.height - 1)
else:
ancestors = ""
return u"%s%s" % (
self.diff or self.volume.display(sink),
ancestors,
)
def __str__(self):
return unicode(self).encode('utf-8')
@staticmethod
def summary(nodes):
sinks = collections.defaultdict(lambda: Bunch(count=0, size=0))
total = sinks[None]
for n in nodes:
total.count += 1
if n.diff is None:
continue
total.size += n.diff.size
sink = sinks[n.diff.sink]
sink.count += 1
sink.size += n.diff.size
sinksSorted = collections.OrderedDict(
{s: b for s, b in sinks.items() if s is not None}
)
sinksSorted[None] = sinks[None]
return sinksSorted
|
class _Node:
def __init__(self, volume, intermediate=False):
pass
@property
def diffSize(self):
pass
@property
def previous(self):
pass
@property
def sink(self):
pass
def __unicode__(self):
pass
def display(self, sink=None):
pass
def __str__(self):
pass
@staticmethod
def summary(nodes):
pass
| 13 | 0 | 6 | 1 | 5 | 0 | 2 | 0 | 0 | 2 | 1 | 0 | 7 | 4 | 8 | 8 | 60 | 15 | 45 | 23 | 32 | 0 | 35 | 19 | 26 | 3 | 0 | 2 | 14 |
4,505 |
AmesCornish/buttersink
|
AmesCornish_buttersink/buttersink/SSHStore.py
|
buttersink.SSHStore._Dict2Obj
|
class _Dict2Obj:
def __init__(self, store):
self.sink = store
def vol(self, values):
return Store.Volume(**values)
def diff(self, values):
return Store.Diff(sink=self.sink, **values)
|
class _Dict2Obj:
def __init__(self, store):
pass
def vol(self, values):
pass
def diff(self, values):
pass
| 4 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 0 | 2 | 2 | 0 | 3 | 1 | 3 | 3 | 10 | 3 | 7 | 5 | 3 | 0 | 7 | 5 | 3 | 1 | 0 | 0 | 3 |
4,506 |
AmesCornish/buttersink
|
AmesCornish_buttersink/buttersink/SSHStore.py
|
buttersink.SSHStore._SSHStream
|
class _SSHStream(io.RawIOBase):
def __init__(self, client, progress=None):
self._client = client
self._open = True
self._progress = progress
self.totalSize = 0
def __enter__(self):
if self._progress:
self._progress.__enter__()
return self
def __exit__(self, exceptionType, exception, trace):
if self._progress:
self._progress.__exit__(exceptionType, exception, trace)
if not self._open:
return False
try:
result = self._client.streamWrite(0)
self._open = False
except Exception as error:
if exceptionType is None:
raise
else:
logger.debug("Secondary error: %s", error)
if exceptionType is None and result and 'error' in result:
raise Exception(result)
return False # Don't supress exception
def write(self, data):
size = len(data)
if size == 0:
return
try:
result = self._client.streamWrite(size)
if self._progress:
self._progress.update(self.totalSize)
if result.get('stream', False):
self._client._process.stdin.write(data)
self.totalSize += size
if self._progress:
self._progress.update(self.totalSize)
result = self._client._getResult()
except Exception as error:
self._client.error = error # Don't try writing to this client again
raise
if result and 'error' in result:
raise Exception(result)
def read(self, size):
if size == 0:
return ''
try:
result = self._client.streamRead(size)
size = result['size']
if size == 0:
self._open = False
return ''
if self._progress:
self._progress.update(self.totalSize)
data = self._client._process.stdout.read(size)
self.totalSize += size
if self._progress:
self._progress.update(self.totalSize)
result = self._client._getResult()
except Exception as error:
self._client.error = error # Don't try reading from this client again
raise
if result and 'error' in result:
raise Exception(result)
return data
|
class _SSHStream(io.RawIOBase):
def __init__(self, client, progress=None):
pass
def __enter__(self):
pass
def __exit__(self, exceptionType, exception, trace):
pass
def write(self, data):
pass
def read(self, size):
pass
| 6 | 0 | 16 | 3 | 13 | 1 | 5 | 0.04 | 1 | 1 | 0 | 0 | 5 | 4 | 5 | 25 | 88 | 21 | 67 | 18 | 61 | 3 | 66 | 15 | 60 | 7 | 5 | 3 | 23 |
4,507 |
AmesCornish/buttersink
|
AmesCornish_buttersink/buttersink/Store.py
|
buttersink.Store.Volume
|
class Volume:
""" Represents a snapshot.
Unique for a UUID (independent of Store and paths).
"""
def __init__(self, uuid, gen, size=None, exclusiveSize=None):
""" Initialize. """
assert uuid is not None
self._uuid = uuid # Must never change!
self.size = size
self.exclusiveSize = exclusiveSize
self.gen = gen
def __cmp__(self, vol):
""" Compare. """
return cmp(self._uuid, vol._uuid) if vol else 1
def __hash__(self):
""" Hash. """
return hash(self._uuid)
@property
def uuid(self):
""" Read-only uuid. """
return self._uuid
def writeInfoLine(self, stream, fromUUID, size):
""" Write one line of diff information. """
if size is None or fromUUID is None:
return
if not isinstance(size, int):
logger.warning("Bad size: %s", size)
return
stream.write(str("%s\t%s\t%d\n" % (
self.uuid,
fromUUID,
size,
)))
def writeInfo(self, stream):
""" Write information about diffs into a file stream for use later. """
for (fromUUID, size) in Diff.theKnownSizes[self.uuid].iteritems():
self.writeInfoLine(stream, fromUUID, size)
def hasInfo(self):
""" Will have information to write. """
count = len([None
for (fromUUID, size)
in Diff.theKnownSizes[self.uuid].iteritems()
if size is not None and fromUUID is not None
])
return count > 0
@staticmethod
def readInfo(stream):
""" Read previously-written information about diffs. """
try:
for line in stream:
(toUUID, fromUUID, size) = line.split()
try:
size = int(size)
except Exception:
logger.warning("Bad size: %s", size)
continue
logger.debug("diff info: %s %s %d", toUUID, fromUUID, size)
Diff.theKnownSizes[toUUID][fromUUID] = size
except Exception as error:
logger.warn("Can't read .bs info file (%s)", error)
def __unicode__(self):
""" Friendly string for volume. """
return self.display()
def __str__(self):
""" Friendly string for volume. """
return unicode(self).encode('utf-8')
def __repr__(self):
""" Python expression to create self. """
return "%s(%s)" % (
self.__class__,
self.__dict__,
)
def display(self, sink=None, detail='phrase'):
""" Friendly string for volume, using sink paths. """
if not isinstance(detail, int):
detail = detailNum[detail]
if detail >= detailNum['line'] and self.size is not None:
size = " (%s%s)" % (
humanize(self.size),
"" if self.exclusiveSize is None else (
" %s exclusive" % (humanize(self.exclusiveSize))
)
)
else:
size = ""
vol = "%s %s" % (
_printUUID(self._uuid, detail - 1),
sink.getSendPath(self) if sink else "",
)
return vol + size
@classmethod
def make(cls, vol):
""" Convert uuid to Volume, if necessary. """
if isinstance(vol, cls):
return vol
elif vol is None:
return None
else:
return cls(vol, None)
|
class Volume:
''' Represents a snapshot.
Unique for a UUID (independent of Store and paths).
'''
def __init__(self, uuid, gen, size=None, exclusiveSize=None):
''' Initialize. '''
pass
def __cmp__(self, vol):
''' Compare. '''
pass
def __hash__(self):
''' Hash. '''
pass
@property
def uuid(self):
''' Read-only uuid. '''
pass
def writeInfoLine(self, stream, fromUUID, size):
''' Write one line of diff information. '''
pass
def writeInfoLine(self, stream, fromUUID, size):
''' Write information about diffs into a file stream for use later. '''
pass
def hasInfo(self):
''' Will have information to write. '''
pass
@staticmethod
def readInfo(stream):
''' Read previously-written information about diffs. '''
pass
def __unicode__(self):
''' Friendly string for volume. '''
pass
def __str__(self):
''' Friendly string for volume. '''
pass
def __repr__(self):
''' Python expression to create self. '''
pass
def display(self, sink=None, detail='phrase'):
''' Friendly string for volume, using sink paths. '''
pass
@classmethod
def make(cls, vol):
''' Convert uuid to Volume, if necessary. '''
pass
| 17 | 14 | 7 | 0 | 6 | 1 | 2 | 0.22 | 0 | 4 | 1 | 0 | 11 | 4 | 13 | 13 | 117 | 18 | 83 | 29 | 66 | 18 | 58 | 24 | 44 | 5 | 0 | 3 | 26 |
4,508 |
AmesCornish/buttersink
|
AmesCornish_buttersink/buttersink/btrfs.py
|
buttersink.btrfs.Control
|
class Control(ioctl.Control):
""" A btrfs IOCTL. """
magic = BTRFS_IOCTL_MAGIC
|
class Control(ioctl.Control):
''' A btrfs IOCTL. '''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.5 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 8 | 5 | 2 | 2 | 2 | 1 | 1 | 2 | 2 | 1 | 0 | 1 | 0 | 0 |
4,509 |
AmesCornish/buttersink
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AmesCornish_buttersink/buttersink/ButterStore.py
|
buttersink.ButterStore.ButterStore.measureSize._Measure
|
class _Measure(io.RawIOBase):
def __init__(self, estimatedSize, showProgress):
self.totalSize = None
self.progress = progress.DisplayProgress(
estimatedSize) if showProgress else None
def __enter__(self):
self.totalSize = 0
if self.progress:
self.progress.__enter__()
return self
def __exit__(self, exceptionType, exceptionValue, traceback):
if self.progress:
self.progress.__exit__(
exceptionType, exceptionValue, traceback)
return False # Don't supress exception
def writable(self):
return True
def write(self, bytes):
self.totalSize += len(bytes)
if self.progress:
self.progress.update(self.totalSize)
|
class _Measure(io.RawIOBase):
def __init__(self, estimatedSize, showProgress):
pass
def __enter__(self):
pass
def __exit__(self, exceptionType, exceptionValue, traceback):
pass
def writable(self):
pass
def write(self, bytes):
pass
| 6 | 0 | 4 | 0 | 4 | 0 | 2 | 0.05 | 1 | 0 | 0 | 0 | 5 | 2 | 5 | 25 | 24 | 5 | 19 | 8 | 13 | 1 | 19 | 8 | 13 | 2 | 5 | 1 | 9 |
4,510 |
AmesCornish/buttersink
|
AmesCornish_buttersink/buttersink/btrfs.py
|
buttersink.btrfs._BtrfsError
|
class _BtrfsError(Exception):
pass
|
class _BtrfsError(Exception):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 2 | 0 | 2 | 1 | 1 | 0 | 2 | 1 | 1 | 0 | 3 | 0 | 0 |
4,511 |
AmesCornish/buttersink
|
AmesCornish_buttersink/buttersink/btrfs.py
|
buttersink.btrfs.SnapShot
|
class SnapShot(ioctl.Device):
""" SnapShot (read-only subvolume) identified by path. """
SET_RECEIVED_SUBVOL = Control.IOWR(37, btrfs_ioctl_received_subvol_args)
SUBVOL_GETFLAGS = Control.IOR(25, btrfs_flags)
SUBVOL_SETFLAGS = Control.IOW(26, btrfs_flags)
|
class SnapShot(ioctl.Device):
''' SnapShot (read-only subvolume) identified by path. '''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.25 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 3 | 7 | 2 | 4 | 4 | 3 | 1 | 4 | 4 | 3 | 0 | 2 | 0 | 0 |
4,512 |
AmesCornish/buttersink
|
AmesCornish_buttersink/buttersink/Store.py
|
buttersink.Store.Diff
|
class Diff:
""" Represents a btrfs send diff that creates toVol from fromVol. """
def __init__(self, sink, toVol, fromVol, size=None, sizeIsEstimated=False):
""" Initialize. """
self.sink = sink # AKA store
self.toVol = Volume.make(toVol)
self.fromVol = Volume.make(fromVol)
self.setSize(size, sizeIsEstimated)
# {toVolume: {fromVolume: size}}
theKnownSizes = collections.defaultdict(lambda: collections.defaultdict(lambda: None))
@property
def toUUID(self):
""" 'to' volume's UUID. """
return self.toVol.uuid
@property
def fromUUID(self):
""" 'from' volume's UUID, if any. """
return self.fromVol.uuid if self.fromVol else None
@property
def toGen(self):
""" 'to' volume's transid. """
return self.toVol.gen
@property
def fromGen(self):
""" 'from' volume's transid. """
return self.fromVol.gen if self.fromVol else None
@property
def size(self):
""" Return size. """
self._updateSize()
return self._size
@property
def sizeIsEstimated(self):
""" Return whether size is estimated. """
self._updateSize()
return self._sizeIsEstimated
def setSize(self, size, sizeIsEstimated):
""" Update size. """
self._size = size
self._sizeIsEstimated = sizeIsEstimated
if self.fromVol is not None and size is not None and not sizeIsEstimated:
Diff.theKnownSizes[self.toUUID][self.fromUUID] = size
def sendTo(self, dest, chunkSize):
""" Send this difference to the dest Store. """
vol = self.toVol
paths = self.sink.getPaths(vol)
if self.sink == dest:
logger.info("Keep: %s", self)
self.sink.keep(self)
else:
# Log, but don't skip yet, so we can log more detailed skipped actions later
skipDryRun(logger, dest.dryrun, 'INFO')("Xfer: %s", self)
receiveContext = dest.receive(self, paths)
sendContext = self.sink.send(self)
# try:
# receiveContext.metadata['btrfsVersion'] = self.btrfsVersion
# except AttributeError:
# pass
transfer(sendContext, receiveContext, chunkSize)
if vol.hasInfo():
infoContext = dest.receiveVolumeInfo(paths)
if infoContext is None:
# vol.writeInfo(sys.stdout)
pass
else:
with infoContext as stream:
vol.writeInfo(stream)
def _updateSize(self):
if self._size and not self._sizeIsEstimated:
return
size = Diff.theKnownSizes[self.toUUID][self.fromUUID]
if size is None:
return
self._size = size
self._sizeIsEstimated = False
def __str__(self):
""" human-readable string. """
return u"%s from %s (%s%s)" % (
self.toVol.display(self.sink),
self.fromVol.display(self.sink) if self.fromVol else "None",
"~" if self.sizeIsEstimated else "",
humanize(self.size),
# self.sink,
)
|
class Diff:
''' Represents a btrfs send diff that creates toVol from fromVol. '''
def __init__(self, sink, toVol, fromVol, size=None, sizeIsEstimated=False):
''' Initialize. '''
pass
@property
def toUUID(self):
''' 'to' volume's UUID. '''
pass
@property
def fromUUID(self):
''' 'from' volume's UUID, if any. '''
pass
@property
def toGen(self):
''' 'to' volume's transid. '''
pass
@property
def fromGen(self):
''' 'from' volume's transid. '''
pass
@property
def size(self):
''' Return size. '''
pass
@property
def sizeIsEstimated(self):
''' Return whether size is estimated. '''
pass
def setSize(self, size, sizeIsEstimated):
''' Update size. '''
pass
def sendTo(self, dest, chunkSize):
''' Send this difference to the dest Store. '''
pass
def _updateSize(self):
pass
def __str__(self):
''' human-readable string. '''
pass
| 18 | 11 | 8 | 1 | 5 | 2 | 2 | 0.31 | 0 | 1 | 1 | 0 | 11 | 5 | 11 | 11 | 108 | 24 | 65 | 31 | 47 | 20 | 52 | 24 | 40 | 4 | 0 | 3 | 21 |
4,513 |
AmesCornish/buttersink
|
AmesCornish_buttersink/buttersink/SSHStore.py
|
buttersink.SSHStore._Obj2Arg
|
class _Obj2Arg:
def vol(self, vol):
return 'None' if vol is None else vol.uuid
def diff(self, diff):
if diff is None:
return ('None', 'None')
else:
return (self.vol(diff.toVol), self.vol(diff.fromVol), )
|
class _Obj2Arg:
def vol(self, vol):
pass
def diff(self, diff):
pass
| 3 | 0 | 4 | 0 | 4 | 0 | 2 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 2 | 2 | 10 | 2 | 8 | 3 | 5 | 0 | 7 | 3 | 4 | 2 | 0 | 1 | 4 |
4,514 |
Amsterdam/authorization_django
|
Amsterdam_authorization_django/authorization_django/config.py
|
authorization_django.config.AuthzConfigurationError
|
class AuthzConfigurationError(Exception):
""" Error for missing / invalid configuration """
|
class AuthzConfigurationError(Exception):
''' Error for missing / invalid configuration '''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 3 | 0 | 0 | 0 | 10 | 2 | 0 | 1 | 1 | 0 | 1 | 1 | 1 | 0 | 0 | 3 | 0 | 0 |
4,515 |
Amsterdam/authorization_django
|
Amsterdam_authorization_django/authorization_django/config.py
|
authorization_django.config.NoRequiredScopesError
|
class NoRequiredScopesError(AuthzConfigurationError):
""" Error for when route is configured as protected
but no required scopes have been set
"""
|
class NoRequiredScopesError(AuthzConfigurationError):
''' Error for when route is configured as protected
but no required scopes have been set
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 3 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 4 | 0 | 1 | 1 | 0 | 3 | 1 | 1 | 0 | 0 | 4 | 0 | 0 |
4,516 |
Amsterdam/authorization_django
|
Amsterdam_authorization_django/authorization_django/config.py
|
authorization_django.config.ProtectedRecourceSyntaxError
|
class ProtectedRecourceSyntaxError(AuthzConfigurationError):
""" Syntax error in configuration of protected resource """
|
class ProtectedRecourceSyntaxError(AuthzConfigurationError):
''' Syntax error in configuration of protected resource '''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 2 | 0 | 1 | 1 | 0 | 1 | 1 | 1 | 0 | 0 | 4 | 0 | 0 |
4,517 |
Amsterdam/authorization_django
|
Amsterdam_authorization_django/authorization_django/config.py
|
authorization_django.config.ProtectedRouteConflictError
|
class ProtectedRouteConflictError(AuthzConfigurationError):
""" Error for a conflicting protected route configuration """
|
class ProtectedRouteConflictError(AuthzConfigurationError):
''' Error for a conflicting protected route configuration '''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 2 | 0 | 1 | 1 | 0 | 1 | 1 | 1 | 0 | 0 | 4 | 0 | 0 |
4,518 |
Amsterdam/authorization_django
|
Amsterdam_authorization_django/authorization_django/middleware.py
|
authorization_django.middleware._AuthorizationHeaderError
|
class _AuthorizationHeaderError(Exception):
def __init__(self, response):
self.response = response
|
class _AuthorizationHeaderError(Exception):
def __init__(self, response):
pass
| 2 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 1 | 1 | 11 | 4 | 1 | 3 | 3 | 1 | 0 | 3 | 3 | 1 | 1 | 3 | 0 | 1 |
4,519 |
Amsterdam/objectstore
|
Amsterdam_objectstore/objectstore/archive_pgtables.py
|
objectstore.archive_pgtables.Archiver
|
class Archiver(object):
"""
Archive specified tables.
- Dumps postgres sql copy format - data
- Dumps schema
- zip the resulting archives
- upload zip file to objectstore
- cleanup tmp files
- truncate tables IF ONLY everything was successfull!
TODO:
drop emptied partitions
NOTE:
avoid version conflict because we dump in copy format.
"""
def make_stamp(self, dt=None):
ts = dt if dt else datetime.datetime.now()
return ts.strftime("%Y%m%d-%H%M%S")
def __init__(self, tmp_folder=None):
self.tmp = tmp_folder if tmp_folder else DEFAULT_TMPFOLDER
self.stamp = self.make_stamp()
def cmd(self, cmd, filename=None):
log.info(f'Cmd: {cmd}, outputfile: {filename}')
try:
if filename:
with open(filename, 'wb') as outfile:
p = subprocess.Popen(cmd, stdout=outfile)
p.wait()
else:
p = subprocess.Popen(cmd)
p.wait()
log.info(f'Ret. code: {p.returncode}')
return p.returncode
except Exception as ex:
log.error(ex)
# import traceback
# print(traceback.format_exc())
return -1
def make_archive(self):
archive = f'{self.tmp}/archive-{self.stamp}.zip'
cmd = [
'zip',
archive,
]
cmd.extend(glob.glob(f'{self.tmp}/*{self.stamp}.sql'))
return archive if self.cmd(cmd) == 0 else None
def cleanup_tmpfiles(self):
cmd = [
'rm',
'-rf'
]
cmd.extend(glob.glob(f'{self.tmp}/*{self.stamp}.sql'))
cmd.extend(glob.glob(f'{self.tmp}/*{self.stamp}.zip'))
return self.cmd(cmd)
def archive_table(self, tbl):
error_count = 0
cmd = [
'pg_dump',
'--data-only', # only data
'--format=p', # plain sql txt output
'-b', # include blobs
'-t', # single table
f'{tbl}'
]
outfile = f'{self.tmp}/{tbl}-data-{self.stamp}.sql'
if self.cmd(cmd, outfile) != 0:
error_count += 1
cmd = [
'pg_dump',
'--schema-only', # only schema
'-t', # single table
f'{tbl}'
]
outfile = f'{self.tmp}/{tbl}-schema-{self.stamp}.sql'
if self.cmd(cmd, outfile) != 0:
error_count += 1
return error_count
def truncate_tables(self, tbls):
tbl_list = ','.join(tbls)
cmd = [
'psql',
'-v',
'ON_ERROR_STOP=1',
'-c',
f'TRUNCATE {tbl_list};',
]
return self.cmd(cmd)
def upload_to_objectstore(self, folder, archive):
try:
log.info('Connecting to objectstore')
connection = objectstore.get_connection()
log.info('Uploading to objectstore')
objectstore.databasedumps.upload_database(connection, folder, archive)
return 0
except Exception as ex:
log.error(ex)
return -1
def process(self, tables, folder):
error_count = 0
for table in tables:
if self.archive_table(table) != 0:
error_count += 1
if error_count == 0:
archive_file = self.make_archive()
# upload to object store
if self.upload_to_objectstore(folder, archive_file) == 0:
# only issue truncate if there are no errors
self.truncate_tables(tables)
self.cleanup_tmpfiles()
|
class Archiver(object):
'''
Archive specified tables.
- Dumps postgres sql copy format - data
- Dumps schema
- zip the resulting archives
- upload zip file to objectstore
- cleanup tmp files
- truncate tables IF ONLY everything was successfull!
TODO:
drop emptied partitions
NOTE:
avoid version conflict because we dump in copy format.
'''
def make_stamp(self, dt=None):
pass
def __init__(self, tmp_folder=None):
pass
def cmd(self, cmd, filename=None):
pass
def make_archive(self):
pass
def cleanup_tmpfiles(self):
pass
def archive_table(self, tbl):
pass
def truncate_tables(self, tbls):
pass
def upload_to_objectstore(self, folder, archive):
pass
def process(self, tables, folder):
pass
| 10 | 1 | 11 | 0 | 10 | 1 | 2 | 0.25 | 1 | 3 | 0 | 0 | 9 | 2 | 9 | 9 | 121 | 13 | 91 | 29 | 81 | 23 | 66 | 26 | 56 | 5 | 1 | 3 | 21 |
4,520 |
Amsterdam/objectstore
|
Amsterdam_objectstore/setup.py
|
setup.PyTest
|
class PyTest(TestCommand):
""" Custom class to avoid depending on pytest-runner.
"""
user_options = [('pytest-args=', 'a', "Arguments to pass into py.test")]
def initialize_options(self):
TestCommand.initialize_options(self)
self.pytest_args = ['--cov', 'objectstore']
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = []
self.test_suite = True
def run_tests(self):
import pytest
errno = pytest.main(self.pytest_args)
sys.exit(errno)
|
class PyTest(TestCommand):
''' Custom class to avoid depending on pytest-runner.
'''
def initialize_options(self):
pass
def finalize_options(self):
pass
def run_tests(self):
pass
| 4 | 1 | 4 | 0 | 4 | 0 | 1 | 0.15 | 1 | 0 | 0 | 0 | 3 | 3 | 3 | 3 | 19 | 4 | 13 | 10 | 8 | 2 | 13 | 10 | 8 | 1 | 1 | 0 | 3 |
4,521 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/binstar_client/errors.py
|
binstar_client.errors.DestinationPathExists
|
class DestinationPathExists(BinstarError):
def __init__(self, location):
self.msg = "destination path '{}' already exists.".format(location)
self.location = location
super().__init__(self.msg)
|
class DestinationPathExists(BinstarError):
def __init__(self, location):
pass
| 2 | 0 | 4 | 0 | 4 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 1 | 2 | 1 | 12 | 6 | 1 | 5 | 4 | 3 | 0 | 5 | 4 | 3 | 1 | 4 | 0 | 1 |
4,522 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/binstar_client/__init__.py
|
binstar_client.Binstar
|
class Binstar(OrgMixin, ChannelsMixin, PackageMixin): # pylint: disable=too-many-public-methods
"""
An object that represents interfaces with the Anaconda repository restful API.
:param token: a token generated by Binstar.authenticate or None for
an anonymous user.
"""
def __init__( # pylint: disable=unused-argument
self, token=None, domain='https://api.anaconda.org',
verify=True, **kwargs
):
self._session = requests.Session()
self._session.headers['x-binstar-api-version'] = __version__
self.session.verify = verify
self.session.auth = NullAuth()
self.token = token
self._token_warning_sent = False
user_agent = 'Anaconda-Client/{} (+https://anaconda.org)'.format(__version__)
self._session.headers.update({
'User-Agent': user_agent,
'Content-Type': 'application/json',
'Accept': 'application/json',
})
if token:
self._session.headers.update({'Authorization': 'token {}'.format(token)})
if domain.endswith('/'):
domain = domain[:-1]
if not domain.startswith(('http://', 'https://')):
domain = 'https://' + domain
self.domain = domain
@property
def session(self):
return self._session
def check_server(self):
"""Check if server is reachable or throw an exception if it isn't."""
msg = 'API server is unavailable. Please check your API url configuration.'
try:
response = self.session.head(self.domain)
except Exception as error: # pylint: disable=broad-except
raise errors.ServerError(msg) from error
try:
self._check_response(response)
except errors.NotFound as error:
raise errors.ServerError(msg) from error
def authentication_type(self):
url = '%s/authentication-type' % self.domain
res = self.session.get(url)
try:
self._check_response(res)
res = res.json()
return res['authentication_type']
except BinstarError:
return 'password'
def krb_authenticate(self, *args, **kwargs):
try:
from requests_kerberos import HTTPKerberosAuth # pylint: disable=import-outside-toplevel
return self._authenticate(HTTPKerberosAuth(), *args, **kwargs)
except ImportError as error:
# pylint: disable=implicit-str-concat
raise BinstarError(
'Kerberos authentication requires the requests-kerberos package to be installed:\n'
' conda install requests-kerberos\n'
'or: \n'
' pip install requests-kerberos'
) from error
def authenticate(self, username, password, *args, **kwargs):
return self._authenticate((username, password), *args, **kwargs)
def _authenticate(self, # pylint: disable=too-many-arguments
auth,
application,
application_url=None,
for_user=None,
scopes=None,
max_age=None,
strength='strong',
fail_if_already_exists=False,
hostname=_platform.node()):
"""
Use basic authentication to create an authentication token using the interface below.
With this technique, a username and password need not be stored permanently, and the user can
revoke access at any time.
:param username: The users name
:param password: The users password
:param application: The application that is requesting access
:param application_url: The application's home page
:param scopes: Scopes let you specify exactly what type of access you need. Scopes limit access for the tokens.
"""
url = '%s/authentications' % (self.domain)
payload = {'scopes': scopes, 'note': application, 'note_url': application_url,
'hostname': hostname,
'user': for_user,
'max-age': max_age,
'strength': strength,
'fail-if-exists': fail_if_already_exists}
data, headers = jencode(payload)
res = self.session.post(url, auth=auth, data=data, headers=headers)
self._check_response(res)
res = res.json()
token = res['token']
self.session.headers.update({'Authorization': 'token %s' % (token)})
return token
def list_scopes(self):
url = f'{self.domain}/scopes'
res = requests.get(url, timeout=60)
self._check_response(res)
return res.json()
def authentication(self):
"""Retrieve information on the current authentication token."""
url = '%s/authentication' % (self.domain)
res = self.session.get(url)
self._check_response(res)
return res.json()
def authentications(self):
"""Get a list of the current authentication tokens."""
url = '%s/authentications' % (self.domain)
res = self.session.get(url)
self._check_response(res)
return res.json()
def remove_authentication(self, auth_name=None, organization=None):
"""
Remove the current authentication or the one given by `auth_name`
"""
if auth_name:
if organization:
url = '%s/authentications/org/%s/name/%s' % (self.domain, organization, auth_name)
else:
url = '%s/authentications/name/%s' % (self.domain, auth_name)
else:
url = '%s/authentications' % (self.domain,)
res = self.session.delete(url)
self._check_response(res, [201])
def _check_response(self, res, allowed=None):
allowed = [200] if allowed is None else allowed
api_version = res.headers.get('x-binstar-api-version', '0.2.1')
if pv(api_version) > pv(__version__):
# pylint: disable=implicit-str-concat
logger.warning(
'The api server is running the binstar-api version %s. you are using %s\n'
'Please update your client with pip install -U binstar or conda update binstar',
api_version,
__version__,
)
if not self._token_warning_sent and 'Conda-Token-Warning' in res.headers:
logger.warning('Token warning: %s', res.headers['Conda-Token-Warning'])
self._token_warning_sent = True
if 'X-Anaconda-Lockdown' in res.headers:
logger.warning('Anaconda repository is currently in LOCKDOWN mode.')
if 'X-Anaconda-Read-Only' in res.headers:
logger.warning('Anaconda repository is currently in READ ONLY mode.')
if res.status_code not in allowed:
short, long = STATUS_CODES.get(res.status_code, ('?', 'Undefined error'))
msg = '%s: %s ([%s] %s -> %s)' % (short, long, res.request.method, res.request.url, res.status_code)
try:
data = res.json()
except Exception: # pylint: disable=broad-except
data = {}
msg = data.get('error', msg)
ErrCls = errors.BinstarError
if res.status_code == 401:
ErrCls = errors.Unauthorized
elif res.status_code == 404:
ErrCls = errors.NotFound
elif res.status_code == 409:
ErrCls = errors.Conflict
elif res.status_code >= 500:
ErrCls = errors.ServerError
raise ErrCls(msg, res.status_code)
def user(self, login=None):
"""
Get user information.
:param login: (optional) the login name of the user or None. If login is None
this method will return the information of the authenticated user.
"""
if login:
url = f'{self.domain}/user/{login}'
elif self.token:
url = f'{self.domain}/user'
else:
raise errors.Unauthorized(
'Authentication token is missing. Please, use `anaconda login` to reauthenticate.', 401)
res = self.session.get(url, verify=self.session.verify)
self._check_response(res)
return res.json()
def user_packages(
self,
login=None,
platform=None,
package_type=None,
type_=None,
access=None):
"""
Returns a list of packages for a given user and optionally filter
by `platform`, `package_type` and `type_`.
:param login: (optional) the login name of the user or None. If login
is None this method will return the packages for the
authenticated user.
:param platform: only find packages that include files for this platform.
(e.g. 'linux-64', 'osx-64', 'win-32')
:param package_type: only find packages that have this kind of file
(e.g. 'env', 'conda', 'pypi')
:param type_: only find packages that have this conda `type`
(i.e. 'app')
:param access: only find packages that have this access level
(e.g. 'private', 'authenticated', 'public')
"""
if login:
url = '{0}/packages/{1}'.format(self.domain, login)
else:
url = '{0}/packages'.format(self.domain)
arguments = collections.OrderedDict()
if platform:
arguments['platform'] = platform
if package_type:
arguments['package_type'] = package_type
if type_:
arguments['type'] = type_
if access:
arguments['access'] = access
res = self.session.get(url, params=arguments)
self._check_response(res)
return res.json()
def package(self, login, package_name):
"""
Get information about a specific package
:param login: the login of the package owner
:param package_name: the name of the package
"""
url = '%s/package/%s/%s' % (self.domain, login, package_name)
res = self.session.get(url)
self._check_response(res)
return res.json()
def package_add_collaborator(self, owner, package_name, collaborator):
url = '%s/packages/%s/%s/collaborators/%s' % (self.domain, owner, package_name, collaborator)
res = self.session.put(url)
self._check_response(res, [201])
def package_remove_collaborator(self, owner, package_name, collaborator):
url = '%s/packages/%s/%s/collaborators/%s' % (self.domain, owner, package_name, collaborator)
res = self.session.delete(url)
self._check_response(res, [201])
def package_collaborators(self, owner, package_name):
url = '%s/packages/%s/%s/collaborators' % (self.domain, owner, package_name)
res = self.session.get(url)
self._check_response(res, [200])
return res.json()
def all_packages(self, modified_after=None):
url = '%s/package_listing' % (self.domain)
data = {'modified_after': modified_after or ''}
res = self.session.get(url, data=data)
self._check_response(res)
return res.json()
def add_package( # pylint: disable=too-many-arguments
self,
login,
package_name,
summary=None,
license=None, # pylint: disable=redefined-builtin
public=True,
license_url=None,
license_family=None,
attrs=None,
package_type=None,
):
"""
Add a new package to a users account
:param login: the login of the package owner
:param package_name: the name of the package to be created
:param package_type: A type identifier for the package (eg. 'pypi' or 'conda', etc.)
:param summary: A short summary about the package
:param license: the name of the package license
:param license_url: the url of the package license
:param public: if true then the package will be hosted publicly
:param attrs: A dictionary of extra attributes for this package
"""
package_types = [] if package_type is None else [package_type.value]
url = '%s/package/%s/%s' % (self.domain, login, package_name)
attrs = attrs or {}
attrs['summary'] = summary
attrs['package_types'] = package_types
attrs['license'] = {
'name': license,
'url': license_url,
'family': license_family,
}
payload = {'public': bool(public), 'publish': False, 'public_attrs': dict(attrs or {})}
data, headers = jencode(payload)
res = self.session.post(url, data=data, headers=headers)
self._check_response(res)
return res.json()
def update_package(self, login, package_name, attrs):
"""
Update public_attrs of the package on a users account
:param login: the login of the package owner
:param package_name: the name of the package to be updated
:param attrs: A dictionary of attributes to update
"""
url = '{}/package/{}/{}'.format(self.domain, login, package_name)
payload = {'public_attrs': dict(attrs)}
data, headers = jencode(payload)
res = self.session.patch(url, data=data, headers=headers)
self._check_response(res)
return res.json()
def update_release(self, login, package_name, version, attrs):
"""
Update release public_attrs of the package on a users account
:param login: the login of the package owner
:param package_name: the name of the package to be updated
:param version: version of the package to update
:param attrs: A dictionary of attributes to update
"""
url = '{}/release/{}/{}/{}'.format(self.domain, login, package_name, version)
payload = {'public_attrs': dict(attrs)}
data, headers = jencode(payload)
res = self.session.patch(url, data=data, headers=headers)
self._check_response(res)
return res.json()
def remove_package(self, username, package_name):
url = '%s/package/%s/%s' % (self.domain, username, package_name)
res = self.session.delete(url)
self._check_response(res, [201])
def release(self, login, package_name, version):
"""
Get information about a specific release
:param login: the login of the package owner
:param package_name: the name of the package
:param version: the name of the package
"""
url = '%s/release/%s/%s/%s' % (self.domain, login, package_name, version)
res = self.session.get(url)
self._check_response(res)
return res.json()
def remove_release(self, username, package_name, version):
"""
Remove a release and all files under it.
:param username: the login of the package owner
:param package_name: the name of the package
:param version: the name of the package
"""
url = '%s/release/%s/%s/%s' % (self.domain, username, package_name, version)
res = self.session.delete(url)
self._check_response(res, [201])
def add_release(self, login, package_name, version, requirements, announce, release_attrs):
"""
Add a new release to a package.
:param login: the login of the package owner
:param package_name: the name of the package
:param version: the version string of the release
:param requirements: A dict of requirements NOTE: describe
:param announce: An announcement that will be posted to all package watchers
"""
url = '%s/release/%s/%s/%s' % (self.domain, login, package_name, version)
if not release_attrs:
release_attrs = {}
payload = {
'requirements': requirements,
'announce': announce,
'description': None, # Will be updated with the one on release_attrs
}
payload.update(release_attrs)
data, headers = jencode(payload)
res = self.session.post(url, data=data, headers=headers)
self._check_response(res)
return res.json()
def distribution(self, login, package_name, release, basename=None):
url = '%s/dist/%s/%s/%s/%s' % (self.domain, login, package_name, release, basename)
res = self.session.get(url)
self._check_response(res)
return res.json()
def remove_dist(self, login, package_name, release, basename=None, _id=None):
if basename:
url = '%s/dist/%s/%s/%s/%s' % (self.domain, login, package_name, release, basename)
elif _id:
url = '%s/dist/%s/%s/%s/-/%s' % (self.domain, login, package_name, release, _id)
else:
raise TypeError("method remove_dist expects either 'basename' or '_id' arguments")
res = self.session.delete(url)
self._check_response(res)
return res.json()
def download(self, login, package_name, release, basename, md5=None):
"""
Download a package distribution
:param login: the login of the package owner
:param package_name: the name of the package
:param version: the version string of the release
:param basename: the basename of the distribution to download
:param md5: (optional) an md5 hash of the download if given and the package has not changed
None will be returned
:returns: a file like object or None
"""
url = '%s/download/%s/%s/%s/%s' % (self.domain, login, package_name, release, basename)
if md5:
headers = {'ETag': md5, }
else:
headers = {}
res = self.session.get(url, headers=headers, allow_redirects=False)
self._check_response(res, allowed=[200, 302, 304])
if res.status_code == 200:
# We received the content directly from anaconda.org
return res
if res.status_code == 304:
# The content has not changed
return None
if res.status_code == 302:
# Download from s3:
# We need to create a new request (without using session) to avoid
# sending the custom headers set on our session to S3 (which causes
# a failure).
res2 = requests.get(res.headers['location'], stream=True, timeout=10 * 60 * 60)
return res2
return None
def upload(self, login, package_name, release, basename, file, distribution_type,
description='', md5=None, sha256=None, size=None, dependencies=None, attrs=None,
channels=('main',)):
"""
Upload a new distribution to a package release.
:param login: the login of the package owner
:param package_name: the name of the package
:param release: the version string of the release
:param basename: the basename of the distribution to download
:param file: a file like object to upload
:param distribution_type: pypi or conda or ipynb, etc.
:param description: (optional) a short description about the file
:param md5: (optional) base64 encoded md5 hash calculated from package file
:param sha256: (optional) base64 encoded sha256 hash calculated from package file
:param size: (optional) size of package file in bytes
:param dependencies: (optional) list package dependencies
:param attrs: any extra attributes about the file (eg. build=1, pyversion='2.7', os='osx')
:param channels: list of labels package will be available from
"""
url = '%s/stage/%s/%s/%s/%s' % (self.domain, login, package_name, release, quote(basename))
if attrs is None:
attrs = {}
if not isinstance(attrs, dict):
raise TypeError('argument attrs must be a dictionary')
sha256 = sha256 if sha256 is not None else compute_hash(file, size=size, hash_algorithm=hashlib.sha256)[0]
if not isinstance(distribution_type, str):
distribution_type = distribution_type.value
payload = {
'distribution_type': distribution_type,
'description': description,
'attrs': attrs,
'dependencies': dependencies,
'channels': channels,
'sha256': sha256,
}
data, headers = jencode(payload)
res = self.session.post(url, data=data, headers=headers)
self._check_response(res)
obj = res.json()
s3url = obj['post_url']
s3data = obj['form_data']
if md5 is None:
_hexmd5, b64md5, size = compute_hash(file, size=size)
elif size is None:
spos = file.tell()
file.seek(0, os.SEEK_END)
size = file.tell() - spos
file.seek(spos)
s3data['Content-Length'] = str(size)
s3data['Content-MD5'] = b64md5
file_size = os.fstat(file.fileno()).st_size
with tqdm(total=file_size, unit='B', unit_scale=True, unit_divisor=1024) as progress:
s3res = multipart_files_upload(
s3url, s3data, {'file': (basename, file)}, progress,
verify=self.session.verify)
if s3res.status_code != 201:
logger.info(s3res.text)
xml_error = ET.fromstring(s3res.text)
msg_tail = ''
if xml_error.find('Code').text == 'InvalidDigest':
msg_tail = ' The Content-MD5 or checksum value is not valid.'
raise errors.BinstarError('Error uploading package!%s' % msg_tail, s3res.status_code)
url = '%s/commit/%s/%s/%s/%s' % (self.domain, login, package_name, release, quote(basename))
payload = {'dist_id': obj['dist_id']}
data, headers = jencode(payload)
res = self.session.post(url, data=data, headers=headers)
self._check_response(res)
return res.json()
def search(self, query, package_type=None, platform=None):
if package_type is not None:
package_type = package_type.value
url = '%s/search' % self.domain
res = self.session.get(url, params={
'name': query,
'type': package_type,
'platform': platform,
})
self._check_response(res)
return res.json()
def user_licenses(self):
"""Download the user current trial/paid licenses."""
url = '{domain}/license'.format(domain=self.domain)
res = self.session.get(url)
self._check_response(res)
return res.json()
|
class Binstar(OrgMixin, ChannelsMixin, PackageMixin):
'''
An object that represents interfaces with the Anaconda repository restful API.
:param token: a token generated by Binstar.authenticate or None for
an anonymous user.
'''
def __init__( # pylint: disable=unused-argument
self, token=None, domain='https://api.anaconda.org',
verify=True, **kwargs
):
pass
@property
def session(self):
pass
def check_server(self):
'''Check if server is reachable or throw an exception if it isn't.'''
pass
def authentication_type(self):
pass
def krb_authenticate(self, *args, **kwargs):
pass
def authenticate(self, username, password, *args, **kwargs):
pass
def _authenticate(self, # pylint: disable=too-many-arguments
auth,
application,
application_url=None,
for_user=None,
scopes=None,
max_age=None,
strength='strong',
fail_if_already_exists=False,
hostname=_platform.node()):
'''
Use basic authentication to create an authentication token using the interface below.
With this technique, a username and password need not be stored permanently, and the user can
revoke access at any time.
:param username: The users name
:param password: The users password
:param application: The application that is requesting access
:param application_url: The application's home page
:param scopes: Scopes let you specify exactly what type of access you need. Scopes limit access for the tokens.
'''
pass
def list_scopes(self):
pass
def authentication_type(self):
'''Retrieve information on the current authentication token.'''
pass
def authentications(self):
'''Get a list of the current authentication tokens.'''
pass
def remove_authentication(self, auth_name=None, organization=None):
'''
Remove the current authentication or the one given by `auth_name`
'''
pass
def _check_response(self, res, allowed=None):
pass
def user(self, login=None):
'''
Get user information.
:param login: (optional) the login name of the user or None. If login is None
this method will return the information of the authenticated user.
'''
pass
def user_packages(
self,
login=None,
platform=None,
package_type=None,
type_=None,
access=None):
'''
Returns a list of packages for a given user and optionally filter
by `platform`, `package_type` and `type_`.
:param login: (optional) the login name of the user or None. If login
is None this method will return the packages for the
authenticated user.
:param platform: only find packages that include files for this platform.
(e.g. 'linux-64', 'osx-64', 'win-32')
:param package_type: only find packages that have this kind of file
(e.g. 'env', 'conda', 'pypi')
:param type_: only find packages that have this conda `type`
(i.e. 'app')
:param access: only find packages that have this access level
(e.g. 'private', 'authenticated', 'public')
'''
pass
def package(self, login, package_name):
'''
Get information about a specific package
:param login: the login of the package owner
:param package_name: the name of the package
'''
pass
def package_add_collaborator(self, owner, package_name, collaborator):
pass
def package_remove_collaborator(self, owner, package_name, collaborator):
pass
def package_collaborators(self, owner, package_name):
pass
def all_packages(self, modified_after=None):
pass
def add_package( # pylint: disable=too-many-arguments
self,
login,
package_name,
summary=None,
license=None, # pylint: disable=redefined-builtin
public=True,
license_url=None,
license_family=None,
attrs=None,
package_type=None,
):
'''
Add a new package to a users account
:param login: the login of the package owner
:param package_name: the name of the package to be created
:param package_type: A type identifier for the package (eg. 'pypi' or 'conda', etc.)
:param summary: A short summary about the package
:param license: the name of the package license
:param license_url: the url of the package license
:param public: if true then the package will be hosted publicly
:param attrs: A dictionary of extra attributes for this package
'''
pass
def update_package(self, login, package_name, attrs):
'''
Update public_attrs of the package on a users account
:param login: the login of the package owner
:param package_name: the name of the package to be updated
:param attrs: A dictionary of attributes to update
'''
pass
def update_release(self, login, package_name, version, attrs):
'''
Update release public_attrs of the package on a users account
:param login: the login of the package owner
:param package_name: the name of the package to be updated
:param version: version of the package to update
:param attrs: A dictionary of attributes to update
'''
pass
def remove_package(self, username, package_name):
pass
def release(self, login, package_name, version):
'''
Get information about a specific release
:param login: the login of the package owner
:param package_name: the name of the package
:param version: the name of the package
'''
pass
def remove_release(self, username, package_name, version):
'''
Remove a release and all files under it.
:param username: the login of the package owner
:param package_name: the name of the package
:param version: the name of the package
'''
pass
def add_release(self, login, package_name, version, requirements, announce, release_attrs):
'''
Add a new release to a package.
:param login: the login of the package owner
:param package_name: the name of the package
:param version: the version string of the release
:param requirements: A dict of requirements NOTE: describe
:param announce: An announcement that will be posted to all package watchers
'''
pass
def distribution(self, login, package_name, release, basename=None):
pass
def remove_dist(self, login, package_name, release, basename=None, _id=None):
pass
def download(self, login, package_name, release, basename, md5=None):
'''
Download a package distribution
:param login: the login of the package owner
:param package_name: the name of the package
:param version: the version string of the release
:param basename: the basename of the distribution to download
:param md5: (optional) an md5 hash of the download if given and the package has not changed
None will be returned
:returns: a file like object or None
'''
pass
def upload(self, login, package_name, release, basename, file, distribution_type,
description='', md5=None, sha256=None, size=None, dependencies=None, attrs=None,
channels=('main',)):
'''
Upload a new distribution to a package release.
:param login: the login of the package owner
:param package_name: the name of the package
:param release: the version string of the release
:param basename: the basename of the distribution to download
:param file: a file like object to upload
:param distribution_type: pypi or conda or ipynb, etc.
:param description: (optional) a short description about the file
:param md5: (optional) base64 encoded md5 hash calculated from package file
:param sha256: (optional) base64 encoded sha256 hash calculated from package file
:param size: (optional) size of package file in bytes
:param dependencies: (optional) list package dependencies
:param attrs: any extra attributes about the file (eg. build=1, pyversion='2.7', os='osx')
:param channels: list of labels package will be available from
'''
pass
def search(self, query, package_type=None, platform=None):
pass
def user_licenses(self):
'''Download the user current trial/paid licenses.'''
pass
| 34 | 18 | 17 | 2 | 11 | 4 | 2 | 0.36 | 3 | 15 | 6 | 1 | 32 | 4 | 32 | 51 | 593 | 100 | 368 | 160 | 302 | 134 | 283 | 125 | 249 | 12 | 1 | 2 | 76 |
4,523 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/binstar_client/commands/authorizations.py
|
binstar_client.commands.authorizations.TimeDeltaGroup
|
class TimeDeltaGroup(typing.NamedTuple):
"""
Rule to format timedelta.
:param amount: maximum allowed amount for this group.
if actual value exceeds it - this rule is skipped and next should be processed.
:param strict: if set to :code:`True` - actual value would be divided by :code:`amount` before checking next rules.
:param format: format string that should be used to format the output value.
:param name: name of the units to display.
"""
amount: int
strict: bool
format: str
name: str
|
class TimeDeltaGroup(typing.NamedTuple):
'''
Rule to format timedelta.
:param amount: maximum allowed amount for this group.
if actual value exceeds it - this rule is skipped and next should be processed.
:param strict: if set to :code:`True` - actual value would be divided by :code:`amount` before checking next rules.
:param format: format string that should be used to format the output value.
:param name: name of the units to display.
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1.6 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 19 | 6 | 5 | 1 | 4 | 8 | 5 | 1 | 4 | 0 | 1 | 0 | 0 |
4,524 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/binstar_client/commands/upload.py
|
binstar_client.commands.upload.CacheRecord
|
class CacheRecord: # pylint: disable=too-few-public-methods
"""Common interface for cached server records."""
__slots__ = ('empty',)
def __init__(self, empty: bool = True) -> None:
"""Initialize new :class:`~CacheRecord` instance."""
self.empty: bool = empty
@staticmethod
def cleanup(
storage: typing.Dict[KeyT, CacheRecordT],
action: typing.Optional[typing.Callable[[KeyT, CacheRecordT], typing.Any]] = None,
) -> int:
"""
Remove all empty records from :code:`storage`.
Optional :code:`action` function might be called for each instance being removed.
"""
to_remove: typing.List[KeyT] = []
key: KeyT
record: CacheRecordT
for key, record in storage.items():
if record.empty:
to_remove.append(key)
if action is not None:
action(key, record)
for key in to_remove:
storage.pop(key)
return len(to_remove)
|
class CacheRecord:
'''Common interface for cached server records.'''
def __init__(self, empty: bool = True) -> None:
'''Initialize new :class:`~CacheRecord` instance.'''
pass
@staticmethod
def cleanup(
storage: typing.Dict[KeyT, CacheRecordT],
action: typing.Optional[typing.Callable[[KeyT, CacheRecordT], typing.Any]] = None,
) -> int:
'''
Remove all empty records from :code:`storage`.
Optional :code:`action` function might be called for each instance being removed.
'''
pass
| 4 | 3 | 13 | 2 | 9 | 3 | 3 | 0.35 | 0 | 3 | 0 | 2 | 1 | 1 | 2 | 2 | 33 | 7 | 20 | 10 | 13 | 7 | 16 | 6 | 13 | 5 | 0 | 3 | 6 |
4,525 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/binstar_client/commands/upload.py
|
binstar_client.commands.upload.PackageCacheRecord
|
class PackageCacheRecord(CacheRecord):
"""Cached details on a package stored on a server."""
__slots__ = ('name', 'package_types')
def __init__(self, name: str, empty: bool = True, package_types: typing.Iterable[PackageType] = ()) -> None:
"""Initialize new :class:`~PackageCacheRecord` instance."""
super().__init__(empty=empty)
self.name: typing.Final[str] = name
self.package_types: typing.List[PackageType] = list(package_types)
def update(self, package_type: PackageType) -> None:
"""Update record after a file is uploaded to this package."""
self.empty = False
if package_type not in self.package_types:
self.package_types.append(package_type)
|
class PackageCacheRecord(CacheRecord):
'''Cached details on a package stored on a server.'''
def __init__(self, name: str, empty: bool = True, package_types: typing.Iterable[PackageType] = ()) -> None:
'''Initialize new :class:`~PackageCacheRecord` instance.'''
pass
def update(self, package_type: PackageType) -> None:
'''Update record after a file is uploaded to this package.'''
pass
| 3 | 3 | 5 | 0 | 4 | 1 | 2 | 0.3 | 1 | 5 | 1 | 0 | 2 | 3 | 2 | 4 | 16 | 3 | 10 | 7 | 7 | 3 | 10 | 7 | 7 | 2 | 1 | 1 | 3 |
4,526 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/binstar_client/commands/upload.py
|
binstar_client.commands.upload.PackageMeta
|
class PackageMeta:
"""Collected details on a package file being currently uploaded."""
__slots__ = (
'filename', 'meta',
'__file_attrs', '__name', '__package_attrs', '__release_attrs', '__version',
)
def __init__(self, filename: str, meta: detect.Meta) -> None:
"""Initialize new :class:`~PackageMeta` instance."""
self.filename: typing.Final[str] = filename
self.meta: typing.Final[detect.Meta] = meta
self.__file_attrs: typing.Optional[detect.FileAttributes] = None
self.__name: typing.Optional[str] = None
self.__package_attrs: typing.Optional[detect.PackageAttributes] = None
self.__release_attrs: typing.Optional[detect.ReleaseAttributes] = None
self.__version: typing.Optional[str] = None
@property
def extension(self) -> str: # noqa: D401
"""File extension of the package file."""
return self.meta.extension
@property
def file_attrs(self) -> detect.FileAttributes: # noqa: D401
"""Attributes of a file being uploaded."""
if self.__file_attrs is None:
self._update_attrs()
return typing.cast(detect.FileAttributes, self.__file_attrs)
@property
def name(self) -> str: # noqa: D401
"""Name of a package for which file is being uploaded."""
if self.__name is None:
self._update_name()
return typing.cast(str, self.__name)
@name.setter
def name(self, value: str) -> None:
"""Update value of a :attr:`~PackageMeta.name`."""
self._update_name(value)
@property
def package_attrs(self) -> detect.PackageAttributes: # noqa: D401
"""Attributes of a package for which file is being uploaded."""
if self.__package_attrs is None:
self._update_attrs()
return typing.cast(detect.PackageAttributes, self.__package_attrs)
@property
def package_key(self) -> PackageKey: # noqa: D401
"""Key for accessing related cached package record."""
return self.name
@property
def package_type(self) -> PackageType: # noqa: D401
"""Type of a package being uploaded."""
return self.meta.package_type
@property
def release_attrs(self) -> detect.ReleaseAttributes: # noqa: D401
"""Attributes of a release for which file is being uploaded."""
if self.__release_attrs is None:
self._update_attrs()
return typing.cast(detect.ReleaseAttributes, self.__release_attrs)
@property
def release_key(self) -> ReleaseKey: # noqa: D401
"""Key for accessing related cached release record."""
return self.name, self.version
@property
def version(self) -> str: # noqa: D401
"""Version of a package being uploaded."""
if self.__version is None:
self._update_version()
return typing.cast(str, self.__version)
@version.setter
def version(self, value: str) -> None:
"""Update value of a :attr:`~PackageMeta.version`."""
self._update_version(value)
def rebuild_basename(self) -> str:
"""
Rebuild package basename from its attributes.
Usually basename contains actual filename being uploaded, which may not include expected metadata in the
expected format. This function allows to enforce the standard without requiring user to rename the file.
:return: New basename.
"""
subdir: typing.Optional[str] = self.file_attrs.setdefault('attrs', {}).get('subdir', None)
if not subdir:
try:
subdir, _ = self.file_attrs.get('basename', '').split('/', 1)
except ValueError:
subdir = 'noarch'
self.file_attrs['attrs']['subdir'] = subdir
build: str = self.file_attrs['attrs'].setdefault('build', '0')
self.file_attrs['basename'] = f'{subdir}/{self.name}-{self.version}-{build}{self.extension}'
return self.file_attrs['basename']
def _update_attrs(self, *args: typing.Any, **kwargs: typing.Any) -> None:
"""Update content of all attribute fields."""
logger.info('Extracting %s attributes for upload', self.package_type.label.lower())
try:
self.__package_attrs, self.__release_attrs, self.__file_attrs = detect.get_attrs(
self.package_type, self.filename, *args, **kwargs,
)
except Exception as error:
message: str = (
f'Trouble reading metadata from "{self.filename}". '
f'Is this a valid {self.package_type.label.lower()} package?'
)
logger.error(message)
raise errors.BinstarError(message) from error
def _update_name(self, value: typing.Optional[str] = None) -> None:
"""Update value of a :attr:`~PackageMeta.name`."""
name: str = self.package_attrs.get('name', '')
if value:
if name:
good_names: typing.List[str] = [name := name.lower()]
if self.package_type is PackageType.STANDARD_PYTHON:
good_names.append(name.replace('-', '_'))
if value.lower() not in good_names:
message: str = (
f'Package name on the command line "{value.lower()}" '
f'does not match the package name in the file "{self.package_attrs["name"].lower()}"'
)
logger.error(message)
raise errors.BinstarError(message)
name = value
elif not name:
message = (
f'Could not detect package name for package type {self.package_type.label.lower()}, '
f'please use the --package option'
)
logger.error(message)
raise errors.BinstarError(message)
self.__name = name
def _update_version(self, value: typing.Optional[str] = None) -> None:
"""Update value of a :attr:`~PackageMeta.version`."""
if not value:
value = self.release_attrs.get('version', None)
if not value:
message: str = (
f'Could not detect package version for package type "{self.package_type.label.lower()}", '
f'please use the --version option'
)
logger.error(message)
raise errors.BinstarError(message)
self.__version = value
|
class PackageMeta:
'''Collected details on a package file being currently uploaded.'''
def __init__(self, filename: str, meta: detect.Meta) -> None:
'''Initialize new :class:`~PackageMeta` instance.'''
pass
@property
def extension(self) -> str:
'''File extension of the package file.'''
pass
@property
def file_attrs(self) -> detect.FileAttributes:
'''Attributes of a file being uploaded.'''
pass
@property
def name(self) -> str:
'''Name of a package for which file is being uploaded.'''
pass
@name.setter
def name(self) -> str:
'''Update value of a :attr:`~PackageMeta.name`.'''
pass
@property
def package_attrs(self) -> detect.PackageAttributes:
'''Attributes of a package for which file is being uploaded.'''
pass
@property
def package_key(self) -> PackageKey:
'''Key for accessing related cached package record.'''
pass
@property
def package_type(self) -> PackageType:
'''Type of a package being uploaded.'''
pass
@property
def release_attrs(self) -> detect.ReleaseAttributes:
'''Attributes of a release for which file is being uploaded.'''
pass
@property
def release_key(self) -> ReleaseKey:
'''Key for accessing related cached release record.'''
pass
@property
def version(self) -> str:
'''Version of a package being uploaded.'''
pass
@version.setter
def version(self) -> str:
'''Update value of a :attr:`~PackageMeta.version`.'''
pass
def rebuild_basename(self) -> str:
'''
Rebuild package basename from its attributes.
Usually basename contains actual filename being uploaded, which may not include expected metadata in the
expected format. This function allows to enforce the standard without requiring user to rename the file.
:return: New basename.
'''
pass
def _update_attrs(self, *args: typing.Any, **kwargs: typing.Any) -> None:
'''Update content of all attribute fields.'''
pass
def _update_name(self, value: typing.Optional[str] = None) -> None:
'''Update value of a :attr:`~PackageMeta.name`.'''
pass
def _update_version(self, value: typing.Optional[str] = None) -> None:
'''Update value of a :attr:`~PackageMeta.version`.'''
pass
| 28 | 17 | 8 | 1 | 6 | 2 | 2 | 0.27 | 0 | 7 | 3 | 0 | 16 | 7 | 16 | 16 | 162 | 26 | 114 | 45 | 86 | 31 | 85 | 33 | 68 | 6 | 0 | 3 | 31 |
4,527 |
Anaconda-Platform/anaconda-client
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Anaconda-Platform_anaconda-client/tests/test_login.py
|
tests.test_login.Test
|
class Test(CLITestCase):
"""Tests for authentication commands."""
@unittest.mock.patch('binstar_client.commands.login.store_token')
@unittest.mock.patch('getpass.getpass')
@unittest.mock.patch('binstar_client.commands.login.input')
@urlpatch
def test_login(self, urls, data, getpass, store_token):
data.return_value = 'test_user'
getpass.return_value = 'password'
urls.register(path='/', method='HEAD', status=200)
urls.register(path='/authentication-type',
content='{"authentication_type": "password"}')
auth = urls.register(
method='POST', path='/authentications', content='{"token": "a-token"}')
main(['--show-traceback', 'login'])
self.assertIn('login successful', self.stream.getvalue())
auth.assertCalled()
self.assertIn('Authorization', auth.req.headers)
self.assertIn('Basic ', auth.req.headers['Authorization'])
self.assertTrue(store_token.called)
self.assertEqual(store_token.call_args[0][0], 'a-token')
@unittest.mock.patch('binstar_client.commands.login.store_token')
@unittest.mock.patch('getpass.getpass')
@unittest.mock.patch('binstar_client.commands.login.input')
@urlpatch
def test_login_compatible(self, urls, data, getpass, store_token):
data.return_value = 'test_user'
getpass.return_value = 'password'
urls.register(path='/', method='HEAD', status=200)
urls.register(path='/authentication-type', status=404)
auth = urls.register(
method='POST', path='/authentications', content='{"token": "a-token"}')
main(['--show-traceback', 'login'])
self.assertIn('login successful', self.stream.getvalue())
auth.assertCalled()
self.assertIn('Authorization', auth.req.headers)
self.assertIn('Basic ', auth.req.headers['Authorization'])
self.assertTrue(store_token.called)
self.assertEqual(store_token.call_args[0][0], 'a-token')
|
class Test(CLITestCase):
'''Tests for authentication commands.'''
@unittest.mock.patch('binstar_client.commands.login.store_token')
@unittest.mock.patch('getpass.getpass')
@unittest.mock.patch('binstar_client.commands.login.input')
@urlpatch
def test_login(self, urls, data, getpass, store_token):
pass
@unittest.mock.patch('binstar_client.commands.login.store_token')
@unittest.mock.patch('getpass.getpass')
@unittest.mock.patch('binstar_client.commands.login.input')
@urlpatch
def test_login_compatible(self, urls, data, getpass, store_token):
pass
| 11 | 1 | 18 | 5 | 13 | 0 | 1 | 0.03 | 1 | 0 | 0 | 0 | 2 | 0 | 2 | 76 | 48 | 12 | 35 | 7 | 24 | 1 | 27 | 5 | 24 | 1 | 3 | 0 | 2 |
4,528 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/binstar_client/commands/upload.py
|
binstar_client.commands.upload.Uploader
|
class Uploader: # pylint: disable=too-many-instance-attributes
"""Manager for package and project uploads."""
__slots__ = (
'arguments', 'uploaded_packages', 'uploaded_projects',
'__api', '__config', '__username',
'__package_cache', '__release_cache',
)
def __init__(self, arguments: argparse.Namespace) -> None:
"""Initialize new :class:`~Uploader` instance."""
self.arguments: typing.Final[argparse.Namespace] = arguments
self.uploaded_packages: typing.Final[typing.List[UploadedPackage]] = []
self.uploaded_projects: typing.Final[typing.List[projects.UploadedProject]] = []
self.__api: typing.Optional[binstar_client.Binstar] = None
self.__config: typing.Optional[typing.Mapping[str, typing.Any]] = None
self.__username: typing.Optional[str] = None
self.__package_cache: typing.Final[typing.Dict[PackageKey, PackageCacheRecord]] = {}
self.__release_cache: typing.Final[typing.Dict[ReleaseKey, ReleaseCacheRecord]] = {}
@property
def api(self) -> binstar_client.Binstar: # noqa: D401
"""Client used to access anaconda.org API."""
if self.__api is None:
self.__api = get_server_api(token=self.arguments.token, site=self.arguments.site, config=self.config)
return self.__api
@property
def config(self) -> typing.Mapping[str, typing.Any]: # noqa: D401
"""Configuration of the :code:`anaconda-client`."""
if self.__config is None:
self.__config = get_config(site=self.arguments.site)
return self.__config
@property
def username(self) -> str: # noqa: D401
"""Name of the user or organization to upload packages and projects to."""
if self.__username is None:
details: str = ''
username: str = self.arguments.user or ''
if (not username) and (username := self.config.get('upload_user', '')):
details = ' (from "upload_user" preference)'
if username:
try:
self.api.user(username)
except errors.NotFound as error:
message: str = f'User "{username}" does not exist{details}'
logger.error(message)
raise errors.BinstarError(message) from error
else:
username = self.api.user()['login']
logger.info('Using "%s" as upload username%s', username, details)
self.__username = username
return self.__username
def cleanup(self) -> None:
"""
Remove empty releases and packages.
Package or release considered to be empty if it was created to upload files to, but all file uploads failed.
"""
def remove_empty_release(_key: ReleaseKey, record: ReleaseCacheRecord) -> None:
try:
if not self.api.release(self.username, record.name, record.version).get('distributions', []):
logger.info('Removing empty "%s/%s" release after failed upload', record.name, record.version)
self.api.remove_release(self.username, record.name, record.version)
except (AttributeError, TypeError, errors.NotFound):
pass
def remove_empty_package(_key: PackageKey, record: PackageCacheRecord) -> None:
try:
if not self.api.package(self.username, record.name).get('files', []):
logger.info('Removing empty "%s" package after failed upload', record.name)
self.api.remove_package(self.username, record.name)
except (AttributeError, TypeError, errors.NotFound):
pass
CacheRecord.cleanup(self.__release_cache, remove_empty_release)
CacheRecord.cleanup(self.__package_cache, remove_empty_package)
def get_package(self, meta: PackageMeta, *, force: bool = False) -> PackageCacheRecord:
"""
Retrieve details on a package from the server.
If not forced - may return cached record.
"""
key: typing.Final[PackageKey] = meta.package_key
cache_record: typing.Optional[PackageCacheRecord]
if (not force) and (cache_record := self.__package_cache.get(key, None)):
return cache_record
try:
instance: typing.Mapping[str, typing.Any] = self.api.package(self.username, meta.name)
cache_record = PackageCacheRecord(
name=meta.name,
empty=False,
package_types=list(map(PackageType, instance.get('package_types', ())))
)
except errors.NotFound as error:
if not self.arguments.auto_register:
message: str = (
f'Anaconda repository package {self.username}/{meta.name} does not exist. '
f'Please run "anaconda package --create" to create this package namespace in the cloud.'
)
logger.error(message)
raise errors.UserError(message) from error
summary: typing.Optional[str] = self.arguments.summary
if (summary is None) and ((summary := meta.package_attrs.get('summary', None)) is None):
message = (
f'Could not detect package summary for package type {meta.package_type.label.lower()}, '
f'please use the --summary option'
)
logger.error(message)
raise errors.BinstarError(message) from error
self.api.add_package(
self.username,
meta.name,
summary,
meta.package_attrs.get('license'),
public=not self.arguments.private,
attrs=meta.package_attrs,
license_url=meta.package_attrs.get('license_url'),
license_family=meta.package_attrs.get('license_family'),
package_type=meta.package_type,
)
cache_record = PackageCacheRecord(name=meta.name, empty=True, package_types=[])
self.__package_cache[key] = cache_record
return cache_record
def get_release(self, meta: PackageMeta, *, force: bool = False) -> ReleaseCacheRecord:
"""
Retrieve details on a release from the server.
If not forced - may return cached record.
"""
key: typing.Final[ReleaseKey] = meta.release_key
cache_record: typing.Optional[ReleaseCacheRecord]
if (not force) and (cache_record := self.__release_cache.get(key, None)):
return cache_record
try:
self.api.release(self.username, meta.name, meta.version)
if self.arguments.force_metadata_update:
self.api.update_release(self.username, meta.name, meta.version, meta.release_attrs)
cache_record = ReleaseCacheRecord(name=meta.name, version=meta.version, empty=False)
except errors.NotFound:
announce: typing.Optional[str] = None
if self.arguments.mode == 'interactive':
logger.info('The release "%s/%s/%s" does not exist', self.username, meta.name, meta.version)
if not bool_input('Would you like to create it now?'):
logger.info('good-bye')
raise SystemExit(-1) from None
logger.info('Announcements are emailed to your package followers.')
if bool_input('Would you like to make an announcement to the package followers?', False):
announce = input('Markdown Announcement:\n')
self.api.add_release(self.username, meta.name, meta.version, [], announce, meta.release_attrs)
cache_record = ReleaseCacheRecord(name=meta.name, version=meta.version, empty=True)
self.__release_cache[key] = cache_record
return cache_record
def print_uploads(self) -> None:
"""Print details on all successful package and project uploads."""
package_info: UploadedPackage
for package_info in self.uploaded_packages:
logger.info('%s located at:\n %s\n', package_info['package_type'].label.lower(), package_info['url'])
project_info: projects.UploadedProject
for project_info in self.uploaded_projects:
logger.info('Project %s uploaded to:\n %s\n', project_info['name'], project_info['url'])
def upload(self, filename: str) -> bool:
"""Upload a file to the server."""
if not os.path.exists(filename):
message: str = f'File "{filename}" does not exist'
logger.error(message)
raise errors.BinstarError(message)
logger.info('Processing "%s"', filename)
package_meta: detect.Meta = self.detect_package_meta(
filename,
package_type=self.arguments.package_type and PackageType(self.arguments.package_type),
)
if package_meta.package_type is PackageType.PROJECT:
return self.upload_project(filename)
return self.upload_package(filename, package_meta)
def upload_package(self, filename: str, package_meta: detect.Meta) -> bool:
"""Upload a package to the server."""
if package_meta.package_type is PackageType.NOTEBOOK:
logger.error(DEPRECATION_MESSAGE_NOTEBOOKS_PROJECTS_ENVIRONMENTS_REMOVED)
return False
meta: PackageMeta = PackageMeta(filename=filename, meta=package_meta)
meta._update_attrs(parser_args=self.arguments) # pylint: disable=protected-access
meta._update_name(self.arguments.package) # pylint: disable=protected-access
meta._update_version(self.arguments.version) # pylint: disable=protected-access
if self.arguments.build_id is not None:
meta.file_attrs.setdefault('attrs', {})['binstar_build'] = self.arguments.build_id
if self.arguments.summary is not None:
meta.release_attrs['summary'] = self.arguments.summary
if self.arguments.description is not None:
meta.release_attrs['description'] = self.arguments.description
if (meta.package_type is PackageType.CONDA) and (not self.arguments.keep_basename):
meta.rebuild_basename()
if not self._check_file(meta):
return False
logger.info('Creating package "%s"', meta.name)
package: PackageCacheRecord = self.get_package(meta)
if not self.validate_package_type(package, meta.package_type):
return False
logger.info('Creating release "%s"', meta.version)
self.get_release(meta)
logger.info('Uploading file "%s/%s/%s/%s"', self.username, meta.name, meta.version, meta.file_attrs['basename'])
return self._upload_file(meta)
def upload_project(self, filename: str) -> bool:
"""Upload a project to the server."""
uploaded_project: projects.UploadedProject = projects.upload_project(filename, self.arguments, self.username)
self.uploaded_projects.append(uploaded_project)
return True
def _check_file(self, meta: PackageMeta) -> bool:
""""""
basename: str = meta.file_attrs['basename']
try:
self.api.distribution(self.username, meta.name, meta.version, basename)
except errors.NotFound:
return True
if self.arguments.mode == 'skip':
logger.info('Distribution already exists. Skipping upload.\n')
return False
if self.arguments.mode == 'force':
logger.warning('Distribution "%s" already exists. Removing.', basename)
self.api.remove_dist(self.username, meta.name, meta.version, basename)
return True
if self.arguments.mode == 'interactive':
if bool_input(f'Distribution "{basename}" already exists. Would you like to replace it?'):
self.api.remove_dist(self.username, meta.name, meta.version, basename)
return True
logger.info('Not replacing distribution "%s"', basename)
return False
logger.info(
(
'Distribution already exists. ' # pylint: disable=implicit-str-concat
'Please use the -i/--interactive or --force or --skip options or `anaconda remove %s/%s/%s/%s`'
),
self.username, meta.name, meta.version, basename,
)
raise errors.Conflict(f'file {basename} already exists for package {meta.name} version {meta.version}', 409)
def _upload_file(self, meta: PackageMeta) -> bool:
"""Perform upload of a file after its metadata and related package and release are prepared."""
basename: str = meta.file_attrs['basename']
package_type: typing.Union[PackageType, str] = meta.file_attrs.pop('binstar_package_type', meta.package_type)
stream: typing.BinaryIO
with open(meta.filename, 'rb') as stream:
result: typing.Mapping[str, typing.Any] = self.api.upload(
self.username,
meta.name,
meta.version,
basename,
stream,
package_type,
self.arguments.description,
dependencies=meta.file_attrs.get('dependencies'),
attrs=meta.file_attrs['attrs'],
channels=self.arguments.labels,
)
self.uploaded_packages.append({
'package_type': meta.package_type,
'username': self.username,
'name': meta.name,
'version': meta.version,
'basename': basename,
'url': result.get('url', f'https://anaconda.org/{self.username}/{meta.name}'),
})
self.__package_cache[meta.package_key].update(meta.package_type)
self.__release_cache[meta.release_key].update()
logger.info('Upload complete\n')
return True
@staticmethod
def detect_package_meta(filename: str, package_type: typing.Optional[PackageType] = None) -> detect.Meta:
"""Detect primary details on package being uploaded."""
if package_type is None:
logger.info('Detecting file type...')
result: detect.OptMeta = detect.detect_package_meta(filename)
if result is None:
message: str = (
f'Could not detect package type of file {filename!r} '
f'please specify package type with option --package-type'
)
logger.error(message)
raise errors.BinstarError(message)
logger.info('File type is "%s"', result.package_type.label)
else:
result = detect.complete_package_meta(filename, package_type)
if result is None:
result = detect.Meta(package_type=package_type, extension=os.path.splitext(filename)[1])
return result
@staticmethod
def validate_package_type(package: PackageCacheRecord, package_type: PackageType) -> bool:
"""Check if file of :code:`package_type` might be uploaded to :code:`package`."""
if not package.package_types:
return True
if package_type in package.package_types:
return True
group: typing.Set[PackageType]
for group in [{PackageType.CONDA, PackageType.STANDARD_PYTHON}]:
if (not group.isdisjoint(package.package_types)) and (package_type in group):
return True
message: str = (
f'You already have a {package.package_types[0].label.lower()} named "{package.name}". '
f'Use a different name for this {package_type.label.lower()}.'
)
logger.error(message)
raise errors.BinstarError(message)
|
class Uploader:
'''Manager for package and project uploads.'''
def __init__(self, arguments: argparse.Namespace) -> None:
'''Initialize new :class:`~Uploader` instance.'''
pass
@property
def api(self) -> binstar_client.Binstar:
'''Client used to access anaconda.org API.'''
pass
@property
def config(self) -> typing.Mapping[str, typing.Any]:
'''Configuration of the :code:`anaconda-client`.'''
pass
@property
def username(self) -> str:
'''Name of the user or organization to upload packages and projects to.'''
pass
def cleanup(self) -> None:
'''
Remove empty releases and packages.
Package or release considered to be empty if it was created to upload files to, but all file uploads failed.
'''
pass
def remove_empty_release(_key: ReleaseKey, record: ReleaseCacheRecord) -> None:
pass
def remove_empty_package(_key: PackageKey, record: PackageCacheRecord) -> None:
pass
def get_package(self, meta: PackageMeta, *, force: bool = False) -> PackageCacheRecord:
'''
Retrieve details on a package from the server.
If not forced - may return cached record.
'''
pass
def get_release(self, meta: PackageMeta, *, force: bool = False) -> ReleaseCacheRecord:
'''
Retrieve details on a release from the server.
If not forced - may return cached record.
'''
pass
def print_uploads(self) -> None:
'''Print details on all successful package and project uploads.'''
pass
def upload(self, filename: str) -> bool:
'''Upload a file to the server.'''
pass
def upload_package(self, filename: str, package_meta: detect.Meta) -> bool:
'''Upload a package to the server.'''
pass
def upload_project(self, filename: str) -> bool:
'''Upload a project to the server.'''
pass
def _check_file(self, meta: PackageMeta) -> bool:
''''''
pass
def _upload_file(self, meta: PackageMeta) -> bool:
'''Perform upload of a file after its metadata and related package and release are prepared.'''
pass
@staticmethod
def detect_package_meta(filename: str, package_type: typing.Optional[PackageType] = None) -> detect.Meta:
'''Detect primary details on package being uploaded.'''
pass
@staticmethod
def validate_package_type(package: PackageCacheRecord, package_type: PackageType) -> bool:
'''Check if file of :code:`package_type` might be uploaded to :code:`package`.'''
pass
| 23 | 16 | 19 | 2 | 16 | 2 | 4 | 0.12 | 0 | 23 | 13 | 0 | 13 | 8 | 15 | 15 | 340 | 48 | 267 | 55 | 244 | 33 | 203 | 48 | 185 | 8 | 0 | 3 | 60 |
4,529 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/binstar_client/errors.py
|
binstar_client.errors.BinstarError
|
class BinstarError(Exception):
def __init__(self, *args):
super().__init__(*args)
if not hasattr(self, 'message'):
try:
self.message = str(args[0])
except IndexError:
self.message = None
|
class BinstarError(Exception):
def __init__(self, *args):
pass
| 2 | 0 | 8 | 1 | 7 | 0 | 3 | 0 | 1 | 3 | 0 | 9 | 1 | 1 | 1 | 11 | 10 | 2 | 8 | 3 | 6 | 0 | 8 | 3 | 6 | 3 | 3 | 2 | 3 |
4,530 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/binstar_client/errors.py
|
binstar_client.errors.PillowNotInstalled
|
class PillowNotInstalled(BinstarError):
def __init__(self):
self.msg = 'pillow is not installed. Install it with:\n\tconda install pillow'
super().__init__(self.msg)
|
class PillowNotInstalled(BinstarError):
def __init__(self):
pass
| 2 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 1 | 1 | 1 | 12 | 5 | 1 | 4 | 3 | 2 | 0 | 4 | 3 | 2 | 1 | 4 | 0 | 1 |
4,531 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/binstar_client/errors.py
|
binstar_client.errors.NotFound
|
class NotFound(BinstarError, IndexError):
def __init__(self, *args):
super().__init__(*args)
self.msg = self.message
|
class NotFound(BinstarError, IndexError):
def __init__(self, *args):
pass
| 2 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 2 | 1 | 0 | 0 | 1 | 1 | 1 | 14 | 5 | 1 | 4 | 3 | 2 | 0 | 4 | 3 | 2 | 1 | 5 | 0 | 1 |
4,532 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/binstar_client/errors.py
|
binstar_client.errors.NoMetadataError
|
class NoMetadataError(BinstarError):
pass
|
class NoMetadataError(BinstarError):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 11 | 2 | 0 | 2 | 1 | 1 | 0 | 2 | 1 | 1 | 0 | 4 | 0 | 0 |
4,533 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/binstar_client/errors.py
|
binstar_client.errors.Conflict
|
class Conflict(BinstarError):
pass
|
class Conflict(BinstarError):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 11 | 2 | 0 | 2 | 1 | 1 | 0 | 2 | 1 | 1 | 0 | 4 | 0 | 0 |
4,534 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/binstar_client/commands/upload.py
|
binstar_client.commands.upload.ReleaseCacheRecord
|
class ReleaseCacheRecord(CacheRecord):
"""Cached details on a release stored on a server."""
__slots__ = ('name', 'version')
def __init__(self, name: str, version: str, empty: bool = True) -> None:
"""Initialize new :class:`~ReleaseCacheRecord` instance."""
super().__init__(empty=empty)
self.name: typing.Final[str] = name
self.version: typing.Final[str] = version
def update(self) -> None:
"""Update record after a file is uploaded to this release."""
self.empty = False
|
class ReleaseCacheRecord(CacheRecord):
'''Cached details on a release stored on a server.'''
def __init__(self, name: str, version: str, empty: bool = True) -> None:
'''Initialize new :class:`~ReleaseCacheRecord` instance.'''
pass
def update(self) -> None:
'''Update record after a file is uploaded to this release.'''
pass
| 3 | 3 | 4 | 0 | 3 | 1 | 1 | 0.38 | 1 | 3 | 0 | 0 | 2 | 3 | 2 | 4 | 14 | 3 | 8 | 7 | 5 | 3 | 8 | 7 | 5 | 1 | 1 | 0 | 2 |
4,535 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/binstar_client/commands/upload.py
|
binstar_client.commands.upload.UploadedPackage
|
class UploadedPackage(typing.TypedDict):
"""General details on a package successfully uploaded to a server."""
package_type: PackageType
username: str
name: str
version: str
basename: str
url: str
|
class UploadedPackage(typing.TypedDict):
'''General details on a package successfully uploaded to a server.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.14 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 9 | 1 | 7 | 1 | 6 | 1 | 7 | 1 | 6 | 0 | 1 | 0 | 0 |
4,536 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/tests/test_config.py
|
tests.test_config.Test
|
class Test(CLITestCase):
"""Tests for configuration management."""
def test_write_env(self):
tmpdir = tempfile.mkdtemp()
self.addCleanup(shutil.rmtree, tmpdir)
with unittest.mock.patch('binstar_client.commands.config.USER_CONFIG', os.path.join(tmpdir, 'config.yaml')), \
unittest.mock.patch('binstar_client.commands.config.SEARCH_PATH', [tmpdir]):
main(['config', '--set', 'url', 'http://localhost:5000'])
self.assertTrue(os.path.exists(os.path.join(tmpdir, 'config.yaml')))
with open(os.path.join(tmpdir, 'config.yaml'), encoding='utf-8') as conf_file:
config_output = conf_file.read()
expected_config_output = 'url: http://localhost:5000\n'
self.assertEqual(config_output, expected_config_output)
main(['config', '--show-sources'])
expected_show_sources_output = '==> {config} <==\nurl: http://localhost:5000\n\n'.format(
config=os.path.join(tmpdir, 'config.yaml'),
)
self.assertIn(expected_show_sources_output, self.stream.getvalue())
|
class Test(CLITestCase):
'''Tests for configuration management.'''
def test_write_env(self):
pass
| 2 | 1 | 21 | 5 | 16 | 0 | 1 | 0.06 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 75 | 24 | 6 | 17 | 7 | 15 | 1 | 14 | 6 | 12 | 1 | 3 | 2 | 1 |
4,537 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/binstar_client/utils/conda.py
|
binstar_client.utils.conda.Empty
|
class Empty(typing.TypedDict):
"""
Empty dictionary.
Alternative to :class:`~CondaInfo` in case :code:`conda` is not found.
"""
|
class Empty(typing.TypedDict):
'''
Empty dictionary.
Alternative to :class:`~CondaInfo` in case :code:`conda` is not found.
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 4 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 | 1 | 1 | 1 | 0 | 4 | 1 | 1 | 0 | 0 | 1 | 0 | 0 |
4,538 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/binstar_client/utils/conda.py
|
binstar_client.utils.conda.CondaInfo
|
class CondaInfo(typing.TypedDict):
"""Details on detected conda instance."""
# pylint: disable=invalid-name
CONDA_EXE: str
CONDA_PREFIX: str
CONDA_ROOT: str
|
class CondaInfo(typing.TypedDict):
'''Details on detected conda instance.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.5 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 | 1 | 4 | 1 | 3 | 2 | 4 | 1 | 3 | 0 | 1 | 0 | 0 |
4,539 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/binstar_client/utils/appdirs.py
|
binstar_client.utils.appdirs.EnvAppDirs
|
class EnvAppDirs:
def __init__(self, root_path):
self.root_path = root_path
@property
def user_data_dir(self):
return os.path.join(self.root_path, 'data')
@property
def user_config_dir(self):
return os.path.join(self.root_path, 'data')
@property
def site_data_dir(self):
return os.path.join(self.root_path, 'data')
@property
def user_cache_dir(self):
return os.path.join(self.root_path, 'cache')
@property
def user_log_dir(self):
return os.path.join(self.root_path, 'log')
|
class EnvAppDirs:
def __init__(self, root_path):
pass
@property
def user_data_dir(self):
pass
@property
def user_config_dir(self):
pass
@property
def site_data_dir(self):
pass
@property
def user_cache_dir(self):
pass
@property
def user_log_dir(self):
pass
| 12 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 6 | 1 | 6 | 6 | 24 | 6 | 18 | 13 | 6 | 0 | 13 | 8 | 6 | 1 | 0 | 0 | 6 |
4,540 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/binstar_client/scripts/cli.py
|
binstar_client.scripts.cli._JSONHelp
|
class _JSONHelp(argparse.Action):
# pylint: disable-next=redefined-builtin
def __init__(self, option_strings, dest, nargs=0, help=argparse.SUPPRESS, **kwargs):
argparse.Action.__init__(self, option_strings, dest, nargs=nargs, help=help, **kwargs)
def __call__(self, parser, namespace, values, option_string=None):
# pylint: disable=protected-access # intentional access of argparse object members
self.nargs = 0
docs = {
'prog': parser.prog,
'usage': parser.format_usage()[7:],
'description': parser.description,
'epilog': parser.epilog,
}
docs['groups'] = []
for group in parser._action_groups:
if group._group_actions:
docs['groups'].append(_json_group(group))
json.dump(docs, sys.stdout, indent=2)
raise SystemExit(0)
|
class _JSONHelp(argparse.Action):
def __init__(self, option_strings, dest, nargs=0, help=argparse.SUPPRESS, **kwargs):
pass
def __call__(self, parser, namespace, values, option_string=None):
pass
| 3 | 0 | 10 | 1 | 8 | 1 | 2 | 0.12 | 1 | 1 | 0 | 0 | 2 | 1 | 2 | 9 | 22 | 3 | 17 | 6 | 14 | 2 | 12 | 6 | 9 | 3 | 3 | 2 | 4 |
4,541 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/binstar_client/requests_ext.py
|
binstar_client.requests_ext.NullAuth
|
class NullAuth(AuthBase): # pylint: disable=too-few-public-methods
"""force requests to ignore the ``.netrc``
Some sites do not support regular authentication, but we still
want to store credentials in the ``.netrc`` file and submit them
as form elements. Without this, requests would otherwise use the
.netrc which leads, on some sites, to a 401 error.
https://github.com/psf/requests/issues/2773
Use with::
requests.get(url, auth=NullAuth())
"""
def __call__(self, r):
return r
|
class NullAuth(AuthBase):
'''force requests to ignore the ``.netrc``
Some sites do not support regular authentication, but we still
want to store credentials in the ``.netrc`` file and submit them
as form elements. Without this, requests would otherwise use the
.netrc which leads, on some sites, to a 401 error.
https://github.com/psf/requests/issues/2773
Use with::
requests.get(url, auth=NullAuth())
'''
def __call__(self, r):
pass
| 2 | 1 | 2 | 0 | 2 | 0 | 1 | 3.33 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 2 | 17 | 5 | 3 | 2 | 1 | 10 | 3 | 2 | 1 | 1 | 1 | 0 | 1 |
4,542 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/binstar_client/requests_ext.py
|
binstar_client.requests_ext.MultiPartIO
|
class MultiPartIO:
def __init__(self, body, callback=None):
self.to_read = body
self.have_read = []
self._total = 0
self.callback = callback
self.cursor = None
def read(self, n=-1): # pylint: disable=invalid-name
if self.callback:
self.callback(self.tell(), self._total)
if n == -1:
return b''.join(fd.read() for fd in self.to_read)
if not self.to_read:
return b''
while self.to_read:
data = self.to_read[0].read(n)
if data:
return data
file_obj = self.to_read.pop(0)
self.have_read.append(file_obj)
return b''
def tell(self):
cursor = sum(fd.tell() for fd in self.have_read)
if self.to_read:
cursor += self.to_read[0].tell()
return cursor
def seek(self, pos, mode=0):
assert pos == 0 # nosec
if mode == 0:
self.to_read = self.have_read + self.to_read
self.have_read = []
[fd.seek(pos, mode) for fd in self.to_read] # pylint: disable=expression-not-assigned
self.cursor = 0
elif mode == 2:
self.have_read = self.have_read + self.to_read
self.to_read = []
[fd.seek(pos, mode) for fd in self.have_read] # pylint: disable=expression-not-assigned
self._total = self.tell()
|
class MultiPartIO:
def __init__(self, body, callback=None):
pass
def read(self, n=-1):
pass
def tell(self):
pass
def seek(self, pos, mode=0):
pass
| 5 | 0 | 11 | 2 | 9 | 1 | 3 | 0.11 | 0 | 0 | 0 | 0 | 4 | 5 | 4 | 4 | 48 | 10 | 38 | 13 | 33 | 4 | 37 | 13 | 32 | 6 | 0 | 2 | 12 |
4,543 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/binstar_client/mixins/package.py
|
binstar_client.mixins.package.PackageMixin
|
class PackageMixin: # pylint: disable=too-few-public-methods
def copy(self, owner, package, version, basename=None, # pylint: disable=too-many-arguments,too-many-locals
to_owner=None, from_label='main', to_label='main', replace=False, update=False):
copy_path = '/'.join((owner, package, version, basename or ''))
url = '{}/copy/package/{}'.format(self.domain, copy_path)
payload = {'to_owner': to_owner, 'from_channel': from_label, 'to_channel': to_label}
data, headers = jencode(payload)
if replace:
res = self.session.put(url, data=data, headers=headers)
elif update:
res = self.session.patch(url, data=data, headers=headers)
else:
res = self.session.post(url, data=data, headers=headers)
try:
self._check_response(res)
except Conflict as conflict:
raise Conflict(
'File conflict while copying! Try to use --replace or --update options for force copying') from conflict
return res.json()
|
class PackageMixin:
def copy(self, owner, package, version, basename=None, # pylint: disable=too-many-arguments,too-many-locals
to_owner=None, from_label='main', to_label='main', replace=False, update=False):
pass
| 2 | 0 | 23 | 5 | 18 | 1 | 4 | 0.11 | 0 | 1 | 1 | 1 | 1 | 0 | 1 | 1 | 25 | 6 | 19 | 9 | 16 | 2 | 15 | 7 | 13 | 4 | 0 | 1 | 4 |
4,544 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/binstar_client/mixins/organizations.py
|
binstar_client.mixins.organizations.OrgMixin
|
class OrgMixin:
def user_orgs(self, username=None):
if username:
url = '%s/users/%s/orgs' % (self.domain, username)
else:
url = '%s/user/orgs' % (self.domain)
res = self.session.get(url)
self._check_response(res)
return res.json()
def groups(self, owner=None):
if owner:
url = '%s/groups/%s' % (self.domain, owner)
else:
url = '%s/groups' % (self.domain,)
res = self.session.get(url)
self._check_response(res)
return res.json()
def group(self, owner, group_name):
url = '%s/group/%s/%s' % (self.domain, owner, group_name)
res = self.session.get(url)
self._check_response(res)
return res.json()
def group_members(self, org, name):
url = '%s/group/%s/%s/members' % (self.domain, org, name)
res = self.session.get(url)
self._check_response(res)
return res.json()
def is_group_member(self, org, name, member):
url = '%s/group/%s/%s/members/%s' % (self.domain, org, name, member)
res = self.session.get(url)
self._check_response(res, [204, 404])
return res.status_code == 204
def add_group_member(self, org, name, member):
url = '%s/group/%s/%s/members/%s' % (self.domain, org, name, member)
res = self.session.put(url)
self._check_response(res, [204])
def remove_group_member(self, org, name, member):
url = '%s/group/%s/%s/members/%s' % (self.domain, org, name, member)
res = self.session.delete(url)
self._check_response(res, [204])
def remove_group_package(self, org, name, package):
url = '%s/group/%s/%s/packages/%s' % (self.domain, org, name, package)
res = self.session.delete(url)
self._check_response(res, [204])
def group_packages(self, org, name):
url = '%s/group/%s/%s/packages' % (self.domain, org, name)
res = self.session.get(url)
self._check_response(res, [200])
return res.json()
def add_group_package(self, org, name, package):
url = '%s/group/%s/%s/packages/%s' % (self.domain, org, name, package)
res = self.session.put(url)
self._check_response(res, [204])
def add_group(self, org, name, perms='read'):
url = '%s/group/%s/%s' % (self.domain, org, name)
payload = {'perms': perms}
data, headers = jencode(payload)
res = self.session.post(url, data=data, headers=headers)
self._check_response(res, [204])
|
class OrgMixin:
def user_orgs(self, username=None):
pass
def groups(self, owner=None):
pass
def groups(self, owner=None):
pass
def group_members(self, org, name):
pass
def is_group_member(self, org, name, member):
pass
def add_group_member(self, org, name, member):
pass
def remove_group_member(self, org, name, member):
pass
def remove_group_package(self, org, name, package):
pass
def group_packages(self, org, name):
pass
def add_group_package(self, org, name, package):
pass
def add_group_member(self, org, name, member):
pass
| 12 | 0 | 6 | 1 | 5 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 11 | 0 | 11 | 11 | 78 | 19 | 59 | 36 | 47 | 0 | 57 | 36 | 45 | 2 | 0 | 1 | 13 |
4,545 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/binstar_client/mixins/channels.py
|
binstar_client.mixins.channels.ChannelsMixin
|
class ChannelsMixin:
def list_channels(self, owner):
"""
List the channels for owner.
If owner is none, the currently logged in user is used.
"""
url = '%s/channels/%s' % (self.domain, owner)
res = self.session.get(url)
self._check_response(res, [200])
return res.json()
def show_channel(self, channel, owner):
"""
List the channels for owner.
If owner is none, the currently logged in user is used.
"""
url = '%s/channels/%s/%s' % (self.domain, owner, channel)
res = self.session.get(url)
self._check_response(res, [200])
return res.json()
def add_channel( # pylint: disable=too-many-arguments
self, channel, owner, package=None, version=None, filename=None):
"""
Add a channel to the specified files
:param channel: channel to add
:param owner: The user to add the channel to (all files of all packages for this user)
:param package: The package to add the channel to (all files in this package)
:param version: The version to add the channel to (all files in this version of the package)
:param filename: The exact file to add the channel to
"""
url = '%s/channels/%s/%s' % (self.domain, owner, channel)
data, headers = jencode(package=package, version=version, basename=filename)
res = self.session.post(url, data=data, headers=headers)
self._check_response(res, [201])
def remove_channel( # pylint: disable=too-many-arguments
self, channel, owner, package=None, version=None, filename=None):
"""
Remove a channel from the specified files.
:param channel: channel to remove
:param owner: The user to remove the channel from (all files of all packages for this user)
:param package: The package to remove the channel from (all files in this package)
:param version: The version to remove the channel to (all files in this version of the package)
:param filename: The exact file to remove the channel from
"""
url = '%s/channels/%s/%s' % (self.domain, owner, channel)
data, headers = jencode(package=package, version=version, basename=filename)
res = self.session.delete(url, data=data, headers=headers)
self._check_response(res, [201])
def copy_channel(self, channel, owner, to_channel):
"""
Tag all files in channel <channel> also as channel <to_channel>.
:param channel: channel to copy
:param owner: Perform this operation on all packages of this user
:param to_channel: Destination name (may be a channel that already exists)
"""
url = '%s/channels/%s/%s/copy/%s' % (self.domain, owner, channel, to_channel)
res = self.session.post(url)
self._check_response(res, [201])
def lock_channel(self, channel, owner):
"""
Tag all files in channel <channel> also as channel <to_channel>.
:param channel: channel to copy
:param owner: Perform this operation on all packages of this user
:param to_channel: Destination name (may be a channel that already exists)
"""
url = '%s/channels/%s/%s/lock' % (self.domain, owner, channel)
res = self.session.post(url)
self._check_response(res, [201])
def unlock_channel(self, channel, owner):
"""
Tag all files in channel <channel> also as channel <to_channel>.
:param channel: channel to copy
:param owner: Perform this operation on all packages of this user
:param to_channel: Destination name (may be a channel that already exists)
"""
url = '%s/channels/%s/%s/lock' % (self.domain, owner, channel)
res = self.session.delete(url)
self._check_response(res, [201])
|
class ChannelsMixin:
def list_channels(self, owner):
'''
List the channels for owner.
If owner is none, the currently logged in user is used.
'''
pass
def show_channel(self, channel, owner):
'''
List the channels for owner.
If owner is none, the currently logged in user is used.
'''
pass
def add_channel( # pylint: disable=too-many-arguments
self, channel, owner, package=None, version=None, filename=None):
'''
Add a channel to the specified files
:param channel: channel to add
:param owner: The user to add the channel to (all files of all packages for this user)
:param package: The package to add the channel to (all files in this package)
:param version: The version to add the channel to (all files in this version of the package)
:param filename: The exact file to add the channel to
'''
pass
def remove_channel( # pylint: disable=too-many-arguments
self, channel, owner, package=None, version=None, filename=None):
'''
Remove a channel from the specified files.
:param channel: channel to remove
:param owner: The user to remove the channel from (all files of all packages for this user)
:param package: The package to remove the channel from (all files in this package)
:param version: The version to remove the channel to (all files in this version of the package)
:param filename: The exact file to remove the channel from
'''
pass
def copy_channel(self, channel, owner, to_channel):
'''
Tag all files in channel <channel> also as channel <to_channel>.
:param channel: channel to copy
:param owner: Perform this operation on all packages of this user
:param to_channel: Destination name (may be a channel that already exists)
'''
pass
def lock_channel(self, channel, owner):
'''
Tag all files in channel <channel> also as channel <to_channel>.
:param channel: channel to copy
:param owner: Perform this operation on all packages of this user
:param to_channel: Destination name (may be a channel that already exists)
'''
pass
def unlock_channel(self, channel, owner):
'''
Tag all files in channel <channel> also as channel <to_channel>.
:param channel: channel to copy
:param owner: Perform this operation on all packages of this user
:param to_channel: Destination name (may be a channel that already exists)
'''
pass
| 8 | 7 | 12 | 2 | 5 | 6 | 1 | 1.26 | 0 | 0 | 0 | 1 | 7 | 0 | 7 | 7 | 95 | 18 | 35 | 26 | 25 | 44 | 33 | 24 | 25 | 1 | 0 | 0 | 7 |
4,546 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/binstar_client/utils/tables.py
|
binstar_client.utils.tables.TableDesign
|
class TableDesign:
"""
Definition of the design used for table borders.
This design allows you to set borders between cells of different kinds. It is up to you to define cell kinds - no
strict limitations here.
"""
__slots__ = (
'__horizontal', '__horizontal_view',
'__intersection', '__intersection_view',
'__vertical', '__vertical_view',
)
def __init__(self) -> None:
"""Initialize new :class:`~TableDesign` instance."""
self.__horizontal: 'typing_extensions.Final[typing.Dict[typing.Tuple[str, ...], str]]' = {}
self.__horizontal_view: 'typing_extensions.Final[ValuesView]' = ValuesView(self.__horizontal, 2, default='')
self.__intersection: 'typing_extensions.Final[typing.Dict[typing.Tuple[str, ...], str]]' = {}
self.__intersection_view: 'typing_extensions.Final[ValuesView]' = ValuesView(self.__intersection, 4, default='')
self.__vertical: 'typing_extensions.Final[typing.Dict[typing.Tuple[str, ...], str]]' = {}
self.__vertical_view: 'typing_extensions.Final[ValuesView]' = ValuesView(self.__vertical, 2, default='')
@property
def horizontal(self) -> ValuesView: # noqa: D401
"""Horizontal borders between cells above it and below it."""
return self.__horizontal_view
@property
def intersection(self) -> ValuesView:
"""Intersection between the cells on the top-left, top-right, bottom-left and bottom right of it."""
return self.__intersection_view
@property
def vertical(self) -> ValuesView:
"""Vertical borders between cells on the left of it and on the right"""
return self.__vertical_view
def with_border_style( # pylint: disable=too-many-arguments
self,
horizontal: str,
vertical: str,
corner_nw: str,
corner_ne: str,
corner_se: str,
corner_sw: str,
) -> 'TableDesign':
"""
Define a style for an external border of the table.
.. warning::
This would create a new :class:`~TableDesign` with requested modifications. There would be no modifications
to the original instance.
"""
# pylint: disable=protected-access
result: 'TableDesign' = self.__copy()
result.__horizontal[EMPTY, ANY] = horizontal
result.__horizontal[ANY, EMPTY] = horizontal
result.__intersection[EMPTY, EMPTY, EMPTY, ANY] = corner_nw
result.__intersection[EMPTY, EMPTY, ANY, EMPTY] = corner_ne
result.__intersection[EMPTY, ANY, EMPTY, EMPTY] = corner_sw
result.__intersection[ANY, EMPTY, EMPTY, EMPTY] = corner_se
result.__vertical[EMPTY, ANY] = vertical
result.__vertical[ANY, EMPTY] = vertical
return result
def with_border_transition( # pylint: disable=too-many-arguments
self,
kind: str,
top: str,
right: str,
bottom: str,
left: str,
) -> 'TableDesign':
"""
Define how external border should transition into borders of a :code:`kind`.
.. warning::
This would create a new :class:`~TableDesign` with requested modifications. There would be no modifications
to the original instance.
"""
# pylint: disable=protected-access
result: 'TableDesign' = self.__copy()
result.__intersection[EMPTY, EMPTY, kind, kind] = top
result.__intersection[EMPTY, kind, EMPTY, kind] = left
result.__intersection[kind, EMPTY, kind, EMPTY] = right
result.__intersection[kind, kind, EMPTY, EMPTY] = bottom
return result
def with_cell_style(
self,
kind: str,
horizontal: str,
vertical: str,
intersection: str,
) -> 'TableDesign':
"""
Define the borders between cells of the same :code:`kind`.
.. warning::
This would create a new :class:`~TableDesign` with requested modifications. There would be no modifications
to the original instance.
"""
# pylint: disable=protected-access
result: 'TableDesign' = self.__copy()
result.__horizontal[kind, kind] = horizontal
result.__intersection[kind, kind, kind, kind] = intersection
result.__vertical[kind, kind] = vertical
return result
def with_horizontal(
self,
top_kind: str,
bottom_kind: str,
value: str,
) -> 'TableDesign':
"""
Define a single horizontal border rule.
.. warning::
This would create a new :class:`~TableDesign` with requested modifications. There would be no modifications
to the original instance.
"""
# pylint: disable=protected-access
result: 'TableDesign' = self.__copy()
result.__horizontal[top_kind, bottom_kind] = value
return result
def with_intersection( # pylint: disable=too-many-arguments
self,
top_left_kind: str,
top_right_kind: str,
bottom_left_kind: str,
bottom_right_kind: str,
value: str,
) -> 'TableDesign':
"""
Define a single intersection border rule.
.. warning::
This would create a new :class:`~TableDesign` with requested modifications. There would be no modifications
to the original instance.
"""
# pylint: disable=protected-access
result: 'TableDesign' = self.__copy()
result.__intersection[top_left_kind, top_right_kind, bottom_left_kind, bottom_right_kind] = value
return result
def with_vertical(
self,
left_kind: str,
right_kind: str,
value: str,
) -> 'TableDesign':
"""
Define a single vertical border rule.
.. warning::
This would create a new :class:`~TableDesign` with requested modifications. There would be no modifications
to the original instance.
"""
# pylint: disable=protected-access
result: 'TableDesign' = self.__copy()
result.__vertical[left_kind, right_kind] = value
return result
def __copy(self) -> 'TableDesign':
"""
Create a full copy of the current instance.
Used for safe modifications without any changes to the original value.
"""
# pylint: disable=protected-access
result: 'TableDesign' = TableDesign()
result.__horizontal.update(self.__horizontal)
result.__intersection.update(self.__intersection)
result.__vertical.update(self.__vertical)
return result
|
class TableDesign:
'''
Definition of the design used for table borders.
This design allows you to set borders between cells of different kinds. It is up to you to define cell kinds - no
strict limitations here.
'''
def __init__(self) -> None:
'''Initialize new :class:`~TableDesign` instance.'''
pass
@property
def horizontal(self) -> ValuesView:
'''Horizontal borders between cells above it and below it.'''
pass
@property
def intersection(self) -> ValuesView:
'''Intersection between the cells on the top-left, top-right, bottom-left and bottom right of it.'''
pass
@property
def vertical(self) -> ValuesView:
'''Vertical borders between cells on the left of it and on the right'''
pass
def with_border_style( # pylint: disable=too-many-arguments
self,
horizontal: str,
vertical: str,
corner_nw: str,
corner_ne: str,
corner_se: str,
corner_sw: str,
) -> 'TableDesign':
'''
Define a style for an external border of the table.
.. warning::
This would create a new :class:`~TableDesign` with requested modifications. There would be no modifications
to the original instance.
'''
pass
def with_border_transition( # pylint: disable=too-many-arguments
self,
kind: str,
top: str,
right: str,
bottom: str,
left: str,
) -> 'TableDesign':
'''
Define how external border should transition into borders of a :code:`kind`.
.. warning::
This would create a new :class:`~TableDesign` with requested modifications. There would be no modifications
to the original instance.
'''
pass
def with_cell_style(
self,
kind: str,
horizontal: str,
vertical: str,
intersection: str,
) -> 'TableDesign':
'''
Define the borders between cells of the same :code:`kind`.
.. warning::
This would create a new :class:`~TableDesign` with requested modifications. There would be no modifications
to the original instance.
'''
pass
def with_horizontal(
self,
top_kind: str,
bottom_kind: str,
value: str,
) -> 'TableDesign':
'''
Define a single horizontal border rule.
.. warning::
This would create a new :class:`~TableDesign` with requested modifications. There would be no modifications
to the original instance.
'''
pass
def with_intersection( # pylint: disable=too-many-arguments
self,
top_left_kind: str,
top_right_kind: str,
bottom_left_kind: str,
bottom_right_kind: str,
value: str,
) -> 'TableDesign':
'''
Define a single intersection border rule.
.. warning::
This would create a new :class:`~TableDesign` with requested modifications. There would be no modifications
to the original instance.
'''
pass
def with_vertical(
self,
left_kind: str,
right_kind: str,
value: str,
) -> 'TableDesign':
'''
Define a single vertical border rule.
.. warning::
This would create a new :class:`~TableDesign` with requested modifications. There would be no modifications
to the original instance.
'''
pass
def __copy(self) -> 'TableDesign':
'''
Create a full copy of the current instance.
Used for safe modifications without any changes to the original value.
'''
pass
| 15 | 12 | 14 | 1 | 8 | 5 | 1 | 0.59 | 0 | 2 | 1 | 0 | 11 | 6 | 11 | 11 | 186 | 28 | 102 | 67 | 49 | 60 | 57 | 26 | 45 | 1 | 0 | 0 | 11 |
4,547 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/binstar_client/utils/tables.py
|
binstar_client.utils.tables.ValuesView
|
class ValuesView(typing.Mapping[typing.Tuple[str, ...], str]):
"""
Helper view which allows parent collection to have patterns as its keys.
Each key of the parent collection should be a tuple of strings of a particular length (defined via
:code:`key_length` argument). In case you don't use patterns for your original collections keys - this view would
return only full values for fully matched keys.
For a key to become a pattern - it is enough to set any part to :code:`ANY` (or :code:`'*'`). Basically, this value
means that on this particular place there might be any string value. If you request a value for some key tuple and
everything matches except :code:`ANY` key parts - corresponding value might be returned to the user. Unless there is
another value where key matches with less number of :code:`ANY` entries.
.. warning::
Patterns might be used only on the parent collection side. Each :code:`ANY` in your requested key would be
treated as an exact value.
:param content: Parent collection to look for values in.
:param key_length: Length of a tuple keys used for this collection.
:param default: Value to use on each lookup miss.
"""
__slots__ = ('__content', '__default', '__key_length')
def __init__(
self,
content: typing.Mapping[typing.Tuple[str, ...], str],
key_length: int,
*,
default: typing.Optional[str] = None,
) -> None:
"""Initialize new :class:`~ValuesView` instance."""
self.__content: 'typing_extensions.Final[typing.Mapping[typing.Tuple[str, ...], str]]' = content
self.__default: 'typing_extensions.Final[typing.Optional[str]]' = default
self.__key_length: 'typing_extensions.Final[int]' = key_length
if key_length not in COMBINATIONS:
COMBINATIONS[key_length] = [
indexes
for step in range(self.__key_length + 1)
for indexes in itertools.combinations(range(self.__key_length), step)
]
def __getitem__(self, key: typing.Tuple[str, ...]) -> str:
"""Retrieve a value for the :code:`key`."""
if len(key) != self.__key_length:
raise ValueError('invalid length of a key')
combination: typing.Tuple[int, ...]
for combination in COMBINATIONS[self.__key_length]:
current_key = tuple(
ANY if (index in combination) else value
for index, value in enumerate(key)
)
try:
return self.__content[current_key]
except KeyError:
continue
if self.__default is not None:
return self.__default
raise KeyError(f'no value found for {key}')
def __iter__(self) -> typing.Iterator[typing.Tuple[str, ...]]:
"""Iterate through registered keys and patterns."""
return iter(self.__content)
def __len__(self) -> int:
"""Retrieve total number of records in the collection."""
return len(self.__content)
|
class ValuesView(typing.Mapping[typing.Tuple[str, ...], str]):
'''
Helper view which allows parent collection to have patterns as its keys.
Each key of the parent collection should be a tuple of strings of a particular length (defined via
:code:`key_length` argument). In case you don't use patterns for your original collections keys - this view would
return only full values for fully matched keys.
For a key to become a pattern - it is enough to set any part to :code:`ANY` (or :code:`'*'`). Basically, this value
means that on this particular place there might be any string value. If you request a value for some key tuple and
everything matches except :code:`ANY` key parts - corresponding value might be returned to the user. Unless there is
another value where key matches with less number of :code:`ANY` entries.
.. warning::
Patterns might be used only on the parent collection side. Each :code:`ANY` in your requested key would be
treated as an exact value.
:param content: Parent collection to look for values in.
:param key_length: Length of a tuple keys used for this collection.
:param default: Value to use on each lookup miss.
'''
def __init__(
self,
content: typing.Mapping[typing.Tuple[str, ...], str],
key_length: int,
*,
default: typing.Optional[str] = None,
) -> None:
'''Initialize new :class:`~ValuesView` instance.'''
pass
def __getitem__(self, key: typing.Tuple[str, ...]) -> str:
'''Retrieve a value for the :code:`key`.'''
pass
def __iter__(self) -> typing.Iterator[typing.Tuple[str, ...]]:
'''Iterate through registered keys and patterns.'''
pass
def __len__(self) -> int:
'''Retrieve total number of records in the collection.'''
pass
| 5 | 5 | 11 | 1 | 9 | 1 | 3 | 0.53 | 1 | 8 | 0 | 0 | 4 | 3 | 4 | 4 | 71 | 13 | 38 | 17 | 27 | 20 | 25 | 10 | 20 | 6 | 1 | 2 | 10 |
4,548 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/tests/fixture.py
|
tests.fixture.AnyIO
|
class AnyIO(io.StringIO): # pylint: disable=missing-class-docstring
def write(self, msg):
if hasattr('msg', 'decode'):
msg = msg.decode()
return io.StringIO.write(self, msg)
|
class AnyIO(io.StringIO):
def write(self, msg):
pass
| 2 | 0 | 4 | 0 | 4 | 0 | 2 | 0.2 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 1 | 6 | 1 | 5 | 2 | 3 | 1 | 5 | 2 | 3 | 2 | 0 | 1 | 2 |
4,549 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/tests/fixture.py
|
tests.fixture.CLITestCase
|
class CLITestCase(unittest.TestCase): # pylint: disable=too-many-instance-attributes,missing-class-docstring
def setUp(self):
self.get_config_patch = unittest.mock.patch('binstar_client.utils.get_config')
self.get_config = self.get_config_patch.start()
self.get_config.return_value = {}
self.load_token_patch = unittest.mock.patch('binstar_client.utils.config.load_token')
self.load_token = self.load_token_patch.start()
self.load_token.return_value = '123'
self.store_token_patch = unittest.mock.patch('binstar_client.utils.config.store_token')
self.store_token = self.store_token_patch.start()
self.setup_logging_patch = unittest.mock.patch('binstar_client.utils.logging_utils.setup_logging')
self.setup_logging_patch.start()
self.logger = logger = logging.getLogger('binstar')
logger.setLevel(logging.INFO)
self.stream = AnyIO()
self.hndlr = hndlr = logging.StreamHandler(stream=self.stream)
hndlr.setLevel(logging.INFO)
logger.addHandler(hndlr)
def tearDown(self):
self.setup_logging_patch.stop()
self.get_config_patch.stop()
self.load_token_patch.stop()
self.store_token_patch.stop()
self.logger.removeHandler(self.hndlr)
|
class CLITestCase(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
| 3 | 0 | 14 | 3 | 12 | 0 | 1 | 0.04 | 1 | 2 | 1 | 9 | 2 | 10 | 2 | 74 | 31 | 7 | 24 | 13 | 21 | 1 | 24 | 13 | 21 | 1 | 2 | 0 | 2 |
4,550 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/tests/inspect_package/test_conda.py
|
tests.inspect_package.test_conda.Test
|
class Test(unittest.TestCase):
def test_conda_old(self):
filename = data_dir('conda_gc_test-1.2.1-py27_3.tar.bz2')
package_data, version_data, file_data = conda.inspect_conda_package(filename)
self.assertEqual(expected_package_data, package_data)
self.assertEqual(expected_version_data_121, version_data)
self.assertEqual(expected_file_data_121, file_data)
def test_conda(self):
filename = data_dir('conda_gc_test-2.2.1-py27_3.tar.bz2')
package_data, version_data, file_data = conda.inspect_conda_package(filename)
self.assertEqual(expected_package_data, package_data)
self.assertEqual(expected_version_data_221, version_data)
self.assertEqual(expected_file_data_221, file_data)
def test_conda_app_image(self):
filename = data_dir('test-app-package-icon-0.1-0.tar.bz2')
package_data, version_data, _ = conda.inspect_conda_package(filename)
self.assertEqual(app_expected_package_data, package_data)
self.assertEqual(app_expected_version_data.pop('icon'), version_data.pop('icon'))
self.assertEqual(app_expected_version_data, version_data)
def test_conda_v2_format(self):
filename = data_dir('conda_gc_test-2.2.1-py27_3.conda')
package_data, version_data, file_data = conda.inspect_conda_package(filename)
self.assertEqual(expected_package_data, package_data)
self.assertEqual(expected_version_data_221, version_data)
self.assertEqual(expected_file_data_221_conda, file_data)
|
class Test(unittest.TestCase):
def test_conda_old(self):
pass
def test_conda_old(self):
pass
def test_conda_app_image(self):
pass
def test_conda_v2_format(self):
pass
| 5 | 0 | 7 | 1 | 6 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 4 | 0 | 4 | 76 | 33 | 8 | 25 | 13 | 20 | 0 | 25 | 13 | 20 | 1 | 2 | 0 | 4 |
4,551 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/tests/inspect_package/test_env.py
|
tests.inspect_package.test_env.EnvInspectorTestCase
|
class EnvInspectorTestCase(unittest.TestCase):
def test_package_name(self):
with open(data_dir('environment.yml')) as fileobj:
assert EnvInspector('environment.yml', fileobj).name == 'stats' # nosec
def test_version(self):
with open(data_dir('environment.yml')) as fileobj:
self.assertIsInstance(EnvInspector('environment.yml', fileobj).version, str)
|
class EnvInspectorTestCase(unittest.TestCase):
def test_package_name(self):
pass
def test_version(self):
pass
| 3 | 0 | 3 | 0 | 3 | 1 | 1 | 0.14 | 1 | 2 | 1 | 0 | 2 | 0 | 2 | 74 | 8 | 1 | 7 | 5 | 4 | 1 | 7 | 3 | 4 | 1 | 2 | 1 | 2 |
4,552 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/tests/inspect_package/test_env.py
|
tests.inspect_package.test_env.InspectEnvironmentPackageTest
|
class InspectEnvironmentPackageTest(unittest.TestCase):
def test_inspect_env_package(self):
with open(data_dir('environment.yml')) as fileobj:
package_data, release_data, file_data = inspect_env_package( # pylint: disable=unused-variable
'environment.yml', fileobj)
self.assertEqual({
'name': 'stats',
'summary': 'Environment file'
}, package_data)
self.assertEqual({
'basename': 'environment.yml',
'attrs': {}
}, file_data)
|
class InspectEnvironmentPackageTest(unittest.TestCase):
def test_inspect_env_package(self):
pass
| 2 | 0 | 14 | 2 | 12 | 1 | 1 | 0.08 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 73 | 15 | 2 | 13 | 4 | 11 | 1 | 6 | 3 | 4 | 1 | 2 | 1 | 1 |
4,553 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/tests/inspect_package/test_ipynb.py
|
tests.inspect_package.test_ipynb.InspectIPYNBPackageTest
|
class InspectIPYNBPackageTest(unittest.TestCase):
def test_package_data(self):
with open(data_dir('notebook.ipynb')) as file:
package_data, _, _ = inspect_ipynb_package('notebook.ipynb', file)
self.assertEqual({
'name': 'notebook',
'description': 'ipynb description',
'summary': 'ipynb summary',
}, package_data)
def test_package_data_no_metadata(self):
with open(data_dir('notebook-no-metadata.ipynb')) as file:
package_data, _, _ = inspect_ipynb_package('notebook.ipynb', file)
self.assertEqual({
'name': 'notebook',
'description': 'Jupyter Notebook',
'summary': 'Jupyter Notebook',
}, package_data)
def test_package_data_normalized_name(self):
with open(data_dir('notebook.ipynb')) as file:
package_data, _, _ = inspect_ipynb_package('test nótëbOOk.ipynb', file)
self.assertIn('name', package_data)
self.assertEqual(package_data['name'], 'test-notebook')
def test_package_thumbnail(self):
parser_args = namedtuple('parser_args', ['thumbnail'])(data_dir('43c9b994a4d96f779dad87219d645c9f.png'))
with open(data_dir('notebook.ipynb')) as file:
package_data, _, _ = inspect_ipynb_package('notebook.ipynb', file, parser_args=parser_args)
self.assertIn('thumbnail', package_data)
def test_release_data(self):
with freeze_time('2018-02-01 09:10:00', tz_offset=0):
with open(data_dir('notebook.ipynb')) as file:
_, release_data, _ = inspect_ipynb_package('notebook.ipynb', file)
self.assertEqual({
'version': '2018.02.01.0910',
'description': 'ipynb description',
'summary': 'ipynb summary',
}, release_data)
def test_release_data_no_metadata(self):
with freeze_time('2018-05-03 12:30:00', tz_offset=0):
with open(data_dir('notebook-no-metadata.ipynb')) as file:
_, release_data, _ = inspect_ipynb_package('notebook-no-metadata.ipynb', file)
self.assertEqual({
'version': '2018.05.03.1230',
'description': 'Jupyter Notebook',
'summary': 'Jupyter Notebook',
}, release_data)
def test_file_data(self):
with open(data_dir('notebook.ipynb')) as file:
_, _, file_data = inspect_ipynb_package('notebook.ipynb', file)
self.assertEqual({
'basename': 'notebook.ipynb',
'attrs': {}
}, file_data)
|
class InspectIPYNBPackageTest(unittest.TestCase):
def test_package_data(self):
pass
def test_package_data_no_metadata(self):
pass
def test_package_data_normalized_name(self):
pass
def test_package_thumbnail(self):
pass
def test_release_data(self):
pass
def test_release_data_no_metadata(self):
pass
def test_file_data(self):
pass
| 8 | 0 | 8 | 1 | 7 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 7 | 0 | 7 | 79 | 65 | 13 | 52 | 23 | 44 | 0 | 33 | 16 | 25 | 1 | 2 | 2 | 7 |
4,554 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/tests/inspect_package/test_pypi.py
|
tests.inspect_package.test_pypi.Test
|
class Test(unittest.TestCase):
maxDiff = None
def test_sdist(self):
filename = data_dir('test_package34-0.3.1.tar.gz')
with open(filename, 'rb') as file:
package_data, version_data, file_data = pypi.inspect_pypi_package(filename, file)
expected_file_data = {'attrs': {'packagetype': 'sdist', 'python_version': 'source'},
'basename': 'test_package34-0.3.1.tar.gz',
'dependencies': expected_dependencies}
self.assertEqual(expected_package_data, package_data)
self.assertEqual(expected_version_data, version_data)
self.assertEqual(set(expected_file_data), set(file_data))
for key, item in expected_file_data.items():
self.assertEqual(item, file_data[key])
def test_bdist_wheel(self):
filename = data_dir('test_package34-0.3.1-py2-none-any.whl')
with open(filename, 'rb') as file:
package_data, version_data, file_data = pypi.inspect_pypi_package(filename, file)
expected_file_data = {'attrs': {'abi': None, 'build_no': 0,
'packagetype': 'bdist_wheel',
'python_version': 'py2'},
'basename': 'test_package34-0.3.1-py2-none-any.whl',
'dependencies': expected_whl_dependencies,
'platform': None}
self.assertEqual(expected_package_data, package_data)
self.assertEqual(expected_version_data, version_data)
self.assertEqual(set(expected_file_data), set(file_data))
for key, item in expected_file_data.items():
self.assertEqual(item, file_data[key])
def test_bdist_wheel_newer_version(self):
filename_whl = 'azure_cli_extension-0.2.1-py2.py3-none-any.whl'
filename = data_dir(filename_whl)
with open(filename, 'rb') as file:
package_data, version_data, file_data = pypi.inspect_pypi_package(filename, file)
expected_file_data = {
'platform': None,
'basename': filename_whl,
'dependencies': {
'depends': [
{'name': 'azure-cli-command-modules-nspkg', 'specs': [('>=', '2.0.0')]},
{'name': 'azure-cli-core', 'specs': []}, {'name': 'pip', 'specs': []},
{'name': 'wheel', 'specs': [('==', '0.30.0')]}
],
'extras': [],
'has_dep_errors': False,
'environments': []},
'attrs': {
'abi': None,
'packagetype': 'bdist_wheel',
'python_version': 'py2.py3',
'build_no': 0
}
}
expected_package_data = {
'name': 'azure-cli-extension',
'license': 'MIT',
'summary': 'Microsoft Azure Command-Line Tools Extension Command Module',
}
expected_version_data = {
'home_page': 'https://github.com/Azure/azure-cli',
'version': '0.2.1',
'description': "Microsoft Azure CLI 'extension' Command Module",
}
self.assertEqual(expected_package_data, package_data)
self.assertEqual(expected_version_data, version_data)
self.assertEqual(set(expected_file_data), set(file_data))
for key, item in expected_file_data.items():
self.assertEqual(item, file_data[key])
def test_bdist_egg(self):
filename = data_dir('test_package34-0.3.1-py2.7.egg')
with open(filename, 'rb') as file:
package_data, version_data, file_data = pypi.inspect_pypi_package(filename, file)
self.assertEqual(expected_package_data, package_data)
self.assertEqual(expected_version_data, version_data)
self.assertEqual(set(expected_egg_file_data), set(file_data))
for key, item in expected_egg_file_data.items():
self.assertEqual(item, file_data[key])
def test_bdist_egg_dashed_path(self):
filename = data_dir('test_package34-0.3.1-py2.7.egg')
tmpdir = tempfile.gettempdir()
dash_count = tmpdir.count('-')
if dash_count == 0:
tmpdir = os.path.join(tmpdir, 'has-dash')
try:
os.mkdir(tmpdir)
except (IOError, OSError) as error:
raise unittest.SkipTest('Cannot create temporary directory %r' % tmpdir) from error
elif dash_count > 1:
raise unittest.SkipTest('Too many dashes in temporary directory path %r' % tmpdir)
try:
shutil.copy(filename, tmpdir)
except (IOError, OSError) as error:
raise unittest.SkipTest('Cannot copy package to temporary directory') from error
tmpfilename = os.path.join(tmpdir, 'test_package34-0.3.1-py2.7.egg')
with open(tmpfilename, 'rb') as file:
package_data, version_data, file_data = pypi.inspect_pypi_package(tmpfilename, file)
# If we could create this file, we ought to be able to delete it
os.remove(tmpfilename)
if dash_count == 0:
# We created a temporary directory like /tmp/has-dash, delete it
os.rmdir(tmpdir)
self.assertEqual(expected_package_data, package_data)
self.assertEqual(expected_version_data, version_data)
self.assertEqual(set(expected_egg_file_data), set(file_data))
self.assertEqual(expected_egg_file_data['platform'], file_data['platform'])
self.assertEqual(expected_egg_file_data['attrs']['python_version'],
file_data['attrs']['python_version'])
def test_sdist_distutils(self):
filename = data_dir('test_package34-distutils-0.3.1.tar.gz')
with open(filename, 'rb') as file:
package_data, version_data, file_data = pypi.inspect_pypi_package(filename, file)
expected_file_data = {'attrs': {'packagetype': 'sdist', 'python_version': 'source'},
'basename': 'test_package34-distutils-0.3.1.tar.gz',
'dependencies': {'depends': [{'name': 'requests',
'specs': [('>=', '2.0'), ('<=', '3.0')]},
{'name': 'pyyaml', 'specs': [('==', '2.0')]},
{'name': 'pytz', 'specs': []}],
'extras': [],
'has_dep_errors': False}}
dexpected_package_data = expected_package_data.copy()
dexpected_package_data['name'] = dexpected_package_data['name'].replace('-', '_')
self.assertEqual(dexpected_package_data, package_data)
self.assertEqual(expected_version_data, version_data)
self.assertEqual(set(expected_file_data), set(file_data))
for key, item in expected_file_data.items():
print(item)
print(file_data[key])
self.assertEqual(item, file_data[key])
|
class Test(unittest.TestCase):
def test_sdist(self):
pass
def test_bdist_wheel(self):
pass
def test_bdist_wheel_newer_version(self):
pass
def test_bdist_egg(self):
pass
def test_bdist_egg_dashed_path(self):
pass
def test_sdist_distutils(self):
pass
| 7 | 0 | 25 | 4 | 21 | 0 | 3 | 0.02 | 1 | 3 | 0 | 0 | 6 | 0 | 6 | 78 | 155 | 27 | 126 | 43 | 119 | 2 | 84 | 36 | 77 | 6 | 2 | 2 | 16 |
4,555 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/tests/inspect_package/test_r.py
|
tests.inspect_package.test_r.Test
|
class Test(unittest.TestCase):
maxDiff = None
def test_r(self):
filename = data_dir('rfordummies_0.1.2.tar.gz')
with open(filename, 'rb') as file:
package_data, version_data, file_data = r.inspect_r_package(filename, file)
self.assertEqual(expected_package_data, package_data)
self.assertEqual(expected_version_data, version_data)
self.assertEqual(expected_file_data, file_data)
|
class Test(unittest.TestCase):
def test_r(self):
pass
| 2 | 0 | 8 | 1 | 7 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 73 | 11 | 2 | 9 | 6 | 7 | 0 | 9 | 5 | 7 | 1 | 2 | 1 | 1 |
4,556 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/tests/runner.py
|
tests.runner.ColorTextTestResult
|
class ColorTextTestResult(TextTestResult):
def addSuccess(self, test):
super().addSuccess(test)
if self.showAll:
self.stream.writeln(green('ok'))
elif self.dots:
self.stream.write('.')
self.stream.flush()
def addError(self, test, err):
super().addError(test, err)
if self.showAll:
self.stream.writeln(red('ERROR'))
elif self.dots:
self.stream.write(red('E'))
self.stream.flush()
def addFailure(self, test, err):
super().addFailure(test, err)
if self.showAll:
self.stream.writeln(red('FAIL'))
elif self.dots:
self.stream.write(red('F'))
self.stream.flush()
def addSkip(self, test, reason):
super().addSkip(test, reason)
if self.showAll:
self.stream.writeln(blue('skipped {0!r}'.format(reason)))
elif self.dots:
self.stream.write(blue('s'))
self.stream.flush()
def addExpectedFailure(self, test, err):
super().addExpectedFailure(test, err)
if self.showAll:
self.stream.writeln(blue('expected failure'))
elif self.dots:
self.stream.write(blue('x'))
self.stream.flush()
def addUnexpectedSuccess(self, test):
super().addUnexpectedSuccess(test)
if self.showAll:
self.stream.writeln(blue('unexpected success'))
elif self.dots:
self.stream.write(blue('u'))
self.stream.flush()
def printErrors(self):
if self.dots or self.showAll:
self.stream.writeln()
self.printErrorList(red('ERROR'), self.errors)
self.printErrorList(red('FAIL'), self.failures)
|
class ColorTextTestResult(TextTestResult):
def addSuccess(self, test):
pass
def addError(self, test, err):
pass
def addFailure(self, test, err):
pass
def addSkip(self, test, reason):
pass
def addExpectedFailure(self, test, err):
pass
def addUnexpectedSuccess(self, test):
pass
def printErrors(self):
pass
| 8 | 0 | 7 | 0 | 7 | 0 | 3 | 0 | 1 | 1 | 0 | 0 | 7 | 0 | 7 | 42 | 54 | 6 | 48 | 8 | 40 | 0 | 42 | 8 | 34 | 3 | 3 | 1 | 20 |
4,557 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/tests/runner.py
|
tests.runner.ColorTextTestRunner
|
class ColorTextTestRunner(TextTestRunner):
def __init__(self, # pylint: disable=unspecified-encoding,too-many-arguments
stream=sys.stderr, descriptions=True, verbosity=1,
failfast=False, buffer=False, resultclass=ColorTextTestResult):
TextTestRunner.__init__(self, stream=stream, descriptions=descriptions,
verbosity=verbosity, failfast=failfast, buffer=buffer,
resultclass=resultclass)
def run(self, test):
'Run the given test case or test suite.'
result = self._makeResult()
registerResult(result)
result.failfast = self.failfast
result.buffer = self.buffer
startTime = time.time()
startTestRun = getattr(result, 'startTestRun', None)
if startTestRun is not None:
startTestRun()
try:
test(result)
finally:
stopTestRun = getattr(result, 'stopTestRun', None)
if stopTestRun is not None:
stopTestRun()
stopTime = time.time()
timeTaken = stopTime - startTime
result.printErrors()
if hasattr(result, 'separator2'):
self.stream.writeln(result.separator2)
run = result.testsRun
self.stream.writeln('Ran %d test%s in %.3fs' %
(run, run != 1 and 's' or '', timeTaken))
self.stream.writeln()
return result
def write_end(self, result):
expectedFails = unexpectedSuccesses = skipped = 0
try:
results = map(len, (result.expectedFailures,
result.unexpectedSuccesses,
result.skipped))
except AttributeError:
pass
else:
expectedFails, unexpectedSuccesses, skipped = results
infos = []
if not result.wasSuccessful():
self.stream.write('Tests: ' + red('FAILED'))
failed, errored = map(len, (result.failures, result.errors))
if failed:
infos.append('failures=%d' % failed)
if errored:
infos.append('errors=%d' % errored)
else:
self.stream.write('Tests: ' + green('OK'))
if skipped:
infos.append('skipped=%d' % skipped)
if expectedFails:
infos.append('expected failures=%d' % expectedFails)
if unexpectedSuccesses:
infos.append('unexpected successes=%d' % unexpectedSuccesses)
if infos:
self.stream.write(' (%s)' % (', '.join(infos),))
|
class ColorTextTestRunner(TextTestRunner):
def __init__(self, # pylint: disable=unspecified-encoding,too-many-arguments
stream=sys.stderr, descriptions=True, verbosity=1,
failfast=False, buffer=False, resultclass=ColorTextTestResult):
pass
def run(self, test):
'''Run the given test case or test suite.'''
pass
def write_end(self, result):
pass
| 4 | 1 | 21 | 1 | 20 | 1 | 5 | 0.03 | 1 | 3 | 1 | 0 | 3 | 0 | 3 | 6 | 68 | 7 | 60 | 17 | 54 | 2 | 51 | 15 | 47 | 9 | 2 | 2 | 14 |
4,558 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/binstar_client/utils/config.py
|
binstar_client.utils.config.PackageType
|
class PackageType(enum.Enum):
CONDA = 'conda'
ENV = 'env'
FILE = 'file'
NOTEBOOK = 'ipynb'
STANDARD_PYTHON = 'pypi'
STANDARD_R = 'r'
PROJECT = 'project'
INSTALLER = 'installer'
@property
def label(self) -> str:
return PACKAGE_TYPE_LABELS.get(self, self.value)
@classmethod
def _missing_(cls, value: typing.Any) -> PackageType:
try:
return cls(PACKAGE_TYPE_ALIASES[value])
except KeyError:
return super()._missing_(value)
|
class PackageType(enum.Enum):
@property
def label(self) -> str:
pass
@classmethod
def _missing_(cls, value: typing.Any) -> PackageType:
pass
| 5 | 0 | 4 | 0 | 4 | 0 | 2 | 0 | 1 | 4 | 0 | 0 | 1 | 0 | 2 | 51 | 20 | 2 | 18 | 13 | 13 | 0 | 16 | 11 | 13 | 2 | 4 | 1 | 3 |
4,559 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/tests/test_authorizations.py
|
tests.test_authorizations.Test
|
class Test(CLITestCase):
"""Tests for anaconda-client authorizations and token management."""
@urlpatch
def test_remove_token_from_org(self, urls):
remove_token = urls.register(
method='DELETE',
path='/authentications/org/orgname/name/tokenname',
content='{"token": "a-token"}',
status=201
)
main(['--show-traceback', 'auth', '--remove', 'tokenname', '-o', 'orgname'])
self.assertIn('Removed token tokenname', self.stream.getvalue())
remove_token.assertCalled()
@urlpatch
def test_remove_token(self, urls):
remove_token = urls.register(
method='DELETE',
path='/authentications/name/tokenname',
content='{"token": "a-token"}',
status=201
)
main(['--show-traceback', 'auth', '--remove', 'tokenname'])
self.assertIn('Removed token tokenname', self.stream.getvalue())
remove_token.assertCalled()
@urlpatch
def test_remove_token_forbidden(self, urls):
remove_token = urls.register(
method='DELETE',
path='/authentications/org/wrong_org/name/tokenname',
content='{"token": "a-token"}',
status=403
)
with self.assertRaises(BinstarError):
main(['--show-traceback', 'auth', '--remove', 'tokenname', '-o', 'wrong_org'])
remove_token.assertCalled()
|
class Test(CLITestCase):
'''Tests for anaconda-client authorizations and token management.'''
@urlpatch
def test_remove_token_from_org(self, urls):
pass
@urlpatch
def test_remove_token_from_org(self, urls):
pass
@urlpatch
def test_remove_token_forbidden(self, urls):
pass
| 7 | 1 | 11 | 1 | 10 | 0 | 1 | 0.03 | 1 | 1 | 1 | 0 | 3 | 0 | 3 | 77 | 41 | 6 | 34 | 10 | 27 | 1 | 16 | 7 | 12 | 1 | 3 | 1 | 3 |
4,560 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/binstar_client/utils/tables.py
|
binstar_client.utils.tables.TableCore
|
class TableCore:
"""
Core for any table implementation.
It is used to store the whole table data and visualize it.
:param default: What to show for cells with no values.
"""
__slots__ = ('__columns', '__content', '__default', '__rows')
def __init__(self, *, default: TableCell) -> None:
"""Initialize new :class:`~TableCore` instance."""
self.__columns: typing.Optional[int] = 0
self.__content: 'typing_extensions.Final[typing.List[typing.List[typing.Optional[TableCell]]]]' = []
self.__default: TableCell = default
self.__rows: typing.Optional[int] = 0
@property
def columns(self) -> int: # noqa: D401
"""Total number o columns in this table."""
if self.__columns is None:
self.__columns = max(map(len, self.__content))
return self.__columns
@property
def default(self) -> TableCell: # noqa: D401
"""Default cell content to show for empty cells."""
return self.__default
@default.setter
def default(self, value: TableCell) -> None:
"""Update the `default` value."""
self.__default = value
@property
def rows(self) -> int: # noqa: D401
"""Total number of rows in this table."""
if self.__rows is None:
self.__rows = len(self.__content)
return self.__rows
def append_row(self, values: typing.Iterable[typing.Optional[TableCell]]) -> None:
"""Append new row to the bottom of this table."""
row: typing.List[typing.Optional[TableCell]] = list(values)
self.__content.append(row)
if self.__columns is not None:
self.__columns = max(self.__columns, len(row))
if self.__rows is not None:
self.__rows += 1
def remove_column(self, column: int) -> None:
"""Remove a single column from the table."""
row: typing.List[typing.Optional[TableCell]]
for row in self.__content:
try:
del row[column]
except IndexError:
pass
if self.__columns is not None:
self.__columns -= 1
def remove_row(self, row: int) -> None:
"""Remove a single row from the table."""
try:
del self.__content[row]
except IndexError:
pass
if self.__rows is not None:
self.__rows -= 1
def render(self, design: TableDesign) -> typing.Iterator[str]:
"""Print table to the user (in terminal)."""
empty_row = [EMPTY_CELL] * self.columns
widths: typing.Sequence[int] = self.__render_analysis(design=design)
current: typing.Sequence[typing.Optional[TableCell]]
previous: typing.Sequence[typing.Optional[TableCell]] = empty_row
for current in self.__content:
yield from self.__render_separator(above_row=previous, below_row=current, widths=widths, design=design)
yield from self.__render_row(row=current, widths=widths, design=design)
previous = current
yield from self.__render_separator(above_row=previous, below_row=empty_row, widths=widths, design=design)
def trim(
self,
*,
empty_columns: bool = False,
empty_rows: bool = False,
empty_values: bool = False,
) -> typing.Tuple[typing.List[int], typing.List[int]]:
"""
Remove trailing empty cells from each row.
:param empty_columns: Also remove columns if all of their cells are empty.
:param empty_rows: Also remove rows if all of their cells are empty
:param empty_values: If any cell contains an empty value - convert it to empty cell.
This action is performed before anything else.
:return: Lists of removed columns and rows
"""
removed_columns: typing.List[int] = []
removed_columns_offset: int = 0
removed_rows: typing.List[int] = []
removed_rows_offset: int = 0
index: int = 0
while index < len(self.__content):
# remove cells with empty values
if empty_values:
self.__content[index] = [
cell if (cell is not None) and cell.value else None
for cell in self.__content[index]
]
# remove trailing columns
while self.__content[index] and (self.__content[index][-1] is None):
self.__content[index].pop()
# remove empty rows if requested
if (not self.__content[index]) and empty_rows:
self.remove_row(index)
removed_rows.append(removed_rows_offset + index)
removed_rows_offset += 1
else:
index += 1
# remove trailing empty rows
while self.__content and (not self.__content[-1]):
self.remove_row(-1)
# remove empty columns
index = 0
while empty_columns:
no_column: bool = True
has_value: bool = False
row: typing.List[typing.Optional[TableCell]]
for row in self.__content:
try:
has_value |= row[index] is not None
except LookupError:
continue
else:
no_column = False
if no_column:
break
if has_value:
index += 1
continue
self.remove_column(index)
removed_columns.append(removed_columns_offset + index)
removed_columns_offset += 1
# invalidate counters
self.__columns = None
self.__rows = None
# return result
return removed_columns, removed_rows
def __iterate_row(self, row: typing.Iterable[typing.Optional[TableCell]]) -> typing.Iterator[TableCell]:
"""
Iterate all cells in a single row.
This may add trailing cells to ensure the number of columns.
"""
for value in itertools.islice(itertools.chain(row, itertools.repeat(self.__default)), self.__columns):
yield value or self.__default
def __render_analysis(self, design: TableDesign) -> typing.Sequence[int]:
"""Measure each column and vertical border."""
curr: typing.Sequence[typing.Optional[TableCell]]
curr_cell: TableCell
curr_prev: str
prev: typing.Sequence[typing.Optional[TableCell]]
prev_cell: TableCell
prev_prev: str
index: int
temp: int
steps: typing.List[int] = [1] * (2 * self.columns + 1)
widths: typing.List[int] = [0] * (2 * self.columns + 1)
# analysis
prev = [EMPTY_CELL] * self.columns
for curr in self.__content:
index = 0
curr_prev = EMPTY
prev_prev = EMPTY
for prev_cell, curr_cell in zip(self.__iterate_row(prev), self.__iterate_row(curr)):
widths[index] = max(
widths[index],
len(design.intersection[prev_prev, prev_cell.kind, curr_prev, curr_cell.kind]),
len(design.vertical[curr_prev, curr_cell.kind]),
)
index += 1
steps[index] = lcm(steps[index], len(design.horizontal[prev_cell.kind, curr_cell.kind]))
widths[index] = max(widths[index], len(curr_cell.value))
index += 1
prev_prev = prev_cell.kind
curr_prev = curr_cell.kind
widths[index] = max(
widths[index],
len(design.intersection[prev_prev, EMPTY, curr_prev, EMPTY]),
len(design.vertical[curr_prev, EMPTY]),
)
prev = curr
index = 0
prev_prev = EMPTY
for prev_cell in self.__iterate_row(prev):
widths[index] = max(widths[index], len(design.intersection[prev_prev, prev_cell.kind, EMPTY, EMPTY]))
index += 1
steps[index] = lcm(steps[index], len(design.horizontal[prev_cell.kind, EMPTY]))
index += 1
prev_prev = prev_cell.kind
widths[index] = max(widths[index], len(design.intersection[prev_prev, EMPTY, EMPTY, EMPTY]))
# normalization
for index in range(len(widths)): # pylint: disable=consider-using-enumerate
temp = widths[index] % steps[index]
if temp > 0:
widths[index] += steps[index] - temp
# result
return widths
def __render_row(
self,
row: typing.Sequence[typing.Optional[TableCell]],
widths: typing.Iterable[int],
design: TableDesign,
) -> typing.Iterator[str]:
"""Render a row with values."""
cell: typing.Optional[TableCell]
result: str = ''
previous_kind: str = EMPTY
widths = iter(widths)
for cell in self.__iterate_row(row):
result += TEMPLATE.format(next(widths, 0), '^').format(design.vertical[previous_kind, cell.kind])
result += TEMPLATE.format(next(widths, 0), cell.alignment).format(cell.value)
previous_kind = cell.kind
yield result + design.vertical[previous_kind, EMPTY]
def __render_separator(
self,
above_row: typing.Sequence[typing.Optional[TableCell]],
below_row: typing.Sequence[typing.Optional[TableCell]],
widths: typing.Iterable[int],
design: TableDesign,
) -> typing.Iterator[str]:
"""Render a string that contains of horizontal separators and intersections."""
above_cell: typing.Optional[TableCell]
above_kind: str = EMPTY
below_cell: typing.Optional[TableCell]
below_kind: str = EMPTY
good: bool = False
result: str = ''
widths = iter(widths)
for above_cell, below_cell in zip(self.__iterate_row(above_row), self.__iterate_row(below_row)):
result += TEMPLATE.format(next(widths, 0), '^').format(
design.intersection[above_kind, above_cell.kind, below_kind, below_cell.kind],
)
temp = design.horizontal[above_cell.kind, below_cell.kind]
if temp:
good = True
result += temp * (next(widths, 0) // len(temp))
else:
result += ' ' * next(widths, 0)
above_kind = above_cell.kind
below_kind = below_cell.kind
if good:
yield result + TEMPLATE.format(next(widths, 0), '^').format(
design.intersection[above_kind, EMPTY, below_kind, EMPTY],
)
def __delitem__(self, cell: typing.Tuple[int, int]) -> None:
"""Remove a single cell from the table (set it to empty)."""
try:
self.__content[cell[0]][cell[1]] = None
except IndexError:
pass
def __getitem__(self, cell: typing.Tuple[int, int]) -> TableCell:
"""Retrieve a single cell from the table."""
try:
return self.__content[cell[0]][cell[1]] or self.__default
except IndexError:
return self.__default
def __setitem__(self, cell: typing.Tuple[int, int], value: TableCell) -> None:
"""Update a single cell in a table."""
while len(self.__content) <= cell[0]:
self.__content.append([])
while len(self.__content[cell[0]]) <= cell[1]:
self.__content[cell[0]].append(None)
self.__content[cell[0]][cell[1]] = value
if self.__columns is not None:
self.__columns = max(self.__columns, cell[1] + 1)
if self.__rows is not None:
self.__rows = max(self.__rows, cell[0] + 1)
|
class TableCore:
'''
Core for any table implementation.
It is used to store the whole table data and visualize it.
:param default: What to show for cells with no values.
'''
def __init__(self, *, default: TableCell) -> None:
'''Initialize new :class:`~TableCore` instance.'''
pass
@property
def columns(self) -> int:
'''Total number o columns in this table.'''
pass
@property
def default(self) -> TableCell:
'''Default cell content to show for empty cells.'''
pass
@default.setter
def default(self) -> TableCell:
'''Update the `default` value.'''
pass
@property
def rows(self) -> int:
'''Total number of rows in this table.'''
pass
def append_row(self, values: typing.Iterable[typing.Optional[TableCell]]) -> None:
'''Append new row to the bottom of this table.'''
pass
def remove_column(self, column: int) -> None:
'''Remove a single column from the table.'''
pass
def remove_row(self, row: int) -> None:
'''Remove a single row from the table.'''
pass
def render(self, design: TableDesign) -> typing.Iterator[str]:
'''Print table to the user (in terminal).'''
pass
def trim(
self,
*,
empty_columns: bool = False,
empty_rows: bool = False,
empty_values: bool = False,
) -> typing.Tuple[typing.List[int], typing.List[int]]:
'''
Remove trailing empty cells from each row.
:param empty_columns: Also remove columns if all of their cells are empty.
:param empty_rows: Also remove rows if all of their cells are empty
:param empty_values: If any cell contains an empty value - convert it to empty cell.
This action is performed before anything else.
:return: Lists of removed columns and rows
'''
pass
def __iterate_row(self, row: typing.Iterable[typing.Optional[TableCell]]) -> typing.Iterator[TableCell]:
'''
Iterate all cells in a single row.
This may add trailing cells to ensure the number of columns.
'''
pass
def __render_analysis(self, design: TableDesign) -> typing.Sequence[int]:
'''Measure each column and vertical border.'''
pass
def __render_row(
self,
row: typing.Sequence[typing.Optional[TableCell]],
widths: typing.Iterable[int],
design: TableDesign,
) -> typing.Iterator[str]:
'''Render a row with values.'''
pass
def __render_separator(
self,
above_row: typing.Sequence[typing.Optional[TableCell]],
below_row: typing.Sequence[typing.Optional[TableCell]],
widths: typing.Iterable[int],
design: TableDesign,
) -> typing.Iterator[str]:
'''Render a string that contains of horizontal separators and intersections.'''
pass
def __delitem__(self, cell: typing.Tuple[int, int]) -> None:
'''Remove a single cell from the table (set it to empty).'''
pass
def __getitem__(self, cell: typing.Tuple[int, int]) -> TableCell:
'''Retrieve a single cell from the table.'''
pass
def __setitem__(self, cell: typing.Tuple[int, int], value: TableCell) -> None:
'''Update a single cell in a table.'''
pass
| 22 | 18 | 17 | 2 | 13 | 2 | 3 | 0.21 | 0 | 14 | 2 | 0 | 17 | 4 | 17 | 17 | 314 | 49 | 223 | 65 | 184 | 46 | 185 | 44 | 167 | 12 | 0 | 3 | 54 |
4,561 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/binstar_client/utils/tables.py
|
binstar_client.utils.tables.SimpleTableWithAliases
|
class SimpleTableWithAliases(SimpleTable):
"""
Extended version of the :class:`~SimpleTable` which allows columns to have aliases.
:param aliases: Aliases for the columns in the table.
If at least a single alias is provided as tuple of alias and verbose name, or the whole aliases
value is a mapping - first row with verbose values would be added automatically to the table. In
case some column doesn't have a verbose name - its alias would be displayed.
:param heading_rows: How many rows should be used as a headings.
:param heading_columns: How many columns should be used as a headings.
"""
__slots__ = ('__aliases',)
def __init__(
self,
aliases: typing.Union[typing.Iterable[typing.Union[str, typing.Tuple[str, str]]], typing.Mapping[str, str]],
heading_rows: int = 0,
heading_columns: int = 0,
) -> None:
"""Initialize new :class:`~SimpleTableWithAliases` instance."""
super().__init__(heading_rows=heading_rows, heading_columns=heading_columns)
column_aliases: typing.List[str] = []
column_titles: typing.List[str] = []
column_titles_ready: bool = False
if isinstance(aliases, typing.Mapping):
raw_aliases: typing.Tuple[str, ...]
raw_titles: typing.Tuple[str, ...]
raw_aliases, raw_titles = zip(*aliases.items())
column_aliases.extend(map(str, raw_aliases))
column_titles.extend(map(str, raw_titles))
column_titles_ready = True
else:
item: typing.Union[str, typing.Tuple[str, str]]
for item in aliases:
if isinstance(item, str):
column_aliases.append(item)
column_titles.append(item)
else:
alias: str
title: str
alias, title = item
column_aliases.append(str(alias))
column_titles.append(str(title))
column_titles_ready = True
self.__aliases: 'typing_extensions.Final[typing.List[str]]' = column_aliases
if column_titles_ready:
super().append_row(column_titles)
def align_cell(self, row: int, column: typing.Union[int, str], alignment: 'Alignment') -> None:
"""Align a single cell in the table."""
if isinstance(column, str):
column = self.__aliases.index(column)
super().align_cell(row=row, column=column, alignment=alignment)
def align_column(self, column: typing.Union[int, str], alignment: 'Alignment') -> None:
"""Align each cell in a single column of the table."""
if isinstance(column, str):
column = self.__aliases.index(column)
super().align_column(column=column, alignment=alignment)
def append_row(
self,
values: typing.Union[typing.Iterable[typing.Any], typing.Mapping[str, typing.Any]],
*,
strict: bool = False,
) -> None:
"""Append new row to the bottom of this table."""
if isinstance(values, typing.Mapping):
old_values: typing.Dict[str, typing.Any] = dict(values)
values = [old_values.pop(alias, None) for alias in self.__aliases]
if strict and old_values:
raise ValueError(f'unexpected values: {list(old_values)}')
super().append_row(values)
def remove_column(self, column: typing.Union[int, str]) -> None:
"""Remove a single column from the table."""
if isinstance(column, str):
column = self.__aliases.index(column)
super().remove_column(column)
def __normalize_cell_index(self, cell: typing.Tuple[int, typing.Union[int, str]]) -> typing.Tuple[int, int]:
"""Normalize value of a cell index."""
row: int
column: typing.Union[int, str]
row, column = cell
if isinstance(column, str):
column = self.__aliases.index(column)
return row, column
def __delitem__(self, cell: typing.Tuple[int, typing.Union[int, str]]) -> None:
"""Remove a single cell from the table (set it to default)."""
super().__delitem__(self.__normalize_cell_index(cell))
def __getitem__(self, cell: typing.Tuple[int, typing.Union[int, str]]) -> str:
"""Retrieve a value of a single cell in the table."""
return super().__getitem__(self.__normalize_cell_index(cell))
def __setitem__(self, cell: typing.Tuple[int, typing.Union[int, str]], value: str) -> None:
"""Update a value of a single cell in the table."""
super().__setitem__(self.__normalize_cell_index(cell), value)
|
class SimpleTableWithAliases(SimpleTable):
'''
Extended version of the :class:`~SimpleTable` which allows columns to have aliases.
:param aliases: Aliases for the columns in the table.
If at least a single alias is provided as tuple of alias and verbose name, or the whole aliases
value is a mapping - first row with verbose values would be added automatically to the table. In
case some column doesn't have a verbose name - its alias would be displayed.
:param heading_rows: How many rows should be used as a headings.
:param heading_columns: How many columns should be used as a headings.
'''
def __init__(
self,
aliases: typing.Union[typing.Iterable[typing.Union[str, typing.Tuple[str, str]]], typing.Mapping[str, str]],
heading_rows: int = 0,
heading_columns: int = 0,
) -> None:
'''Initialize new :class:`~SimpleTableWithAliases` instance.'''
pass
def align_cell(self, row: int, column: typing.Union[int, str], alignment: 'Alignment') -> None:
'''Align a single cell in the table.'''
pass
def align_column(self, column: typing.Union[int, str], alignment: 'Alignment') -> None:
'''Align each cell in a single column of the table.'''
pass
def append_row(
self,
values: typing.Union[typing.Iterable[typing.Any], typing.Mapping[str, typing.Any]],
*,
strict: bool = False,
) -> None:
'''Append new row to the bottom of this table.'''
pass
def remove_column(self, column: typing.Union[int, str]) -> None:
'''Remove a single column from the table.'''
pass
def __normalize_cell_index(self, cell: typing.Tuple[int, typing.Union[int, str]]) -> typing.Tuple[int, int]:
'''Normalize value of a cell index.'''
pass
def __delitem__(self, cell: typing.Tuple[int, typing.Union[int, str]]) -> None:
'''Remove a single cell from the table (set it to default).'''
pass
def __getitem__(self, cell: typing.Tuple[int, typing.Union[int, str]]) -> str:
'''Retrieve a value of a single cell in the table.'''
pass
def __setitem__(self, cell: typing.Tuple[int, typing.Union[int, str]], value: str) -> None:
'''Update a value of a single cell in the table.'''
pass
| 10 | 10 | 9 | 1 | 8 | 1 | 2 | 0.25 | 1 | 10 | 0 | 0 | 9 | 1 | 9 | 26 | 108 | 18 | 72 | 26 | 52 | 18 | 60 | 16 | 50 | 5 | 1 | 3 | 19 |
4,562 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/binstar_client/utils/logging_utils.py
|
binstar_client.utils.logging_utils.ConsoleFormatter
|
class ConsoleFormatter(logging.Formatter):
"""Custom logging formatter."""
FORMAT_DEFAULT: typing.Final[str] = '[%(levelname)s] %(message)s'
FORMAT_CUSTOM: typing.Final[typing.Mapping[int, str]] = {logging.INFO: '%(message)s'}
def format(self, record: logging.LogRecord) -> str:
"""Format log record before printing it."""
# pylint: disable=protected-access
self._style._fmt = self.FORMAT_CUSTOM.get(record.levelno, self.FORMAT_DEFAULT)
return super().format(record)
|
class ConsoleFormatter(logging.Formatter):
'''Custom logging formatter.'''
def format(self, record: logging.LogRecord) -> str:
'''Format log record before printing it.'''
pass
| 2 | 2 | 5 | 0 | 3 | 2 | 1 | 0.5 | 1 | 3 | 0 | 0 | 1 | 0 | 1 | 8 | 11 | 2 | 6 | 4 | 4 | 3 | 6 | 4 | 4 | 1 | 2 | 0 | 1 |
4,563 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/binstar_client/utils/handlers.py
|
binstar_client.utils.handlers.JSONFormatter
|
class JSONFormatter: # pylint: disable=too-few-public-methods
def __init__(self, *args, **extra_tags):
self.dumps = extra_tags.pop('dumps', lambda obj: json.dumps(obj, default=str))
object.__init__(self, *args)
self.extra_tags = extra_tags
def format(self, record):
if isinstance(record.msg, dict):
data = record.msg
elif isinstance(record.msg, (list, tuple)):
data = {'items': record.msg}
else:
data = {'msg': record.msg}
kwargs = self.extra_tags.copy()
data.update(logLevel=record.levelname,
logModule=record.module,
logName=record.name,
pid=os.getpid(),
**kwargs)
if record.exc_info:
etype, value, trace = record.exc_info
trace = '\n'.join(traceback.format_exception(etype, value, trace))
data['exception'] = True
data['traceback'] = trace
msg = self.dumps(data)
return msg
|
class JSONFormatter:
def __init__(self, *args, **extra_tags):
pass
def format(self, record):
pass
| 3 | 0 | 15 | 3 | 12 | 0 | 3 | 0.04 | 0 | 5 | 0 | 0 | 2 | 2 | 2 | 2 | 33 | 8 | 25 | 9 | 22 | 1 | 19 | 9 | 16 | 4 | 0 | 1 | 5 |
4,564 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/binstar_client/utils/detect.py
|
binstar_client.utils.detect.Meta
|
class Meta(typing.NamedTuple):
"""General details on detected package."""
package_type: PackageType
extension: str
|
class Meta(typing.NamedTuple):
'''General details on detected package.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.33 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 5 | 1 | 3 | 1 | 2 | 1 | 3 | 1 | 2 | 0 | 1 | 0 | 0 |
4,565 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/binstar_client/utils/notebook/uploader.py
|
binstar_client.utils.notebook.uploader.Uploader
|
class Uploader: # pylint: disable=too-many-instance-attributes
"""
* Find or create a package (project)
* Find or create release (version)
* List files from project
* Upload new files to project
"""
_package = None
_release = None
_project = None
def __init__(self, aserver_api, filepath, **kwargs):
self.aserver_api = aserver_api
self.filepath = filepath
self._username = kwargs.get('user', None)
self._version = kwargs.get('version', None)
self._summary = kwargs.get('summary', None)
self._thumbnail = kwargs.get('thumbnail', None)
if 'name' in kwargs and kwargs['name'] is not None:
self._project = parameterize(kwargs['name'])
def upload(self, force=False):
"""
Uploads a notebook
:param force: True/False
:returns {}
"""
try:
return self.aserver_api.upload(self.username, self.project, self.version,
basename(self.filepath), open(self.filepath, 'rb'),
self.filepath.split('.')[-1])
except errors.Conflict as error:
if force:
self.remove()
return self.upload()
msg = 'Conflict: {} already exist in {}/{}'.format(self.filepath, self.project, self.version)
raise errors.BinstarError(msg) from error
def remove(self):
return self.aserver_api.remove_dist(
self, self.username, self.project, self.version, basename=self.notebook, # pylint: disable=no-member
)
@property
def notebook_attrs(self):
if self._thumbnail is not None:
return {'thumbnail': data_uri_from(self._thumbnail)}
return {}
@property
def project(self):
if self._project is None:
return re.sub('\\-ipynb$', '', parameterize(os.path.basename(self.filepath)))
return self._project
@property
def username(self):
if self._username is None:
self._username = self.aserver_api.user()['login']
return self._username
@property
def version(self):
if self._version is None:
self._version = time.strftime('%Y.%m.%d.%H%M')
return self._version
@property
def summary(self):
if self._summary is None:
self._summary = 'IPython notebook'
return self._summary
@property
def package(self):
if self._package is None:
try:
self._package = self.aserver_api.package(self.username, self.project)
except errors.NotFound:
self._package = self.aserver_api.add_package(self.username, self.project,
summary=self.summary,
attrs=self.notebook_attrs)
return self._package
@property
def release(self):
if self._release is None:
try:
self._release = self.aserver_api.release(self.username, self.project, self.version)
except errors.NotFound:
self._release = self.aserver_api.add_release(self.username, self.project,
self.version, None, None, None)
return self._release
@property
def files(self):
return self.package['files']
|
class Uploader:
'''
* Find or create a package (project)
* Find or create release (version)
* List files from project
* Upload new files to project
'''
def __init__(self, aserver_api, filepath, **kwargs):
pass
def upload(self, force=False):
'''
Uploads a notebook
:param force: True/False
:returns {}
'''
pass
def remove(self):
pass
@property
def notebook_attrs(self):
pass
@property
def project(self):
pass
@property
def username(self):
pass
@property
def version(self):
pass
@property
def summary(self):
pass
@property
def package(self):
pass
@property
def release(self):
pass
@property
def files(self):
pass
| 20 | 2 | 6 | 0 | 6 | 1 | 2 | 0.17 | 0 | 3 | 3 | 0 | 11 | 6 | 11 | 11 | 97 | 11 | 75 | 31 | 55 | 13 | 60 | 22 | 48 | 3 | 0 | 2 | 23 |
4,566 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/binstar_client/utils/projects/__init__.py
|
binstar_client.utils.projects.UploadedProject
|
class UploadedProject(typing.TypedDict):
"""Details on uploaded project."""
username: str
name: str
url: str
|
class UploadedProject(typing.TypedDict):
'''Details on uploaded project.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.25 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 | 1 | 4 | 1 | 3 | 1 | 4 | 1 | 3 | 0 | 1 | 0 | 0 |
4,567 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/binstar_client/utils/projects/__init__.py
|
binstar_client.utils.projects._TmpDir
|
class _TmpDir:
def __init__(self, prefix: str = '') -> None:
self._dir: str = tempfile.mkdtemp(prefix=prefix)
def __enter__(self) -> str:
return self._dir
def __exit__(
self,
_type: typing.Optional[typing.Type[Exception]] = None,
value: typing.Optional[Exception] = None,
traceback: typing.Optional[types.TracebackType] = None,
) -> None:
try:
shutil.rmtree(path=self._dir)
except Exception as error: # pylint: disable=broad-except
logger.debug('Failed to clean up TmpDir "%s": %s', self._dir, str(error))
|
class _TmpDir:
def __init__(self, prefix: str = '') -> None:
pass
def __enter__(self) -> str:
pass
def __exit__(
self,
_type: typing.Optional[typing.Type[Exception]] = None,
value: typing.Optional[Exception] = None,
traceback: typing.Optional[types.TracebackType] = None,
) -> None:
pass
| 4 | 0 | 5 | 0 | 5 | 0 | 1 | 0.07 | 0 | 2 | 0 | 0 | 3 | 1 | 3 | 3 | 18 | 3 | 15 | 11 | 6 | 1 | 10 | 5 | 6 | 2 | 0 | 1 | 4 |
4,568 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/binstar_client/utils/projects/filters.py
|
binstar_client.utils.projects.filters.FilesFilter
|
class FilesFilter(FilterBase): # pylint: disable=abstract-method
"""Ignore specific files."""
ignored = ['.anaconda/project-local.yml', '.anaconda/project-local.yaml']
def __init__(self, pfiles, *args, **kwargs): # pylint: disable=super-init-not-called
self.pfiles = pfiles
def run(self, pfile):
return pfile.relativepath not in self.ignored
|
class FilesFilter(FilterBase):
'''Ignore specific files.'''
def __init__(self, pfiles, *args, **kwargs):
pass
def run(self, pfile):
pass
| 3 | 1 | 2 | 0 | 2 | 1 | 1 | 0.5 | 1 | 0 | 0 | 0 | 2 | 1 | 2 | 5 | 10 | 3 | 6 | 5 | 3 | 3 | 6 | 5 | 3 | 1 | 1 | 0 | 2 |
4,569 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/binstar_client/utils/projects/filters.py
|
binstar_client.utils.projects.filters.LargeFilesFilter
|
class LargeFilesFilter(FilterBase): # pylint: disable=abstract-method
max_file_size = 2097152
def __init__(self, pfiles, *args, **kwargs): # pylint: disable=super-init-not-called
self.pfiles = pfiles
def run(self, pfile):
if pfile.size > self.max_file_size:
return False
return True
|
class LargeFilesFilter(FilterBase):
def __init__(self, pfiles, *args, **kwargs):
pass
def run(self, pfile):
pass
| 3 | 0 | 3 | 0 | 3 | 1 | 2 | 0.25 | 1 | 0 | 0 | 0 | 2 | 1 | 2 | 5 | 10 | 2 | 8 | 5 | 5 | 2 | 8 | 5 | 5 | 2 | 1 | 1 | 3 |
4,570 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/binstar_client/utils/projects/filters.py
|
binstar_client.utils.projects.filters.NoIgnoreFileException
|
class NoIgnoreFileException(IOError):
def __init__(self, msg, *args, **kwargs):
self.msg = msg
super().__init__(msg, *args, **kwargs)
|
class NoIgnoreFileException(IOError):
def __init__(self, msg, *args, **kwargs):
pass
| 2 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 1 | 1 | 1 | 1 | 4 | 0 | 4 | 3 | 2 | 0 | 4 | 3 | 2 | 1 | 1 | 0 | 1 |
4,571 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/binstar_client/utils/projects/filters.py
|
binstar_client.utils.projects.filters.ProjectIgnoreFilter
|
class ProjectIgnoreFilter(FilterBase): # pylint: disable=abstract-method
def __init__(self, pfiles, *args, **kwargs): # pylint: disable=super-init-not-called
self._patterns = None
self.pfiles = pfiles
self.basepath = kwargs.get('basepath', '.')
@property
def patterns(self):
if self._patterns is None:
try:
self._patterns = ignore_patterns(self.basepath)
except NoIgnoreFileException:
logger.debug('No ignore file')
return self._patterns
def can_filter(self):
return self.patterns is not None and len(self.patterns) > 0
def run(self, pfile):
for pattern in self.patterns:
if fnmatch.fnmatch(pfile.relativepath, pattern):
return False
if fnmatch.fnmatch(pfile.relativepath.split('/')[0], pattern):
return False
return True
|
class ProjectIgnoreFilter(FilterBase):
def __init__(self, pfiles, *args, **kwargs):
pass
@property
def patterns(self):
pass
def can_filter(self):
pass
def run(self, pfile):
pass
| 6 | 0 | 5 | 0 | 5 | 0 | 2 | 0.09 | 1 | 1 | 1 | 0 | 4 | 3 | 4 | 7 | 25 | 3 | 22 | 10 | 16 | 2 | 21 | 9 | 16 | 4 | 1 | 2 | 9 |
4,572 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/binstar_client/utils/projects/filters.py
|
binstar_client.utils.projects.filters.VCSFilter
|
class VCSFilter(FilterBase): # pylint: disable=abstract-method
"""Version Control System Filtering."""
def __init__(self, pfiles, *args, **kwargs): # pylint: disable=super-init-not-called
self.pfiles = pfiles
def run(self, pfile):
if pfile.relativepath.startswith('.git/'):
return False
if pfile.relativepath.startswith('.svn/'):
return False
if pfile.relativepath.startswith('.hg/'):
return False
if pfile.relativepath.startswith('.anaconda/'):
return False
return True
|
class VCSFilter(FilterBase):
'''Version Control System Filtering.'''
def __init__(self, pfiles, *args, **kwargs):
pass
def run(self, pfile):
pass
| 3 | 1 | 6 | 0 | 6 | 1 | 3 | 0.23 | 1 | 0 | 0 | 0 | 2 | 1 | 2 | 5 | 16 | 2 | 13 | 4 | 10 | 3 | 13 | 4 | 10 | 5 | 1 | 1 | 6 |
4,573 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/binstar_client/utils/projects/inspectors.py
|
binstar_client.utils.projects.inspectors.ConfigurationInspector
|
class ConfigurationInspector:
valid_names = [
'project.yml',
'project.yaml'
]
def __init__(self, pfiles):
self.pfiles = pfiles
self.config_pfile = None
def update(self, metadata):
try:
if self.has_config():
with open(self.config_pfile.fullpath) as configfile: # pylint: disable=unspecified-encoding
metadata['configuration'] = yaml_load(configfile)
except Exception: # pylint: disable=broad-except
logger.warning('Could not parse configuration file.')
return metadata
def has_config(self):
def is_config(basename, relativepath, fullpath): # pylint: disable=unused-argument
return basename == relativepath and basename in self.valid_names
for pfile in self.pfiles:
if pfile.validate(is_config):
self.config_pfile = pfile
break
return self.config_pfile is not None
|
class ConfigurationInspector:
def __init__(self, pfiles):
pass
def update(self, metadata):
pass
def has_config(self):
pass
def is_config(basename, relativepath, fullpath):
pass
| 5 | 0 | 6 | 1 | 5 | 1 | 2 | 0.13 | 0 | 1 | 0 | 0 | 3 | 2 | 3 | 3 | 29 | 5 | 24 | 10 | 19 | 3 | 21 | 9 | 16 | 3 | 0 | 3 | 8 |
4,574 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/binstar_client/utils/projects/inspectors.py
|
binstar_client.utils.projects.inspectors.DocumentationInspector
|
class DocumentationInspector:
valid_names = [
'README.md',
'README.rst',
'README.txt',
'README'
]
def __init__(self, pfiles):
self.pfiles = pfiles
self.doc_pfile = None
def update(self, metadata):
if self.has_doc():
with open(self.doc_pfile.fullpath) as docfile: # pylint: disable=unspecified-encoding
metadata['readme'] = docfile.read()
return metadata
def has_doc(self):
def is_readme(basename, relativepath, fullpath): # pylint: disable=unused-argument
return basename == relativepath and basename in self.valid_names
for pfile in self.pfiles:
if pfile.validate(is_readme):
self.doc_pfile = pfile
break
return self.doc_pfile is not None
|
class DocumentationInspector:
def __init__(self, pfiles):
pass
def update(self, metadata):
pass
def has_doc(self):
pass
def is_readme(basename, relativepath, fullpath):
pass
| 5 | 0 | 5 | 1 | 5 | 1 | 2 | 0.09 | 0 | 0 | 0 | 0 | 3 | 2 | 3 | 3 | 28 | 5 | 23 | 10 | 18 | 2 | 18 | 9 | 13 | 3 | 0 | 2 | 7 |
4,575 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/binstar_client/utils/projects/inspectors.py
|
binstar_client.utils.projects.inspectors.ProjectFilesInspector
|
class ProjectFilesInspector: # pylint: disable=too-few-public-methods
def __init__(self, pfiles):
self.pfiles = pfiles
def update(self, metadata):
metadata['files'] = [pfile.to_dict() for pfile in self.pfiles]
return metadata
|
class ProjectFilesInspector:
def __init__(self, pfiles):
pass
def update(self, metadata):
pass
| 3 | 0 | 3 | 0 | 3 | 0 | 1 | 0.17 | 0 | 0 | 0 | 0 | 2 | 1 | 2 | 2 | 7 | 1 | 6 | 4 | 3 | 1 | 6 | 4 | 3 | 1 | 0 | 0 | 2 |
4,576 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/binstar_client/utils/projects/models.py
|
binstar_client.utils.projects.models.CondaProject
|
class CondaProject:
# NOTE: This class will be moved into Anaconda-Project
def __init__(self, project_path, *args, **kwargs): # pylint: disable=unused-argument
self.project_path = project_path
self._name = None
self._tar = None
self._size = None
self.pfiles = []
self.metadata = {
'summary': kwargs.get('summary', None),
'description': kwargs.get('description', None),
'version': kwargs.get('version', None)
}
self.metadata = {
key: value
for key, value in self.metadata.items()
if value
}
def tar_it(self, file=SpooledTemporaryFile()): # pylint: disable=consider-using-with
with tarfile.open(mode='w', fileobj=file) as tar:
for pfile in self.pfiles:
tar.add(pfile.fullpath, arcname=pfile.relativepath)
file.seek(0)
self._tar = file
return file
def to_project_creation(self):
return {
'name': self.name,
'access': 'public',
'profile': {
'description': self.metadata.get('description', ''),
'summary': self.metadata.get('summary', ''),
}
}
def to_stage(self):
return {
'basename': self.basename,
'configuration': self.configuration,
}
@property
def tar(self):
if self._tar is None:
self.tar_it()
return self._tar
@property
def configuration(self):
output = self.metadata.get('configuration', {})
output.update({
'size': self.size,
'num_of_files': self.get_file_count()
})
return output
def get_file_count(self):
if os.path.isfile(self.project_path):
return 1
return len(self.pfiles)
@property
def basename(self):
return f'{self.name}.tar'
@property
def size(self):
if self._size is None:
spos = self._tar.tell()
self._tar.seek(0, os.SEEK_END)
self._size = self._tar.tell() - spos
self._tar.seek(spos)
return self._size
@property
def name(self):
if self._name is None:
self._name = self._get_project_name()
return self._name
def _get_project_name(self):
if os.path.isdir(self.project_path):
return os.path.basename(os.path.abspath(self.project_path))
return os.path.splitext(os.path.basename(self.project_path))[0]
|
class CondaProject:
def __init__(self, project_path, *args, **kwargs):
pass
def tar_it(self, file=SpooledTemporaryFile()):
pass
def to_project_creation(self):
pass
def to_stage(self):
pass
@property
def tar_it(self, file=SpooledTemporaryFile()):
pass
@property
def configuration(self):
pass
def get_file_count(self):
pass
@property
def basename(self):
pass
@property
def size(self):
pass
@property
def name(self):
pass
def _get_project_name(self):
pass
| 17 | 0 | 6 | 0 | 6 | 0 | 2 | 0.04 | 0 | 1 | 0 | 0 | 11 | 6 | 11 | 11 | 87 | 11 | 75 | 27 | 58 | 3 | 49 | 21 | 37 | 2 | 0 | 2 | 17 |
4,577 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/binstar_client/utils/projects/models.py
|
binstar_client.utils.projects.models.PFile
|
class PFile:
def __init__(self, **kwargs):
self.fullpath = kwargs.get('fullpath', None)
self.basename = kwargs.get('basename', None)
self.relativepath = kwargs.get('relativepath', None)
self.size = kwargs.get('size', None)
self.populate()
def __str__(self):
if self.is_dir():
return self.relativepath
return f'[{self.size}] {self.relativepath}'
def __repr__(self):
return self.__str__()
def __eq__(self, other):
return self.fullpath == other.fullpath
def is_dir(self):
return os.path.isdir(self.fullpath)
def validate(self, validator):
if inspect.isfunction(validator):
return validator(basename=self.basename,
relativepath=self.relativepath,
fullpath=self.fullpath)
if inspect.isclass(validator):
return validator(self)()
raise BinstarError(f'Invalid validator {validator}')
def populate(self):
if self.size is None:
self.size = os.stat(self.fullpath).st_size
if self.basename is None:
self.basename = os.path.basename(self.fullpath)
def to_dict(self):
return {
'basename': self.basename,
'size': self.size,
'relativepath': self.relativepath
}
|
class PFile:
def __init__(self, **kwargs):
pass
def __str__(self):
pass
def __repr__(self):
pass
def __eq__(self, other):
pass
def is_dir(self):
pass
def validate(self, validator):
pass
def populate(self):
pass
def to_dict(self):
pass
| 9 | 0 | 5 | 0 | 4 | 0 | 2 | 0 | 0 | 1 | 1 | 0 | 8 | 4 | 8 | 8 | 44 | 8 | 36 | 13 | 27 | 0 | 30 | 13 | 21 | 3 | 0 | 1 | 13 |
4,578 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/binstar_client/utils/projects/uploader.py
|
binstar_client.utils.projects.uploader.ProjectUploader
|
class ProjectUploader(binstar_client.Binstar):
def __init__(self, token, **kwargs):
domain = kwargs.get('domain', 'https://api.anaconda.org')
verify = kwargs.get('verify', True)
self.username = kwargs.get('username', None)
self.project = kwargs.get('project', None)
super().__init__(token, domain, verify)
def exists(self):
url = '{}/apps/{}/projects/{}'.format(
self.domain, self.username, self.project.name)
res = self.session.get(url)
return res.status_code == 200
def create(self):
url = '{}/apps/{}/projects'.format(self.domain, self.username)
data, headers = jencode(self.project.to_project_creation())
res = self.session.post(url, data=data, headers=headers)
return res
def stage(self):
url = '{}/apps/{}/projects/{}/stage'.format(
self.domain, self.username, self.project.name)
data, headers = jencode(self.project.to_stage())
res = self.session.post(url, data=data, headers=headers)
self._check_response(res)
return res
def commit(self, revision_id):
url = '{}/apps/{}/projects/{}/commit/{}'.format(
self.domain, self.username,
self.project.name, revision_id
)
data, headers = jencode({})
res = self.session.post(url, data=data, headers=headers)
self._check_response(res, [201])
return res
def file_upload(self, url, obj):
_hexmd5, b64md5, size = compute_hash(
self.project.tar, size=self.project.size)
s3data = obj['form_data']
s3data['Content-Length'] = str(size)
s3data['Content-MD5'] = b64md5
with tqdm.tqdm(total=size, unit='B', unit_scale=True, unit_divisor=1024) as progress:
s3res = multipart_files_upload(
url,
data=s3data,
files={'file': (self.project.basename, self.project.tar)},
progress_bar=progress,
verify=self.session.verify)
if s3res.status_code != 201:
raise binstar_client.errors.BinstarError(
'Error uploading package', s3res.status_code)
return s3res
def projects(self):
url = '{}/apps/{}/projects'.format(self.domain, self.username)
data, headers = jencode(self.project.to_project_creation())
return self.session.get(url, data=data, headers=headers)
def upload(self): # pylint: disable=arguments-differ
"""
* Check if project already exists
* if it doesn't, then create it
* stage a new revision
* upload
* commit revision
"""
if not self.exists():
self.create()
data = self.stage().json()
self.file_upload(data['post_url'], data)
res = self.commit(data['dist_id'])
data = res.json()
return data
|
class ProjectUploader(binstar_client.Binstar):
def __init__(self, token, **kwargs):
pass
def exists(self):
pass
def create(self):
pass
def stage(self):
pass
def commit(self, revision_id):
pass
def file_upload(self, url, obj):
pass
def projects(self):
pass
def upload(self):
'''
* Check if project already exists
* if it doesn't, then create it
* stage a new revision
* upload
* commit revision
'''
pass
| 9 | 1 | 9 | 1 | 8 | 1 | 1 | 0.13 | 1 | 4 | 1 | 0 | 8 | 2 | 8 | 59 | 80 | 11 | 62 | 32 | 53 | 8 | 50 | 31 | 41 | 2 | 2 | 1 | 10 |
4,579 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/binstar_client/utils/spec.py
|
binstar_client.utils.spec.GroupSpec
|
class GroupSpec:
def __init__(self, org, group_name=None, member=None, spec_str=None):
self._org = org
self._group_name = group_name
self._member = member
if not spec_str:
spec_str = str(org)
if group_name:
spec_str = f'{spec_str}/{group_name}'
if member:
spec_str = f'{spec_str}/{member}'
self.spec_str = spec_str
def __str__(self):
return self.spec_str
def __repr__(self):
return f'<GroupSpec {self.spec_str!r}>'
@property
def org(self):
if self._org is None:
raise UserError(f'Organization not given (got {self.spec_str!r} expected <organization>)')
return self._org
@property
def group_name(self):
if self._group_name is None:
raise UserError(f'Group name not given (got {self.spec_str!r} expected <organization>/<group_name>)')
return self._group_name
@property
def member(self):
if self._member is None:
raise UserError(
f'Member name not given (got {self.spec_str!r} expected <organization>/<group_name>/<member>)'
)
return self._member
|
class GroupSpec:
def __init__(self, org, group_name=None, member=None, spec_str=None):
pass
def __str__(self):
pass
def __repr__(self):
pass
@property
def org(self):
pass
@property
def group_name(self):
pass
@property
def member(self):
pass
| 10 | 0 | 5 | 0 | 5 | 0 | 2 | 0 | 0 | 2 | 1 | 0 | 6 | 4 | 6 | 6 | 39 | 6 | 33 | 14 | 23 | 0 | 28 | 11 | 21 | 4 | 0 | 2 | 12 |
4,580 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/binstar_client/utils/spec.py
|
binstar_client.utils.spec.PackageSpec
|
class PackageSpec:
def __init__( # pylint: disable=too-many-arguments
self,
user,
package=None,
version=None,
basename=None,
attrs=None,
spec_str=None
):
self._user = user
self._package = package
self._version = version
self._basename = basename
self.attrs = attrs
if spec_str:
self.spec_str = spec_str
else:
spec_str = str(user)
if package:
spec_str = f'{spec_str}/{package}'
if version:
spec_str = f'{spec_str}/{version}'
if basename:
spec_str = f'{spec_str}/{basename}'
self.spec_str = spec_str
def __str__(self):
return self.spec_str
def __repr__(self):
return f'<PackageSpec {self.spec_str!r}>'
@property
def user(self):
if self._user is None:
raise UserError(f'user not given (got {self.spec_str!r} expected <username>)')
return self._user
@property
def name(self):
if self._package is None:
raise UserError(f'package not given in spec (got {self.spec_str!r} expected <username>/<package>)')
return self._package
@property
def package(self):
if self._package is None:
raise UserError(f'package not given in spec (got {self.spec_str!r} expected <username>/<package>)')
return self._package
@property
def version(self):
if self._version is None:
raise UserError(
f'version not given in spec (got {self.spec_str!r} expected <username>/<package>/<version>)'
)
return self._version
@property
def basename(self):
if self._basename is None:
raise UserError(
f'basename not given in spec (got {self.spec_str!r} expected <username>/<package>/<version>/<filename>)'
)
return self._basename
|
class PackageSpec:
def __init__( # pylint: disable=too-many-arguments
self,
user,
package=None,
version=None,
basename=None,
attrs=None,
spec_str=None
):
pass
def __str__(self):
pass
def __repr__(self):
pass
@property
def user(self):
pass
@property
def name(self):
pass
@property
def package(self):
pass
@property
def version(self):
pass
@property
def basename(self):
pass
| 14 | 0 | 7 | 0 | 7 | 0 | 2 | 0.02 | 0 | 2 | 1 | 0 | 8 | 6 | 8 | 8 | 67 | 8 | 59 | 28 | 37 | 1 | 41 | 15 | 32 | 5 | 0 | 2 | 17 |
4,581 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/binstar_client/utils/detect.py
|
binstar_client.utils.detect.Inspector
|
class Inspector(typing.Protocol): # pylint: disable=too-few-public-methods
"""Common interface for package inspectors."""
def __call__(self, filename: str, fileobj: typing.BinaryIO, *args: typing.Any, **kwargs: typing.Any) -> Attributes:
"""Collect metadata on a package."""
|
class Inspector(typing.Protocol):
'''Common interface for package inspectors.'''
def __call__(self, filename: str, fileobj: typing.BinaryIO, *args: typing.Any, **kwargs: typing.Any) -> Attributes:
'''Collect metadata on a package.'''
pass
| 2 | 2 | 2 | 0 | 1 | 1 | 1 | 1.5 | 1 | 3 | 0 | 0 | 1 | 0 | 1 | 25 | 5 | 1 | 2 | 2 | 0 | 3 | 2 | 2 | 0 | 1 | 5 | 0 | 1 |
4,582 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/binstar_client/utils/tables.py
|
binstar_client.utils.tables.SimpleTable
|
class SimpleTable:
"""
Table with headings.
:param heading_rows: How many rows should be used as a headings.
:param heading_columns: How many columns should be used as a headings.
"""
__slots__ = ('__alignment', '__clean', '__core', '__heading_columns', '__heading_rows')
def __init__(
self,
heading_rows: int = 0,
heading_columns: int = 0,
) -> None:
"""Initialize new :class:`~SimpleTable` instance."""
self.__alignment: typing.Dict[typing.Tuple[int, int], 'Alignment'] = {(-1, -1): '<'}
self.__clean: bool = True
self.__core: 'typing_extensions.Final[TableCore]' = TableCore(default=TableCell(kind=CELL, value=''))
self.__heading_columns: 'typing_extensions.Final[int]' = heading_columns
self.__heading_rows: 'typing_extensions.Final[int]' = heading_rows
@property
def alignment(self) -> 'Alignment': # noqa: D401
"""Default alignment value for all cells."""
return self.__alignment[-1, -1]
@alignment.setter
def alignment(self, value: 'Alignment') -> None:
"""Update default alignment value."""
self.__alignment[-1, -1] = value
@property
def columns(self) -> int: # noqa: D401
"""Number of columns in this table."""
return self.__core.columns
@property
def rows(self) -> int: # noqa: D401
"""Number of rows in this table."""
return self.__core.rows
def align_cell(self, row: int, column: int, alignment: 'Alignment') -> None:
"""Align a single cell in the table."""
if row < 0:
raise AttributeError(f'row index must be at least 0, not {row}')
if column < 0:
raise AttributeError(f'column index must be at least 0, not {column}')
self.__alignment[row, column] = alignment
self.__clean = False
def align_column(self, column: int, alignment: 'Alignment') -> None:
"""Align each cell in a single column of the table."""
new_alignment: typing.Dict[typing.Tuple[int, int], 'Alignment'] = {
key: value
for key, value in self.__alignment.items()
if key[1] != column
}
new_alignment[-1, column] = alignment
self.__alignment = new_alignment
self.__clean = False
def align_row(self, row: int, alignment: 'Alignment') -> None:
"""Aline each cell in a single row of the table."""
new_alignment: typing.Dict[typing.Tuple[int, int], 'Alignment'] = {
key: value
for key, value in self.__alignment.items()
if key[0] != row
}
new_alignment[row, -1] = alignment
self.__alignment = new_alignment
self.__clean = False
def append_row(self, values: typing.Iterable[typing.Any]) -> None:
"""Append new row to the bottom of this table."""
self.__core.append_row([TableCell(kind=CELL, value=value) for value in values])
self.__clean = False
def remove_column(self, column: int) -> None:
"""Remove a single column from the table."""
self.__core.remove_column(column)
new_alignment: typing.Dict[typing.Tuple[int, int], 'Alignment'] = {
(key_row, key_column - (key_column > column)): value
for (key_row, key_column), value in self.__alignment.items()
if key_column != column
}
self.__alignment = new_alignment
self.__clean = False
def remove_row(self, row: int) -> None:
"""Remove a single row from the table."""
self.__core.remove_row(row)
new_alignment: typing.Dict[typing.Tuple[int, int], 'Alignment'] = {
(key_row - (key_row > row), key_column): value
for (key_row, key_column), value in self.__alignment.items()
if key_row != row
}
self.__alignment = new_alignment
self.__clean = False
def render(self, design: TableDesign) -> typing.Iterator[str]:
"""Print table to the user (in terminal)."""
self._normalize()
return self.__core.render(design)
def trim(self, *, empty_columns: bool = False, empty_rows: bool = False, empty_values: bool = False) -> None:
"""
Remove trailing empty cells from each row.
:param empty_columns: Also remove columns if all of their cells are empty.
:param empty_rows: Also remove rows if all of their cells are empty
:param empty_values: If any cell contains an empty value - convert it to empty cell.
This action is performed before anything else.
"""
removed_columns: typing.Sequence[int]
removed_rows: typing.Sequence[int]
removed_columns, removed_rows = self.__core.trim(
empty_columns=empty_columns,
empty_rows=empty_rows,
empty_values=empty_values,
)
new_alignment: typing.Dict[typing.Tuple[int, int], 'Alignment'] = {
(
key_row - sum(key_row > row for row in removed_rows),
key_column - sum(key_column > column for column in removed_columns),
): value
for (key_row, key_column), value in self.__alignment.items()
if (key_column not in removed_columns) and (key_row not in removed_rows)
}
self.__alignment = new_alignment
self.__clean = False
def _normalize(self) -> None:
"""Apply table visualization preferences to the table (e.g. alignments)."""
if self.__clean:
return
for row in range(self.__core.rows):
for column in range(self.__core.columns):
kind: str
if (row < self.__heading_rows) or (column < self.__heading_columns):
kind = HEADING
else:
kind = CELL
alignment: 'Alignment' = (
self.__alignment.get((row, column), None) or # type: ignore
self.__alignment.get((row, -1), None) or
self.__alignment.get((-1, column), None) or
self.__alignment.get((-1, -1), None) or
'<'
)
cell: TableCell = self.__core[row, column]
if (cell.kind == kind) and (cell.alignment == alignment or not cell.value):
continue
if cell is self.__core.default:
self.__core[row, column] = TableCell(kind=kind, value=cell.value, alignment=alignment)
else:
self.__core[row, column].alignment = alignment
self.__core[row, column].kind = kind
self.__clean = True
def __delitem__(self, cell: typing.Tuple[int, int]) -> None:
"""Remove a single cell from the table (set it to default)."""
del self.__core[cell]
def __getitem__(self, cell: typing.Tuple[int, int]) -> str:
"""Retrieve a value of a single cell in the table."""
return self.__core[cell].value
def __setitem__(self, cell: typing.Tuple[int, int], value: str) -> None:
"""Update a value of a single cell in the table."""
self.__core[cell] = TableCell(kind=CELL, value=value)
self.__clean = False
|
class SimpleTable:
'''
Table with headings.
:param heading_rows: How many rows should be used as a headings.
:param heading_columns: How many columns should be used as a headings.
'''
def __init__(
self,
heading_rows: int = 0,
heading_columns: int = 0,
) -> None:
'''Initialize new :class:`~SimpleTable` instance.'''
pass
@property
def alignment(self) -> 'Alignment':
'''Default alignment value for all cells.'''
pass
@alignment.setter
def alignment(self) -> 'Alignment':
'''Update default alignment value.'''
pass
@property
def columns(self) -> int:
'''Number of columns in this table.'''
pass
@property
def rows(self) -> int:
'''Number of rows in this table.'''
pass
def align_cell(self, row: int, column: int, alignment: 'Alignment') -> None:
'''Align a single cell in the table.'''
pass
def align_column(self, column: int, alignment: 'Alignment') -> None:
'''Align each cell in a single column of the table.'''
pass
def align_row(self, row: int, alignment: 'Alignment') -> None:
'''Aline each cell in a single row of the table.'''
pass
def append_row(self, values: typing.Iterable[typing.Any]) -> None:
'''Append new row to the bottom of this table.'''
pass
def remove_column(self, column: int) -> None:
'''Remove a single column from the table.'''
pass
def remove_row(self, row: int) -> None:
'''Remove a single row from the table.'''
pass
def render(self, design: TableDesign) -> typing.Iterator[str]:
'''Print table to the user (in terminal).'''
pass
def trim(self, *, empty_columns: bool = False, empty_rows: bool = False, empty_values: bool = False) -> None:
'''
Remove trailing empty cells from each row.
:param empty_columns: Also remove columns if all of their cells are empty.
:param empty_rows: Also remove rows if all of their cells are empty
:param empty_values: If any cell contains an empty value - convert it to empty cell.
This action is performed before anything else.
'''
pass
def _normalize(self) -> None:
'''Apply table visualization preferences to the table (e.g. alignments).'''
pass
def __delitem__(self, cell: typing.Tuple[int, int]) -> None:
'''Remove a single cell from the table (set it to default).'''
pass
def __getitem__(self, cell: typing.Tuple[int, int]) -> str:
'''Retrieve a value of a single cell in the table.'''
pass
def __setitem__(self, cell: typing.Tuple[int, int], value: str) -> None:
'''Update a value of a single cell in the table.'''
pass
| 22 | 18 | 9 | 1 | 7 | 2 | 1 | 0.26 | 0 | 9 | 3 | 1 | 17 | 5 | 17 | 17 | 182 | 30 | 124 | 41 | 98 | 32 | 81 | 33 | 63 | 7 | 0 | 3 | 25 |
4,583 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/binstar_client/utils/tables.py
|
binstar_client.utils.tables.TableCell
|
class TableCell:
"""
General definition of a table cell.
:param kind: Kind of the cell (used for styling purposes, see :class:`~TableDesign`).
:param value: Exact content of the cell.
:param alignment: How text should be aligned in the cell.
"""
__slots__ = ('alignment', 'kind', 'value')
def __init__(
self,
kind: str,
value: typing.Any,
*,
alignment: 'Alignment' = '<',
) -> None:
"""Initialize new :class:`~TableCell` instance."""
if value is None:
value = ''
self.alignment: 'Alignment' = alignment
self.kind: str = kind
self.value: str = str(value)
def __repr__(self) -> str:
"""Prepare a string representation of the instance."""
return f'{type(self).__name__}(kind={self.kind!r}, value={self.value!r}, alignment={self.alignment!r})'
def __str__(self) -> str:
"""Prepare a string representation of the instance."""
return self.value
|
class TableCell:
'''
General definition of a table cell.
:param kind: Kind of the cell (used for styling purposes, see :class:`~TableDesign`).
:param value: Exact content of the cell.
:param alignment: How text should be aligned in the cell.
'''
def __init__(
self,
kind: str,
value: typing.Any,
*,
alignment: 'Alignment' = '<',
) -> None:
'''Initialize new :class:`~TableCell` instance.'''
pass
def __repr__(self) -> str:
'''Prepare a string representation of the instance.'''
pass
def __str__(self) -> str:
'''Prepare a string representation of the instance.'''
pass
| 4 | 4 | 7 | 0 | 5 | 1 | 1 | 0.5 | 0 | 3 | 0 | 0 | 3 | 3 | 3 | 3 | 33 | 6 | 18 | 14 | 8 | 9 | 12 | 8 | 8 | 2 | 0 | 1 | 4 |
4,584 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/binstar_client/utils/notebook/downloader.py
|
binstar_client.utils.notebook.downloader.Downloader
|
class Downloader:
"""
Download files from your Anaconda repository.
"""
def __init__(self, aserver_api, username, notebook):
self.aserver_api = aserver_api
self.username = username
self.notebook = notebook
self.output = None
def __call__(self, package_types, output='.', force=False):
self.output = output
self.ensure_output()
return self.download_files(package_types, force)
def list_download_files(self, package_types, output='.', force=False):
"""
This additional method was created to better handle the log output
as files are downloaded one by one on the commands/download.py.
"""
self.output = output
self.ensure_output()
files = OrderedDict()
for file in self.list_files():
pkg_type = file.get('type', '')
with suppress(ValueError):
pkg_type = PackageType(pkg_type)
if pkg_type in package_types:
if self.can_download(file, force):
files[file['basename']] = file
else:
raise DestinationPathExists(file['basename'])
return files
def download_files(self, package_types, force=False):
output = []
for file in self.list_files():
# Check type
pkg_type = file.get('type', '')
with suppress(ValueError):
pkg_type = PackageType(pkg_type)
if pkg_type in package_types:
if self.can_download(file, force):
self.download(file)
output.append(file['basename'])
else:
raise DestinationPathExists(file['basename'])
return sorted(output)
def download(self, dist):
"""
Download file into location.
"""
filename = dist['basename']
requests_handle = self.aserver_api.download(
self.username, self.notebook, dist['version'], filename
)
if not os.path.exists(os.path.dirname(filename)):
try:
os.makedirs(os.path.dirname(filename))
except OSError:
pass
with open(os.path.join(self.output, filename), 'wb') as fdout:
for chunk in requests_handle.iter_content(4096):
fdout.write(chunk)
def can_download(self, dist, force=False):
"""
Can download if location/file does not exist or if force=True
:param dist:
:param force:
:return: True/False
"""
return not os.path.exists(os.path.join(self.output, dist['basename'])) or force
def ensure_output(self):
"""
Ensure output's directory exists
"""
if not os.path.exists(self.output):
os.makedirs(self.output)
def list_files(self):
"""
List available files in a project (aka notebook).
:return: list
"""
output = []
tmp = {}
files = self.aserver_api.package(self.username, self.notebook)['files']
for file in files:
if file['basename'] in tmp:
tmp[file['basename']].append(file)
else:
tmp[file['basename']] = [file]
for basename, versions in tmp.items(): # pylint: disable=unused-variable
try:
output.append(max(versions, key=lambda x: int(x['version'])))
except ValueError:
output.append(
max(versions, key=lambda x: mktime(parse(x['upload_time']).timetuple()))
)
except Exception: # pylint: disable=broad-except
output.append(versions[-1])
return output
|
class Downloader:
'''
Download files from your Anaconda repository.
'''
def __init__(self, aserver_api, username, notebook):
pass
def __call__(self, package_types, output='.', force=False):
pass
def list_download_files(self, package_types, output='.', force=False):
'''
This additional method was created to better handle the log output
as files are downloaded one by one on the commands/download.py.
'''
pass
def download_files(self, package_types, force=False):
pass
def download_files(self, package_types, force=False):
'''
Download file into location.
'''
pass
def can_download(self, dist, force=False):
'''
Can download if location/file does not exist or if force=True
:param dist:
:param force:
:return: True/False
'''
pass
def ensure_output(self):
'''
Ensure output's directory exists
'''
pass
def list_files(self):
'''
List available files in a project (aka notebook).
:return: list
'''
pass
| 9 | 6 | 13 | 1 | 9 | 3 | 3 | 0.35 | 0 | 8 | 2 | 0 | 8 | 4 | 8 | 8 | 114 | 16 | 74 | 28 | 65 | 26 | 67 | 27 | 58 | 6 | 0 | 3 | 23 |
4,585 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/binstar_client/utils/notebook/data_uri.py
|
binstar_client.utils.notebook.data_uri.DataURIConverter
|
class DataURIConverter:
def __init__(self, location, data=None):
self.check_pillow_installed()
self.location = location
self.data = data
def check_pillow_installed(self):
if Image is None:
raise PillowNotInstalled()
def __call__(self):
if self.data:
file = io.BytesIO(self.data)
b64 = self._encode(self.resize_and_convert(file).read())
elif os.path.exists(self.location):
with open(self.location, 'rb') as file:
b64 = self._encode(self.resize_and_convert(file).read())
elif self.is_url():
content = requests.get(self.location, timeout=10 * 60 * 60).content
file = io.BytesIO()
file.write(content)
file.seek(0)
b64 = self._encode(self.resize_and_convert(file).read())
else:
raise IOError('{} not found'.format(self.location))
return b64
def resize_and_convert(self, file):
if Image is None:
raise PillowNotInstalled()
image = Image.open(file)
image.thumbnail(THUMB_SIZE)
out = io.BytesIO()
image.save(out, format='png')
out.seek(0)
return out
def is_py3(self):
return sys.version_info[0] == 3
def is_url(self):
return self.location is not None and urlparse(self.location).scheme in ['http', 'https']
def _encode(self, content):
if self.is_py3():
data64 = base64.b64encode(content).decode('ascii')
else:
data64 = content.encode('base64').replace('\n', '')
return data64
|
class DataURIConverter:
def __init__(self, location, data=None):
pass
def check_pillow_installed(self):
pass
def __call__(self):
pass
def resize_and_convert(self, file):
pass
def is_py3(self):
pass
def is_url(self):
pass
def _encode(self, content):
pass
| 8 | 0 | 6 | 0 | 6 | 0 | 2 | 0 | 0 | 1 | 1 | 0 | 7 | 2 | 7 | 7 | 49 | 6 | 43 | 16 | 35 | 0 | 39 | 16 | 31 | 4 | 0 | 2 | 13 |
4,586 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/tests/test_groups.py
|
tests.test_groups.Test
|
class Test(CLITestCase):
"""Tests for group management commands."""
@urlpatch
def test_show(self, urls):
urls.register(
method='GET',
path='/groups/org',
content='{"groups": [{"name":"grp", "permission": "read"}]}',
)
main(['--show-traceback', 'groups', 'show', 'org'])
urls.assertAllCalled()
@urlpatch
def test_show_group(self, urls):
urls.register(
method='GET',
path='/group/org/owners',
content='{"name": "owners", "permission": "read", "members_count": 1, "repos_count": 1}',
)
main(['--show-traceback', 'groups', 'show', 'org/owners'])
urls.assertAllCalled()
@urlpatch
def test_create(self, urls):
urls.register(
method='POST',
path='/group/org/new_grp',
status=204,
)
main(['--show-traceback', 'groups', 'add', 'org/new_grp'])
urls.assertAllCalled()
def test_create_missing_group(self):
with self.assertRaisesRegex(errors.UserError, 'Group name not given'):
main(['--show-traceback', 'groups', 'add', 'org'])
@urlpatch
def test_add_member(self, urls):
urls.register(
method='PUT',
path='/group/org/grp/members/new_member',
status=204,
)
main(['--show-traceback', 'groups', 'add_member', 'org/grp/new_member'])
urls.assertAllCalled()
def test_add_member_missing_member(self):
with self.assertRaisesRegex(errors.UserError, 'Member name not given'):
main(['--show-traceback', 'groups', 'add_member', 'org/grp'])
@urlpatch
def test_remove_member(self, urls):
urls.register(
method='DELETE',
path='/group/org/grp/members/new_member',
status=204,
)
main(['--show-traceback', 'groups', 'remove_member', 'org/grp/new_member'])
urls.assertAllCalled()
@urlpatch
def test_packages(self, urls):
urls.register(
method='GET',
path='/group/org/grp/packages',
content='[{"name": "pkg", "full_name": "org/pkg", "summary": "An org pkg"}]'
)
main(['--show-traceback', 'groups', 'packages', 'org/grp'])
urls.assertAllCalled()
@urlpatch
def test_add_package(self, urls):
urls.register(
method='PUT',
path='/group/org/grp/packages/pkg',
status=204,
)
main(['--show-traceback', 'groups', 'add_package', 'org/grp/pkg'])
urls.assertAllCalled()
@urlpatch
def test_remove_package(self, urls):
urls.register(
method='DELETE',
path='/group/org/grp/packages/pkg',
status=204,
)
main(['--show-traceback', 'groups', 'remove_package', 'org/grp/pkg'])
urls.assertAllCalled()
|
class Test(CLITestCase):
'''Tests for group management commands.'''
@urlpatch
def test_show(self, urls):
pass
@urlpatch
def test_show_group(self, urls):
pass
@urlpatch
def test_create(self, urls):
pass
def test_create_missing_group(self):
pass
@urlpatch
def test_add_member(self, urls):
pass
def test_add_member_missing_member(self):
pass
@urlpatch
def test_remove_member(self, urls):
pass
@urlpatch
def test_packages(self, urls):
pass
@urlpatch
def test_add_package(self, urls):
pass
@urlpatch
def test_remove_package(self, urls):
pass
| 19 | 1 | 9 | 2 | 7 | 0 | 1 | 0.01 | 1 | 1 | 1 | 0 | 10 | 0 | 10 | 84 | 106 | 26 | 79 | 19 | 60 | 1 | 39 | 11 | 28 | 1 | 3 | 1 | 10 |
4,587 |
Anaconda-Platform/anaconda-client
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Anaconda-Platform_anaconda-client/tests/utils/test_config.py
|
tests.utils.test_config.Test
|
class Test(unittest.TestCase):
CONFIG_DATA = {'ssl_verify': False} # pylint: disable=invalid-name
def create_config_dirs(self):
tmpdir = tempfile.mkdtemp()
self.addCleanup(shutil.rmtree, tmpdir)
system_dir = os.path.join(tmpdir, 'system')
user_dir = os.path.join(tmpdir, 'user')
os.mkdir(system_dir)
os.mkdir(user_dir)
return user_dir, system_dir
def test_defaults(self):
user_dir, system_dir = self.create_config_dirs()
with open(os.path.join(user_dir, 'config.yaml'), 'wb') as file:
file.write(b'')
with unittest.mock.patch('binstar_client.utils.config.SEARCH_PATH', [system_dir, user_dir]):
cfg = config.get_config()
self.assertEqual(cfg, config.DEFAULT_CONFIG)
def test_global_url(self):
"""
Test regression reported on:
https://github.com/Anaconda-Platform/anaconda-client/issues/464
"""
user_dir, system_dir = self.create_config_dirs()
with open(os.path.join(user_dir, 'config.yaml'), 'wb') as file:
file.write(b'')
url_data = {'url': 'https://blob.org'}
config_data = config.DEFAULT_CONFIG.copy()
config_data.update(url_data)
with unittest.mock.patch('binstar_client.utils.config.SEARCH_PATH', [system_dir, user_dir]):
config.save_config(url_data, os.path.join(user_dir, 'config.yaml'))
cfg = config.get_config()
self.assertEqual(cfg, config_data)
def test_merge(self):
user_dir, system_dir = self.create_config_dirs()
with open(os.path.join(system_dir, 'config.yaml'), 'wb') as file:
file.write(b'''
ssl_verify: false
sites:
develop:
url: http://develop.anaconda.org
''')
with open(os.path.join(user_dir, 'config.yaml'), 'wb') as file:
file.write(b'''
ssl_verify: true
sites:
develop:
ssl_verify: false
''')
with unittest.mock.patch('binstar_client.utils.config.SEARCH_PATH', [system_dir, user_dir]), \
unittest.mock.patch('binstar_client.utils.config.DEFAULT_CONFIG', {}):
cfg = config.get_config()
self.assertEqual(cfg, {
'ssl_verify': True,
'sites': {
'develop': {
'url': 'http://develop.anaconda.org',
'ssl_verify': False,
}
}
})
def test_support_tags(self):
user_dir, system_dir = self.create_config_dirs() # pylint: disable=unused-variable
with open(os.path.join(user_dir, 'config.yaml'), 'wb') as file:
file.write(b'''
!!python/unicode 'sites':
!!python/unicode 'alpha': {!!python/unicode 'url': !!python/unicode 'foobar'}
!!python/unicode 'binstar': {!!python/unicode 'url': !!python/unicode 'barfoo'}
ssl_verify: False
''')
with unittest.mock.patch('binstar_client.utils.config.SEARCH_PATH', [user_dir]), \
unittest.mock.patch('binstar_client.utils.config.DEFAULT_CONFIG', {}):
cfg = config.get_config()
self.assertEqual(cfg, {
'ssl_verify': False,
'sites': {
'alpha': {
'url': 'foobar',
},
'binstar': {
'url': 'barfoo',
},
}
})
@unittest.mock.patch('binstar_client.utils.config.warnings')
@unittest.mock.patch('binstar_client.utils.config.yaml_load', wraps=config.yaml_load)
def test_load_config(self, mock_yaml_load, mock_warnings):
tmpdir = tempfile.mkdtemp()
tmp_config = os.path.join(tmpdir, 'config.yaml')
with open(tmp_config, 'w', encoding='utf-8') as file:
config.yaml_dump(self.CONFIG_DATA, file)
with self.subTest('OK'):
self.assertEqual(self.CONFIG_DATA, config.load_config(tmp_config))
mock_warnings.warn.assert_not_called()
with self.subTest('yaml.YAMLError'):
mock_yaml_load.side_effect = yaml.YAMLError
self.assertEqual({}, config.load_config(tmp_config))
self.assertTrue(os.path.exists(tmp_config + '.bak'))
os.remove(tmp_config + '.bak')
mock_warnings.warn.assert_called()
mock_warnings.reset_mock()
with self.subTest('PermissionError'):
mock_yaml_load.side_effect = PermissionError
self.assertEqual({}, config.load_config(tmp_config))
mock_warnings.warn.assert_called()
mock_warnings.reset_mock()
with self.subTest('OSError'):
mock_yaml_load.side_effect = OSError
self.assertEqual({}, config.load_config(tmp_config))
mock_warnings.warn.assert_not_called()
shutil.rmtree(tmpdir)
@unittest.mock.patch('binstar_client.utils.config.os.makedirs', wraps=os.makedirs)
@unittest.mock.patch('binstar_client.utils.config.os.replace', wraps=os.replace)
def test_save_config(self, mock_os_replace, mock_os_makedirs):
config_filename = 'config.yaml'
with self.subTest('OK'), tempfile.TemporaryDirectory() as test_config_dir:
config_path = os.path.join(test_config_dir, config_filename)
config.save_config(self.CONFIG_DATA, config_path)
self.assertEqual(self.CONFIG_DATA, config.load_config(config_path))
mock_os_makedirs.assert_called_once_with(
test_config_dir, exist_ok=True)
mock_os_replace.assert_called_once_with(
config_path + '~', config_path)
mock_os_replace.reset_mock()
mock_os_makedirs.reset_mock()
with self.subTest('OSError'), tempfile.TemporaryDirectory() as test_config_dir:
mock_os_replace.side_effect = OSError
config_path = os.path.join(test_config_dir, config_filename)
with self.assertRaises(BinstarError):
config.save_config(self.CONFIG_DATA, config_path)
self.assertFalse(os.path.exists(config_path))
mock_os_makedirs.assert_called_once_with(
test_config_dir, exist_ok=True)
mock_os_replace.assert_called_once_with(
config_path + '~', config_path)
|
class Test(unittest.TestCase):
def create_config_dirs(self):
pass
def test_defaults(self):
pass
def test_global_url(self):
'''
Test regression reported on:
https://github.com/Anaconda-Platform/anaconda-client/issues/464
'''
pass
def test_merge(self):
pass
def test_support_tags(self):
pass
@unittest.mock.patch('binstar_client.utils.config.warnings')
@unittest.mock.patch('binstar_client.utils.config.yaml_load', wraps=config.yaml_load)
def test_load_config(self, mock_yaml_load, mock_warnings):
pass
@unittest.mock.patch('binstar_client.utils.config.os.makedirs', wraps=os.makedirs)
@unittest.mock.patch('binstar_client.utils.config.os.replace', wraps=os.replace)
def test_save_config(self, mock_os_replace, mock_os_makedirs):
pass
| 12 | 1 | 21 | 3 | 17 | 1 | 1 | 0.05 | 1 | 4 | 1 | 0 | 7 | 0 | 7 | 79 | 161 | 31 | 126 | 34 | 102 | 6 | 87 | 26 | 79 | 1 | 2 | 2 | 7 |
4,588 |
Anaconda-Platform/anaconda-client
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Anaconda-Platform_anaconda-client/tests/test_upload.py
|
tests.test_upload.Test
|
class Test(CLITestCase):
"""Tests for package upload commands."""
@urlpatch
def test_upload_bad_package(self, registry):
registry.register(method='HEAD', path='/', status=200)
registry.register(method='GET', path='/user',
content='{"login": "eggs"}')
registry.register(method='GET', path='/package/eggs/foo',
content='{}', status=404)
registry.register(method='POST', path='/package/eggs/foo',
content={'package_types': ['conda']}, status=200)
registry.register(
method='GET', path='/release/eggs/foo/0.1', content='{}')
registry.register(
method='GET', path='/dist/eggs/foo/0.1/osx-64/foo-0.1-0.tar.bz2', status=404, content='{}')
staging_response = registry.register(
method='POST',
path='/stage/eggs/foo/0.1/osx-64/foo-0.1-0.tar.bz2',
content={'post_url': 'http://s3url.com/s3_url',
'form_data': {}, 'dist_id': 'dist_id'},
)
registry.register(method='POST', path='/s3_url', status=201)
registry.register(
method='POST', path='/commit/eggs/foo/0.1/osx-64/foo-0.1-0.tar.bz2', status=200, content={})
main(['--show-traceback', 'upload', data_dir('foo-0.1-0.tar.bz2')])
self.assertIsNotNone(json.loads(
staging_response.req.body).get('sha256'))
@urlpatch
def test_upload_bad_package_no_register(self, registry):
registry.register(method='HEAD', path='/', status=200)
registry.register(method='GET', path='/user',
content='{"login": "eggs"}')
registry.register(
method='GET', path='/dist/eggs/foo/0.1/osx-64/foo-0.1-0.tar.bz2', status=404)
registry.register(method='GET', path='/package/eggs/foo', status=404)
with self.assertRaises(errors.UserError):
main(['--show-traceback', 'upload', '--no-register',
data_dir('foo-0.1-0.tar.bz2')])
registry.assertAllCalled()
@urlpatch
def test_upload_conda(self, registry):
registry.register(method='HEAD', path='/', status=200)
registry.register(method='GET', path='/user',
content='{"login": "eggs"}')
registry.register(
method='GET', path='/dist/eggs/foo/0.1/osx-64/foo-0.1-0.tar.bz2', status=404)
registry.register(method='GET', path='/package/eggs/foo',
content={'package_types': ['conda']})
registry.register(
method='GET', path='/release/eggs/foo/0.1', content='{}')
staging_response = registry.register(
method='POST',
path='/stage/eggs/foo/0.1/osx-64/foo-0.1-0.tar.bz2',
content={'post_url': 'http://s3url.com/s3_url',
'form_data': {}, 'dist_id': 'dist_id'},
)
registry.register(method='POST', path='/s3_url', status=201)
registry.register(
method='POST', path='/commit/eggs/foo/0.1/osx-64/foo-0.1-0.tar.bz2', status=200, content={})
main(['--show-traceback', 'upload', data_dir('foo-0.1-0.tar.bz2')])
registry.assertAllCalled()
self.assertIsNotNone(json.loads(
staging_response.req.body).get('sha256'))
@urlpatch
def test_upload_conda_v2(self, registry):
registry.register(method='HEAD', path='/', status=200)
registry.register(method='GET', path='/user',
content='{"login": "eggs"}')
registry.register(
method='GET', path='/dist/eggs/mock/2.0.0/osx-64/mock-2.0.0-py37_1000.conda', status=404)
registry.register(method='GET', path='/package/eggs/mock',
content={'package_types': ['conda']})
registry.register(
method='GET', path='/release/eggs/mock/2.0.0', content='{}')
staging_response = registry.register(
method='POST',
path='/stage/eggs/mock/2.0.0/osx-64/mock-2.0.0-py37_1000.conda',
content={'post_url': 'http://s3url.com/s3_url',
'form_data': {}, 'dist_id': 'dist_id'},
)
registry.register(method='POST', path='/s3_url', status=201)
registry.register(
method='POST', path='/commit/eggs/mock/2.0.0/osx-64/mock-2.0.0-py37_1000.conda', status=200, content={},
)
main(['--show-traceback', 'upload', data_dir('mock-2.0.0-py37_1000.conda')])
registry.assertAllCalled()
self.assertIsNotNone(json.loads(
staging_response.req.body).get('sha256'))
@urlpatch
def test_upload_use_pkg_metadata(self, registry):
registry.register(method='HEAD', path='/', status=200)
registry.register(method='GET', path='/user',
content='{"login": "eggs"}')
registry.register(
method='GET', path='/dist/eggs/mock/2.0.0/osx-64/mock-2.0.0-py37_1000.conda', status=404)
registry.register(method='GET', path='/package/eggs/mock',
content={'package_types': ['conda']})
registry.register(
method='GET', path='/release/eggs/mock/2.0.0', content='{}')
registry.register(
method='PATCH', path='/release/eggs/mock/2.0.0', content='{}')
staging_response = registry.register(
method='POST',
path='/stage/eggs/mock/2.0.0/osx-64/mock-2.0.0-py37_1000.conda',
content={'post_url': 'http://s3url.com/s3_url',
'form_data': {}, 'dist_id': 'dist_id'},
)
registry.register(method='POST', path='/s3_url', status=201)
registry.register(
method='POST',
path='/commit/eggs/mock/2.0.0/osx-64/mock-2.0.0-py37_1000.conda',
status=200,
content={},
)
main(['--show-traceback', 'upload', '--force-metadata-update',
data_dir('mock-2.0.0-py37_1000.conda')])
registry.assertAllCalled()
self.assertIsNotNone(json.loads(
staging_response.req.body).get('sha256'))
@urlpatch
def test_upload_pypi(self, registry):
registry.register(method='HEAD', path='/', status=200)
registry.register(method='GET', path='/user',
content='{"login": "eggs"}')
registry.register(
method='GET', path='/dist/eggs/test-package34/0.3.1/test_package34-0.3.1.tar.gz', status=404)
registry.register(method='GET', path='/package/eggs/test-package34',
content={'package_types': ['pypi']})
registry.register(
method='GET', path='/release/eggs/test-package34/0.3.1', content='{}')
staging_response = registry.register(
method='POST',
path='/stage/eggs/test-package34/0.3.1/test_package34-0.3.1.tar.gz',
content={'post_url': 'http://s3url.com/s3_url',
'form_data': {}, 'dist_id': 'dist_id'},
)
registry.register(method='POST', path='/s3_url', status=201)
registry.register(
method='POST',
path='/commit/eggs/test-package34/0.3.1/test_package34-0.3.1.tar.gz',
status=200,
content={},
)
main(['--show-traceback', 'upload', data_dir('test_package34-0.3.1.tar.gz')])
registry.assertAllCalled()
self.assertIsNotNone(json.loads(
staging_response.req.body).get('sha256'))
@urlpatch
def test_upload_pypi_with_conda_package_name_allowed(self, registry):
registry.register(method='HEAD', path='/', status=200)
registry.register(method='GET', path='/user',
content='{"login": "eggs"}')
registry.register(
method='GET', path='/dist/eggs/test_package34/0.3.1/test_package34-0.3.1.tar.gz', status=404)
registry.register(method='GET', path='/package/eggs/test_package34',
content={'package_types': ['pypi']})
registry.register(
method='GET', path='/release/eggs/test_package34/0.3.1', content='{}')
staging_response = registry.register(
method='POST',
path='/stage/eggs/test_package34/0.3.1/test_package34-0.3.1.tar.gz',
content={'post_url': 'http://s3url.com/s3_url',
'form_data': {}, 'dist_id': 'dist_id'},
)
registry.register(method='POST', path='/s3_url', status=201)
registry.register(
method='POST',
path='/commit/eggs/test_package34/0.3.1/test_package34-0.3.1.tar.gz',
status=200,
content={},
)
# Pass -o to override the channel/package pypi package should go to
main([
'--show-traceback', 'upload', '--package', 'test_package34', '--package-type', 'pypi',
data_dir('test_package34-0.3.1.tar.gz'),
])
registry.assertAllCalled()
self.assertIsNotNone(json.loads(
staging_response.req.body).get('sha256'))
@urlpatch
def test_upload_conda_package_with_name_override_fails(self, registry):
registry.register(method='HEAD', path='/', status=200)
registry.register(method='GET', path='/user',
content='{"login": "eggs"}')
# Passing -o for `file` package_type doesn't override channel
with self.assertRaises(errors.BinstarError):
main([
'--show-traceback', 'upload', '--package', 'test_package', '--package-type', 'file',
data_dir('test_package34-0.3.1.tar.gz'),
])
registry.assertAllCalled()
@urlpatch
def test_upload_pypi_with_random_name(self, registry):
registry.register(method='HEAD', path='/', status=200)
registry.register(method='GET', path='/user',
content='{"login": "eggs"}')
with self.assertRaises(errors.BinstarError):
main(['--show-traceback', 'upload', '--package',
'alpha_omega', data_dir('test_package34-0.3.1.tar.gz')])
registry.assertAllCalled()
@urlpatch
def test_upload_file(self, registry):
registry.register(method='HEAD', path='/', status=200)
registry.register(method='GET', path='/user',
content='{"login": "eggs"}')
registry.register(
method='GET', path='/dist/eggs/test-package34/0.3.1/test_package34-0.3.1.tar.gz', status=404)
registry.register(method='GET', path='/package/eggs/test-package34',
content={'package_types': ['file']})
registry.register(
method='GET', path='/release/eggs/test-package34/0.3.1', content='{}')
staging_response = registry.register(
method='POST',
path='/stage/eggs/test-package34/0.3.1/test_package34-0.3.1.tar.gz',
content={'post_url': 'http://s3url.com/s3_url',
'form_data': {}, 'dist_id': 'dist_id'},
)
registry.register(method='POST', path='/s3_url', status=201)
registry.register(
method='POST',
path='/commit/eggs/test-package34/0.3.1/test_package34-0.3.1.tar.gz',
status=200,
content={},
)
main([
'--show-traceback', 'upload', '--package-type', 'file', '--package', 'test-package34', '--version', '0.3.1',
data_dir('test_package34-0.3.1.tar.gz'),
])
registry.assertAllCalled()
self.assertIsNotNone(json.loads(
staging_response.req.body).get('sha256'))
@pytest.mark.xfail(reason='anaconda-project removed')
@urlpatch
def test_upload_project(self, registry):
# there's redundant work between anaconda-client which checks auth and anaconda-project also checks auth;
# -project has no way to know it was already checked :-/
registry.register(method='HEAD', path='/', status=200)
registry.register(method='GET', path='/user/eggs',
content='{"login": "eggs"}')
registry.register(method='GET', path='/user',
content='{"login": "eggs"}')
registry.register(
method='GET', path='/apps/eggs/projects/dog', content='{}')
registry.register(
method='POST',
path='/apps/eggs/projects/dog/stage',
content='{"post_url":"http://s3url.com/s3_url", "form_data":{"foo":"bar"}, "dist_id":"dist42"}',
)
registry.register(method='POST', path='/s3_url', status=201)
registry.register(
method='POST', path='/apps/eggs/projects/dog/commit/dist42', content='{}')
main(['--show-traceback', 'upload',
'--package-type', 'project', data_dir('bar')])
registry.assertAllCalled()
@pytest.mark.xfail(reason='anaconda-project removed')
@urlpatch
def test_upload_notebook_as_project(self, registry):
registry.register(method='HEAD', path='/', status=200)
registry.register(method='GET', path='/user/eggs',
content='{"login": "eggs"}')
registry.register(method='GET', path='/user',
content='{"login": "eggs"}')
registry.register(
method='GET', path='/apps/eggs/projects/foo', content='{}')
registry.register(
method='POST',
path='/apps/eggs/projects/foo/stage',
content='{"post_url":"http://s3url.com/s3_url", "form_data":{"foo":"bar"}, "dist_id":"dist42"}',
)
registry.register(method='POST', path='/s3_url', status=201)
registry.register(
method='POST', path='/apps/eggs/projects/foo/commit/dist42', content='{}')
main(['--show-traceback', 'upload', '--package-type',
'project', data_dir('foo.ipynb')])
registry.assertAllCalled()
@pytest.mark.xfail(reason='anaconda-project removed')
@urlpatch
def test_upload_project_specifying_user(self, registry):
registry.register(method='HEAD', path='/', status=200)
registry.register(method='GET', path='/user/alice',
content='{"login": "alice"}')
registry.register(
method='GET', path='/apps/alice/projects/dog', content='{}')
registry.register(
method='POST',
path='/apps/alice/projects/dog/stage',
content='{"post_url":"http://s3url.com/s3_url", "form_data":{"foo":"bar"}, "dist_id":"dist42"}',
)
registry.register(method='POST', path='/s3_url', status=201)
registry.register(
method='POST', path='/apps/alice/projects/dog/commit/dist42', content='{}')
main(['--show-traceback', 'upload', '--package-type',
'project', '--user', 'alice', data_dir('bar')])
registry.assertAllCalled()
@pytest.mark.xfail(reason='anaconda-project removed')
@urlpatch
def test_upload_project_specifying_token(self, registry):
registry.register(method='HEAD', path='/', status=200)
registry.register(
method='GET',
path='/user/eggs',
content='{"login": "eggs"}',
expected_headers={'Authorization': 'token abcdefg'},
)
registry.register(method='GET', path='/user',
content='{"login": "eggs"}')
registry.register(
method='GET', path='/apps/eggs/projects/dog', content='{}')
registry.register(
method='POST',
path='/apps/eggs/projects/dog/stage',
content='{"post_url":"http://s3url.com/s3_url", "form_data":{"foo":"bar"}, "dist_id":"dist42"}',
)
registry.register(method='POST', path='/s3_url', status=201)
registry.register(
method='POST', path='/apps/eggs/projects/dog/commit/dist42', content='{}')
main(['--show-traceback', '--token', 'abcdefg', 'upload',
'--package-type', 'project', data_dir('bar')])
registry.assertAllCalled()
@urlpatch
@unittest.mock.patch('binstar_client.commands.upload.bool_input')
def test_upload_interactive_no_overwrite(self, registry, bool_input):
# regression test for #364
registry.register(method='HEAD', path='/', status=200)
registry.register(method='GET', path='/user',
content='{"login": "eggs"}')
registry.register(
method='GET', path='/dist/eggs/foo/0.1/osx-64/foo-0.1-0.tar.bz2', content='{}')
bool_input.return_value = False # do not overwrite package
main(['--show-traceback', 'upload', '-i', data_dir('foo-0.1-0.tar.bz2')])
registry.assertAllCalled()
@urlpatch
@unittest.mock.patch('binstar_client.commands.upload.bool_input')
def test_upload_interactive_overwrite(self, registry, bool_input):
registry.register(method='HEAD', path='/', status=200)
registry.register(method='GET', path='/user',
content='{"login": "eggs"}')
registry.register(
method='GET', path='/dist/eggs/foo/0.1/osx-64/foo-0.1-0.tar.bz2', content='{}')
registry.register(
method='DELETE', path='/dist/eggs/foo/0.1/osx-64/foo-0.1-0.tar.bz2', content='{}')
registry.register(method='GET', path='/package/eggs/foo',
content={'package_types': ['conda']})
registry.register(
method='GET', path='/release/eggs/foo/0.1', content='{}')
staging_response = registry.register(
method='POST',
path='/stage/eggs/foo/0.1/osx-64/foo-0.1-0.tar.bz2',
content={'post_url': 'http://s3url.com/s3_url',
'form_data': {}, 'dist_id': 'dist_id'},
)
registry.register(method='POST', path='/s3_url', status=201)
registry.register(
method='POST', path='/commit/eggs/foo/0.1/osx-64/foo-0.1-0.tar.bz2', status=200, content={})
bool_input.return_value = True
main(['--show-traceback', 'upload', '-i', data_dir('foo-0.1-0.tar.bz2')])
registry.assertAllCalled()
self.assertIsNotNone(json.loads(
staging_response.req.body).get('sha256'))
@urlpatch
def test_upload_private_package(self, registry):
registry.register(method='HEAD', path='/', status=200)
registry.register(method='GET', path='/user',
content='{"login": "eggs"}')
registry.register(
method='GET', path='/dist/eggs/foo/0.1/osx-64/foo-0.1-0.tar.bz2', status=404)
registry.register(method='GET', path='/package/eggs/foo',
content='{}', status=404)
registry.register(method='POST', path='/package/eggs/foo',
content={'package_types': ['conda']}, status=200)
registry.register(
method='GET', path='/release/eggs/foo/0.1', content='{}')
staging_response = registry.register(
method='POST',
path='/stage/eggs/foo/0.1/osx-64/foo-0.1-0.tar.bz2',
content={'post_url': 'http://s3url.com/s3_url',
'form_data': {}, 'dist_id': 'dist_id'},
)
registry.register(method='POST', path='/s3_url', status=201)
registry.register(
method='POST', path='/commit/eggs/foo/0.1/osx-64/foo-0.1-0.tar.bz2', status=200, content={})
main(['--show-traceback', 'upload', '--private',
data_dir('foo-0.1-0.tar.bz2')])
registry.assertAllCalled()
self.assertIsNotNone(json.loads(
staging_response.req.body).get('sha256'))
@urlpatch
def test_upload_private_package_not_allowed(self, registry):
registry.register(method='HEAD', path='/', status=200)
registry.register(method='GET', path='/user',
content='{"login": "eggs"}')
registry.register(
method='GET', path='/dist/eggs/foo/0.1/osx-64/foo-0.1-0.tar.bz2', status=404)
registry.register(method='GET', path='/package/eggs/foo',
content='{}', status=404)
registry.register(
method='POST',
path='/package/eggs/foo',
content='{"error": "You can not create a private package."}',
status=400,
)
with self.assertRaises(errors.BinstarError):
main(['--show-traceback', 'upload', '--private',
data_dir('foo-0.1-0.tar.bz2')])
|
class Test(CLITestCase):
'''Tests for package upload commands.'''
@urlpatch
def test_upload_bad_package(self, registry):
pass
@urlpatch
def test_upload_bad_package_no_register(self, registry):
pass
@urlpatch
def test_upload_conda(self, registry):
pass
@urlpatch
def test_upload_conda_v2(self, registry):
pass
@urlpatch
def test_upload_use_pkg_metadata(self, registry):
pass
@urlpatch
def test_upload_pypi(self, registry):
pass
@urlpatch
def test_upload_pypi_with_conda_package_name_allowed(self, registry):
pass
@urlpatch
def test_upload_conda_package_with_name_override_fails(self, registry):
pass
@urlpatch
def test_upload_pypi_with_random_name(self, registry):
pass
@urlpatch
def test_upload_file(self, registry):
pass
@pytest.mark.xfail(reason='anaconda-project removed')
@urlpatch
def test_upload_project(self, registry):
pass
@pytest.mark.xfail(reason='anaconda-project removed')
@urlpatch
def test_upload_notebook_as_project(self, registry):
pass
@pytest.mark.xfail(reason='anaconda-project removed')
@urlpatch
def test_upload_project_specifying_user(self, registry):
pass
@pytest.mark.xfail(reason='anaconda-project removed')
@urlpatch
def test_upload_project_specifying_token(self, registry):
pass
@urlpatch
@unittest.mock.patch('binstar_client.commands.upload.bool_input')
def test_upload_interactive_no_overwrite(self, registry, bool_input):
pass
@urlpatch
@unittest.mock.patch('binstar_client.commands.upload.bool_input')
def test_upload_interactive_overwrite(self, registry, bool_input):
pass
@urlpatch
def test_upload_private_package(self, registry):
pass
@urlpatch
def test_upload_private_package_not_allowed(self, registry):
pass
| 43 | 1 | 18 | 2 | 16 | 0 | 1 | 0.02 | 1 | 2 | 2 | 0 | 18 | 0 | 18 | 92 | 364 | 54 | 304 | 46 | 261 | 7 | 187 | 28 | 168 | 1 | 3 | 1 | 18 |
4,589 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/tests/test_copy.py
|
tests.test_copy.Test
|
class Test(CLITestCase):
"""Tests for package copy operations."""
@urlpatch
def test_copy_label(self, urls):
urls.register(method='GET', path='/channels/u1', content='["dev"]')
copy = urls.register(
method='POST', path='/copy/package/u1/p1/1.0/', content='[{"basename": "copied-file_1.0.tgz"}]')
main(['--show-traceback', 'copy', '--from-label', 'dev', '--to-label', 'release/xyz', 'u1/p1/1.0'])
urls.assertAllCalled()
req = json.loads(copy.req.body)
self.assertEqual(req['from_channel'], 'dev')
self.assertEqual(req['to_channel'], 'release/xyz')
@urlpatch
def test_copy_replace(self, urls):
urls.register(method='GET', path='/channels/u1', content='["dev"]')
copy = urls.register(
method='PUT', path='/copy/package/u1/p1/1.0/', content='[{"basename": "copied-file_1.0.tgz"}]')
main(['--show-traceback', 'copy', '--from-label', 'dev', '--to-label', 'release/xyz', 'u1/p1/1.0', '--replace'])
urls.assertAllCalled()
req = json.loads(copy.req.body)
self.assertEqual(req['from_channel'], 'dev')
self.assertEqual(req['to_channel'], 'release/xyz')
@urlpatch
def test_copy_update(self, urls):
urls.register(method='GET', path='/channels/u1', content='["dev"]')
copy = urls.register(
method='PATCH', path='/copy/package/u1/p1/1.0/', content='[{"basename": "copied-file_1.0.tgz"}]')
main(['--show-traceback', 'copy', '--from-label', 'dev', '--to-label', 'release/xyz', 'u1/p1/1.0', '--update'])
urls.assertAllCalled()
req = json.loads(copy.req.body)
self.assertEqual(req['from_channel'], 'dev')
self.assertEqual(req['to_channel'], 'release/xyz')
@urlpatch
def test_copy_file_conflict(self, urls):
urls.register(method='GET', path='/channels/u1', content='["dev"]')
copy = urls.register(
method='POST', path='/copy/package/u1/p1/1.0/', status=409
)
with self.assertRaises(Conflict):
main(['--show-traceback', 'copy', '--from-label', 'dev', '--to-label', 'release/xyz', 'u1/p1/1.0'])
urls.assertAllCalled()
req = json.loads(copy.req.body)
self.assertEqual(req['from_channel'], 'dev')
self.assertEqual(req['to_channel'], 'release/xyz')
@urlpatch
def test_copy_argument_error(self, urls):
urls.register(method='GET', path='/channels/u1', content='["dev"]')
with self.assertRaises(SystemExit):
main([
'--show-traceback', 'copy', '--from-label', 'dev',
'--to-label', 'release/xyz', 'u1/p1/1.0', '--update', '--replace',
])
|
class Test(CLITestCase):
'''Tests for package copy operations.'''
@urlpatch
def test_copy_label(self, urls):
pass
@urlpatch
def test_copy_replace(self, urls):
pass
@urlpatch
def test_copy_update(self, urls):
pass
@urlpatch
def test_copy_file_conflict(self, urls):
pass
@urlpatch
def test_copy_argument_error(self, urls):
pass
| 11 | 1 | 10 | 1 | 9 | 0 | 1 | 0.02 | 1 | 2 | 1 | 0 | 5 | 0 | 5 | 79 | 64 | 12 | 51 | 19 | 40 | 1 | 38 | 14 | 32 | 1 | 3 | 1 | 5 |
4,590 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/binstar_client/errors.py
|
binstar_client.errors.ServerError
|
class ServerError(BinstarError):
pass
|
class ServerError(BinstarError):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 11 | 2 | 0 | 2 | 1 | 1 | 0 | 2 | 1 | 1 | 0 | 4 | 0 | 0 |
4,591 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/binstar_client/errors.py
|
binstar_client.errors.ShowHelp
|
class ShowHelp(BinstarError):
pass
|
class ShowHelp(BinstarError):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 11 | 2 | 0 | 2 | 1 | 1 | 0 | 2 | 1 | 1 | 0 | 4 | 0 | 0 |
4,592 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/tests/urlmock.py
|
tests.urlmock.Responses
|
class Responses:
def __init__(self):
self._resps = []
def append(self, res):
self._resps.append(res)
@property
def called(self):
return len(self._resps)
@property
def req(self): # pylint: disable=inconsistent-return-statements
if self._resps:
return self._resps[0][1]
def assertCalled(self, url=''):
assert self.called, 'The url %s was not called' % url # nosec
def assertNotCalled(self, url=''):
assert not self.called, 'The url %s was called' % url
|
class Responses:
def __init__(self):
pass
def append(self, res):
pass
@property
def called(self):
pass
@property
def req(self):
pass
def assertCalled(self, url=''):
pass
def assertNotCalled(self, url=''):
pass
| 9 | 0 | 2 | 0 | 2 | 1 | 1 | 0.19 | 0 | 0 | 0 | 0 | 6 | 1 | 6 | 6 | 21 | 5 | 16 | 10 | 7 | 3 | 14 | 8 | 7 | 2 | 0 | 1 | 7 |
4,593 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/tests/utils/notebook/test_base.py
|
tests.utils.notebook.test_base.HasEnvironmentTestCase
|
class HasEnvironmentTestCase(unittest.TestCase):
def test_has_no_environment(self):
self.assertFalse(has_environment(data_dir('notebook.ipynb')))
def test_has_environment(self):
self.assertTrue(has_environment(data_dir('notebook_with_env.ipynb')))
def test_no_file(self):
self.assertFalse(has_environment('no-file'))
|
class HasEnvironmentTestCase(unittest.TestCase):
def test_has_no_environment(self):
pass
def test_has_environment(self):
pass
def test_no_file(self):
pass
| 4 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 3 | 0 | 3 | 75 | 9 | 2 | 7 | 4 | 3 | 0 | 7 | 4 | 3 | 1 | 2 | 0 | 3 |
4,594 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/tests/utils/notebook/test_base.py
|
tests.utils.notebook.test_base.NotebookURLTestCase
|
class NotebookURLTestCase(unittest.TestCase):
def test_anaconda_org_installation(self):
upload_info = {'url': 'http://anaconda.org/darth/deathstart-ipynb'}
url = 'http://notebooks.anaconda.org/darth/deathstart-ipynb'
self.assertEqual(notebook_url(upload_info), url)
def test_anaconda_server_installation(self):
upload_info = {'url': 'http://custom/darth/deathstart-ipynb'}
url = 'http://custom/notebooks/darth/deathstart-ipynb'
self.assertEqual(notebook_url(upload_info), url)
|
class NotebookURLTestCase(unittest.TestCase):
def test_anaconda_org_installation(self):
pass
def test_anaconda_server_installation(self):
pass
| 3 | 0 | 4 | 0 | 4 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 2 | 0 | 2 | 74 | 10 | 1 | 9 | 7 | 6 | 0 | 9 | 7 | 6 | 1 | 2 | 0 | 2 |
4,595 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/binstar_client/errors.py
|
binstar_client.errors.UserError
|
class UserError(BinstarError):
pass
|
class UserError(BinstarError):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 11 | 2 | 0 | 2 | 1 | 1 | 0 | 2 | 1 | 1 | 0 | 4 | 0 | 0 |
4,596 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/binstar_client/inspect_package/env.py
|
binstar_client.inspect_package.env.EnvInspector
|
class EnvInspector:
def __init__(self, filename, fileobj):
self._name = None
self._version = None
self.filename = filename
self.content = yaml_load(fileobj)
@property
def basename(self):
return os.path.basename(self.filename)
@property
def name(self):
if self._name is None:
self._name = self.content['name']
return self._name
def get_package_data(self):
return {
'name': self.name,
'summary': 'Environment file'
}
@property
def version(self):
if self._version is None:
self._version = time.strftime('%Y.%m.%d.%H%M%S')
return self._version
|
class EnvInspector:
def __init__(self, filename, fileobj):
pass
@property
def basename(self):
pass
@property
def name(self):
pass
def get_package_data(self):
pass
@property
def version(self):
pass
| 9 | 0 | 4 | 0 | 4 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 5 | 4 | 5 | 5 | 29 | 5 | 24 | 13 | 15 | 0 | 18 | 10 | 12 | 2 | 0 | 1 | 7 |
4,597 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/tests/utils/notebook/test_base.py
|
tests.utils.notebook.test_base.ParseTestCase
|
class ParseTestCase(unittest.TestCase):
def test_parse(self):
self.assertEqual(parse('user/notebook-ipynb')[0], 'user')
self.assertEqual(parse('user/notebook-ipynb')[1], 'notebook-ipynb')
self.assertIsNone(parse('notebook')[0])
self.assertEqual(parse('notebook')[1], 'notebook')
|
class ParseTestCase(unittest.TestCase):
def test_parse(self):
pass
| 2 | 0 | 6 | 1 | 5 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 73 | 7 | 1 | 6 | 2 | 4 | 0 | 6 | 2 | 4 | 1 | 2 | 0 | 1 |
4,598 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/tests/utils/notebook/test_data_uri.py
|
tests.utils.notebook.test_data_uri.DataURIConverterTestCase
|
class DataURIConverterTestCase(unittest.TestCase):
def test_local_image(self):
location = data_dir('bokeh-logo.png')
output = DataURIConverter(location)()
self.assertEqual(output[0:5], 'iVBOR')
def test_file_not_found(self):
location = data_dir('no-exists.png')
with self.assertRaises(IOError):
DataURIConverter(location)()
def test_is_python_3(self):
output = DataURIConverter('')
self.assertIsInstance(output.is_py3(), bool)
def test_is_url(self):
location = 'http://docs.continuum.io/_static/img/continuum_analytics_logo.png'
self.assertTrue(DataURIConverter(location).is_url())
location = data_dir('bokeh-logo.png')
self.assertNotEqual(DataURIConverter(location).is_url(), True)
|
class DataURIConverterTestCase(unittest.TestCase):
def test_local_image(self):
pass
def test_file_not_found(self):
pass
def test_is_python_3(self):
pass
def test_is_url(self):
pass
| 5 | 0 | 4 | 0 | 4 | 0 | 1 | 0 | 1 | 2 | 1 | 0 | 4 | 0 | 4 | 76 | 21 | 4 | 17 | 10 | 12 | 0 | 17 | 10 | 12 | 1 | 2 | 1 | 4 |
4,599 |
Anaconda-Platform/anaconda-client
|
Anaconda-Platform_anaconda-client/binstar_client/errors.py
|
binstar_client.errors.Unauthorized
|
class Unauthorized(BinstarError):
pass
|
class Unauthorized(BinstarError):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 11 | 2 | 0 | 2 | 1 | 1 | 0 | 2 | 1 | 1 | 0 | 4 | 0 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.