14
14
# You should have received a copy of the GNU General Public License
15
15
# along with this program; if not, write to the Free Software
16
16
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17
from contextlib import contextmanager
23
from subprocess import Popen, PIPE
20
from bzrlib import urlutils
21
from bzrlib.errors import (
28
26
from bzrlib.bzrdir import BzrDir
31
dirname = tempfile.mkdtemp("temp-branch")
32
return BzrDir.create_standalone_workingtree(dirname)
35
shutil.rmtree(tree.basedir)
37
def is_clean(cur_tree):
39
Return true if no files are modifed or unknown
41
>>> tree = temp_tree()
44
>>> fooname = os.path.join(tree.basedir, "foo")
45
>>> file(fooname, "wb").write("bar")
48
>>> bzrlib.add.smart_add_tree(tree, [tree.basedir])
52
>>> tree.commit("added file")
57
from bzrlib.diff import compare_trees
58
old_tree = cur_tree.basis_tree()
61
for path, file_class, kind, file_id, entry in new_tree.list_files():
62
if file_class in ('?', 'I'):
63
non_source.append(path)
64
delta = compare_trees(old_tree, new_tree, want_unchanged=False)
65
return not delta.has_changed(), non_source
67
def set_push_data(tree, location):
68
push_file = file (tree._control_files.controlfilename("x-push-data"), "wb")
69
push_file.write("%s\n" % location)
71
def get_push_data(tree):
73
>>> tree = temp_tree()
74
>>> get_push_data(tree) is None
76
>>> set_push_data(tree, 'http://somewhere')
77
>>> get_push_data(tree)
81
filename = tree._control_files.controlfilename("x-push-data")
82
if not os.path.exists(filename):
84
push_file = file (filename, "rb")
85
(location,) = [f.rstrip('\n') for f in push_file]
89
>>> shell_escape('hello')
92
def shell_escape(arg):
93
return "".join(['\\'+c for c in arg])
95
def safe_system(args):
97
>>> real_system = os.system
98
>>> os.system = sys.stdout.write
99
>>> safe_system(['a', 'b', 'cd'])
101
>>> os.system = real_system
103
arg_str = " ".join([shell_escape(a) for a in args])
104
return os.system(arg_str)
106
class RsyncUnknownStatus(Exception):
107
def __init__(self, status):
108
Exception.__init__(self, "Unknown status: %d" % status)
110
class NoRsync(Exception):
111
def __init__(self, rsync_name):
112
Exception.__init__(self, "%s not found." % rsync_name)
114
def rsync(source, target, ssh=False, excludes=(), silent=False,
117
>>> new_dir = tempfile.mkdtemp()
118
>>> old_dir = os.getcwd()
119
>>> os.chdir(new_dir)
120
>>> rsync("a", "b", silent=True)
121
Traceback (most recent call last):
122
RsyncNoFile: No such file a
123
>>> rsync("a", "b", excludes=("*.py",), silent=True)
124
Traceback (most recent call last):
125
RsyncNoFile: No such file a
126
>>> rsync("a", "b", excludes=("*.py",), silent=True, rsync_name="rsyncc")
127
Traceback (most recent call last):
128
NoRsync: rsyncc not found.
129
>>> os.chdir(old_dir)
130
>>> os.rmdir(new_dir)
132
cmd = [rsync_name, "-av", "--delete"]
134
cmd.extend(('-e', 'ssh'))
135
if len(excludes) > 0:
136
cmd.extend(('--exclude-from', '-'))
137
cmd.extend((source, target))
145
proc = Popen(cmd, stdin=PIPE, stderr=stderr, stdout=stdout)
147
if e.errno == errno.ENOENT:
148
raise NoRsync(rsync_name)
150
proc.stdin.write('\n'.join(excludes)+'\n')
158
if proc.returncode == 12:
159
raise RsyncStreamIO()
160
elif proc.returncode == 23:
161
raise RsyncNoFile(source)
162
elif proc.returncode != 0:
163
raise RsyncUnknownStatus(proc.returncode)
167
def rsync_ls(source, ssh=False, silent=True):
170
cmd.extend(('-e', 'ssh'))
176
proc = Popen(cmd, stderr=stderr, stdout=PIPE)
177
result = proc.stdout.read()
183
if proc.returncode == 12:
184
raise RsyncStreamIO()
185
elif proc.returncode == 23:
186
raise RsyncNoFile(source)
187
elif proc.returncode != 0:
188
raise RsyncUnknownStatus(proc.returncode)
189
return [l.split(' ')[-1].rstrip('\n') for l in result.splitlines(True)]
191
exclusions = ('.bzr/x-push-data', '.bzr/parent', '.bzr/x-pull-data',
192
'.bzr/x-pull', '.bzr/pull', '.bzr/stat-cache',
196
def read_revision_history(fname):
197
return [l.rstrip('\r\n') for l in
198
codecs.open(fname, 'rb', 'utf-8').readlines()]
200
class RsyncNoFile(Exception):
201
def __init__(self, path):
202
Exception.__init__(self, "No such file %s" % path)
204
class RsyncStreamIO(Exception):
206
Exception.__init__(self, "Error in rsync protocol data stream.")
208
def get_revision_history(location):
209
tempdir = tempfile.mkdtemp('push')
211
history_fname = os.path.join(tempdir, 'revision-history')
212
cmd = rsync(location+'.bzr/revision-history', history_fname,
214
history = read_revision_history(history_fname)
27
from bzrlib.transport import get_transport
31
def read_locked(lockable):
32
"""Read-lock a tree, branch or repository in this context."""
216
shutil.rmtree(tempdir)
219
def history_subset(location, branch):
220
remote_history = get_revision_history(location)
221
local_history = branch.revision_history()
222
if len(remote_history) > len(local_history):
224
for local, remote in zip(remote_history, local_history):
229
def empty_or_absent(location):
231
files = rsync_ls(location)
232
return files == ['.']
236
def push(tree, location=None, overwrite=False, working_tree=True):
237
push_location = get_push_data(tree)
238
if location is not None:
239
if not location.endswith('/'):
241
push_location = location
243
if push_location is None:
244
raise bzrlib.errors.MustUseDecorated
246
if push_location.find('://') != -1:
247
raise bzrlib.errors.MustUseDecorated
249
if push_location.find(':') == -1:
250
raise bzrlib.errors.MustUseDecorated
252
clean, non_source = is_clean(tree)
254
print """Error: This tree has uncommitted changes or unknown (?) files.
255
Use "bzr status" to list them."""
258
final_exclusions = non_source[:]
261
final_exclusions = []
262
for path, status, kind, file_id, entry in wt.list_files():
263
final_exclusions.append(path)
265
final_exclusions.extend(exclusions)
268
if not history_subset(push_location, tree.branch):
269
raise bzrlib.errors.BzrCommandError("Local branch is not a"
270
" newer version of remote"
273
if not empty_or_absent(push_location):
274
raise bzrlib.errors.BzrCommandError("Remote location is not a"
275
" bzr branch (or empty"
277
except RsyncStreamIO:
278
raise bzrlib.errors.BzrCommandError("Rsync could not use the"
279
" specified location. Please ensure that"
280
' "%s" is of the form "machine:/path".' % push_location)
281
print "Pushing to %s" % push_location
282
rsync(tree.basedir+'/', push_location, ssh=True,
283
excludes=final_exclusions)
285
set_push_data(tree, push_location)
287
40
def short_committer(committer):
288
41
new_committer = re.sub('<.*>', '', committer).strip(' ')