1 ;;; tramp-adb.el --- Functions for calling Android Debug Bridge from Tramp
3 ;; Copyright (C) 2011-2013 Free Software Foundation, Inc.
5 ;; Author: Juergen Hoetzel <juergen@archlinux.org>
6 ;; Keywords: comm, processes
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26 ;; The Android Debug Bridge must be installed on your local machine.
27 ;; Add the following form into your .emacs:
29 ;; (setq tramp-adb-sdk-dir "/path/to/android/sdk")
31 ;; Due to security it is not possible to access non-root devices.
37 (defvar dired-move-to-filename-regexp)
39 (defcustom tramp-adb-sdk-dir "~/Android/sdk"
40 "Set to the directory containing the Android SDK."
46 (defconst tramp-adb-method "adb"
47 "*When this method name is used, forward all calls to Android Debug Bridge.")
49 (defcustom tramp-adb-prompt
50 "^\\(?:[[:alnum:]]*@[[:alnum:]]*[^#\\$]*\\)?[#\\$][[:space:]]"
51 "Regexp used as prompt in almquist shell."
56 (defconst tramp-adb-ls-date-regexp
57 "[[:space:]][0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9][[:space:]][0-9][0-9]:[0-9][0-9][[:space:]]")
59 (defconst tramp-adb-ls-toolbox-regexp
61 "^[[:space:]]*\\([-[:alpha:]]+\\)" ; \1 permissions
62 "[[:space:]]*\\([^[:space:]]+\\)" ; \2 username
63 "[[:space:]]+\\([^[:space:]]+\\)" ; \3 group
64 "[[:space:]]+\\([[:digit:]]\\)" ; \4 size
65 "[[:space:]]+\\([-[:digit:]]+[[:space:]][:[:digit:]]+\\)" ; \5 date
66 "[[:space:]]+\\(.*\\)$")) ; \6 filename
69 (add-to-list 'tramp-methods `(,tramp-adb-method))
72 (eval-after-load 'tramp
73 '(tramp-set-completion-function
74 tramp-adb-method '((tramp-adb-parse-device-names ""))))
77 (add-to-list 'tramp-foreign-file-name-handler-alist
78 (cons 'tramp-adb-file-name-p 'tramp-adb-file-name-handler))
80 (defconst tramp-adb-file-name-handler-alist
81 '((directory-file-name . tramp-handle-directory-file-name)
82 (dired-uncache . tramp-handle-dired-uncache)
83 (file-name-as-directory . tramp-handle-file-name-as-directory)
84 (file-name-completion . tramp-handle-file-name-completion)
85 (file-name-all-completions . tramp-adb-handle-file-name-all-completions)
86 (file-attributes . tramp-adb-handle-file-attributes)
87 (file-name-directory . tramp-handle-file-name-directory)
88 (file-name-nondirectory . tramp-handle-file-name-nondirectory)
89 (file-truename . tramp-adb-handle-file-truename)
90 (file-newer-than-file-p . tramp-handle-file-newer-than-file-p)
91 (file-name-as-directory . tramp-handle-file-name-as-directory)
92 (file-regular-p . tramp-handle-file-regular-p)
93 (file-remote-p . tramp-handle-file-remote-p)
94 (file-accessible-directory-p . tramp-handle-file-accessible-directory-p)
95 (file-directory-p . tramp-adb-handle-file-directory-p)
96 (file-symlink-p . tramp-handle-file-symlink-p)
97 ;; FIXME: This is too sloppy.
98 (file-executable-p . file-exists-p)
99 (file-exists-p . tramp-adb-handle-file-exists-p)
100 (file-readable-p . tramp-handle-file-exists-p)
101 (file-writable-p . tramp-adb-handle-file-writable-p)
102 (file-local-copy . tramp-adb-handle-file-local-copy)
103 (file-modes . tramp-handle-file-modes)
104 (expand-file-name . tramp-adb-handle-expand-file-name)
105 (find-backup-file-name . tramp-handle-find-backup-file-name)
106 (directory-files . tramp-handle-directory-files)
107 (directory-files-and-attributes
108 . tramp-adb-handle-directory-files-and-attributes)
109 (file-name-all-completions . tramp-sh-handle-file-name-all-completions)
110 (make-directory . tramp-adb-handle-make-directory)
111 (delete-directory . tramp-adb-handle-delete-directory)
112 (delete-file . tramp-adb-handle-delete-file)
113 (load . tramp-handle-load)
114 (insert-directory . tramp-adb-handle-insert-directory)
115 (insert-file-contents . tramp-handle-insert-file-contents)
116 (substitute-in-file-name . tramp-handle-substitute-in-file-name)
117 (unhandled-file-name-directory . tramp-handle-unhandled-file-name-directory)
118 (vc-registered . ignore) ;no vc control files on Android devices
119 (write-region . tramp-adb-handle-write-region)
120 (set-file-modes . tramp-adb-handle-set-file-modes)
121 (set-file-times . ignore)
122 (copy-file . tramp-adb-handle-copy-file)
123 (rename-file . tramp-adb-handle-rename-file)
124 (process-file . tramp-adb-handle-process-file)
125 (shell-command . tramp-adb-handle-shell-command)
126 (start-file-process . tramp-adb-handle-start-file-process))
127 "Alist of handler functions for Tramp ADB method.")
129 ;; It must be a `defsubst' in order to push the whole code into
130 ;; tramp-loaddefs.el. Otherwise, there would be recursive autoloading.
132 (defsubst tramp-adb-file-name-p (filename)
133 "Check if it's a filename for ADB."
134 (let ((v (tramp-dissect-file-name filename)))
135 (string= (tramp-file-name-method v) tramp-adb-method)))
138 (defun tramp-adb-file-name-handler (operation &rest args)
139 "Invoke the ADB handler for OPERATION.
140 First arg specifies the OPERATION, second arg is a list of arguments to
141 pass to the OPERATION."
142 (let ((fn (assoc operation tramp-adb-file-name-handler-alist))
143 ;; `tramp-default-host's default value is (system-name). Not
146 (unless (equal (eval (car (get 'tramp-default-host 'standard-value)))
148 tramp-default-host)))
150 (save-match-data (apply (cdr fn) args))
151 (tramp-run-real-handler operation args))))
153 ;; This cannot be a constant, because `tramp-adb-sdk-dir' is customizable.
154 (defun tramp-adb-program ()
155 "The Android Debug Bridge."
156 (expand-file-name "platform-tools/adb" tramp-adb-sdk-dir))
159 (defun tramp-adb-parse-device-names (ignore)
160 "Return a list of (nil host) tuples allowed to access."
162 (when (zerop (call-process (tramp-adb-program) nil t nil "devices"))
164 (goto-char (point-min))
165 (while (search-forward-regexp "^\\(\\S-+\\)[[:space:]]+device$" nil t)
166 (add-to-list 'result (list nil (match-string 1))))
169 (defun tramp-adb-handle-expand-file-name (name &optional dir)
170 "Like `expand-file-name' for Tramp files."
171 ;; If DIR is not given, use DEFAULT-DIRECTORY or "/".
172 (setq dir (or dir default-directory "/"))
173 ;; Unless NAME is absolute, concat DIR and NAME.
174 (unless (file-name-absolute-p name)
175 (setq name (concat (file-name-as-directory dir) name)))
176 ;; If NAME is not a Tramp file, run the real handler.
177 (if (not (tramp-tramp-file-p name))
178 (tramp-run-real-handler 'expand-file-name (list name nil))
180 (with-parsed-tramp-file-name name nil
181 (unless (tramp-run-real-handler 'file-name-absolute-p (list localname))
182 (setq localname (concat "/" localname)))
183 ;; Do normal `expand-file-name' (this does "/./" and "/../").
184 ;; We bind `directory-sep-char' here for XEmacs on Windows,
185 ;; which would otherwise use backslash. `default-directory' is
186 ;; bound, because on Windows there would be problems with UNC
187 ;; shares or Cygwin mounts.
188 (let ((directory-sep-char ?/)
189 (default-directory (tramp-compat-temporary-file-directory)))
190 (tramp-make-tramp-file-name
192 (tramp-drop-volume-letter
193 (tramp-run-real-handler
194 'expand-file-name (list localname))))))))
196 (defun tramp-adb-handle-file-directory-p (filename)
197 "Like `file-directory-p' for Tramp files."
198 (car (file-attributes (file-truename filename))))
200 ;; This is derived from `tramp-sh-handle-file-truename'. Maybe the
201 ;; code could be shared?
202 (defun tramp-adb-handle-file-truename (filename &optional counter prev-dirs)
203 "Like `file-truename' for Tramp files."
204 (with-parsed-tramp-file-name (expand-file-name filename) nil
205 (with-tramp-file-property v localname "file-truename"
206 (let ((result nil)) ; result steps in reverse order
207 (tramp-message v 4 "Finding true name for `%s'" filename)
208 (let* ((directory-sep-char ?/)
209 (steps (tramp-compat-split-string localname "/"))
210 (localnamedir (tramp-run-real-handler
211 'file-name-as-directory (list localname)))
212 (is-dir (string= localname localnamedir))
215 ;; Don't make the following value larger than
216 ;; necessary. People expect an error message in a
217 ;; timely fashion when something is wrong; otherwise
218 ;; they might think that Emacs is hung. Of course,
219 ;; correctness has to come first.
222 (while (and steps (< numchase numchase-limit))
223 (setq thisstep (pop steps))
227 (append '("") (reverse result) (list thisstep))
230 (nth 0 (file-attributes
231 (tramp-make-tramp-file-name
238 (cond ((string= "." thisstep)
239 (tramp-message v 5 "Ignoring step `.'"))
240 ((string= ".." thisstep)
241 (tramp-message v 5 "Processing step `..'")
243 ((stringp symlink-target)
244 ;; It's a symlink, follow it.
245 (tramp-message v 5 "Follow symlink to %s" symlink-target)
246 (setq numchase (1+ numchase))
247 (when (file-name-absolute-p symlink-target)
249 ;; If the symlink was absolute, we'll get a string
250 ;; like "/user@host:/some/target"; extract the
251 ;; "/some/target" part from it.
252 (when (tramp-tramp-file-p symlink-target)
253 (unless (tramp-equal-remote filename symlink-target)
256 "Symlink target `%s' on wrong host" symlink-target))
257 (setq symlink-target localname))
259 (append (tramp-compat-split-string
264 (setq result (cons thisstep result)))))
265 (when (>= numchase numchase-limit)
268 "Maximum number (%d) of symlinks exceeded" numchase-limit))
269 (setq result (reverse result))
270 ;; Combine list to form string.
273 (mapconcat 'identity (cons "" result) "/")
275 (when (and is-dir (or (string= "" result)
276 (not (string= (substring result -1) "/"))))
277 (setq result (concat result "/"))))
279 (tramp-message v 4 "True name of `%s' is `%s'" filename result)
280 (tramp-make-tramp-file-name method user host result)))))
282 (defun tramp-adb-handle-file-attributes (filename &optional id-format)
283 "Like `file-attributes' for Tramp files."
284 (unless id-format (setq id-format 'integer))
286 (with-parsed-tramp-file-name filename nil
287 (with-tramp-file-property
288 v localname (format "file-attributes-%s" id-format)
289 (tramp-adb-barf-unless-okay
290 v (format "%s -d -l %s"
291 (tramp-adb-get-ls-command v)
292 (tramp-shell-quote-argument localname)) "")
293 (with-current-buffer (tramp-get-buffer v)
294 (tramp-adb-sh-fix-ls-output)
295 (cdar (tramp-do-parse-file-attributes-with-ls v id-format)))))))
297 (defun tramp-do-parse-file-attributes-with-ls (vec &optional id-format)
298 "Parse `file-attributes' for Tramp files using the ls(1) command."
299 (with-current-buffer (tramp-get-buffer vec)
300 (goto-char (point-min))
301 (let ((file-properties nil))
302 (while (re-search-forward tramp-adb-ls-toolbox-regexp nil t)
303 (let* ((mod-string (match-string 1))
304 (is-dir (eq ?d (aref mod-string 0)))
305 (is-symlink (eq ?l (aref mod-string 0)))
306 (uid (match-string 2))
307 (gid (match-string 3))
308 (size (string-to-number (match-string 4)))
309 (date (match-string 5))
310 (name (match-string 6))
313 (cadr (split-string name "\\( -> \\|\n\\)")))))
316 (or is-dir symlink-target)
318 ;; no way to handle numeric ids in Androids ash
319 (if (eq id-format 'integer) 0 uid)
320 (if (eq id-format 'integer) 0 gid)
322 (date-to-time date) ; mtime
328 (tramp-get-device vec))
332 (defun tramp-adb-handle-directory-files-and-attributes
333 (directory &optional full match nosort id-format)
334 "Like `directory-files-and-attributes' for Tramp files."
335 (when (file-directory-p directory)
336 (with-parsed-tramp-file-name (expand-file-name directory) nil
337 (with-tramp-file-property
338 v localname (format "directory-files-attributes-%s-%s-%s-%s"
339 full match id-format nosort)
340 (tramp-adb-barf-unless-okay
341 v (format "%s -a -l %s"
342 (tramp-adb-get-ls-command v)
343 (tramp-shell-quote-argument localname)) "")
344 (with-current-buffer (tramp-get-buffer v)
345 (tramp-adb-sh-fix-ls-output)
346 (let ((result (tramp-do-parse-file-attributes-with-ls
347 v (or id-format 'integer))))
352 (cons (expand-file-name (car x) directory) (cdr x)))
356 (sort result (lambda (x y) (string< (car x) (car y))))))
359 (if (or (not match) (string-match match (car x)))
363 (defun tramp-adb-get-ls-command (vec)
364 (with-tramp-connection-property vec "ls"
365 (tramp-message vec 5 "Finding a suitable `ls' command")
366 (if (zerop (tramp-adb-command-exit-status
367 vec "ls --color=never -al /dev/null"))
368 ;; On CyanogenMod based system BusyBox is used and "ls" output
369 ;; coloring is enabled by default. So we try to disable it
374 (defun tramp-adb-get-toolbox (vec)
375 "Get shell toolbox implementation: `toolbox' for orginal distributions
376 or `busybox' for CynagenMode based distributions"
377 (with-tramp-connection-property vec "toolbox"
378 (tramp-message vec 5 "Checking shell toolbox implementation")
380 ((zerop (tramp-adb-command-exit-status vec "busybox")) 'busybox)
381 ((zerop (tramp-adb-command-exit-status vec "toolbox")) 'toolbox)
384 (defun tramp-adb--gnu-switches-to-ash
386 "Almquist shell can't handle multiple arguments.
387 Convert (\"-al\") to (\"-a\" \"-l\"). Remove arguments like \"--dired\"."
391 (replace-regexp-in-string
393 (replace-regexp-in-string "^-" "" s)))
394 ;; FIXME: Warning about removed switches (long and non-dash).
398 (and (not (string-match "\\(^--\\|^[^-]\\)" s)) s))
401 (defun tramp-adb-handle-insert-directory
402 (filename switches &optional wildcard full-directory-p)
403 "Like `insert-directory' for Tramp files."
404 (when (stringp switches)
405 (setq switches (tramp-adb--gnu-switches-to-ash (split-string switches))))
406 (with-parsed-tramp-file-name (file-truename filename) nil
407 (with-current-buffer (tramp-get-buffer v)
408 (let ((name (tramp-shell-quote-argument (directory-file-name localname)))
409 (switch-d (member "-d" switches))
410 (switch-t (member "-t" switches))
411 (switches (mapconcat 'identity (remove "-t" switches) " ")))
412 (tramp-adb-barf-unless-okay
413 v (format "%s %s %s" (tramp-adb-get-ls-command v) switches name)
414 "Cannot insert directory listing: %s" filename)
416 ;; We insert also filename/. and filename/.., because "ls" doesn't.
417 (narrow-to-region (point) (point))
419 (tramp-adb-barf-unless-okay
420 v (format "%s -d %s %s %s"
421 (tramp-adb-get-ls-command v)
423 (concat (file-name-as-directory name) ".")
424 (concat (file-name-as-directory name) ".."))
425 "Cannot insert directory listing: %s" filename))
427 (tramp-adb-sh-fix-ls-output switch-t)))
428 (insert-buffer-substring (tramp-get-buffer v))))
430 (defun tramp-adb-sh-fix-ls-output (&optional sort-by-time)
431 "Insert dummy 0 in empty size columns.
432 Androids \"ls\" command doesn't insert size column for directories:
433 Emacs dired can't find files."
435 ;; Insert missing size.
436 (goto-char (point-min))
438 (search-forward-regexp
439 "[[:space:]]\\([[:space:]][0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9][[:space:]]\\)" nil t)
440 (replace-match "0\\1" "\\1" nil)
441 ;; Insert missing "/".
442 (when (looking-at "[0-9][0-9]:[0-9][0-9][[:space:]]+$")
446 (let* ((lines (split-string (buffer-string) "\n" t))
451 'tramp-adb-ls-output-time-less-p
452 'tramp-adb-ls-output-name-less-p))))
453 (delete-region (point-min) (point-max))
454 (insert " " (mapconcat 'identity sorted-lines "\n ")))
455 ;; Add final newline.
456 (goto-char (point-max))
457 (unless (= (point) (line-beginning-position))
461 (defun tramp-adb-ls-output-time-less-p (a b)
462 "Sort \"ls\" output by time, descending."
464 (string-match tramp-adb-ls-date-regexp a)
465 (setq time-a (apply 'encode-time (parse-time-string (match-string 0 a))))
466 (string-match tramp-adb-ls-date-regexp b)
467 (setq time-b (apply 'encode-time (parse-time-string (match-string 0 b))))
468 (time-less-p time-b time-a)))
470 (defun tramp-adb-ls-output-name-less-p (a b)
471 "Sort \"ls\" output by name, ascending."
473 (string-match dired-move-to-filename-regexp a)
474 (setq posa (match-end 0))
475 (string-match dired-move-to-filename-regexp b)
476 (setq posb (match-end 0))
477 (string-lessp (substring a posa) (substring b posb))))
479 (defun tramp-adb-handle-make-directory (dir &optional parents)
480 "Like `make-directory' for Tramp files."
481 (setq dir (expand-file-name dir))
482 (with-parsed-tramp-file-name dir nil
484 (let ((par (expand-file-name ".." dir)))
485 (unless (file-directory-p par)
486 (make-directory par parents))))
487 (tramp-adb-barf-unless-okay
488 v (format "mkdir %s" (tramp-shell-quote-argument localname))
489 "Couldn't make directory %s" dir)
490 (tramp-flush-directory-property v (file-name-directory localname))))
492 (defun tramp-adb-handle-delete-directory (directory &optional recursive)
493 "Like `delete-directory' for Tramp files."
494 (setq directory (expand-file-name directory))
495 (with-parsed-tramp-file-name directory nil
496 (tramp-flush-file-property v (file-name-directory localname))
497 (tramp-flush-directory-property v localname)
498 (tramp-adb-barf-unless-okay
500 (if recursive "rm -r" "rmdir")
501 (tramp-shell-quote-argument localname))
502 "Couldn't delete %s" directory)))
504 (defun tramp-adb-handle-delete-file (filename &optional trash)
505 "Like `delete-file' for Tramp files."
506 (setq filename (expand-file-name filename))
507 (with-parsed-tramp-file-name filename nil
508 (tramp-flush-file-property v (file-name-directory localname))
509 (tramp-flush-file-property v localname)
510 (tramp-adb-barf-unless-okay
511 v (format "rm %s" (tramp-shell-quote-argument localname))
512 "Couldn't delete %s" filename)))
514 (defun tramp-adb-handle-file-name-all-completions (filename directory)
515 "Like `file-name-all-completions' for Tramp files."
518 (with-parsed-tramp-file-name directory nil
519 (with-tramp-file-property v localname "file-name-all-completions"
521 (tramp-adb-send-command
523 (tramp-adb-get-ls-command v)
524 (tramp-shell-quote-argument localname)))
527 (if (file-directory-p f)
528 (file-name-as-directory f)
530 (with-current-buffer (tramp-get-buffer v)
534 (lambda (l) (and (not (string-match "^[[:space:]]*$" l)) l))
535 (split-string (buffer-string) "\n"))))))))))
537 (defun tramp-adb-handle-file-local-copy (filename)
538 "Like `file-local-copy' for Tramp files."
539 (with-parsed-tramp-file-name filename nil
540 (unless (file-exists-p (file-truename filename))
543 "Cannot make local copy of non-existing file `%s'" filename))
544 (let ((tmpfile (tramp-compat-make-temp-file filename)))
545 (with-tramp-progress-reporter
546 v 3 (format "Fetching %s to tmp file %s" filename tmpfile)
547 (when (tramp-adb-execute-adb-command v "pull" localname tmpfile)
548 (delete-file tmpfile)
550 v 'file-error "Cannot make local copy of file `%s'" filename))
551 (set-file-modes tmpfile (file-modes filename)))
554 (defun tramp-adb-handle-file-writable-p (filename)
555 "Like `tramp-sh-handle-file-writable-p'.
556 But handle the case, if the \"test\" command is not available."
557 (with-parsed-tramp-file-name filename nil
558 (with-tramp-file-property v localname "file-writable-p"
559 (if (tramp-adb-find-test-command v)
560 (if (file-exists-p filename)
562 (tramp-adb-command-exit-status
563 v (format "test -w %s" (tramp-shell-quote-argument localname))))
565 (file-directory-p (file-name-directory filename))
566 (file-writable-p (file-name-directory filename))))
568 ;; Missing "test" command on Android < 4.
569 (let ((rw-path "/data/data"))
572 "Not implemented yet (assuming \"/data/data\" is writable): %s"
574 (and (>= (length localname) (length rw-path))
575 (string= (substring localname 0 (length rw-path))
578 (defun tramp-adb-handle-write-region
579 (start end filename &optional append visit lockname confirm)
580 "Like `write-region' for Tramp files."
581 (setq filename (expand-file-name filename))
582 (with-parsed-tramp-file-name filename nil
585 v 'file-error "Cannot append to file using Tramp (`%s')" filename))
586 (when (and confirm (file-exists-p filename))
587 (unless (y-or-n-p (format "File %s exists; overwrite anyway? "
589 (tramp-error v 'file-error "File not overwritten")))
590 ;; We must also flush the cache of the directory, because
591 ;; `file-attributes' reads the values from there.
592 (tramp-flush-file-property v (file-name-directory localname))
593 (tramp-flush-file-property v localname)
594 (let* ((curbuf (current-buffer))
595 (tmpfile (tramp-compat-make-temp-file filename)))
596 (tramp-run-real-handler
598 (list start end tmpfile append 'no-message lockname confirm))
599 (with-tramp-progress-reporter
600 v 3 (format "Moving tmp file %s to %s" tmpfile filename)
602 (when (tramp-adb-execute-adb-command v "push" tmpfile localname)
603 (tramp-error v 'file-error "Cannot write: `%s' filename"))
604 (delete-file tmpfile)))
606 (unless (equal curbuf (current-buffer))
609 "Buffer has changed from `%s' to `%s'" curbuf (current-buffer))))))
611 (defun tramp-adb-handle-set-file-modes (filename mode)
612 "Like `set-file-modes' for Tramp files."
613 (with-parsed-tramp-file-name filename nil
614 (tramp-flush-file-property v localname)
615 (tramp-adb-barf-unless-okay
616 v (format "chmod %s %s" (tramp-compat-decimal-to-octal mode) localname)
617 "Error while changing file's mode %s" filename)))
619 (defun tramp-adb-handle-copy-file
620 (filename newname &optional ok-if-already-exists keep-date
621 preserve-uid-gid preserve-extended-attributes)
622 "Like `copy-file' for Tramp files.
623 PRESERVE-UID-GID and PRESERVE-EXTENDED-ATTRIBUTES are completely ignored."
624 (setq filename (expand-file-name filename)
625 newname (expand-file-name newname))
627 (if (file-directory-p filename)
628 (copy-directory filename newname keep-date t)
629 (with-tramp-progress-reporter
630 (tramp-dissect-file-name (if (file-remote-p filename) filename newname))
631 0 (format "Copying %s to %s" filename newname)
633 (let ((tmpfile (file-local-copy filename)))
638 (rename-file tmpfile newname ok-if-already-exists)
640 (delete-file tmpfile)
641 (signal (car err) (cdr err))))
644 (when (file-directory-p newname)
646 (expand-file-name (file-name-nondirectory filename) newname)))
648 (with-parsed-tramp-file-name newname nil
649 (when (and (not ok-if-already-exists)
650 (file-exists-p newname))
651 (tramp-error v 'file-already-exists newname))
653 ;; We must also flush the cache of the directory, because
654 ;; `file-attributes' reads the values from there.
655 (tramp-flush-file-property v (file-name-directory localname))
656 (tramp-flush-file-property v localname)
657 (when (tramp-adb-execute-adb-command v "push" filename localname)
659 v 'file-error "Cannot copy `%s' `%s'" filename newname))))))
661 ;; KEEP-DATE handling.
663 (set-file-times newname (nth 5 (file-attributes filename))))))
665 (defun tramp-adb-handle-rename-file
666 (filename newname &optional ok-if-already-exists)
667 "Like `rename-file' for Tramp files."
668 (setq filename (expand-file-name filename)
669 newname (expand-file-name newname))
671 (with-parsed-tramp-file-name
672 (if (file-remote-p filename) filename newname) nil
673 (with-tramp-progress-reporter
674 v 0 (format "Renaming %s to %s" newname filename)
676 (if (and (tramp-equal-remote filename newname)
677 (not (file-directory-p filename)))
679 (when (and (not ok-if-already-exists)
680 (file-exists-p newname))
681 (tramp-error v 'file-already-exists newname))
682 ;; We must also flush the cache of the directory, because
683 ;; `file-attributes' reads the values from there.
684 (tramp-flush-file-property v (file-name-directory localname))
685 (tramp-flush-file-property v localname)
687 (tramp-adb-barf-unless-okay
688 v (format "mv %s %s" (file-remote-p filename 'localname) localname)
689 "Error renaming %s to %s" filename newname))
692 (copy-file filename newname ok-if-already-exists t t)
693 (delete-file filename)))))
695 (defun tramp-adb-handle-process-file
696 (program &optional infile destination display &rest args)
697 "Like `process-file' for Tramp files."
698 ;; The implementation is not complete yet.
699 (when (and (numberp destination) (zerop destination))
700 (error "Implementation does not handle immediate return"))
702 (with-parsed-tramp-file-name default-directory nil
703 (let (command input tmpinput stderr tmpstderr outbuf ret)
705 (setq command (mapconcat 'tramp-shell-quote-argument
706 (cons program args) " "))
709 (setq input "/dev/null")
710 (setq infile (expand-file-name infile))
711 (if (tramp-equal-remote default-directory infile)
712 ;; INFILE is on the same remote host.
713 (setq input (with-parsed-tramp-file-name infile nil localname))
714 ;; INFILE must be copied to remote host.
715 (setq input (tramp-make-tramp-temp-file v)
716 tmpinput (tramp-make-tramp-file-name method user host input))
717 (copy-file infile tmpinput t)))
718 (when input (setq command (format "%s <%s" command input)))
723 ((bufferp destination)
724 (setq outbuf destination))
726 ((stringp destination)
727 (setq outbuf (get-buffer-create destination)))
728 ;; (REAL-DESTINATION ERROR-DESTINATION)
732 ((bufferp (car destination))
733 (setq outbuf (car destination)))
734 ((stringp (car destination))
735 (setq outbuf (get-buffer-create (car destination))))
737 (setq outbuf (current-buffer))))
740 ((stringp (cadr destination))
741 (setcar (cdr destination) (expand-file-name (cadr destination)))
742 (if (tramp-equal-remote default-directory (cadr destination))
743 ;; stderr is on the same remote host.
744 (setq stderr (with-parsed-tramp-file-name
745 (cadr destination) nil localname))
746 ;; stderr must be copied to remote host. The temporary
747 ;; file must be deleted after execution.
748 (setq stderr (tramp-make-tramp-temp-file v)
749 tmpstderr (tramp-make-tramp-file-name
750 method user host stderr))))
751 ;; stderr to be discarded.
752 ((null (cadr destination))
753 (setq stderr "/dev/null"))))
756 (setq outbuf (current-buffer))))
757 (when stderr (setq command (format "%s 2>%s" command stderr)))
759 ;; Send the command. It might not return in time, so we protect
760 ;; it. Call it in a subshell, in order to preserve working
766 (tramp-adb-barf-unless-okay
767 v (format "(cd %s; %s)"
768 (tramp-shell-quote-argument localname)
771 ;; We should show the output anyway.
773 (with-current-buffer outbuf
774 (insert-buffer-substring (tramp-get-connection-buffer v)))
775 (when display (display-buffer outbuf))))
776 ;; When the user did interrupt, we should do it also. We use
777 ;; return code -1 as marker.
779 (kill-buffer (tramp-get-connection-buffer v))
783 (kill-buffer (tramp-get-connection-buffer v))
786 ;; Provide error file.
787 (when tmpstderr (rename-file tmpstderr (cadr destination) t))
789 ;; Cleanup. We remove all file cache values for the connection,
790 ;; because the remote process could have changed them.
791 (when tmpinput (delete-file tmpinput))
793 ;; `process-file-side-effects' has been introduced with GNU
794 ;; Emacs 23.2. If set to `nil', no remote file will be changed
795 ;; by `program'. If it doesn't exist, we assume its default
797 (unless (and (boundp 'process-file-side-effects)
798 (not (symbol-value 'process-file-side-effects)))
799 (tramp-flush-directory-property v ""))
801 ;; Return exit status.
806 (defun tramp-adb-handle-shell-command
807 (command &optional output-buffer error-buffer)
808 "Like `shell-command' for Tramp files."
809 (let* ((asynchronous (string-match "[ \t]*&[ \t]*\\'" command))
810 ;; We cannot use `shell-file-name' and `shell-command-switch',
811 ;; they are variables of the local host.
812 (args (list "sh" "-c" (substring command 0 asynchronous)))
816 ((bufferp output-buffer) output-buffer)
817 ((stringp output-buffer) (get-buffer-create output-buffer))
819 (setq current-buffer-p t)
821 (t (get-buffer-create
823 "*Async Shell Command*"
824 "*Shell Command Output*")))))
827 ((bufferp error-buffer) error-buffer)
828 ((stringp error-buffer) (get-buffer-create error-buffer))))
830 (if (and (not asynchronous) error-buffer)
831 (with-parsed-tramp-file-name default-directory nil
832 (list output-buffer (tramp-make-tramp-temp-file v)))
834 (p (get-buffer-process output-buffer)))
836 ;; Check whether there is another process running. Tramp does not
837 ;; support 2 (asynchronous) processes in parallel.
839 (if (yes-or-no-p "A command is running. Kill it? ")
840 (ignore-errors (kill-process p))
841 (error "Shell command in progress")))
845 (barf-if-buffer-read-only)
847 (with-current-buffer output-buffer
848 (setq buffer-read-only nil)
851 (if (and (not current-buffer-p) (integerp asynchronous))
854 (apply 'start-file-process "*Async Shell*" buffer args)
856 (pop-to-buffer output-buffer)
857 (setq mode-line-process '(":%s"))
862 (apply 'process-file (car args) nil buffer nil (cdr args))
863 ;; Insert error messages if they were separated.
865 (with-current-buffer error-buffer
866 (insert-file-contents (cadr buffer)))
867 (delete-file (cadr buffer)))
869 ;; This is like exchange-point-and-mark, but doesn't
870 ;; activate the mark. It is cleaner to avoid activation,
871 ;; even though the command loop would deactivate the mark
872 ;; because we inserted text.
873 (goto-char (prog1 (mark t)
874 (set-marker (mark-marker) (point)
876 ;; There's some output, display it.
877 (when (with-current-buffer output-buffer (> (point-max) (point-min)))
878 (if (functionp 'display-message-or-buffer)
879 (tramp-compat-funcall 'display-message-or-buffer output-buffer)
880 (pop-to-buffer output-buffer))))))))
882 ;; We use BUFFER also as connection buffer during setup. Because of
883 ;; this, its original contents must be saved, and restored once
884 ;; connection has been setup.
885 (defun tramp-adb-handle-start-file-process (name buffer program &rest args)
886 "Like `start-file-process' for Tramp files."
887 (with-parsed-tramp-file-name default-directory nil
888 ;; When PROGRAM is nil, we just provide a tty.
890 (when (stringp program)
892 (tramp-shell-quote-argument localname)
893 (mapconcat 'tramp-shell-quote-argument
894 (cons program args) " "))))
895 (tramp-process-connection-type
896 (or (null program) tramp-process-connection-type))
897 (bmp (and (buffer-live-p buffer) (buffer-modified-p buffer)))
904 ;; BUFFER can be nil. We use a temporary buffer.
905 (setq buffer (generate-new-buffer tramp-temp-buffer-name)))
906 (while (get-process name1)
907 ;; NAME must be unique as process name.
909 name1 (format "%s<%d>" name i)))
911 ;; Set the new process properties.
912 (tramp-set-connection-property v "process-name" name)
913 (tramp-set-connection-property v "process-buffer" buffer)
914 ;; Activate narrowing in order to save BUFFER contents.
915 ;; Clear also the modification time; otherwise we might
916 ;; be interrupted by `verify-visited-file-modtime'.
917 (with-current-buffer (tramp-get-connection-buffer v)
918 (let ((buffer-undo-list t))
919 (clear-visited-file-modtime)
920 (narrow-to-region (point-max) (point-max))
923 (tramp-adb-send-command v command)
924 ;; Open the connection.
925 (tramp-adb-maybe-open-connection v))))
926 (let ((p (tramp-get-connection-process v)))
927 ;; Set sentinel and query flag for this process.
928 (tramp-set-connection-property p "vector" v)
929 (set-process-sentinel p 'tramp-process-sentinel)
930 (tramp-compat-set-process-query-on-exit-flag p t)
934 (with-current-buffer (tramp-get-connection-buffer v)
935 (if (string-match tramp-temp-buffer-name (buffer-name))
937 (set-process-buffer (tramp-get-connection-process v) nil)
938 (kill-buffer (current-buffer)))
939 (set-buffer-modified-p bmp)))
940 (tramp-set-connection-property v "process-name" nil)
941 (tramp-set-connection-property v "process-buffer" nil)))))
943 ;; Android < 4 doesn't provide test command.
945 (defun tramp-adb-handle-file-exists-p (filename)
946 "Like `file-exists-p' for Tramp files."
947 (with-parsed-tramp-file-name filename nil
948 (with-tramp-file-property v localname "file-exists-p"
949 (file-attributes filename))))
953 (defun tramp-adb-execute-adb-command (vec &rest args)
954 "Returns nil on success error-output on failure."
955 (when (tramp-file-name-host vec)
956 (setq args (append (list "-s" (tramp-file-name-host vec)) args)))
959 (unless (zerop (apply 'call-process (tramp-adb-program) nil t nil args))
963 (tramp-adb-program) (mapconcat 'identity args " ") (buffer-string)))))
965 (defun tramp-adb-find-test-command (vec)
966 "Checks, whether the ash has a builtin \"test\" command.
967 This happens for Android >= 4.0."
968 (with-tramp-connection-property vec "test"
969 (zerop (tramp-adb-command-exit-status vec "type test"))))
971 ;; Connection functions
973 (defun tramp-adb-send-command (vec command)
974 "Send the COMMAND to connection VEC."
975 (tramp-adb-maybe-open-connection vec)
976 (tramp-message vec 6 "%s" command)
977 (tramp-send-string vec command)
978 ;; fixme: Race condition
979 (tramp-adb-wait-for-output (tramp-get-connection-process vec))
980 (with-current-buffer (tramp-get-connection-buffer vec)
982 (goto-char (point-min))
983 ;; We can't use stty to disable echo of command.
984 (delete-matching-lines (regexp-quote command))
985 ;; When the local machine is W32, there are still trailing ^M.
986 ;; There must be a better solution by setting the correct coding
987 ;; system, but this requires changes in core Tramp.
988 (goto-char (point-min))
989 (while (re-search-forward "\r+$" nil t)
990 (replace-match "" nil nil)))))
992 (defun tramp-adb-barf-unless-okay (vec command fmt &rest args)
993 "Run COMMAND, check exit status, throw error if exit status not okay.
994 FMT and ARGS are passed to `error'."
995 (tramp-adb-send-command vec (format "%s; echo tramp_exit_status $?" command))
996 (with-current-buffer (tramp-get-connection-buffer vec)
997 (goto-char (point-max))
998 (unless (re-search-backward "tramp_exit_status [0-9]+" nil t)
1000 vec 'file-error "Couldn't find exit status of `%s'" command))
1001 (skip-chars-forward "^ ")
1002 (unless (zerop (read (current-buffer)))
1003 (apply 'tramp-error vec 'file-error fmt args))
1004 (let (buffer-read-only)
1005 (delete-region (match-beginning 0) (point-max)))))
1007 (defun tramp-adb-command-exit-status
1009 "Run COMMAND and return its exit status.
1010 Sends `echo $?' along with the COMMAND for checking the exit status. If
1011 COMMAND is nil, just sends `echo $?'. Returns the exit status found."
1012 (tramp-adb-send-command vec (format "%s; echo tramp_exit_status $?" command))
1013 (with-current-buffer (tramp-get-connection-buffer vec)
1014 (goto-char (point-max))
1015 (unless (re-search-backward "tramp_exit_status [0-9]+" nil t)
1017 vec 'file-error "Couldn't find exit status of `%s'" command))
1018 (skip-chars-forward "^ ")
1019 (read (current-buffer))))
1021 (defun tramp-adb-wait-for-output (proc &optional timeout)
1022 "Wait for output from remote command."
1023 (unless (buffer-live-p (process-buffer proc))
1024 (delete-process proc)
1025 (tramp-error proc 'file-error "Process `%s' not available, try again" proc))
1026 (with-current-buffer (process-buffer proc)
1027 (if (tramp-wait-for-regexp proc timeout tramp-adb-prompt)
1028 (let (buffer-read-only)
1029 (goto-char (point-min))
1030 ;; ADB terminal sends "^H" sequences.
1031 (when (re-search-forward "<\b+" (point-at-eol) t)
1033 (delete-region (point-min) (point)))
1034 ;; Delete the prompt.
1035 (goto-char (point-min))
1036 (when (re-search-forward tramp-adb-prompt (point-at-eol) t)
1038 (delete-region (point-min) (point)))
1039 (goto-char (point-max))
1040 (re-search-backward tramp-adb-prompt nil t)
1041 (delete-region (point) (point-max)))
1045 "[[Remote adb prompt `%s' not found in %d secs]]"
1046 tramp-adb-prompt timeout)
1049 "[[Remote prompt `%s' not found]]" tramp-adb-prompt)))))
1051 (defun tramp-adb-maybe-open-connection (vec)
1052 "Maybe open a connection VEC.
1053 Does not do anything if a connection is already open, but re-opens the
1054 connection if a previous connection has died for some reason."
1055 (let* ((buf (tramp-get-connection-buffer vec))
1056 (p (get-buffer-process buf))
1057 (devices (mapcar 'cadr (tramp-adb-parse-device-names nil))))
1059 (and p (processp p) (memq (process-status p) '(run open)))
1061 (when (and p (processp p)) (delete-process p))
1063 (tramp-error vec 'file-error "No device connected"))
1064 (if (and (tramp-file-name-host vec)
1065 (not (member (tramp-file-name-host vec) devices)))
1068 "Device %s not connected" (tramp-file-name-host vec)))
1069 (if (and (not (eq (length devices) 1))
1070 (not (tramp-file-name-host vec)))
1073 "Multiple Devices connected: No Host/Device specified"))
1074 (with-tramp-progress-reporter vec 3 "Opening adb shell connection"
1075 (let* ((coding-system-for-read 'utf-8-dos) ;is this correct?
1076 (process-connection-type tramp-process-connection-type)
1077 (args (if (tramp-file-name-host vec)
1078 (list "-s" (tramp-file-name-host vec) "shell")
1080 (p (let ((default-directory
1081 (tramp-compat-temporary-file-directory)))
1082 (apply 'start-process (tramp-get-connection-name vec) buf
1083 (tramp-adb-program) args))))
1085 vec 6 "%s" (mapconcat 'identity (process-command p) " "))
1086 ;; Wait for initial prompt.
1087 (tramp-adb-wait-for-output p)
1088 (unless (eq 'run (process-status p))
1089 (tramp-error vec 'file-error "Terminated!"))
1090 (set-process-query-on-exit-flag p nil)
1092 ;; Check whether the properties have been changed. If
1093 ;; yes, this is a strong indication that we must expire all
1094 ;; connection properties. We start again.
1095 (tramp-message vec 5 "Checking system information")
1096 (tramp-adb-send-command
1097 vec "echo \\\"`getprop ro.product.model` `getprop ro.product.version` `getprop ro.build.version.release`\\\"")
1099 (tramp-get-connection-property vec "getprop" nil))
1101 (tramp-set-connection-property
1103 (with-current-buffer (tramp-get-connection-buffer vec)
1104 ;; Read the expression.
1105 (goto-char (point-min))
1106 (read (current-buffer))))))
1107 (when (and (stringp old-getprop)
1108 (not (string-equal old-getprop new-getprop)))
1112 "Connection reset, because remote host changed from `%s' to `%s'"
1113 old-getprop new-getprop)
1114 (tramp-adb-maybe-open-connection vec)))))))))
1116 (provide 'tramp-adb)
1117 ;;; tramp-adb.el ends here