001/*
002 * (C) Copyright 2006-2010 Nuxeo SAS (http://nuxeo.com/) and contributors.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the GNU Lesser General Public License
006 * (LGPL) version 2.1 which accompanies this distribution, and is available at
007 * http://www.gnu.org/licenses/lgpl.html
008 *
009 * This library is distributed in the hope that it will be useful,
010 * but WITHOUT ANY WARRANTY; without even the implied warranty of
011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012 * Lesser General Public License for more details.
013 *
014 * Contributors:
015 *     bstefanescu
016 */
017package org.nuxeo.shell.automation.cmds;
018
019import org.nuxeo.ecm.automation.client.model.Document;
020import org.nuxeo.shell.Argument;
021import org.nuxeo.shell.Command;
022import org.nuxeo.shell.Context;
023import org.nuxeo.shell.ShellConsole;
024import org.nuxeo.shell.ShellException;
025import org.nuxeo.shell.automation.DocRefCompletor;
026import org.nuxeo.shell.automation.DocumentHelper;
027import org.nuxeo.shell.automation.RemoteContext;
028
029/**
030 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
031 */
032@Command(name = "tree", help = "List a subtree")
033public class Tree implements Runnable {
034
035    @Context
036    protected RemoteContext ctx;
037
038    @Argument(name = "doc", index = 0, required = false, completor = DocRefCompletor.class, help = "A document to list its subtree. If not specified list the current document subtree. To use UID references prefix them with 'doc:'.")
039    protected String path;
040
041    public void run() {
042        ShellConsole console = ctx.getShell().getConsole();
043        Document root = ctx.resolveDocument(path);
044        printTree(console, root, "");
045    }
046
047    protected void printTree(ShellConsole console, Document root, String prefix) {
048        try {
049            DocumentHelper.printName(console, root, prefix.length() == 0 ? prefix : prefix + "+- ");
050            prefix += "|  ";
051            for (Document doc : ctx.getDocumentService().getChildren(root)) {
052                printTree(console, doc, prefix);
053            }
054        } catch (Exception e) {
055            throw new ShellException("Failed to list document " + path, e);
056        }
057    }
058}