-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcash.lua
1354 lines (1294 loc) · 53 KB
/
cash.lua
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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
--[[
MIT License
Copyright (c) 2019-2020 JackMacWindows
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
]]--
-- To silence IDE warnings
kernel = kernel
users = users
signal = signal
local topshell = _ENV.shell
local shell = {}
local multishell = {}
local pack = {}
_ENV.package = nil
_G.package = nil
package = nil
_ENV.require = nil
_G.require = nil
local start_time = os.epoch()
local args = {...}
local running = true
local shell_retval = 0
local shell_title = nil
local execCommand
local shell_env = _ENV
local pausedJob
local CCKernel2 = kernel and users and kernel.getPID
local OpusOS = kernel and kernel.hook
local make_require = dofile("/rom/modules/main/cc/require.lua").make
local expect = dofile("/rom/modules/main/cc/expect.lua").expect
if table.maxn == nil then table.maxn = function(t) local i = 1 while t[i] ~= nil do i = i + 1 end return i - 1 end end
local function trim(s) return string.match(s, '^()%s*$') and '' or string.match(s, '^%s*(.*%S)') end
HOME = "/"
SHELL = topshell and topshell.getRunningProgram() or "/usr/bin/cash"
PATH = topshell and string.gsub(topshell.path(), "%.:", "") or "/rom/programs:/rom/programs/fun:/rom/programs/rednet"
USER = CCKernel2 and users.getShortName(users.getuid()) or "root"
EDITOR = "edit"
OLDPWD = topshell and topshell.dir() or "/"
PWD = topshell and topshell.dir() or "/"
SHLVL = SHLVL and SHLVL + 1 or 1
TERM = "craftos"
COLORTERM = "16color"
local vars = {
PS1 = "\\s-\\v\\$ ",
PS2 = "> ",
IFS = "\n",
CASH = topshell and topshell.getRunningProgram() or "cash.lua",
CASH_VERSION = "0.3",
RANDOM = function() return math.random(0, 32767) end,
SECONDS = function() return math.floor((os.epoch() - start_time) / 1000) end,
HOSTNAME = os.getComputerLabel(),
TERMINATE_QUIT = "no",
["*"] = table.concat(args, " "),
["@"] = function() return table.concat(args, " ") end,
["#"] = #args,
["?"] = 0,
["0"] = topshell and topshell.getRunningProgram() or "cash.lua",
_ = topshell and topshell.getRunningProgram() or "cash.lua",
["$"] = CCKernel2 and kernel.getPID() or (OpusOS and kernel.getCurrent() or 0),
}
local aliases = topshell and topshell.aliases() or {}
local completion = topshell and topshell.getCompletionInfo() or {}
local if_table, if_statement = {}, 0
local while_table, while_statement = {}, 0
local case_table, case_statement = {}, 0
local function_name = nil
local functions = {}
local history = {}
local historyfile
local run_tokens
local function_running = false
local should_break = false
local no_funcs = false
local dirstack = {}
local jobs = {}
local completed_jobs = {}
local builtins
builtins = {
[":"] = function() return 0 end,
["."] = function(path)
path = fs.exists(path) and path or shell.resolve(path)
local file = io.open(path, "r")
if not file then return 1 end
vars.LINENUM = 1
for line in file:lines() do
shell.run(line)
vars.LINENUM = vars.LINENUM + 1
end
vars.LINENUM = nil
file:close()
end,
echo = function(...) print(...); return 0 end,
builtin = function(name, ...) return builtins[name](...) end,
cd = function(dir)
if not fs.isDir(shell.resolve(dir or "/")) then
printError("cash: cd: " .. dir .. ": No such file or directory")
return 1
end
OLDPWD = PWD
PWD = shell.resolve(dir or "/")
end,
command = function(...) no_funcs = true; shell.run(...); no_funcs = false; return vars["?"] end,
complete = function() end, -- TODO
eval = function(...) shell.run(...); return vars["?"] end,
exec = function(...) execCommand = table.concat({...}, ' '); shell.exit() end,
exit = shell.exit,
export = function(...)
local vars = {...}
if #vars == 0 or vars[1] == "-p" then for k,v in pairs(_ENV) do if type(v) == "string" or type(v) == "number" then print("export " .. k .. "=" .. v) end end else
for k,v in ipairs(vars) do
local kk, vv = string.match(v, "(.+)=(.+)")
if not (kk == nil or vv == nil) and (_ENV[kk] == nil or type(_ENV[kk]) == "string" or type(_ENV[kk]) == "number") then _ENV[kk] = vv end
end
end
end,
history = function(...)
if ({...})[1] == "-c" then
historyfile.close()
historyfile = fs.open(CCKernel2 and "/~/.cash_history" or ".cash_history", "w")
history = {}
return
end
local lines = {}
for k,v in ipairs(history) do print(" " .. k .. string.rep(" ", math.floor(math.log10(#history)) - math.floor(math.log10(k)) + 2) .. v) end
--textutils.tabulate(table.unpack(lines))
end,
jobs = function(...)
local filter = {...}
for k,v in pairs(jobs) do if v.cmd ~= "jobs" then
if #filter == 0 then print("[" .. k .. "]+ " .. (v.paused and "Paused" or "Running") .. " " .. v.cmd)
else for l,w in ipairs(filter) do
if k == w then print("[" .. k .. "]+ " .. (v.paused and "Paused" or "Running") .. " " .. v.cmd) end
end end
end end
end,
pushd = function(newdir)
table.insert(dirstack, PWD)
if newdir then PWD = shell.resolve(newdir) end
write((PWD == "" and "/" or PWD) .. " ")
for i = #dirstack, 1, -1 do write((dirstack[i] == "" and "/" or dirstack[i]) .. " ") end
print()
end,
popd = function()
if #dirstack == 0 then
printError("cash: popd: directory stack empty")
return -1
end
PWD = table.remove(dirstack, #dirstack)
write((PWD == "" and "/" or PWD) .. " ")
for i = #dirstack, 1, -1 do write((dirstack[i] == "" and "/" or dirstack[i]) .. " ") end
print()
end,
dirs = function()
write((PWD == "" and "/" or PWD) .. " ")
for i = #dirstack, 1, -1 do write((dirstack[i] == "" and "/" or dirstack[i]) .. " ") end
print()
end,
pwd = function() print(PWD) end,
read = function(var) -- TODO: expand
vars[var] = read()
end,
set = function(...)
local lvars = {...}
if #lvars == 0 then for k,v in pairs(vars) do print(k .. "=" .. v) end else
for k,v in ipairs(lvars) do
if string.find(v, "=") then
local kk, vv = string.match(v, "(.+)=(.+)")
vars[kk] = vv
end
end
end
end,
alias = function(...)
local vars = {...}
if #vars == 0 or vars[1] == "-p" then for k,v in pairs(aliases) do print("alias " .. k .. "=" .. v) end else
for k,v in ipairs(vars) do
local kk, vv = string.match(v, "(.+)=(.+)")
aliases[kk] = vv
end
end
end,
sleep = function(time) sleep(tonumber(time)) end,
test = function(...) -- TODO: add and/or
local args = {...}
if #args < 1 then
printError("cash: test: unary operator expected")
return -1
end
local function n(v) return v end
if args[1] == "!" then
table.remove(args, 1)
n = function(v) return not v end
end
if string.sub(args[1], 1, 1) == "-" then
if args[2] == nil then return n(true)
elseif args[1] == "-d" then return n(fs.exists(shell.resolve(args[2])) and fs.isDir(shell.resolve(args[2])))
elseif args[1] == "-e" then return n(fs.exists(shell.resolve(args[2])))
elseif args[1] == "-f" then return n(fs.exists(shell.resolve(args[2])) and not fs.isDir(shell.resolve(args[2])))
elseif args[1] == "-n" then return n(#args[2] > 0)
elseif args[1] == "-s" then return n(fs.getSize(shell.resolve(args[2])) > 0)
elseif args[1] == "-u" and type(CCKernel2) == "table" then return n(fs.hasPermissions(shell.resolve(args[2]), fs.permissions.setuid))
elseif args[1] == "-w" then return n(not fs.isReadOnly(shell.resolve(args[2])))
elseif args[1] == "-x" then return n(true)
elseif args[1] == "-z" then return n(#args[2] == 0)
else return n(false) end
elseif args[3] and string.sub(args[2], 1, 1) == "-" then
if args[2] == "-eq" then return n(tonumber(args[1]) == tonumber(args[3]))
elseif args[2] == "-ne" then return n(tonumber(args[1]) ~= tonumber(args[3]))
elseif args[2] == "-lt" then return n(tonumber(args[1]) < tonumber(args[3]))
elseif args[2] == "-gt" then return n(tonumber(args[1]) > tonumber(args[3]))
elseif args[2] == "-le" then return n(tonumber(args[1]) <= tonumber(args[3]))
elseif args[2] == "-ge" then return n(tonumber(args[1]) >= tonumber(args[3]))
else return n(false) end
elseif args[2] == "=" then return n(args[1] == args[3])
elseif args[2] == "!=" then return n(args[1] ~= args[3])
else
printError("cash: test: unary operator expected")
return 2
end
end,
["true"] = function() return 0 end,
["false"] = function() return 1 end,
unalias = function(...) for k,v in ipairs({...}) do aliases[v] = nil end end,
unset = function(...) for k,v in ipairs({...}) do vars[v] = nil end end,
wait = function(job)
if job then while jobs[tonumber(job)] ~= nil do sleep(0.1) end
else while table.maxn(jobs) ~= 0 do sleep(0.1) end end
end,
lua = function(...)
if #({...}) > 0 then
if fs.exists(shell.resolve(...)) then
local args = {...}
table.remove(args, 1)
shell.run(shell.resolve(...), table.unpack(args))
else
local s = table.concat({...}, " ")
local tEnv = setmetatable({shell = shell, multishell = multishell, package = pack, require = require, _echo = function(...) return ... end}, {__index = _ENV})
local nForcePrint = 0
local func, e = load( s, "lua", "t", tEnv )
local func2, e2 = load( "return _echo("..s..");", "lua", "t", tEnv )
if not func then
if func2 then
func = func2
e = nil
nForcePrint = 1
end
else
if func2 then
func = func2
end
end
if func then
local tResults = table.pack( pcall( func ) )
if tResults[1] then
local n = 1
while n < tResults.n or (n <= nForcePrint) do
local value = tResults[ n + 1 ]
if type( value ) == "table" then
local metatable = getmetatable( value )
if type(metatable) == "table" and type(metatable.__tostring) == "function" then
print( tostring( value ) )
else
local ok, serialised = pcall( textutils.serialise, value )
if ok then
print( serialised )
else
print( tostring( value ) )
end
end
else
print( tostring( value ) )
end
n = n + 1
end
else
printError( tResults[2] )
end
else
printError( e )
end
end
else shell.run("/rom/programs/lua.lua") end
end,
cat = function(...)
for k,v in ipairs({...}) do
local file = fs.open(v, "r")
if file ~= nil then
print(file.readAll())
file.close()
end
end
end,
which = function(name) local name, v = shell.resolveProgram(name); if not v and name then print(name) end end,
["if"] = function(...)
shell.run(...)
table.insert(if_table, {cond = vars["?"] == 0, inv = false})
end,
["then"] = function(...)
if if_statement >= table.maxn(if_table) then
printError("cash: syntax error near unexpected token `then'")
return -1
end
if_statement = if_statement + 1
shell.run(...)
return vars["?"]
end,
["else"] = function(...)
if if_statement < 1 or if_table[if_statement].inv then
printError("cash: syntax error near unexpected token `else'")
return -1
end
if_table[if_statement].inv = true
if_table[if_statement].cond = not if_table[if_statement].cond
shell.run(...)
return vars["?"]
end,
fi = function()
if if_statement < 1 then
printError("cash: syntax error near unexpected token `fi'")
return -1
end
table.remove(if_table, if_statement)
if_statement = if_statement - 1
end,
["while"] = function(...)
table.insert(while_table, {cond = {...}, lines = {}})
end,
["do"] = function(...)
if table.maxn(while_table) == 0 then
printError("cash: syntax error near unexpected token `do'")
return -1
end
while_statement = while_statement + 1
end,
done = function()
if while_statement < 1 then
printError("cash: syntax error near unexpected token `done'")
return -1
end
while_statement = while_statement - 1
if while_statement == 0 then
local last = table.remove(while_table, while_statement + 1)
if type(last.cond) == "function" then last.cond()
else shell.run(table.unpack(last.cond)) end
local cond = vars["?"]
should_break = false
while cond == 0 and not should_break do
for k,v in ipairs(last.lines) do
if type(v) == "function" then v()
else shell.run(v) end
end
if type(last.cond) == "function" then last.cond()
else shell.run(table.unpack(last.cond)) end
cond = vars["?"]
end
end
end,
["break"] = function() should_break = true end,
["for"] = function(...)
local args = {...}
if args[2] ~= "in" then
printError("cash: missing `in' in for loop")
return -1
end
local i = 2
table.insert(while_table, {cond = function() i = i + 1; vars["?"] = args[i] ~= nil and 0 or 1 end, lines = {function() vars[args[1]] = args[i] end}})
end,
["function"] = function(name, p)
if function_name ~= nil then
printError("cash: syntax error near unexpected token `function'")
return -1
end
if p ~= "{" then
printError("cash: syntax error near token `" .. name .. "'")
return -1
end
function_name = name
functions[function_name] = {}
end,
["}"] = function()
if function_name == nil then
printError("cash: syntax error near unexpected token `}'")
return -1
end
function_name = nil
end,
["return"] = function(var)
if function_running == false then
printError("cash: syntax error near unexpected token `return'")
return -1
end
function_running = false
return var
end,
bg = function(t)
if pausedJob then
jobs[pausedJob].isfg = false
jobs[pausedJob].paused = false
if CCKernel2 then kernel.signal(signal.SIGCONT, jobs[pausedJob].pid) end
pausedJob = nil
return 0
elseif tonumber(t) and jobs[tonumber(t)] then
local task = tonumber(t)
jobs[task].isfg = false
jobs[task].paused = false
if CCKernel2 then kernel.signal(signal.SIGCONT, jobs[task].pid) end
return 0
else
printError("cash: bg: current: no such job")
return 1
end
end,
fg = function(t)
if pausedJob then
jobs[pausedJob].isfg = true
jobs[pausedJob].paused = false
if CCKernel2 then kernel.signal(signal.SIGCONT, jobs[pausedJob].pid) end
pausedJob = nil
return 0
elseif tonumber(t) and jobs[tonumber(t)] then
local task = tonumber(t)
jobs[task].isfg = true
jobs[task].paused = false
if CCKernel2 then kernel.signal(signal.SIGCONT, jobs[task].pid) end
return 0
else
printError("cash: fg: current: no such job")
return 1
end
end,
}
builtins["["] = builtins.test
function shell.exit(retval)
running = false
shell_retval = retval or 0
end
function shell.dir()
return PWD
end
function shell.setDir(path)
expect(1, path, "string")
OLDPWD = PWD
PWD = path
end
function shell.path()
return PATH
end
function shell.setPath(path)
expect(1, path, "string")
PATH = path
end
function shell.resolve(localPath)
expect(1, localPath, "string")
if string.sub(localPath, 1, 1) == "/" then return fs.combine(localPath, "")
else return fs.combine(PWD, localPath) end
end
function shell.resolveProgram(name)
expect(1, name, "string")
if builtins[name] ~= nil then return name end
if aliases[name] ~= nil then name = aliases[name] end
for path in string.gmatch(PATH, "[^:]+") do
if fs.exists(fs.combine(shell.resolve(path), name)) and not fs.isDir(fs.combine(shell.resolve(path), name)) then return fs.combine(shell.resolve(path), name)
elseif fs.exists(fs.combine(shell.resolve(path), name .. ".lua")) and not fs.isDir(fs.combine(shell.resolve(path), name .. ".lua")) then return fs.combine(shell.resolve(path), name .. ".lua") end
end
if fs.exists(shell.resolve(name)) and not fs.isDir(shell.resolve(name)) then return shell.resolve(name), string.find(name, "/") == nil end
if fs.exists(shell.resolve(name .. ".lua")) and not fs.isDir(shell.resolve(name .. ".lua")) then return shell.resolve(name .. ".lua"), string.find(name, "/") == nil end
return nil
end
function shell.aliases()
return aliases
end
function shell.setAlias(alias, program)
expect(1, alias, "string")
expect(2, program, "string")
aliases[alias] = program
end
function shell.clearAlias(alias)
expect(1, alias, "string")
aliases[alias] = nil
end
local function combineArray(dst, src, prefix)
for k,v in ipairs(src) do table.insert(dst, (prefix or "") .. v) end
return dst
end
function shell.programs(showHidden)
-- todo: implement showHidden
local retval = {}
for path in string.gmatch(PATH, "[^:]+") do combineArray(retval, fs.find(fs.combine(shell.resolve(path), "*"))) end
combineArray(retval, fs.find(fs.combine(PWD, "*")), "./")
return retval
end
function shell.getRunningProgram()
return vars._
end
function shell.complete(prefix)
expect(1, prefix, "string")
return fs.complete(prefix, PWD)
end
function shell.completeProgram(prefix)
expect(1, prefix, "string")
if string.find(prefix, "/") then
return fs.complete(prefix, PWD, true, false)
else
local retval = {}
for path in string.gmatch(PATH, "[^:]+") do combineArray(retval, fs.complete(prefix, path, true, false)) end
return retval
end
end
function shell.setCompletionFunction(path, completionFunction)
expect(1, path, "string")
expect(2, completionFunction, "function")
completion[path] = {fnComplete = completionFunction}
end
function shell.getCompletionInfo()
return completion
end
function shell.switchTab() end
function multishell.getCurrent()
return 1
end
function multishell.getCount()
return 1
end
function multishell.setFocus(id)
expect(1, id, "number")
return id == 1
end
function multishell.setTitle(title)
shell_title = title
end
function multishell.getTitle()
return shell_title
end
function multishell.getFocus()
return 1
end
function shell.environment()
return shell_env
end
function shell.setEnvironment(e)
expect(1, e, "table")
shell_env = e
end
local function expandVar(var)
if string.sub(var, 1, 1) ~= "$" then return nil end
if string.sub(var, 2, 2) == "{" then
local varname = string.sub(string.match(var, "%b{}"), 2, -2)
local retval = _ENV[varname] or vars[varname]
if type(retval) == "function" then return retval(), #varname + 2 else return retval or "", #varname + 2 end
elseif string.sub(var, 2, 3) == "((" then
local expr = string.gsub(string.sub(string.match(string.sub(var, 3), "%b()"), 2, -2), "%$", "")
local fn = loadstring("return " .. expr)
local varenv = setmetatable({}, {__index = _ENV})
for k,v in pairs(vars) do varenv[k] = v end
setfenv(fn, varenv)
return tostring(fn()), #expr + 4
elseif tonumber(string.sub(var, 2, 2)) then
local varname = tonumber(string.match(string.sub(var, 2, 2), "[0-9]+"))
if varname == 0 then return vars["0"], 1 else return args[varname] or "", math.floor(math.log10(varname)) + 1 end
else
local varname = ""
for c in string.gmatch(string.sub(var, 2), ".") do
if c == " " then return "", #varname end
varname = varname .. c
if _ENV[varname] or vars[varname] then
local retval = _ENV[varname] or vars[varname]
if type(retval) == "function" then return retval(), #varname else return retval or "", #varname end
end
end
return "", #var - 1
end
end
local function splitSemicolons(cmdline)
local escape = false
local quoted = false
local j = 1
local retval = {""}
local lastc, lastc2
for c in string.gmatch(cmdline, ".") do
if lastc == '&' and c ~= '&' and lastc2 ~= '&' and not quoted and not escape then
j=j+1
retval[j] = ""
end
local setescape = false
if c == '"' or c == '\'' and not escape then quoted = not quoted
elseif c == '\\' and not quoted and not escape then
setescape = true
escape = true
end
if c == ';' and not quoted and not escape then
j=j+1
retval[j] = ""
elseif not (c == ' ' and retval[j] == "") then retval[j] = retval[j] .. c end
if not setescape then escape = false end
lastc2 = lastc
lastc = c
end
return retval
end
local function tokenize(cmdline, noexpand)
-- Expand vars
local singleQuote = false
local escape = false
local expstr = ""
local i = 1
local function tostr(v)
if type(v) == "boolean" then return v and "true" or "false"
elseif v == nil then return "nil"
elseif type(v) == "table" then return textutils.serialize(v)
elseif type(v) == "string" then return v
else return tostring(v) end
end
if noexpand then expstr = cmdline else
while i <= #cmdline do
local c = string.sub(cmdline, i, i)
if c == '$' and not escape and not singleQuote then
local s, n = expandVar(string.sub(cmdline, i))
s = tostr(s)
expstr = expstr .. s
i = i + n
else
if c == '\'' and not escape then singleQuote = not singleQuote end
escape = c == '\\' and not escape
expstr = expstr .. c
end
i=i+1
end
end
-- Tokenize
local retval = {{[0] = ""}}
i = 0
local j = 1
local quoted = false
escape = false
local lastc
for c in string.gmatch(expstr, ".") do
if (c == '"' or c == '\'') and not escape then quoted = not quoted
elseif c == ' ' and not quoted and not escape then
if #retval[j][i] > 0 then
i=i+1
retval[j][i] = ""
end
elseif c == ';' and not quoted and not escape then
j=j+1
i=0
retval[j] = {[0] = ""}
elseif lastc == '&' and c == '&' and not quoted and not escape then
retval[j][i] = string.sub(retval[j][i], 1, -2)
j=j+1
i=0
retval[j] = {[0] = "", last = 0}
elseif lastc == '|' and c == '|' and not quoted and not escape then
retval[j][i] = string.sub(retval[j][i], 1, -2)
j=j+1
i=0
retval[j] = {[0] = "", last = 1}
elseif not (c == '\\' and not quoted and not escape) then
retval[j][i] = retval[j][i] .. c
end
escape = c == '\\' and not quoted and not escape
lastc = c
end
if lastc == '&' then retval.async = true end
for k,v in ipairs(retval) do if v[0] ~= "" then
local path, islocal = shell.resolveProgram(v[0])
path = path or v[0]
if not (islocal and string.find(v[0], "/") == nil) then v[0] = path end
v.vars = {}
while v[0] and string.find(v[0], "=") do
local l = string.sub(v[0], 1, string.find(v[0], "=") - 1)
v.vars[l] = string.sub(v[0], string.find(v[0], "=") + 1)
v.vars[l] = tonumber(v.vars[l]) or v.vars[l]
v[0] = nil
for i = 1, table.maxn(v) do v[i-1] = v[i]; v[i] = nil end
end
end end
return retval
end
local junOff = 31 + 28 + 31 + 30 + 31 + 30
local function dayToString(day)
if day <= 31 then return "Jan " .. day
elseif day > 31 and day <= 31 + 28 then return "Feb " .. day - 31
elseif day > 31 + 28 and day <= 31 + 28 + 31 then return "Mar " .. day - 31 - 28
elseif day > 31 + 28 + 31 and day <= 31 + 28 + 31 + 30 then return "Apr " .. day - 31 - 28 - 31
elseif day > 31 + 28 + 31 + 30 and day <= 31 + 28 + 31 + 30 + 31 then return "May " .. day - 31 - 28 - 31 - 30
elseif day > 31 + 28 + 31 + 30 + 31 and day <= junOff then return "Jun " .. day - 31 - 28 - 31 - 30 - 31
elseif day > junOff and day <= junOff + 31 then return "Jul " .. day - junOff
elseif day > junOff + 31 and day <= junOff + 31 + 31 then return "Aug " .. day - junOff - 31
elseif day > junOff + 31 + 31 and day <= junOff + 31 + 31 + 30 then return "Sep " .. day - junOff - 31 - 31
elseif day > junOff + 31 + 31 + 30 and day <= junOff + 31 + 31 + 30 + 31 then return "Oct " .. day - junOff - 31 - 31 - 30
elseif day > junOff + 31 + 31 + 30 + 31 and day <= junOff + 31 + 31 + 30 + 31 + 30 then return "Nov " .. day - junOff - 31 - 31 - 30 - 31
else return "Dec " .. day - junOff - 31 - 31 - 30 - 31 - 30 end
end
local function getPrompt()
local retval = (if_statement > 0 or while_statement > 0 or case_statement > 0) and vars.PS2 or vars.PS1 or "\\$ "
for k,v in pairs({
["\\d"] = dayToString(os.day()),
["\\e"] = string.char(0x1b),
["\\h"] = string.sub(os.getComputerLabel() or "localhost", 1, string.find(os.getComputerLabel() or "localhost", "%.")),
["\\H"] = os.getComputerLabel() or "localhost",
["\\n"] = "\n",
["\\s"] = string.gsub(fs.getName(vars["0"]), ".lua", ""),
["\\t"] = textutils.formatTime(os.time(), true),
["\\T"] = textutils.formatTime(os.time(), false),
["\\u"] = USER,
["\\v"] = vars.CASH_VERSION,
["\\V"] = vars.CASH_VERSION,
["\\w"] = PWD,
["\\W"] = fs.getName(PWD) == "." and "/" or fs.getName(PWD),
["\\%#"] = vars.LINENUM,
["\\%$"] = USER == "root" and "#" or "$",
["\\([0-7][0-7][0-7])"] = function(n) return string.char(tonumber(n, 8)) end,
["\\\\"] = "\\",
["\\%[.+\\%]"] = ""
}) do retval = string.gsub(retval, k, v) end
return retval
end
local function run( _tEnv, _sPath, ... )
if type( _tEnv ) ~= "table" then
error( "bad argument #1 (expected table, got " .. type( _tEnv ) .. ")", 2 )
end
if type( _sPath ) ~= "string" then
error( "bad argument #2 (expected string, got " .. type( _sPath ) .. ")", 2 )
end
local tArgs = table.pack( ... )
local tEnv = _tEnv
local fnFile, err = loadfile( _sPath, tEnv )
if fnFile then
local ok, err = pcall( function()
vars["?"] = fnFile( table.unpack( tArgs, 1, tArgs.n ) )
if vars["?"] == nil or vars["?"] == true then vars["?"] = 0
elseif vars["?"] == false then vars["?"] = 1 end
end )
if not ok then
if err and err ~= "" then
printError( err )
end
vars["?"] = 1
return false
end
return true
end
if err and err ~= "" then
printError( err )
end
vars["?"] = 1
return false
end
local function execv(tokens)
local path = tokens[0]
tokens[0] = nil
if path == nil then return end
if #tokens == 0 and string.find(path, "=") ~= nil then
local k = string.sub(path, 1, string.find(path, "=") - 1)
vars[k] = string.sub(path, string.find(path, "=") + 1)
vars[k] = tonumber(vars[k]) or vars[k]
return
end
local oldenv = {}
for k,v in pairs(tokens.vars) do
oldenv[k] = _ENV[k]
_ENV[k] = v
end
if if_statement > 0 and not if_table[if_statement].cond and path ~= "else" and path ~= "elif" and path ~= "fi" then return end
if builtins[path] ~= nil then
vars["?"] = builtins[path](table.unpack(tokens))
if vars["?"] == nil or vars["?"] == true then vars["?"] = 0
elseif vars["?"] == false then vars["?"] = 1 end
elseif functions[path] ~= nil and not no_funcs then
local oldargs = args
args = tokens
function_running = true
for k,v in ipairs(functions[path]) do
shell.run(v)
if not function_running then break end
end
args = oldargs
else
if not fs.exists(path) then
printError("cash: " .. path .. ": No such file or directory")
vars["?"] = -1
return
end
if not CCKernel2 then
local file = fs.open(path, "r")
local firstLine = file.readLine()
file.close()
if firstLine ~= nil and string.sub(firstLine, 1, 2) == "#!" then
table.insert(tokens, 1, path)
path = string.sub(firstLine, 3)
if not fs.exists(path) and fs.exists(path .. ".lua") then path = path .. ".lua" end
end
end
local _old = vars._
vars._ = path
local cmdenv = setmetatable({shell = shell, multishell = multishell}, {__index = shell_env})
cmdenv.require, cmdenv.package = make_require(cmdenv, PWD)
run(cmdenv, path, table.unpack(tokens))
vars._ = _old
end
for k,v in pairs(tokens.vars) do _ENV[k] = oldenv[k] end
end
run_tokens = function(tokens, isAsync)
if tokens.async and not isAsync then
local coro, pid
if CCKernel2 then pid = kernel.fork("cash", function() run_tokens(tokens, true) end)
else coro = coroutine.create(function() run_tokens(tokens, true) end) end
local id = #jobs + 1
jobs[id] = {cmd = tokens[1][0] .. " " .. table.concat(tokens[1], " "), coro = coro, pid = pid, isfg = false, start = true}
print("[" .. (id) .. "] " .. (pid or ""))
else
for k,tok in ipairs(tokens) do
if tok[0] then
if trim(tok[0]) ~= "" and (tok.last == 0 and vars["?"] == 0) or (tok.last == 1 and vars["?"] ~= 0) or tok.last == nil then
execv(tok)
end
else
for k,v in pairs(tok.vars) do vars[k] = tonumber(v) or v end
end
end
end
return vars["?"] == 0
end
local run_tokens_async = function(tokens)
local coro, pid
if CCKernel2 then pid = kernel.fork("cash", function() run_tokens(tokens, true) end)
else coro = coroutine.create(function() run_tokens(tokens, true) end) end
local id = #jobs + 1
jobs[id] = {cmd = tokens[1][0] and (tokens[1][0] .. " " .. table.concat(tokens[1], " ")) or "cash", coro = coro, pid = pid, isfg = not tokens.async, start = true}
if tokens.async then print("[" .. (id) .. "] " .. (pid or "")) end
end
function shell.run(...)
local cmd = table.concat({...}, " ")
if cmd == "" or string.sub(cmd, 1, 1) == "#" then return end
if function_name ~= nil then
if string.find(cmd, "}") then function_name = nil
else table.insert(functions[function_name], cmd) end
return true
elseif while_statement > 0 then
local tokens = splitSemicolons(cmd)
for k,line in ipairs(tokens) do
line = string.sub(line, #string.match(line, "^ *") + 1)
if line == "do" or line == "done" or string.find(line, "^do ") or string.find(line, "^done ") then run_tokens(tokenize(line)) end
if while_statement > 0 then table.insert(while_table[1].lines, line) end
end
return true
end
local lines = splitSemicolons(cmd)
for k,v in ipairs(lines) do run_tokens(tokenize(v, string.sub(v, 1, 6) == "while ")) end
return vars["?"] == 0
end
function shell.runAsync(...)
local cmd = table.concat({...}, " ")
if cmd == "" or string.sub(cmd, 1, 1) == "#" then return end
if function_name ~= nil then
if string.find(cmd, "}") then function_name = nil
else table.insert(functions[function_name], cmd) end
return true
elseif while_statement > 0 then
local tokens = splitSemicolons(cmd)
for k,line in ipairs(tokens) do
line = string.sub(line, #string.match(line, "^ *") + 1)
if line == "do" or line == "done" or string.find(line, "^do ") or string.find(line, "^done ") then run_tokens(tokenize(line)) end
if while_statement > 0 then table.insert(while_table[1].lines, line) end
end
return true
end
local lines = splitSemicolons(cmd)
for k,v in ipairs(lines) do run_tokens_async(tokenize(v, string.sub(v, 1, 6) == "while ")) end
return vars["?"] == 0
end
function multishell.launch(environment, path, ...)
expect(1, environment, "table")
expect(2, path, "string")
local coro, pid
local tok = {[0] = path, ...}
if CCKernel2 then pid = kernel.fork(path, function() execv(tok) end)
else coro = coroutine.create(function() execv(tok) end) end
local id = #jobs + 1
jobs[id] = {cmd = path .. " " .. table.concat({...}, " "), coro = coro, pid = pid, isfg = false}
return id
end
function shell.openTab(...)
local cmd = table.concat({...}, " ")
if cmd == "" or string.sub(cmd, 1, 1) == "#" then return end
if function_name ~= nil then
if string.find(cmd, "}") then function_name = nil
else table.insert(functions[function_name], cmd) end
return true
elseif while_statement > 0 then
local tokens = splitSemicolons(cmd)
for k,line in ipairs(tokens) do
line = string.sub(line, #string.match(line, "^ *") + 1)
if line == "do" or line == "done" or string.find(line, "^do ") or string.find(line, "^done ") then run_tokens(tokenize(line)) end
if while_statement > 0 then table.insert(while_table[1].lines, line) end
end
return true
end
local lines = splitSemicolons(cmd)
for k,v in ipairs(lines) do
local tokens = tokenize(v, string.sub(v, 1, 6) == "while ")
for k,tok in ipairs(tokens) do if tok[0] ~= "" then
local coro, pid
if CCKernel2 then pid = kernel.fork(tok[0], function() execv(tok) end)
else coro = coroutine.create(function() execv(tok) end) end
local id = #jobs + 1
jobs[id] = {cmd = tok[0] .. " " .. table.concat(tok, " "), coro = coro, pid = pid, isfg = false}
print("[" .. (id) .. "] " .. (pid or ""))
end end
end
return vars["?"] == 0
end
if args[1] ~= nil then
local path = table.remove(args, 1)
path = fs.exists(path) and path or shell.resolve(path)
local file = io.open(path, "r")
if not file then return 1 end
vars.LINENUM = 1
for line in file:lines() do
shell.run(line)
vars.LINENUM = vars.LINENUM + 1
if not running then break end
end
file:close()
vars.LINENUM = nil
return shell_retval
end
if topshell == nil then shell.run("rom/startup.lua") end
if CCKernel2 then
if fs.exists("/etc/cashrc") then
local file = io.open("/etc/cashrc", "r")
for line in file:lines() do shell.run(line) end