1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
use {EXIT_ERROR, EXIT_SUCCESS, HOME, POLLED_TWICE};
use clap::{App, AppSettings, Arg, ArgMatches, Result as ClapResult};
use env::{AsyncIoEnvironment, ChangeWorkingDirectoryEnvironment, FileDescEnvironment,
          StringWrapper, ReportErrorEnvironment, VariableEnvironment, WorkingDirectoryEnvironment};
use io::FileDesc;
use future::{Async, EnvFuture, Poll};
use path::NormalizedPath;
use spawn::{ExitResult, Spawn};
use std::borrow::{Borrow, Cow};
use std::error::Error;
use std::fmt;
use std::io;
use std::path::{Component, Path, PathBuf};
use void::Void;

const CD: &str = "cd";
const ARG_LOGICAL: &str = "L";
const ARG_PHYSICAL: &str = "P";
const ARG_DIR: &str = "dir";

const LONG_ABOUT: &str = "Changes the current working directory to the specified
argument, provided the argument points to a valid directory. If the operation is
successful, $PWD will be updated with the new working directory, and $OLDPWD
will be set to the previous working directory.

If no argument is specified, the value of $HOME will be used as the new working
directory. If `-` is specified as an argument, the value of $OLDPWD will be used
instead, and the new working directory will be printed to standard output.

If the specified argument is neither an absolute path, nor begins with ./ or
../, the value of $CDPATH will be searched for alternative directory names
(seprated by `:`) to use as a prefix for the argument. If a valid directory is
discovered using an alternative directory name from $CDPATH, the new working
directory will be printed to standard output.";

lazy_static! {
    static ref CDPATH: String = { String::from("CDPATH") };
    static ref OLDPWD: String = { String::from("OLDPWD") };
}

#[derive(Debug)]
enum VarNotDefinedError {
    Home,
    OldPwd,
}

impl Error for VarNotDefinedError {
    fn description(&self) -> &str {
        match *self {
            VarNotDefinedError::Home => "HOME not set",
            VarNotDefinedError::OldPwd => "OLDPWD not set",
        }
    }
}

impl fmt::Display for VarNotDefinedError {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        write!(fmt, "{}", self.description())
    }
}

impl_generic_builtin_cmd_no_spawn! {
    /// Represents a `cd` builtin command which will
    /// change the current working directory.
    pub struct Cd;

    /// Creates a new `cd` builtin command with the provided arguments.
    pub fn cd();

    /// A future representing a fully spawned `cd` builtin command.
    pub struct SpawnedCd;

    /// A future representing a fully spawned `cd` builtin command
    /// which no longer requires an environment to run.
    pub struct CdFuture;
}

impl<T, I, E: ?Sized> Spawn<E> for Cd<I>
    where T: StringWrapper,
          I: Iterator<Item = T>,
          E: AsyncIoEnvironment
              + ChangeWorkingDirectoryEnvironment
              + FileDescEnvironment
              + ReportErrorEnvironment
              + VariableEnvironment
              + WorkingDirectoryEnvironment,
          E::FileHandle: Borrow<FileDesc>,
          E::VarName: Borrow<String> + From<String>,
          E::Var: Borrow<String> + From<String>,
{
    type EnvFuture = SpawnedCd<I>;
    type Future = ExitResult<CdFuture<E::WriteAll>>;
    type Error = Void;

    fn spawn(self, _env: &E) -> Self::EnvFuture {
        SpawnedCd {
            args: Some(self.args)
        }
    }
}

impl<I> SpawnedCd<I> {
    fn get_matches(&mut self) -> ClapResult<ArgMatches<'static>>
        where I: Iterator,
              I::Item: StringWrapper,
    {
        let app = App::new(CD)
            .setting(AppSettings::NoBinaryName)
            .setting(AppSettings::DisableVersion)
            .about("Changes the current working directory of the shell")
            .long_about(LONG_ABOUT)
            .arg(Arg::with_name(ARG_LOGICAL)
                 .short(ARG_LOGICAL)
                 .multiple(true)
                 .overrides_with(ARG_PHYSICAL)
                 .help("Handle paths logically (symbolic links will not be resolved)")
            )
            .arg(Arg::with_name(ARG_PHYSICAL)
                 .short(ARG_PHYSICAL)
                 .multiple(true)
                 .overrides_with(ARG_LOGICAL)
                 .help("Handle paths physically (all symbolic links resolved)")
            )
            .arg(Arg::with_name(ARG_DIR)
                 .help("An absolute or relative path for the what shall become the new working directory")
            );

        let app_args = self.args.take()
            .expect(POLLED_TWICE)
            .into_iter()
            .map(StringWrapper::into_owned);

        app.get_matches_from_safe(app_args)
    }
}

#[derive(Debug)]
struct Flags<'a> {
    resolve_symlinks: bool,
    dir: Option<&'a str>,
}

fn get_flags<'a>(matches: &'a ArgMatches<'a>) -> Flags<'a> {
    Flags {
        resolve_symlinks: matches.is_present(ARG_PHYSICAL),
        dir: matches.value_of(ARG_DIR),
    }
}

impl<T, I, E: ?Sized> EnvFuture<E> for SpawnedCd<I>
    where T: StringWrapper,
          I: Iterator<Item = T>,
          E: AsyncIoEnvironment
              + ChangeWorkingDirectoryEnvironment
              + FileDescEnvironment
              + ReportErrorEnvironment
              + VariableEnvironment
              + WorkingDirectoryEnvironment,
          E::FileHandle: Borrow<FileDesc>,
          E::VarName: Borrow<String> + From<String>,
          E::Var: Borrow<String> + From<String>,
{
    type Item = ExitResult<CdFuture<E::WriteAll>>;
    type Error = Void;

    fn poll(&mut self, env: &mut E) -> Poll<Self::Item, Self::Error> {
        let matches = try_and_report!(CD, self.get_matches(), env);
        let flags = get_flags(&matches);

        let should_print_pwd;
        let new_working_dir = {
            let (new_working_dir, spp) = try_and_report!(CD, get_dir_arg(flags.dir, env), env);
            should_print_pwd = spp;

            if flags.resolve_symlinks {
                match new_working_dir {
                    Cow::Borrowed(dir) => {
                        let mut normalized_path = NormalizedPath::new();
                        try_and_report!(CD, normalized_path.join_normalized_physical(dir), env);
                        normalized_path
                    },
                    Cow::Owned(b) => try_and_report!(CD, NormalizedPath::new_normalized_physical(b), env),
                }
            } else {
                match new_working_dir {
                    Cow::Borrowed(dir) => {
                        let mut normalized_path = NormalizedPath::new();
                        normalized_path.join_normalized_logial(dir);
                        normalized_path
                    },
                    Cow::Owned(buf) => NormalizedPath::new_normalized_logical(buf),
                }
            }
        };

        let new_working_dir = Cow::Owned(new_working_dir.into_inner());
        match try_and_report!(CD, perform_cd_change(should_print_pwd, new_working_dir, env), env) {
            Some(pwd) => generate_and_print_output!(CD, env, |_| -> Result<_, Void> {
                Ok(pwd.into_bytes())
            }),
            None => Ok(Async::Ready(ExitResult::from(EXIT_SUCCESS))),
        }
    }

    fn cancel(&mut self, _env: &mut E) {
        self.args.take();
    }
}

fn get_dir_arg<'a, E: ?Sized>(dir: Option<&'a str>, env: &'a E)
    -> Result<(Cow<'a, Path>, bool), VarNotDefinedError>
    where E: VariableEnvironment + WorkingDirectoryEnvironment,
          E::VarName: Borrow<String>,
          E::Var: Borrow<String>,
{
    let mut should_print_pwd = false;
    let dir = match dir {
        None => match env.var(&HOME) {
            Some(home) => Path::new((*home).borrow()),
            None => return Err(VarNotDefinedError::Home),
        },
        Some("-") => match env.var(&OLDPWD) {
            Some(oldpwd) => {
                should_print_pwd = true;
                Path::new((*oldpwd).borrow())
            },
            None => return Err(VarNotDefinedError::OldPwd),
        },
        Some(d) => Path::new(d),
    };

    let candidate = if is_cdpath_candidate(dir) {
        env.var(&CDPATH).and_then(|cdpath| cdpath_candidate(dir, cdpath.borrow().as_str(), env))
    } else {
        None
    };

    let dir = match candidate {
        Some(c) => {
            should_print_pwd = true;
            c
        },
        None => env.path_relative_to_working_dir(Cow::Borrowed(dir)),
    };

    Ok((dir, should_print_pwd))
}

fn is_cdpath_candidate(path: &Path) -> bool {
    if path.is_absolute() {
        return false;
    }

    match path.components().next() {
        Some(Component::CurDir) |
        Some(Component::ParentDir) => false,
        _ => true,
    }
}

fn cdpath_candidate<'a, E: ?Sized>(dir: &'a Path, cdpaths: &'a str, env: &'a E)
    -> Option<Cow<'a, Path>>
    where E: WorkingDirectoryEnvironment
{
    cdpaths.split(':')
        .map(PathBuf::from)
        .map(|buf| buf.join(dir))
        .map(|buf| env.path_relative_to_working_dir(Cow::Owned(buf)))
        .find(|path| path.is_dir())
}

fn perform_cd_change<E: ?Sized>(should_print_pwd: bool, new_working_dir: Cow<Path>, env: &mut E)
    -> io::Result<Option<String>>
    where E: ChangeWorkingDirectoryEnvironment
              + VariableEnvironment
              + WorkingDirectoryEnvironment,
          E::VarName: From<String>,
          E::Var: From<String>,
{
    let old_pwd = env.current_working_dir()
        .to_string_lossy()
        .into_owned();

    env.change_working_dir(new_working_dir)?;

    let pwd = env.current_working_dir()
        .to_string_lossy()
        .into_owned();

    let ret = if should_print_pwd {
        Some(format!("{}\n", pwd))
    } else {
        None
    };

    env.set_var(OLDPWD.clone().into(), old_pwd.into());
    env.set_var("PWD".to_owned().into(), pwd.into());

    Ok(ret)
}