[libvirt] [PATCH v2] add cd and pwd commands to virsh

Daniel P. Berrange berrange at redhat.com
Fri Jul 10 19:17:06 UTC 2009


On Fri, Jul 10, 2009 at 06:22:41PM +0200, Paolo Bonzini wrote:

> +static int
> +cmdCd(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
> +{
> +    const char *dir;
> +    int found;
> +
> +    if (!ctl->imode) {
> +        vshError(ctl, FALSE, _("cd: command valid only in interactive mode"));
> +        return -1;
> +    }
> +
> +    dir = vshCommandOptString(cmd, "dir", &found);
> +    if (!found)
> +        dir = getenv ("HOME");

It is perhaps more reliable to use virGetUserDirectory()
here, since that gets the home dir out of /etc/passwd using
getpwuid, not relying on potentially missing environment
variables.

> +    if (!dir)
> +        dir = "/";
> +
> +    if (chdir (dir) == -1) {
> +        vshError(ctl, FALSE, _("cd: %s: %s"), strerror (errno), dir);
> +        return -1;
> +    }
> +
> +    return 0;
> +}
> +
> +/*
> + * "pwd" command
> + */
> +static const vshCmdInfo info_pwd[] = {
> +    {"help", gettext_noop("print the current directory")},
> +    {"desc", gettext_noop("Print the current directory.")},
> +    {NULL, NULL}
> +};
> +
> +static int
> +cmdPwd(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
> +{
> +    char *cwd;
> +    size_t path_max;
> +    int err = TRUE;
> +
> +    path_max = (size_t) PATH_MAX + 2;
> +    cwd = vshMalloc (ctl, path_max);
> +    while (cwd) {
> +        err = getcwd (cwd, path_max) == NULL;
> +        if (!err || errno != ERANGE)
> +            break;
> +
> +        path_max *= 2;
> +        cwd = vshRealloc (ctl, cwd, path_max);
> +    }
> +
> +    if (err)
> +        vshError(ctl, FALSE, _("pwd: cannot get current directory: %s"), strerror (errno));
> +    else
> +        vshPrint (ctl, _("%s\n"), cwd);
> +
> +    free (cwd);
> +    return !err;
> +}
> +
> +/*


Daniel
-- 
|: Red Hat, Engineering, London   -o-   http://people.redhat.com/berrange/ :|
|: http://libvirt.org  -o-  http://virt-manager.org  -o-  http://ovirt.org :|
|: http://autobuild.org       -o-         http://search.cpan.org/~danberr/ :|
|: GnuPG: 7D3B9505  -o-  F3C9 553F A1DA 4AC2 5648 23C1 B3DF F742 7D3B 9505 :|




More information about the libvir-list mailing list