本文整理汇总了Python中git.Repo.archive方法的典型用法代码示例。如果您正苦于以下问题:Python Repo.archive方法的具体用法?Python Repo.archive怎么用?Python Repo.archive使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类git.Repo
的用法示例。
在下文中一共展示了Repo.archive方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: Repository
# 需要导入模块: from git import Repo [as 别名]
# 或者: from git.Repo import archive [as 别名]
class Repository(object):
def __init__(self, directory):
self.root = directory
self.repo = Repo(self.root)
self.tree = self.repo.heads.master.commit.tree
self.description = self.repo.description
def __eq__(self, other):
return hash(self) == hash(other)
def __hash__(self):
return int(md5(str(self)).hexdigest(), 16)
def __repr__(self):
return str(self)
def __str__(self):
return self.root.encode('utf-8')
@memoize
def _get_creation_datetime(self):
timestamp = self.commits[-1].authored_date
return datetime.fromtimestamp(timestamp)
creation_datetime = property(_get_creation_datetime)
@memoize_for_head
def _get_commits(self):
return list(self.repo.iter_commits())
commits = property(_get_commits)
@memoize_for_head
def _get_posts(self):
"""
Returns a list of posts, unsorted.
"""
posts = [Post(self.root, b.path.encode('utf-8')) for b in \
self.tree.blobs]
return posts
posts = property(_get_posts)
@memoize_for_head
def _get_update_datetime(self):
timestamp = self.commits[0].authored_date
return datetime.fromtimestamp(timestamp)
update_datetime = property(_get_update_datetime)
@memoize_for_head
def _get_archive(self):
"""Returns all posts in a POSIX tar archive."""
f = StringIO()
self.repo.archive(f)
return f.getvalue()
archive = property(_get_archive)
示例2: create_buildout_dist
# 需要导入模块: from git import Repo [as 别名]
# 或者: from git.Repo import archive [as 别名]
def create_buildout_dist(buildout_path=".", tag=None):
repo = Repo(buildout_path)
dist_dir = tempfile.mkdtemp()
dist_file = os.path.join(dist_dir, 'buildout.tar')
repo.archive(open(dist_file, 'wb'), treeish=tag,
prefix="buildout-%s/" % get_version(tag=tag))
return dist_file
示例3: archive
# 需要导入模块: from git import Repo [as 别名]
# 或者: from git.Repo import archive [as 别名]
def archive(self, repo_name, archive_dir=tempfile.gettempdir()):
"""Archives the cloudlet on disk as a tar file, and removes it."""
repo = Repo(self.path)
try:
print "Archiving %s to %s." % (repo_name, archive_dir)
archive_file = os.path.join(archive_dir, "%s.tar") % (repo_name)
# TODO: If a tar already exists, rotate/increment it. I tried using
# logging.handlers.RotatingFileHandler for this, but it didn't quite
# work (gave zero-length files).
# Archive and delete the repository
repo.archive(open(archive_file, "w"))
except Exception as e:
print "Archive failed -- aborting!"
print e
exit(1)
else:
if os.path.islink(self.path):
os.unlink(self.path)
else:
rmtree(self.path)
示例4: download
# 需要导入模块: from git import Repo [as 别名]
# 或者: from git.Repo import archive [as 别名]
def download(request):
loc=''
if request.GET['flag']=='project':
proj=getproj(request.user.username,settings.USERS)
loc=os.path.join(settings.REPOS,proj)
loc=loc+'/'
loc=loc+request.GET['target']
elif request.GET['flag']=='store':
loc=os.path.join(settings.STORE,request.user.username)
loc=loc+'/'
loc=loc+request.GET['target']
else:
proj=getproj(request.user.username,settings.USERS)
loc=os.path.join(settings.REPOS,proj)
r=Repo(loc)
f=open(settings.DOWNLOADS+proj+request.user.username+'.tar',"w")
r.archive(f)
f.close()
loc=settings.DOWNLOADS+proj+request.user.username+'.tar'
w=FileWrapper(file(loc))
response = HttpResponse(w,mimetype='text/plain')
n=loc.split('/')
response['Content-Disposition'] = "attachment; filename=%s"%(n[-1])
return response
示例5: test_init_repo_object
# 需要导入模块: from git import Repo [as 别名]
# 或者: from git.Repo import archive [as 别名]
def test_init_repo_object(self, rw_dir):
# [1-test_init_repo_object]
from git import Repo
join = os.path.join
# rorepo is a a Repo instance pointing to the git-python repository.
# For all you know, the first argument to Repo is a path to the repository
# you want to work with
repo = Repo(self.rorepo.working_tree_dir)
assert not repo.bare
# ![1-test_init_repo_object]
# [2-test_init_repo_object]
bare_repo = Repo.init(join(rw_dir, 'bare-repo'), bare=True)
assert bare_repo.bare
# ![2-test_init_repo_object]
# [3-test_init_repo_object]
repo.config_reader() # get a config reader for read-only access
cw = repo.config_writer() # get a config writer to change configuration
cw.release() # call release() to be sure changes are written and locks are released
# ![3-test_init_repo_object]
# [4-test_init_repo_object]
assert not bare_repo.is_dirty() # check the dirty state
repo.untracked_files # retrieve a list of untracked files
# ['my_untracked_file']
# ![4-test_init_repo_object]
# [5-test_init_repo_object]
cloned_repo = repo.clone(join(rw_dir, 'to/this/path'))
assert cloned_repo.__class__ is Repo # clone an existing repository
assert Repo.init(join(rw_dir, 'path/for/new/repo')).__class__ is Repo
# ![5-test_init_repo_object]
# [6-test_init_repo_object]
repo.archive(open(join(rw_dir, 'repo.tar'), 'wb'))
# ![6-test_init_repo_object]
# repository paths
# [7-test_init_repo_object]
assert os.path.isdir(cloned_repo.working_tree_dir) # directory with your work files
assert cloned_repo.git_dir.startswith(cloned_repo.working_tree_dir) # directory containing the git repository
assert bare_repo.working_tree_dir is None # bare repositories have no working tree
# ![7-test_init_repo_object]
# heads, tags and references
# heads are branches in git-speak
# [8-test_init_repo_object]
assert repo.head.ref == repo.heads.master # head is a symbolic reference pointing to master
assert repo.tags['0.3.5'] == repo.tag('refs/tags/0.3.5') # you can access tags in various ways too
assert repo.refs.master == repo.heads['master'] # .refs provides access to all refs, i.e. heads ...
assert repo.refs['origin/master'] == repo.remotes.origin.refs.master # ... remotes ...
assert repo.refs['0.3.5'] == repo.tags['0.3.5'] # ... and tags
# ![8-test_init_repo_object]
# create a new head/branch
# [9-test_init_repo_object]
new_branch = cloned_repo.create_head('feature') # create a new branch ...
assert cloned_repo.active_branch != new_branch # which wasn't checked out yet ...
assert new_branch.commit == cloned_repo.active_branch.commit # and which points to the checked-out commit
# It's easy to let a branch point to the previous commit, without affecting anything else
# Each reference provides access to the git object it points to, usually commits
assert new_branch.set_commit('HEAD~1').commit == cloned_repo.active_branch.commit.parents[0]
# ![9-test_init_repo_object]
# create a new tag reference
# [10-test_init_repo_object]
past = cloned_repo.create_tag('past', ref=new_branch,
message="This is a tag-object pointing to %s" % new_branch.name)
assert past.commit == new_branch.commit # the tag points to the specified commit
assert past.tag.message.startswith("This is") # and its object carries the message provided
now = cloned_repo.create_tag('now') # This is a tag-reference. It may not carry meta-data
assert now.tag is None
# ![10-test_init_repo_object]
# Object handling
# [11-test_init_repo_object]
assert now.commit.message != past.commit.message
# You can read objects directly through binary streams, no working tree required
assert (now.commit.tree / 'VERSION').data_stream.read().decode('ascii').startswith('0')
# You can traverse trees as well to handle all contained files of a particular commit
file_count = 0
tree_count = 0
tree = past.commit.tree
for item in tree.traverse():
file_count += item.type == 'blob'
tree_count += item.type == 'tree'
assert file_count and tree_count # we have accumulated all directories and files
assert len(tree.blobs) + len(tree.trees) == len(tree) # a tree is iterable itself to traverse its children
# ![11-test_init_repo_object]
# remotes allow handling push, pull and fetch operations
# [12-test_init_repo_object]
from git import RemoteProgress
class MyProgressPrinter(RemoteProgress):
def update(self, op_code, cur_count, max_count=None, message=''):
#.........这里部分代码省略.........
示例6: __init__
# 需要导入模块: from git import Repo [as 别名]
# 或者: from git.Repo import archive [as 别名]
class RepoManager:
"""User Repository manager for custom recipes"""
def __init__(self, user):
self.user = user
self.full_path = os.path.join(CONF.clients_git.repo_path, user)
try:
self.repo = Repo(path=self.full_path)
except (GitException.InvalidGitRepositoryError, GitException.NoSuchPathError):
self.repo = self.create()
def create(self):
"""Create a new repo from name"""
LOG.info("Creating new repo in %s" % self.full_path)
if not os.path.exists(self.full_path):
os.makedirs(self.full_path)
return Repo.init(self.full_path)
def delete(self):
"""Delete repo from name"""
shutil.rmtree(self.full_path)
def check_credentials(self):
"""Check user credentials"""
if "community" in self.user['role'].lower():
return True
else:
LOG.warning("Unauthorize repository access for %s" % self.user)
exit(1)
def view(self):
"""List repository entries for current user"""
tree = self.repo.heads.master.commit
return [f for f in tree]
def archive(self):
"""Archive the repository contents to a tar file"""
self.check_credentials()
return self.repo.archive(open(os.path.join(self.full_path, "%s.tar" % self.user)), "wb")
def add_cookbook(self, path):
"""
Adds files from path to user repo
:param path: local path to add from
:return: current path and head version
"""
cb_path = os.path.join(self.full_path, os.path.basename(path))
if os.path.exists(cb_path):
shutil.rmtree(cb_path)
shutil.copytree(path, cb_path)
com = self.repo.git.add(A=True)
self.repo.index.add(com)
self.repo.index.commit("Updated %s" % path)
self.version = self.repo.head.commit.tree.hexsha
LOG.info("Commited at version %s" % self.version)
return cb_path, self.repo.index.version
def browse_file(self, file):
"""
Returns sha1 index of file in repo
:param file: file path
:return: current file version id
"""
item = None
tree = self.repo.head.commit.tree
for item in tree.traverse():
if item.type == 'blob' and item.name == file:
break
return item
def browse_repository(self):
"""Shows repository contents"""
tree = self.repo.commit.tree
return [c for c in tree]
def check_branches(self):
"""Shows repository branches"""
return self.repo.heads
def check_tags(self):
"""Shows repository tags"""
return self.repo.tags
def link_commit(self, message):
"""Commit Repository changes"""
return self.repo.commit(message)
def checkout(self, url):
self.repo.clone_from(url, self.full_path)
def statistics(self):
"""Show several usage statistics"""
message = u""
file_count = 0
tree_count = 0
tree = self.repo.commit.tree
for item in tree.traverse():
file_count += item.type == 'blob'
tree_count += item.type == 'tree'
message += u"files: %d, directories: %d\n" % (len(tree.blobs), len(tree.trees))
#.........这里部分代码省略.........
示例7: GitRepository
# 需要导入模块: from git import Repo [as 别名]
# 或者: from git.Repo import archive [as 别名]
#.........这里部分代码省略.........
return ref
try:
return GitRepository(repository).commit(ref).hexsha
except:
return None
def _traverse_tree(self, path):
rev, path = (path + "/").split("/", 1)
tree = self.repo.tree(rev)
if path == "":
return (x for x in [tree])
return tree.traverse(predicate=lambda i, d: i.path == path[:-1])
def blob(self, path):
try:
gen = self._traverse_tree(path)
return GitRepository.GitBlob(gen.next())
except BadObject:
raise RepositoryError("Repository '%s' has no tree '%s'" % (self.path, path))
except StopIteration:
raise RepositoryError("Repository '%s' has no tree '%s'" % (self.path, path))
def tree(self, path):
try:
gen = self._traverse_tree(path)
return GitRepository.GitTree(gen.next())
except BadObject:
raise RepositoryError("Repository '%s' has no tree '%s'" % (self.path, path))
except StopIteration:
raise RepositoryError("Repository '%s' has no tree '%s'" % (self.path, path))
def last_activities(self, treeish, count=4, skip=0):
return (GitRepository.GitCommit(c) for c in self.repo.iter_commits(treeish, max_count=count, skip=skip))
def commit(self, rev):
try:
return GitRepository.GitCommit(self.repo.commit(rev))
except BadObject:
raise RepositoryError("Repository '%s' has no branch '%s'" % (self.path, rev))
def submodules(self, base, tree):
# let us parse .gitmodules ourselves. the implementation
# of GitPython does not allow to iterate submodules of
# a specific path nor of a specific revision!!
try:
result = []
path = tree + "/.gitmodules"
data = self.blob(path).data.split("\n")
previous = -1
for n in xrange(0, len(data)):
line = data[n]
if line.startswith("[submodule"):
if not previous == -1:
result.append(GitRepository.GitSubmodule(data[previous:n]))
previous = n
if not previous == -1:
result.append(GitRepository.GitSubmodule(data[previous:len(data)]))
return sorted([x for x in result if x.path_base == base], key=lambda x: x.path_name)
except RepositoryError:
pass
return []
def history(self, path):
breadcrumbs = path.split("/")
return (
GitRepository.GitCommit(c) for c in
self.repo.iter_commits(breadcrumbs[0], "/".join(breadcrumbs[1:]))
)
def blame(self, path):
breadcrumbs = path.split("/")
return ((GitRepository.GitCommit(c), b) for c, b in
self.repo.blame(breadcrumbs[0], "/".join(breadcrumbs[1:]))
)
def commit_count(self, start):
try:
commit = self.repo.commit(start)
return commit.count()
except BadObject:
raise RepositoryError("Repository '%s' has no branch '%s'" % (self.path, start))
def archive(self, treeish):
try:
from tempfile import TemporaryFile
with TemporaryFile(mode='w+b') as fp:
self.repo.archive(fp, treeish)
fp.flush()
fp.seek(0)
data = fp.read()
return data
except GitCommandError:
raise RepositoryError("Repository '%s' has no tree '%s'" % (self.path, treeish))