OILS / builtin / dirs_osh.py View on Github | oils.pub

363 lines, 229 significant
1from __future__ import print_function
2
3from _devbuild.gen import arg_types
4from _devbuild.gen.runtime_asdl import cmd_value
5from core import error
6from core.error import e_usage
7from core import pyos
8from core import state
9from display import ui
10from core import vm
11from frontend import flag_util
12from frontend import typed_args
13from mycpp.mylib import log
14from pylib import os_path
15from pylib import path_lib
16from core.value import value,value_e
17from typing import cast
18
19import libc
20import posix_ as posix
21
22from typing import List, Optional, Any, TYPE_CHECKING
23if TYPE_CHECKING:
24 from osh.cmd_eval import CommandEvaluator
25
26_ = log
27
28
29class DirStack(object):
30 """For pushd/popd/dirs."""
31
32 def __init__(self):
33 # type: () -> None
34 self.stack = [] # type: List[str]
35 self.Reset() # Invariant: it always has at least ONE entry.
36
37 def Reset(self):
38 # type: () -> None
39 """ For dirs -c """
40 del self.stack[:]
41 self.stack.append(posix.getcwd())
42
43 def Replace(self, d):
44 # type: (str) -> None
45 """ For cd / """
46 self.stack[-1] = d
47
48 def Push(self, entry):
49 # type: (str) -> None
50 self.stack.append(entry)
51
52 def Pop(self):
53 # type: () -> Optional[str]
54 if len(self.stack) <= 1:
55 return None
56 self.stack.pop() # remove last
57 return self.stack[-1] # return second to last
58
59 def Iter(self):
60 # type: () -> List[str]
61 """Iterate in reverse order."""
62 # mycpp REWRITE:
63 #return reversed(self.stack)
64 ret = [] # type: List[str]
65 ret.extend(self.stack)
66 ret.reverse()
67 return ret
68
69
70class ctx_CdBlock(object):
71
72 def __init__(self, dir_stack, dest_dir, mem, errfmt, out_errs):
73 # type: (DirStack, str, state.Mem, ui.ErrorFormatter, List[bool]) -> None
74 dir_stack.Push(dest_dir)
75
76 self.dir_stack = dir_stack
77 self.mem = mem
78 self.errfmt = errfmt
79 self.out_errs = out_errs
80
81 def __enter__(self):
82 # type: () -> None
83 pass
84
85 def __exit__(self, type, value, traceback):
86 # type: (Any, Any, Any) -> None
87 _PopDirStack('cd', self.mem, self.dir_stack, self.errfmt,
88 self.out_errs)
89
90
91class Cd(vm._Builtin):
92
93 def __init__(self, mem, dir_stack, cmd_ev, errfmt):
94 # type: (state.Mem, DirStack, CommandEvaluator, ui.ErrorFormatter) -> None
95 self.mem = mem
96 self.dir_stack = dir_stack
97 self.cmd_ev = cmd_ev # To run blocks
98 self.errfmt = errfmt
99
100 def Run(self, cmd_val):
101 # type: (cmd_value.Argv) -> int
102 attrs, arg_r = flag_util.ParseCmdVal('cd',
103 cmd_val,
104 accept_typed_args=True)
105 arg = arg_types.cd(attrs.attrs)
106
107 # If a block is passed, we do additional syntax checks
108 cmd_frag = typed_args.OptionalBlockAsFrag(cmd_val)
109
110 dest_dir, arg_loc = arg_r.Peek2()
111 if dest_dir is None:
112 if cmd_frag:
113 raise error.Usage(
114 'requires an argument when a block is passed',
115 cmd_val.arg_locs[0])
116 else:
117 dest_dir = self.mem.env_config.Get('HOME')
118 if dest_dir is None:
119 self.errfmt.Print_(
120 "cd got no argument, and $HOME isn't set")
121 return 1
122
123 # At most 1 arg is accepted
124 arg_r.Next()
125 if self.mem.exec_opts.strict_arg_parse():
126 arg_r.Done()
127
128 # shopt -s cdable_vars allows you to type cd my_dir_var instead of cd $my_dir_var
129 if self.mem.exec_opts.cdable_vars() and dest_dir != '-':
130 if not path_lib.isdir(dest_dir):
131 val = self.mem.GetValue(dest_dir)
132 if val.tag() == value_e.Str:
133 val_str = cast(value.Str, val)
134 dest_dir = val_str.s
135 # Bash echoes the resolved path to stdout
136 print(dest_dir)
137
138 if dest_dir == '-':
139 # Note: $OLDPWD isn't an env var; it's a global
140 try:
141 dest_dir = state.GetString(self.mem, 'OLDPWD')
142 print(dest_dir) # Shells print the directory
143 except error.Runtime as e:
144 self.errfmt.Print_(e.UserErrorString())
145 return 1
146
147 # Save a copy
148 old_pwd = self.mem.pwd
149
150 # Calculate absolute path, e.g. for 'cd ..'
151 # We chdir() to it, then set PWD to it.
152 # We can't call posix.getcwd() because it can raise OSError if the
153 # directory was removed (ENOENT)
154 abspath = os_path.join(old_pwd, dest_dir)
155 if arg.P:
156 # -P means resolve symbolic links, then process '..'
157 real_dest_dir = libc.realpath(abspath)
158 else:
159 # -L means process '..' first. This just does string manipulation.
160 # (But realpath afterward isn't correct?)
161 real_dest_dir = os_path.normpath(abspath)
162
163 #log('real_dest_dir %r', real_dest_dir)
164 err_num = pyos.Chdir(real_dest_dir)
165 if err_num != 0:
166 self.errfmt.Print_("cd %r: %s" %
167 (real_dest_dir, posix.strerror(err_num)),
168 blame_loc=arg_loc)
169 return 1
170
171 state.ExportGlobalString(self.mem, 'PWD', real_dest_dir)
172
173 # WEIRD: We need a copy that is NOT PWD, because the user could mutate
174 # PWD. Other shells use global variables.
175 self.mem.SetPwd(real_dest_dir)
176
177 if cmd_frag:
178 out_errs = [] # type: List[bool]
179 with ctx_CdBlock(self.dir_stack, real_dest_dir, self.mem,
180 self.errfmt, out_errs):
181 unused = self.cmd_ev.EvalCommandFrag(cmd_frag)
182 if len(out_errs):
183 return 1
184
185 else: # No block
186 state.ExportGlobalString(self.mem, 'OLDPWD', old_pwd)
187 self.dir_stack.Replace(real_dest_dir) # for pushd/popd/dirs
188
189 return 0
190
191
192WITH_LINE_NUMBERS = 1
193WITHOUT_LINE_NUMBERS = 2
194SINGLE_LINE = 3
195
196
197def _PrintDirStack(dir_stack, style, home_dir):
198 # type: (DirStack, int, Optional[str]) -> None
199 """ Helper for 'dirs' builtin """
200
201 if style == WITH_LINE_NUMBERS:
202 for i, entry in enumerate(dir_stack.Iter()):
203 print('%2d %s' % (i, ui.PrettyDir(entry, home_dir)))
204
205 elif style == WITHOUT_LINE_NUMBERS:
206 for entry in dir_stack.Iter():
207 print(ui.PrettyDir(entry, home_dir))
208
209 elif style == SINGLE_LINE:
210 parts = [ui.PrettyDir(entry, home_dir) for entry in dir_stack.Iter()]
211 s = ' '.join(parts)
212 print(s)
213
214
215class Pushd(vm._Builtin):
216
217 def __init__(self, mem, dir_stack, errfmt):
218 # type: (state.Mem, DirStack, ui.ErrorFormatter) -> None
219 self.mem = mem
220 self.dir_stack = dir_stack
221 self.errfmt = errfmt
222
223 def Run(self, cmd_val):
224 # type: (cmd_value.Argv) -> int
225 _, arg_r = flag_util.ParseCmdVal('pushd', cmd_val)
226
227 dir_arg, dir_arg_loc = arg_r.Peek2()
228 if dir_arg is None:
229 # TODO: It's suppose to try another dir before doing this?
230 self.errfmt.Print_('pushd: no other directory')
231 # bash oddly returns 1, not 2
232 return 1
233
234 arg_r.Next()
235 arg_r.Done()
236
237 # TODO: 'cd' uses normpath? Is that inconsistent?
238 dest_dir = os_path.abspath(dir_arg)
239 err_num = pyos.Chdir(dest_dir)
240 if err_num != 0:
241 self.errfmt.Print_("pushd: %r: %s" %
242 (dest_dir, posix.strerror(err_num)),
243 blame_loc=dir_arg_loc)
244 return 1
245
246 self.dir_stack.Push(dest_dir)
247 _PrintDirStack(self.dir_stack, SINGLE_LINE,
248 state.MaybeString(self.mem, 'HOME'))
249 state.ExportGlobalString(self.mem, 'PWD', dest_dir)
250 self.mem.SetPwd(dest_dir)
251 return 0
252
253
254def _PopDirStack(label, mem, dir_stack, errfmt, out_errs):
255 # type: (str, state.Mem, DirStack, ui.ErrorFormatter, List[bool]) -> bool
256 """ Helper for popd and cd { ... } """
257 dest_dir = dir_stack.Pop()
258 if dest_dir is None:
259 errfmt.Print_('%s: directory stack is empty' % label)
260 out_errs.append(True) # "return" to caller
261 return False
262
263 err_num = pyos.Chdir(dest_dir)
264 if err_num != 0:
265 # Happens if a directory is deleted in pushing and popping
266 errfmt.Print_('%s: %r: %s' %
267 (label, dest_dir, posix.strerror(err_num)))
268 out_errs.append(True) # "return" to caller
269 return False
270
271 state.SetGlobalString(mem, 'PWD', dest_dir)
272 mem.SetPwd(dest_dir)
273 return True
274
275
276class Popd(vm._Builtin):
277
278 def __init__(self, mem, dir_stack, errfmt):
279 # type: (state.Mem, DirStack, ui.ErrorFormatter) -> None
280 self.mem = mem
281 self.dir_stack = dir_stack
282 self.errfmt = errfmt
283
284 def Run(self, cmd_val):
285 # type: (cmd_value.Argv) -> int
286 _, arg_r = flag_util.ParseCmdVal('pushd', cmd_val)
287
288 extra, extra_loc = arg_r.Peek2()
289 if extra is not None:
290 e_usage('got extra argument', extra_loc)
291
292 out_errs = [] # type: List[bool]
293 _PopDirStack('popd', self.mem, self.dir_stack, self.errfmt, out_errs)
294 if len(out_errs):
295 return 1 # error
296
297 _PrintDirStack(self.dir_stack, SINGLE_LINE,
298 state.MaybeString(self.mem, ('HOME')))
299 return 0
300
301
302class Dirs(vm._Builtin):
303
304 def __init__(self, mem, dir_stack, errfmt):
305 # type: (state.Mem, DirStack, ui.ErrorFormatter) -> None
306 self.mem = mem
307 self.dir_stack = dir_stack
308 self.errfmt = errfmt
309
310 def Run(self, cmd_val):
311 # type: (cmd_value.Argv) -> int
312 attrs, arg_r = flag_util.ParseCmdVal('dirs', cmd_val)
313 arg = arg_types.dirs(attrs.attrs)
314
315 home_dir = state.MaybeString(self.mem, 'HOME')
316 style = SINGLE_LINE
317 arg_r.Done()
318
319 # Following bash order of flag priority
320 if arg.l:
321 home_dir = None # disable pretty ~
322 if arg.c:
323 self.dir_stack.Reset()
324 return 0
325 elif arg.v:
326 style = WITH_LINE_NUMBERS
327 elif arg.p:
328 style = WITHOUT_LINE_NUMBERS
329
330 _PrintDirStack(self.dir_stack, style, home_dir)
331 return 0
332
333
334class Pwd(vm._Builtin):
335 """
336 NOTE: pwd doesn't just call getcwd(), which returns a "physical" dir (not a
337 symlink).
338 """
339
340 def __init__(self, mem, errfmt):
341 # type: (state.Mem, ui.ErrorFormatter) -> None
342 self.mem = mem
343 self.errfmt = errfmt
344
345 def Run(self, cmd_val):
346 # type: (cmd_value.Argv) -> int
347 attrs, arg_r = flag_util.ParseCmdVal('pwd', cmd_val)
348 arg = arg_types.pwd(attrs.attrs)
349
350 if self.mem.exec_opts.strict_arg_parse():
351 arg_r.Done()
352
353 # NOTE: 'pwd' will succeed even if the directory has disappeared. Other
354 # shells behave that way too.
355 pwd = self.mem.pwd
356
357 # '-L' is the default behavior; no need to check it
358 # TODO: ensure that if multiple flags are provided, the *last* one overrides
359 # the others
360 if arg.P:
361 pwd = libc.realpath(pwd)
362 print(pwd)
363 return 0