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 v))
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 v (or id-format 'integer))))
349 (lambda (x) (cons (expand-file-name (car x) directory) (cdr x)))
352 (setq result (sort result (lambda (x y) (string< (car x) (car y))))))
355 (if (or (not match) (string-match match (car x)))
359 (defun tramp-adb-get-ls-command (vec)
360 (with-tramp-connection-property vec "ls"
361 (tramp-message vec 5 "Finding a suitable `ls' command")
362 (if (zerop (tramp-adb-command-exit-status
363 vec "ls --color=never -al /dev/null"))
364 ;; On CyanogenMod based system BusyBox is used and "ls" output
365 ;; coloring is enabled by default. So we try to disable it
370 (defun tramp-adb-get-toolbox (vec)
371 "Get shell toolbox implementation: `toolbox' for orginal distributions
372 or `busybox' for CynagenMode based distributions"
373 (with-tramp-connection-property vec "toolbox"
374 (tramp-message vec 5 "Checking shell toolbox implementation")
376 ((zerop (tramp-adb-command-exit-status vec "busybox")) 'busybox)
377 ((zerop (tramp-adb-command-exit-status vec "toolbox")) 'toolbox)
380 (defun tramp-adb--gnu-switches-to-ash
382 "Almquist shell can't handle multiple arguments.
383 Convert (\"-al\") to (\"-a\" \"-l\"). Remove arguments like \"--dired\"."
387 (replace-regexp-in-string
389 (replace-regexp-in-string "^-" "" s)))
390 ;; FIXME: Warning about removed switches (long and non-dash).
394 (and (not (string-match "\\(^--\\|^[^-]\\)" s)) s))
397 (defun tramp-adb-handle-insert-directory
398 (filename switches &optional wildcard full-directory-p)
399 "Like `insert-directory' for Tramp files."
400 (when (stringp switches)
401 (setq switches (tramp-adb--gnu-switches-to-ash (split-string switches))))
402 (with-parsed-tramp-file-name (file-truename filename) nil
403 (with-current-buffer (tramp-get-buffer v)
404 (let ((name (tramp-shell-quote-argument (directory-file-name localname)))
405 (switch-d (member "-d" switches))
406 (switch-t (member "-t" switches))
407 (switches (mapconcat 'identity (remove "-t" switches) " ")))
408 (tramp-adb-barf-unless-okay
409 v (format "%s %s %s" (tramp-adb-get-ls-command v) switches name)
410 "Cannot insert directory listing: %s" filename)
412 ;; We insert also filename/. and filename/.., because "ls" doesn't.
413 (narrow-to-region (point) (point))
415 (tramp-adb-barf-unless-okay
416 v (format "%s -d %s %s %s"
417 (tramp-adb-get-ls-command v)
419 (concat (file-name-as-directory name) ".")
420 (concat (file-name-as-directory name) ".."))
421 "Cannot insert directory listing: %s" filename))
423 (tramp-adb-sh-fix-ls-output switch-t)))
424 (insert-buffer-substring (tramp-get-buffer v))))
426 (defun tramp-adb-sh-fix-ls-output (&optional sort-by-time)
427 "Insert dummy 0 in empty size columns.
428 Androids \"ls\" command doesn't insert size column for directories:
429 Emacs dired can't find files."
431 ;; Insert missing size.
432 (goto-char (point-min))
434 (search-forward-regexp
435 "[[:space:]]\\([[:space:]][0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9][[:space:]]\\)" nil t)
436 (replace-match "0\\1" "\\1" nil)
437 ;; Insert missing "/".
438 (when (looking-at "[0-9][0-9]:[0-9][0-9][[:space:]]+$")
442 (let* ((lines (split-string (buffer-string) "\n" t))
447 'tramp-adb-ls-output-time-less-p
448 'tramp-adb-ls-output-name-less-p))))
449 (delete-region (point-min) (point-max))
450 (insert " " (mapconcat 'identity sorted-lines "\n ")))
451 ;; Add final newline.
452 (goto-char (point-max))
453 (unless (= (point) (line-beginning-position))
457 (defun tramp-adb-ls-output-time-less-p (a b)
458 "Sort \"ls\" output by time, descending."
460 (string-match tramp-adb-ls-date-regexp a)
461 (setq time-a (apply 'encode-time (parse-time-string (match-string 0 a))))
462 (string-match tramp-adb-ls-date-regexp b)
463 (setq time-b (apply 'encode-time (parse-time-string (match-string 0 b))))
464 (time-less-p time-b time-a)))
466 (defun tramp-adb-ls-output-name-less-p (a b)
467 "Sort \"ls\" output by name, ascending."
469 (string-match dired-move-to-filename-regexp a)
470 (setq posa (match-end 0))
471 (string-match dired-move-to-filename-regexp b)
472 (setq posb (match-end 0))
473 (string-lessp (substring a posa) (substring b posb))))
475 (defun tramp-adb-handle-make-directory (dir &optional parents)
476 "Like `make-directory' for Tramp files."
477 (setq dir (expand-file-name dir))
478 (with-parsed-tramp-file-name dir nil
480 (let ((par (expand-file-name ".." dir)))
481 (unless (file-directory-p par)
482 (make-directory par parents))))
483 (tramp-adb-barf-unless-okay
484 v (format "mkdir %s" (tramp-shell-quote-argument localname))
485 "Couldn't make directory %s" dir)
486 (tramp-flush-directory-property v (file-name-directory localname))))
488 (defun tramp-adb-handle-delete-directory (directory &optional recursive)
489 "Like `delete-directory' for Tramp files."
490 (setq directory (expand-file-name directory))
491 (with-parsed-tramp-file-name directory nil
492 (tramp-flush-file-property v (file-name-directory localname))
493 (tramp-flush-directory-property v localname)
494 (tramp-adb-barf-unless-okay
496 (if recursive "rm -r" "rmdir")
497 (tramp-shell-quote-argument localname))
498 "Couldn't delete %s" directory)))
500 (defun tramp-adb-handle-delete-file (filename &optional trash)
501 "Like `delete-file' for Tramp files."
502 (setq filename (expand-file-name filename))
503 (with-parsed-tramp-file-name filename nil
504 (tramp-flush-file-property v (file-name-directory localname))
505 (tramp-flush-file-property v localname)
506 (tramp-adb-barf-unless-okay
507 v (format "rm %s" (tramp-shell-quote-argument localname))
508 "Couldn't delete %s" filename)))
510 (defun tramp-adb-handle-file-name-all-completions (filename directory)
511 "Like `file-name-all-completions' for Tramp files."
514 (with-parsed-tramp-file-name directory nil
515 (with-tramp-file-property v localname "file-name-all-completions"
517 (tramp-adb-send-command
519 (tramp-adb-get-ls-command v)
520 (tramp-shell-quote-argument localname)))
523 (if (file-directory-p f)
524 (file-name-as-directory f)
526 (with-current-buffer (tramp-get-buffer v)
530 (lambda (l) (and (not (string-match "^[[:space:]]*$" l)) l))
531 (split-string (buffer-string) "\n"))))))))))
533 (defun tramp-adb-handle-file-local-copy (filename)
534 "Like `file-local-copy' for Tramp files."
535 (with-parsed-tramp-file-name filename nil
536 (unless (file-exists-p (file-truename filename))
539 "Cannot make local copy of non-existing file `%s'" filename))
540 (let ((tmpfile (tramp-compat-make-temp-file filename)))
541 (with-tramp-progress-reporter
542 v 3 (format "Fetching %s to tmp file %s" filename tmpfile)
543 (when (tramp-adb-execute-adb-command v "pull" localname tmpfile)
544 (delete-file tmpfile)
546 v 'file-error "Cannot make local copy of file `%s'" filename))
547 (set-file-modes tmpfile (file-modes filename)))
550 (defun tramp-adb-handle-file-writable-p (filename)
551 "Like `tramp-sh-handle-file-writable-p'.
552 But handle the case, if the \"test\" command is not available."
553 (with-parsed-tramp-file-name filename nil
554 (with-tramp-file-property v localname "file-writable-p"
555 (if (tramp-adb-find-test-command v)
556 (if (file-exists-p filename)
558 (tramp-adb-command-exit-status
559 v (format "test -w %s" (tramp-shell-quote-argument localname))))
561 (file-directory-p (file-name-directory filename))
562 (file-writable-p (file-name-directory filename))))
564 ;; Missing "test" command on Android < 4.
565 (let ((rw-path "/data/data"))
568 "Not implemented yet (assuming \"/data/data\" is writable): %s"
570 (and (>= (length localname) (length rw-path))
571 (string= (substring localname 0 (length rw-path))
574 (defun tramp-adb-handle-write-region
575 (start end filename &optional append visit lockname confirm)
576 "Like `write-region' for Tramp files."
577 (setq filename (expand-file-name filename))
578 (with-parsed-tramp-file-name filename nil
581 v 'file-error "Cannot append to file using Tramp (`%s')" filename))
582 (when (and confirm (file-exists-p filename))
583 (unless (y-or-n-p (format "File %s exists; overwrite anyway? "
585 (tramp-error v 'file-error "File not overwritten")))
586 ;; We must also flush the cache of the directory, because
587 ;; `file-attributes' reads the values from there.
588 (tramp-flush-file-property v (file-name-directory localname))
589 (tramp-flush-file-property v localname)
590 (let* ((curbuf (current-buffer))
591 (tmpfile (tramp-compat-make-temp-file filename)))
592 (tramp-run-real-handler
594 (list start end tmpfile append 'no-message lockname confirm))
595 (with-tramp-progress-reporter
596 v 3 (format "Moving tmp file %s to %s" tmpfile filename)
598 (when (tramp-adb-execute-adb-command v "push" tmpfile localname)
599 (tramp-error v 'file-error "Cannot write: `%s' filename"))
600 (delete-file tmpfile)))
602 (unless (equal curbuf (current-buffer))
605 "Buffer has changed from `%s' to `%s'" curbuf (current-buffer))))))
607 (defun tramp-adb-handle-set-file-modes (filename mode)
608 "Like `set-file-modes' for Tramp files."
609 (with-parsed-tramp-file-name filename nil
610 (tramp-flush-file-property v localname)
611 (tramp-adb-barf-unless-okay
612 v (format "chmod %s %s" (tramp-compat-decimal-to-octal mode) localname)
613 "Error while changing file's mode %s" filename)))
615 (defun tramp-adb-handle-copy-file
616 (filename newname &optional ok-if-already-exists keep-date
617 preserve-uid-gid preserve-extended-attributes)
618 "Like `copy-file' for Tramp files.
619 PRESERVE-UID-GID and PRESERVE-EXTENDED-ATTRIBUTES are completely ignored."
620 (setq filename (expand-file-name filename)
621 newname (expand-file-name newname))
623 (if (file-directory-p filename)
624 (copy-directory filename newname keep-date t)
625 (with-tramp-progress-reporter
626 (tramp-dissect-file-name (if (file-remote-p filename) filename newname))
627 0 (format "Copying %s to %s" filename newname)
629 (let ((tmpfile (file-local-copy filename)))
634 (rename-file tmpfile newname ok-if-already-exists)
636 (delete-file tmpfile)
637 (signal (car err) (cdr err))))
640 (when (file-directory-p newname)
642 (expand-file-name (file-name-nondirectory filename) newname)))
644 (with-parsed-tramp-file-name newname nil
645 (when (and (not ok-if-already-exists)
646 (file-exists-p newname))
647 (tramp-error v 'file-already-exists newname))
649 ;; We must also flush the cache of the directory, because
650 ;; `file-attributes' reads the values from there.
651 (tramp-flush-file-property v (file-name-directory localname))
652 (tramp-flush-file-property v localname)
653 (when (tramp-adb-execute-adb-command v "push" filename localname)
655 v 'file-error "Cannot copy `%s' `%s'" filename newname))))))
657 ;; KEEP-DATE handling.
659 (set-file-times newname (nth 5 (file-attributes filename))))))
661 (defun tramp-adb-handle-rename-file
662 (filename newname &optional ok-if-already-exists)
663 "Like `rename-file' for Tramp files."
664 (setq filename (expand-file-name filename)
665 newname (expand-file-name newname))
667 (with-parsed-tramp-file-name
668 (if (file-remote-p filename) filename newname) nil
669 (with-tramp-progress-reporter
670 v 0 (format "Renaming %s to %s" newname filename)
672 (if (and (tramp-equal-remote filename newname)
673 (not (file-directory-p filename)))
675 (when (and (not ok-if-already-exists)
676 (file-exists-p newname))
677 (tramp-error v 'file-already-exists newname))
678 ;; We must also flush the cache of the directory, because
679 ;; `file-attributes' reads the values from there.
680 (tramp-flush-file-property v (file-name-directory localname))
681 (tramp-flush-file-property v localname)
683 (tramp-adb-barf-unless-okay
684 v (format "mv %s %s" (file-remote-p filename 'localname) localname)
685 "Error renaming %s to %s" filename newname))
688 (copy-file filename newname ok-if-already-exists t t)
689 (delete-file filename)))))
691 (defun tramp-adb-handle-process-file
692 (program &optional infile destination display &rest args)
693 "Like `process-file' for Tramp files."
694 ;; The implementation is not complete yet.
695 (when (and (numberp destination) (zerop destination))
696 (error "Implementation does not handle immediate return"))
698 (with-parsed-tramp-file-name default-directory nil
699 (let (command input tmpinput stderr tmpstderr outbuf ret)
701 (setq command (mapconcat 'tramp-shell-quote-argument
702 (cons program args) " "))
705 (setq input "/dev/null")
706 (setq infile (expand-file-name infile))
707 (if (tramp-equal-remote default-directory infile)
708 ;; INFILE is on the same remote host.
709 (setq input (with-parsed-tramp-file-name infile nil localname))
710 ;; INFILE must be copied to remote host.
711 (setq input (tramp-make-tramp-temp-file v)
712 tmpinput (tramp-make-tramp-file-name method user host input))
713 (copy-file infile tmpinput t)))
714 (when input (setq command (format "%s <%s" command input)))
719 ((bufferp destination)
720 (setq outbuf destination))
722 ((stringp destination)
723 (setq outbuf (get-buffer-create destination)))
724 ;; (REAL-DESTINATION ERROR-DESTINATION)
728 ((bufferp (car destination))
729 (setq outbuf (car destination)))
730 ((stringp (car destination))
731 (setq outbuf (get-buffer-create (car destination))))
733 (setq outbuf (current-buffer))))
736 ((stringp (cadr destination))
737 (setcar (cdr destination) (expand-file-name (cadr destination)))
738 (if (tramp-equal-remote default-directory (cadr destination))
739 ;; stderr is on the same remote host.
740 (setq stderr (with-parsed-tramp-file-name
741 (cadr destination) nil localname))
742 ;; stderr must be copied to remote host. The temporary
743 ;; file must be deleted after execution.
744 (setq stderr (tramp-make-tramp-temp-file v)
745 tmpstderr (tramp-make-tramp-file-name
746 method user host stderr))))
747 ;; stderr to be discarded.
748 ((null (cadr destination))
749 (setq stderr "/dev/null"))))
752 (setq outbuf (current-buffer))))
753 (when stderr (setq command (format "%s 2>%s" command stderr)))
755 ;; Send the command. It might not return in time, so we protect
756 ;; it. Call it in a subshell, in order to preserve working
762 (tramp-adb-barf-unless-okay
763 v (format "(cd %s; %s)"
764 (tramp-shell-quote-argument localname)
767 ;; We should show the output anyway.
769 (with-current-buffer outbuf
770 (insert-buffer-substring (tramp-get-connection-buffer v)))
771 (when display (display-buffer outbuf))))
772 ;; When the user did interrupt, we should do it also. We use
773 ;; return code -1 as marker.
775 (kill-buffer (tramp-get-connection-buffer v))
779 (kill-buffer (tramp-get-connection-buffer v))
782 ;; Provide error file.
783 (when tmpstderr (rename-file tmpstderr (cadr destination) t))
785 ;; Cleanup. We remove all file cache values for the connection,
786 ;; because the remote process could have changed them.
787 (when tmpinput (delete-file tmpinput))
789 ;; `process-file-side-effects' has been introduced with GNU
790 ;; Emacs 23.2. If set to `nil', no remote file will be changed
791 ;; by `program'. If it doesn't exist, we assume its default
793 (unless (and (boundp 'process-file-side-effects)
794 (not (symbol-value 'process-file-side-effects)))
795 (tramp-flush-directory-property v ""))
797 ;; Return exit status.
802 (defun tramp-adb-handle-shell-command
803 (command &optional output-buffer error-buffer)
804 "Like `shell-command' for Tramp files."
805 (let* ((asynchronous (string-match "[ \t]*&[ \t]*\\'" command))
806 ;; We cannot use `shell-file-name' and `shell-command-switch',
807 ;; they are variables of the local host.
808 (args (list "sh" "-c" (substring command 0 asynchronous)))
812 ((bufferp output-buffer) output-buffer)
813 ((stringp output-buffer) (get-buffer-create output-buffer))
815 (setq current-buffer-p t)
817 (t (get-buffer-create
819 "*Async Shell Command*"
820 "*Shell Command Output*")))))
823 ((bufferp error-buffer) error-buffer)
824 ((stringp error-buffer) (get-buffer-create error-buffer))))
826 (if (and (not asynchronous) error-buffer)
827 (with-parsed-tramp-file-name default-directory nil
828 (list output-buffer (tramp-make-tramp-temp-file v)))
830 (p (get-buffer-process output-buffer)))
832 ;; Check whether there is another process running. Tramp does not
833 ;; support 2 (asynchronous) processes in parallel.
835 (if (yes-or-no-p "A command is running. Kill it? ")
836 (ignore-errors (kill-process p))
837 (error "Shell command in progress")))
841 (barf-if-buffer-read-only)
843 (with-current-buffer output-buffer
844 (setq buffer-read-only nil)
847 (if (and (not current-buffer-p) (integerp asynchronous))
850 (apply 'start-file-process "*Async Shell*" buffer args)
852 (pop-to-buffer output-buffer)
853 (setq mode-line-process '(":%s"))
858 (apply 'process-file (car args) nil buffer nil (cdr args))
859 ;; Insert error messages if they were separated.
861 (with-current-buffer error-buffer
862 (insert-file-contents (cadr buffer)))
863 (delete-file (cadr buffer)))
865 ;; This is like exchange-point-and-mark, but doesn't
866 ;; activate the mark. It is cleaner to avoid activation,
867 ;; even though the command loop would deactivate the mark
868 ;; because we inserted text.
869 (goto-char (prog1 (mark t)
870 (set-marker (mark-marker) (point)
872 ;; There's some output, display it.
873 (when (with-current-buffer output-buffer (> (point-max) (point-min)))
874 (if (functionp 'display-message-or-buffer)
875 (tramp-compat-funcall 'display-message-or-buffer output-buffer)
876 (pop-to-buffer output-buffer))))))))
878 ;; We use BUFFER also as connection buffer during setup. Because of
879 ;; this, its original contents must be saved, and restored once
880 ;; connection has been setup.
881 (defun tramp-adb-handle-start-file-process (name buffer program &rest args)
882 "Like `start-file-process' for Tramp files."
883 (with-parsed-tramp-file-name default-directory nil
884 ;; When PROGRAM is nil, we just provide a tty.
886 (when (stringp program)
888 (tramp-shell-quote-argument localname)
889 (mapconcat 'tramp-shell-quote-argument
890 (cons program args) " "))))
891 (tramp-process-connection-type
892 (or (null program) tramp-process-connection-type))
893 (bmp (and (buffer-live-p buffer) (buffer-modified-p buffer)))
900 ;; BUFFER can be nil. We use a temporary buffer.
901 (setq buffer (generate-new-buffer tramp-temp-buffer-name)))
902 (while (get-process name1)
903 ;; NAME must be unique as process name.
905 name1 (format "%s<%d>" name i)))
907 ;; Set the new process properties.
908 (tramp-set-connection-property v "process-name" name)
909 (tramp-set-connection-property v "process-buffer" buffer)
910 ;; Activate narrowing in order to save BUFFER contents.
911 ;; Clear also the modification time; otherwise we might
912 ;; be interrupted by `verify-visited-file-modtime'.
913 (with-current-buffer (tramp-get-connection-buffer v)
914 (let ((buffer-undo-list t))
915 (clear-visited-file-modtime)
916 (narrow-to-region (point-max) (point-max))
919 (tramp-adb-send-command v command)
920 ;; Open the connection.
921 (tramp-adb-maybe-open-connection v))))
922 (let ((p (tramp-get-connection-process v)))
923 ;; Set sentinel and query flag for this process.
924 (tramp-set-connection-property p "vector" v)
925 (set-process-sentinel p 'tramp-process-sentinel)
926 (tramp-compat-set-process-query-on-exit-flag p t)
930 (with-current-buffer (tramp-get-connection-buffer v)
931 (if (string-match tramp-temp-buffer-name (buffer-name))
933 (set-process-buffer (tramp-get-connection-process v) nil)
934 (kill-buffer (current-buffer)))
935 (set-buffer-modified-p bmp)))
936 (tramp-set-connection-property v "process-name" nil)
937 (tramp-set-connection-property v "process-buffer" nil)))))
939 ;; Android < 4 doesn't provide test command.
941 (defun tramp-adb-handle-file-exists-p (filename)
942 "Like `file-exists-p' for Tramp files."
943 (with-parsed-tramp-file-name filename nil
944 (with-tramp-file-property v localname "file-exists-p"
945 (file-attributes filename))))
949 (defun tramp-adb-execute-adb-command (vec &rest args)
950 "Returns nil on success error-output on failure."
951 (when (tramp-file-name-host vec)
952 (setq args (append (list "-s" (tramp-file-name-host vec)) args)))
955 (unless (zerop (apply 'call-process (tramp-adb-program) nil t nil args))
959 (tramp-adb-program) (mapconcat 'identity args " ") (buffer-string)))))
961 (defun tramp-adb-find-test-command (vec)
962 "Checks, whether the ash has a builtin \"test\" command.
963 This happens for Android >= 4.0."
964 (with-tramp-connection-property vec "test"
965 (zerop (tramp-adb-command-exit-status vec "type test"))))
967 ;; Connection functions
969 (defun tramp-adb-send-command (vec command)
970 "Send the COMMAND to connection VEC."
971 (tramp-adb-maybe-open-connection vec)
972 (tramp-message vec 6 "%s" command)
973 (tramp-send-string vec command)
974 ;; fixme: Race condition
975 (tramp-adb-wait-for-output (tramp-get-connection-process vec))
976 (with-current-buffer (tramp-get-connection-buffer vec)
978 (goto-char (point-min))
979 ;; We can't use stty to disable echo of command.
980 (delete-matching-lines (regexp-quote command))
981 ;; When the local machine is W32, there are still trailing ^M.
982 ;; There must be a better solution by setting the correct coding
983 ;; system, but this requires changes in core Tramp.
984 (goto-char (point-min))
985 (while (re-search-forward "\r+$" nil t)
986 (replace-match "" nil nil)))))
988 (defun tramp-adb-barf-unless-okay (vec command fmt &rest args)
989 "Run COMMAND, check exit status, throw error if exit status not okay.
990 FMT and ARGS are passed to `error'."
991 (tramp-adb-send-command vec (format "%s; echo tramp_exit_status $?" command))
992 (with-current-buffer (tramp-get-connection-buffer vec)
993 (goto-char (point-max))
994 (unless (re-search-backward "tramp_exit_status [0-9]+" nil t)
996 vec 'file-error "Couldn't find exit status of `%s'" command))
997 (skip-chars-forward "^ ")
998 (unless (zerop (read (current-buffer)))
999 (apply 'tramp-error vec 'file-error fmt args))
1000 (let (buffer-read-only)
1001 (delete-region (match-beginning 0) (point-max)))))
1003 (defun tramp-adb-command-exit-status
1005 "Run COMMAND and return its exit status.
1006 Sends `echo $?' along with the COMMAND for checking the exit status. If
1007 COMMAND is nil, just sends `echo $?'. Returns the exit status found."
1008 (tramp-adb-send-command vec (format "%s; echo tramp_exit_status $?" command))
1009 (with-current-buffer (tramp-get-connection-buffer vec)
1010 (goto-char (point-max))
1011 (unless (re-search-backward "tramp_exit_status [0-9]+" nil t)
1013 vec 'file-error "Couldn't find exit status of `%s'" command))
1014 (skip-chars-forward "^ ")
1015 (read (current-buffer))))
1017 (defun tramp-adb-wait-for-output (proc &optional timeout)
1018 "Wait for output from remote command."
1019 (unless (buffer-live-p (process-buffer proc))
1020 (delete-process proc)
1021 (tramp-error proc 'file-error "Process `%s' not available, try again" proc))
1022 (with-current-buffer (process-buffer proc)
1023 (if (tramp-wait-for-regexp proc timeout tramp-adb-prompt)
1024 (let (buffer-read-only)
1025 (goto-char (point-min))
1026 ;; ADB terminal sends "^H" sequences.
1027 (when (re-search-forward "<\b+" (point-at-eol) t)
1029 (delete-region (point-min) (point)))
1030 ;; Delete the prompt.
1031 (goto-char (point-min))
1032 (when (re-search-forward tramp-adb-prompt (point-at-eol) t)
1034 (delete-region (point-min) (point)))
1035 (goto-char (point-max))
1036 (re-search-backward tramp-adb-prompt nil t)
1037 (delete-region (point) (point-max)))
1041 "[[Remote adb prompt `%s' not found in %d secs]]"
1042 tramp-adb-prompt timeout)
1045 "[[Remote prompt `%s' not found]]" tramp-adb-prompt)))))
1047 (defun tramp-adb-maybe-open-connection (vec)
1048 "Maybe open a connection VEC.
1049 Does not do anything if a connection is already open, but re-opens the
1050 connection if a previous connection has died for some reason."
1051 (let* ((buf (tramp-get-connection-buffer vec))
1052 (p (get-buffer-process buf))
1053 (devices (mapcar 'cadr (tramp-adb-parse-device-names nil))))
1055 (and p (processp p) (memq (process-status p) '(run open)))
1057 (when (and p (processp p)) (delete-process p))
1059 (tramp-error vec 'file-error "No device connected"))
1060 (if (and (tramp-file-name-host vec)
1061 (not (member (tramp-file-name-host vec) devices)))
1064 "Device %s not connected" (tramp-file-name-host vec)))
1065 (if (and (not (eq (length devices) 1))
1066 (not (tramp-file-name-host vec)))
1069 "Multiple Devices connected: No Host/Device specified"))
1070 (with-tramp-progress-reporter vec 3 "Opening adb shell connection"
1071 (let* ((coding-system-for-read 'utf-8-dos) ;is this correct?
1072 (process-connection-type tramp-process-connection-type)
1073 (args (if (tramp-file-name-host vec)
1074 (list "-s" (tramp-file-name-host vec) "shell")
1076 (p (let ((default-directory
1077 (tramp-compat-temporary-file-directory)))
1078 (apply 'start-process (tramp-get-connection-name vec) buf
1079 (tramp-adb-program) args))))
1081 vec 6 "%s" (mapconcat 'identity (process-command p) " "))
1082 ;; Wait for initial prompt.
1083 (tramp-adb-wait-for-output p)
1084 (unless (eq 'run (process-status p))
1085 (tramp-error vec 'file-error "Terminated!"))
1086 (set-process-query-on-exit-flag p nil)
1088 ;; Check whether the properties have been changed. If
1089 ;; yes, this is a strong indication that we must expire all
1090 ;; connection properties. We start again.
1091 (tramp-message vec 5 "Checking system information")
1092 (tramp-adb-send-command
1093 vec "echo \\\"`getprop ro.product.model` `getprop ro.product.version` `getprop ro.build.version.release`\\\"")
1095 (tramp-get-connection-property vec "getprop" nil))
1097 (tramp-set-connection-property
1099 (with-current-buffer (tramp-get-connection-buffer vec)
1100 ;; Read the expression.
1101 (goto-char (point-min))
1102 (read (current-buffer))))))
1103 (when (and (stringp old-getprop)
1104 (not (string-equal old-getprop new-getprop)))
1108 "Connection reset, because remote host changed from `%s' to `%s'"
1109 old-getprop new-getprop)
1110 (tramp-adb-maybe-open-connection vec)))))))))
1112 (provide 'tramp-adb)
1113 ;;; tramp-adb.el ends here