AmberCli.st 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176
  1. Smalltalk createPackage: 'AmberCli'!
  2. Object subclass: #AmberCli
  3. instanceVariableNames: ''
  4. package: 'AmberCli'!
  5. !AmberCli commentStamp!
  6. I am the Amber CLI (CommandLine Interface) tool which runs on Node.js.
  7. My responsibility is to start different Amber programs like the FileServer or the Repl.
  8. Which program to start is determined by the first commandline parameters passed to the AmberCli executable.
  9. Use `help` to get a list of all available options.
  10. Any further commandline parameters are passed to the specific program.
  11. ## Commands
  12. New commands can be added by creating a class side method in the `commands` protocol which takes one parameter.
  13. This parameter is an array of all commandline options + values passed on to the program.
  14. Any `camelCaseCommand` is transformed into a commandline parameter of the form `camel-case-command` and vice versa.!
  15. !AmberCli class methodsFor: 'commandline'!
  16. commandLineSwitches
  17. "Collect all methodnames from the 'commands' protocol of the class
  18. and select the ones with only one parameter.
  19. Then remove the ':' at the end of the name.
  20. Additionally all uppercase letters are made lowercase and preceded by a '-'.
  21. Example: fallbackPage: becomes --fallback-page.
  22. Return the Array containing the commandline switches."
  23. | switches |
  24. switches := ((self class methodsInProtocol: 'commands') collect: [ :each | each selector]).
  25. switches := switches select: [ :each | each match: '^[^:]*:$'].
  26. switches :=switches collect: [ :each |
  27. (each allButLast replace: '([A-Z])' with: '-$1') asLowercase].
  28. ^ switches
  29. !
  30. handleArguments: args
  31. | selector |
  32. selector := self selectorForCommandLineSwitch: (args first).
  33. args remove: args first.
  34. self perform: selector withArguments: (Array with: args)
  35. !
  36. selectorForCommandLineSwitch: aSwitch
  37. "Add ':' at the end and replace all occurences of a lowercase letter preceded by a '-' with the Uppercase letter.
  38. Example: fallback-page becomes fallbackPage:.
  39. If no correct selector is found return 'help:'"
  40. | command selector |
  41. (self commandLineSwitches includes: aSwitch)
  42. ifTrue: [ selector := (aSwitch replace: '-[a-z]' with: [ :each | each second asUppercase ]), ':']
  43. ifFalse: [ selector := 'help:' ].
  44. ^ selector
  45. ! !
  46. !AmberCli class methodsFor: 'commands'!
  47. help: args
  48. Transcript show: 'Available commands'.
  49. self commandLineSwitches do: [ :each | console log: each ]
  50. !
  51. repl: args
  52. ^ Repl new createInterface
  53. !
  54. serve: args
  55. ^ (FileServer createServerWithArguments: args) start
  56. !
  57. tests: arguments
  58. ^ NodeTestRunner runTestSuite
  59. !
  60. version: arguments
  61. ! !
  62. !AmberCli class methodsFor: 'startup'!
  63. main
  64. "Main entry point for Amber applications.
  65. Parses commandline arguments and starts the according subprogram."
  66. | args nodeMinorVersion |
  67. Transcript show: 'Welcome to Amber version ', Smalltalk version, ' (NodeJS ', process versions node, ').'.
  68. nodeMinorVersion := ((process version) tokenize: '.') second asNumber.
  69. nodeMinorVersion < 8 ifTrue: [
  70. Transcript show: 'You are currently using Node.js ', (process version).
  71. Transcript show: 'Required is at least Node.js v0.8.x or greater.'.
  72. ^ -1.
  73. ].
  74. args := process argv.
  75. "Remove the first args which contain the path to the node executable and the script file."
  76. args removeFrom: 1 to: 2.
  77. (args isEmpty)
  78. ifTrue: [self help: nil]
  79. ifFalse: [^self handleArguments: args]
  80. ! !
  81. Object subclass: #FileServer
  82. instanceVariableNames: 'path http fs url host port basePath util username password fallbackPage'
  83. package: 'AmberCli'!
  84. !FileServer commentStamp!
  85. I am the Amber Smalltalk FileServer.
  86. My runtime requirement is a functional Node.js executable.
  87. To start a FileServer instance on port `4000` use the following code:
  88. FileServer new start
  89. A parameterized instance can be created with the following code:
  90. FileServer createServerWithArguments: options
  91. Here, `options` is an array of commandline style strings each followed by a value e.g. `#('--port', '6000', '--host', '0.0.0.0')`.
  92. A list of all available parameters can be printed to the commandline by passing `--help` as parameter.
  93. See the `Options` section for further details on how options are mapped to instance methods.
  94. After startup FileServer checks if the directory layout required by Amber is present and logs a warning on absence.
  95. ## Options
  96. Each option is of the form `--some-option-string` which is transformed into a selector of the format `someOptionString:`.
  97. The trailing `--` gets removed, each `-[a-z]` gets transformed into the according uppercase letter, and a `:` is appended to create a selector which takes a single argument.
  98. Afterwards, the selector gets executed on the `FileServer` instance with the value following in the options array as parameter.
  99. ## Adding new commandline parameters
  100. Adding new commandline parameters to `FileServer` is as easy as adding a new single parameter method to the `accessing` protocol.!
  101. !FileServer methodsFor: 'accessing'!
  102. basePath
  103. ^ basePath ifNil: [self class defaultBasePath]
  104. !
  105. basePath: aString
  106. basePath := aString.
  107. self validateBasePath.
  108. !
  109. fallbackPage
  110. ^ fallbackPage
  111. !
  112. fallbackPage: aString
  113. fallbackPage := aString
  114. !
  115. host
  116. ^ host
  117. !
  118. host: hostname
  119. host := hostname
  120. !
  121. password: aPassword
  122. password := aPassword.
  123. !
  124. port
  125. ^ port
  126. !
  127. port: aNumber
  128. port := aNumber
  129. !
  130. username: aUsername
  131. username := aUsername.
  132. ! !
  133. !FileServer methodsFor: 'initialization'!
  134. checkDirectoryLayout
  135. (fs existsSync: (self withBasePath: 'index.html')) ifFalse: [
  136. console warn: 'Warning: project directory does not contain index.html.'.
  137. console warn: ' You can specify the directory containing index.html with --base-path.'.
  138. console warn: ' You can also specify a page to be served by default,'.
  139. console warn: ' for all paths that do not map to a file, with --fallback-page.'].
  140. !
  141. initialize
  142. super initialize.
  143. path := self require: 'path'.
  144. http := self require: 'http'.
  145. fs := self require: 'fs'.
  146. util := self require: 'util'.
  147. url := self require: 'url'.
  148. host := self class defaultHost.
  149. port := self class defaultPort.
  150. username := nil.
  151. password := nil.
  152. fallbackPage := nil.
  153. ! !
  154. !FileServer methodsFor: 'private'!
  155. base64Decode: aString
  156. <return (new Buffer(aString, 'base64').toString())>
  157. !
  158. isAuthenticated: aRequest
  159. "Basic HTTP Auth: http://stackoverflow.com/a/5957629/293175
  160. and https://gist.github.com/1686663"
  161. | header token auth parts|
  162. (username isNil and: [password isNil]) ifTrue: [^ true].
  163. "get authentication header"
  164. header := (aRequest headers at: 'authorization') ifNil:[''].
  165. (header isEmpty)
  166. ifTrue: [^ false]
  167. ifFalse: [
  168. "get authentication token"
  169. token := (header tokenize: ' ') ifNil:[''].
  170. "convert back from base64"
  171. auth := self base64Decode: (token at: 2).
  172. "split token at colon"
  173. parts := auth tokenize: ':'.
  174. ((username = (parts at: 1)) and: [password = (parts at: 2)])
  175. ifTrue: [^ true]
  176. ifFalse: [^ false]
  177. ].
  178. !
  179. require: aModuleString
  180. "call to the require function"
  181. ^require value: aModuleString
  182. !
  183. validateBasePath
  184. "The basePath must be an existing directory. "
  185. fs stat: self basePath then: [ :err :stat | err
  186. ifNil: [ stat isDirectory ifFalse: [ console warn: 'Warning: --base-path parameter ' , self basePath , ' is not a directory.' ]]
  187. ifNotNil: [ console warn: 'Warning: path at --base-path parameter ' , self basePath , ' does not exist.' ]].
  188. !
  189. withBasePath: aBaseRelativePath
  190. "return a file path which is relative to the basePath."
  191. ^ path join: self basePath with: aBaseRelativePath
  192. !
  193. writeData: data toFileNamed: aFilename
  194. console log: aFilename
  195. ! !
  196. !FileServer methodsFor: 'request handling'!
  197. handleGETRequest: aRequest respondTo: aResponse
  198. | uri filename |
  199. uri := url parse: aRequest url.
  200. filename := path join: self basePath with: uri pathname.
  201. fs exists: filename do: [:aBoolean |
  202. aBoolean
  203. ifFalse: [self respondNotFoundTo: aResponse]
  204. ifTrue: [(fs statSync: filename) isDirectory
  205. ifTrue: [self respondDirectoryNamed: filename from: uri to: aResponse]
  206. ifFalse: [self respondFileNamed: filename to: aResponse]]]
  207. !
  208. handleOPTIONSRequest: aRequest respondTo: aResponse
  209. aResponse writeHead: 200 options: #{'Access-Control-Allow-Origin' -> '*'.
  210. 'Access-Control-Allow-Methods' -> 'GET, PUT, POST, DELETE, OPTIONS'.
  211. 'Access-Control-Allow-Headers' -> 'Content-Type, Accept'.
  212. 'Content-Length' -> 0.
  213. 'Access-Control-Max-Age' -> 10}.
  214. aResponse end
  215. !
  216. handlePUTRequest: aRequest respondTo: aResponse
  217. | file stream |
  218. (self isAuthenticated: aRequest)
  219. ifFalse: [self respondAuthenticationRequiredTo: aResponse. ^ nil].
  220. file := '.', aRequest url.
  221. stream := fs createWriteStream: file.
  222. stream on: 'error' do: [:error |
  223. console warn: 'Error creating WriteStream for file ', file.
  224. console warn: ' Did you forget to create the necessary directory in your project (often /src)?'.
  225. console warn: ' The exact error is: ', error.
  226. self respondNotCreatedTo: aResponse].
  227. stream on: 'close' do: [
  228. self respondCreatedTo: aResponse].
  229. aRequest setEncoding: 'utf8'.
  230. aRequest on: 'data' do: [:data |
  231. stream write: data].
  232. aRequest on: 'end' do: [
  233. stream writable ifTrue: [stream end]]
  234. !
  235. handleRequest: aRequest respondTo: aResponse
  236. aRequest method = 'PUT'
  237. ifTrue: [self handlePUTRequest: aRequest respondTo: aResponse].
  238. aRequest method = 'GET'
  239. ifTrue:[self handleGETRequest: aRequest respondTo: aResponse].
  240. aRequest method = 'OPTIONS'
  241. ifTrue:[self handleOPTIONSRequest: aRequest respondTo: aResponse]
  242. !
  243. respondAuthenticationRequiredTo: aResponse
  244. aResponse
  245. writeHead: 401 options: #{'WWW-Authenticate' -> 'Basic realm="Secured Developer Area"'};
  246. write: '<html><body>Authentication needed</body></html>';
  247. end.
  248. !
  249. respondCreatedTo: aResponse
  250. aResponse
  251. writeHead: 201 options: #{'Content-Type' -> 'text/plain'. 'Access-Control-Allow-Origin' -> '*'};
  252. end.
  253. !
  254. respondDirectoryNamed: aDirname from: aUrl to: aResponse
  255. (aUrl pathname endsWith: '/')
  256. ifTrue: [self respondFileNamed: aDirname, 'index.html' to: aResponse]
  257. ifFalse: [self respondRedirect: aUrl pathname, '/', (aUrl search ifNil: ['']) to: aResponse]
  258. !
  259. respondFileNamed: aFilename to: aResponse
  260. | type filename |
  261. filename := aFilename.
  262. fs readFile: filename do: [:ex :file |
  263. ex notNil
  264. ifTrue: [
  265. console log: filename, ' does not exist'.
  266. self respondNotFoundTo: aResponse]
  267. ifFalse: [
  268. type := self class mimeTypeFor: filename.
  269. type = 'application/javascript'
  270. ifTrue: [ type:=type,';charset=utf-8' ].
  271. aResponse
  272. writeHead: 200 options: #{'Content-Type' -> type};
  273. write: file encoding: 'binary';
  274. end]]
  275. !
  276. respondInternalErrorTo: aResponse
  277. aResponse
  278. writeHead: 500 options: #{'Content-Type' -> 'text/plain'};
  279. write: '500 Internal server error';
  280. end
  281. !
  282. respondNotCreatedTo: aResponse
  283. aResponse
  284. writeHead: 400 options: #{'Content-Type' -> 'text/plain'};
  285. write: 'File could not be created. Did you forget to create the src directory on the server?';
  286. end.
  287. !
  288. respondNotFoundTo: aResponse
  289. self fallbackPage isNil ifFalse: [^self respondFileNamed: self fallbackPage to: aResponse].
  290. aResponse
  291. writeHead: 404 options: #{'Content-Type' -> 'text/html'};
  292. write: '<html><body><p>404 Not found</p>';
  293. write: '<p>Did you forget to put an index.html file into the directory which is served by "bin/amber serve"? To solve this you can:<ul>';
  294. write: '<li>create an index.html in the served directory.</li>';
  295. write: '<li>can also specify the location of a page to be served whenever path does not resolve to a file with the "--fallback-page" option.</li>';
  296. write: '<li>change the directory to be served with the "--base-path" option.</li>';
  297. write: '</ul></p></body></html>';
  298. end
  299. !
  300. respondOKTo: aResponse
  301. aResponse
  302. writeHead: 200 options: #{'Content-Type' -> 'text/plain'. 'Access-Control-Allow-Origin' -> '*'};
  303. end.
  304. !
  305. respondRedirect: aString to: aResponse
  306. aResponse
  307. writeHead: 303 options: #{'Location' -> aString};
  308. end.
  309. ! !
  310. !FileServer methodsFor: 'starting'!
  311. start
  312. "Checks if required directory layout is present (issue warning if not).
  313. Afterwards start the server."
  314. self checkDirectoryLayout.
  315. (http createServer: [:request :response |
  316. self handleRequest: request respondTo: response])
  317. on: 'error' do: [:error | console log: 'Error starting server: ', error];
  318. on: 'listening' do: [console log: 'Starting file server on http://', self host, ':', self port asString];
  319. listen: self port host: self host.
  320. !
  321. startOn: aPort
  322. self port: aPort.
  323. self start
  324. ! !
  325. FileServer class instanceVariableNames: 'mimeTypes'!
  326. !FileServer class methodsFor: 'accessing'!
  327. commandLineSwitches
  328. "Collect all methodnames from the 'accessing' protocol
  329. and select the ones with only one parameter.
  330. Then remove the ':' at the end of the name
  331. and add a '--' at the beginning.
  332. Additionally all uppercase letters are made lowercase and preceded by a '-'.
  333. Example: fallbackPage: becomes --fallback-page.
  334. Return the Array containing the commandline switches."
  335. | switches |
  336. switches := ((self methodsInProtocol: 'accessing') collect: [ :each | each selector]).
  337. switches := switches select: [ :each | each match: '^[^:]*:$'].
  338. switches :=switches collect: [ :each |
  339. (each allButLast replace: '([A-Z])' with: '-$1') asLowercase replace: '^([a-z])' with: '--$1' ].
  340. ^ switches
  341. !
  342. defaultBasePath
  343. ^ './'
  344. !
  345. defaultHost
  346. ^ '127.0.0.1'
  347. !
  348. defaultMimeTypes
  349. ^ #{
  350. '%' -> 'application/x-trash'.
  351. '323' -> 'text/h323'.
  352. 'abw' -> 'application/x-abiword'.
  353. 'ai' -> 'application/postscript'.
  354. 'aif' -> 'audio/x-aiff'.
  355. 'aifc' -> 'audio/x-aiff'.
  356. 'aiff' -> 'audio/x-aiff'.
  357. 'alc' -> 'chemical/x-alchemy'.
  358. 'art' -> 'image/x-jg'.
  359. 'asc' -> 'text/plain'.
  360. 'asf' -> 'video/x-ms-asf'.
  361. 'asn' -> 'chemical/x-ncbi-asn1-spec'.
  362. 'aso' -> 'chemical/x-ncbi-asn1-binary'.
  363. 'asx' -> 'video/x-ms-asf'.
  364. 'au' -> 'audio/basic'.
  365. 'avi' -> 'video/x-msvideo'.
  366. 'b' -> 'chemical/x-molconn-Z'.
  367. 'bak' -> 'application/x-trash'.
  368. 'bat' -> 'application/x-msdos-program'.
  369. 'bcpio' -> 'application/x-bcpio'.
  370. 'bib' -> 'text/x-bibtex'.
  371. 'bin' -> 'application/octet-stream'.
  372. 'bmp' -> 'image/x-ms-bmp'.
  373. 'book' -> 'application/x-maker'.
  374. 'bsd' -> 'chemical/x-crossfire'.
  375. 'c' -> 'text/x-csrc'.
  376. 'c++' -> 'text/x-c++src'.
  377. 'c3d' -> 'chemical/x-chem3d'.
  378. 'cac' -> 'chemical/x-cache'.
  379. 'cache' -> 'chemical/x-cache'.
  380. 'cascii' -> 'chemical/x-cactvs-binary'.
  381. 'cat' -> 'application/vnd.ms-pki.seccat'.
  382. 'cbin' -> 'chemical/x-cactvs-binary'.
  383. 'cc' -> 'text/x-c++src'.
  384. 'cdf' -> 'application/x-cdf'.
  385. 'cdr' -> 'image/x-coreldraw'.
  386. 'cdt' -> 'image/x-coreldrawtemplate'.
  387. 'cdx' -> 'chemical/x-cdx'.
  388. 'cdy' -> 'application/vnd.cinderella'.
  389. 'cef' -> 'chemical/x-cxf'.
  390. 'cer' -> 'chemical/x-cerius'.
  391. 'chm' -> 'chemical/x-chemdraw'.
  392. 'chrt' -> 'application/x-kchart'.
  393. 'cif' -> 'chemical/x-cif'.
  394. 'class' -> 'application/java-vm'.
  395. 'cls' -> 'text/x-tex'.
  396. 'cmdf' -> 'chemical/x-cmdf'.
  397. 'cml' -> 'chemical/x-cml'.
  398. 'cod' -> 'application/vnd.rim.cod'.
  399. 'com' -> 'application/x-msdos-program'.
  400. 'cpa' -> 'chemical/x-compass'.
  401. 'cpio' -> 'application/x-cpio'.
  402. 'cpp' -> 'text/x-c++src'.
  403. 'cpt' -> 'image/x-corelphotopaint'.
  404. 'crl' -> 'application/x-pkcs7-crl'.
  405. 'crt' -> 'application/x-x509-ca-cert'.
  406. 'csf' -> 'chemical/x-cache-csf'.
  407. 'csh' -> 'text/x-csh'.
  408. 'csm' -> 'chemical/x-csml'.
  409. 'csml' -> 'chemical/x-csml'.
  410. 'css' -> 'text/css'.
  411. 'csv' -> 'text/comma-separated-values'.
  412. 'ctab' -> 'chemical/x-cactvs-binary'.
  413. 'ctx' -> 'chemical/x-ctx'.
  414. 'cu' -> 'application/cu-seeme'.
  415. 'cub' -> 'chemical/x-gaussian-cube'.
  416. 'cxf' -> 'chemical/x-cxf'.
  417. 'cxx' -> 'text/x-c++src'.
  418. 'dat' -> 'chemical/x-mopac-input'.
  419. 'dcr' -> 'application/x-director'.
  420. 'deb' -> 'application/x-debian-package'.
  421. 'dif' -> 'video/dv'.
  422. 'diff' -> 'text/plain'.
  423. 'dir' -> 'application/x-director'.
  424. 'djv' -> 'image/vnd.djvu'.
  425. 'djvu' -> 'image/vnd.djvu'.
  426. 'dl' -> 'video/dl'.
  427. 'dll' -> 'application/x-msdos-program'.
  428. 'dmg' -> 'application/x-apple-diskimage'.
  429. 'dms' -> 'application/x-dms'.
  430. 'doc' -> 'application/msword'.
  431. 'dot' -> 'application/msword'.
  432. 'dv' -> 'video/dv'.
  433. 'dvi' -> 'application/x-dvi'.
  434. 'dx' -> 'chemical/x-jcamp-dx'.
  435. 'dxr' -> 'application/x-director'.
  436. 'emb' -> 'chemical/x-embl-dl-nucleotide'.
  437. 'embl' -> 'chemical/x-embl-dl-nucleotide'.
  438. 'ent' -> 'chemical/x-pdb'.
  439. 'eps' -> 'application/postscript'.
  440. 'etx' -> 'text/x-setext'.
  441. 'exe' -> 'application/x-msdos-program'.
  442. 'ez' -> 'application/andrew-inset'.
  443. 'fb' -> 'application/x-maker'.
  444. 'fbdoc' -> 'application/x-maker'.
  445. 'fch' -> 'chemical/x-gaussian-checkpoint'.
  446. 'fchk' -> 'chemical/x-gaussian-checkpoint'.
  447. 'fig' -> 'application/x-xfig'.
  448. 'flac' -> 'application/x-flac'.
  449. 'fli' -> 'video/fli'.
  450. 'fm' -> 'application/x-maker'.
  451. 'frame' -> 'application/x-maker'.
  452. 'frm' -> 'application/x-maker'.
  453. 'gal' -> 'chemical/x-gaussian-log'.
  454. 'gam' -> 'chemical/x-gamess-input'.
  455. 'gamin' -> 'chemical/x-gamess-input'.
  456. 'gau' -> 'chemical/x-gaussian-input'.
  457. 'gcd' -> 'text/x-pcs-gcd'.
  458. 'gcf' -> 'application/x-graphing-calculator'.
  459. 'gcg' -> 'chemical/x-gcg8-sequence'.
  460. 'gen' -> 'chemical/x-genbank'.
  461. 'gf' -> 'application/x-tex-gf'.
  462. 'gif' -> 'image/gif'.
  463. 'gjc' -> 'chemical/x-gaussian-input'.
  464. 'gjf' -> 'chemical/x-gaussian-input'.
  465. 'gl' -> 'video/gl'.
  466. 'gnumeric' -> 'application/x-gnumeric'.
  467. 'gpt' -> 'chemical/x-mopac-graph'.
  468. 'gsf' -> 'application/x-font'.
  469. 'gsm' -> 'audio/x-gsm'.
  470. 'gtar' -> 'application/x-gtar'.
  471. 'h' -> 'text/x-chdr'.
  472. 'h++' -> 'text/x-c++hdr'.
  473. 'hdf' -> 'application/x-hdf'.
  474. 'hh' -> 'text/x-c++hdr'.
  475. 'hin' -> 'chemical/x-hin'.
  476. 'hpp' -> 'text/x-c++hdr'.
  477. 'hqx' -> 'application/mac-binhex40'.
  478. 'hs' -> 'text/x-haskell'.
  479. 'hta' -> 'application/hta'.
  480. 'htc' -> 'text/x-component'.
  481. 'htm' -> 'text/html'.
  482. 'html' -> 'text/html'.
  483. 'hxx' -> 'text/x-c++hdr'.
  484. 'ica' -> 'application/x-ica'.
  485. 'ice' -> 'x-conference/x-cooltalk'.
  486. 'ico' -> 'image/x-icon'.
  487. 'ics' -> 'text/calendar'.
  488. 'icz' -> 'text/calendar'.
  489. 'ief' -> 'image/ief'.
  490. 'iges' -> 'model/iges'.
  491. 'igs' -> 'model/iges'.
  492. 'iii' -> 'application/x-iphone'.
  493. 'inp' -> 'chemical/x-gamess-input'.
  494. 'ins' -> 'application/x-internet-signup'.
  495. 'iso' -> 'application/x-iso9660-image'.
  496. 'isp' -> 'application/x-internet-signup'.
  497. 'ist' -> 'chemical/x-isostar'.
  498. 'istr' -> 'chemical/x-isostar'.
  499. 'jad' -> 'text/vnd.sun.j2me.app-descriptor'.
  500. 'jar' -> 'application/java-archive'.
  501. 'java' -> 'text/x-java'.
  502. 'jdx' -> 'chemical/x-jcamp-dx'.
  503. 'jmz' -> 'application/x-jmol'.
  504. 'jng' -> 'image/x-jng'.
  505. 'jnlp' -> 'application/x-java-jnlp-file'.
  506. 'jpe' -> 'image/jpeg'.
  507. 'jpeg' -> 'image/jpeg'.
  508. 'jpg' -> 'image/jpeg'.
  509. 'js' -> 'application/javascript'.
  510. 'kar' -> 'audio/midi'.
  511. 'key' -> 'application/pgp-keys'.
  512. 'kil' -> 'application/x-killustrator'.
  513. 'kin' -> 'chemical/x-kinemage'.
  514. 'kpr' -> 'application/x-kpresenter'.
  515. 'kpt' -> 'application/x-kpresenter'.
  516. 'ksp' -> 'application/x-kspread'.
  517. 'kwd' -> 'application/x-kword'.
  518. 'kwt' -> 'application/x-kword'.
  519. 'latex' -> 'application/x-latex'.
  520. 'lha' -> 'application/x-lha'.
  521. 'lhs' -> 'text/x-literate-haskell'.
  522. 'lsf' -> 'video/x-la-asf'.
  523. 'lsx' -> 'video/x-la-asf'.
  524. 'ltx' -> 'text/x-tex'.
  525. 'lzh' -> 'application/x-lzh'.
  526. 'lzx' -> 'application/x-lzx'.
  527. 'm3u' -> 'audio/x-mpegurl'.
  528. 'm4a' -> 'audio/mpeg'.
  529. 'maker' -> 'application/x-maker'.
  530. 'man' -> 'application/x-troff-man'.
  531. 'mcif' -> 'chemical/x-mmcif'.
  532. 'mcm' -> 'chemical/x-macmolecule'.
  533. 'mdb' -> 'application/msaccess'.
  534. 'me' -> 'application/x-troff-me'.
  535. 'mesh' -> 'model/mesh'.
  536. 'mid' -> 'audio/midi'.
  537. 'midi' -> 'audio/midi'.
  538. 'mif' -> 'application/x-mif'.
  539. 'mm' -> 'application/x-freemind'.
  540. 'mmd' -> 'chemical/x-macromodel-input'.
  541. 'mmf' -> 'application/vnd.smaf'.
  542. 'mml' -> 'text/mathml'.
  543. 'mmod' -> 'chemical/x-macromodel-input'.
  544. 'mng' -> 'video/x-mng'.
  545. 'moc' -> 'text/x-moc'.
  546. 'mol' -> 'chemical/x-mdl-molfile'.
  547. 'mol2' -> 'chemical/x-mol2'.
  548. 'moo' -> 'chemical/x-mopac-out'.
  549. 'mop' -> 'chemical/x-mopac-input'.
  550. 'mopcrt' -> 'chemical/x-mopac-input'.
  551. 'mov' -> 'video/quicktime'.
  552. 'movie' -> 'video/x-sgi-movie'.
  553. 'mp2' -> 'audio/mpeg'.
  554. 'mp3' -> 'audio/mpeg'.
  555. 'mp4' -> 'video/mp4'.
  556. 'mpc' -> 'chemical/x-mopac-input'.
  557. 'mpe' -> 'video/mpeg'.
  558. 'mpeg' -> 'video/mpeg'.
  559. 'mpega' -> 'audio/mpeg'.
  560. 'mpg' -> 'video/mpeg'.
  561. 'mpga' -> 'audio/mpeg'.
  562. 'ms' -> 'application/x-troff-ms'.
  563. 'msh' -> 'model/mesh'.
  564. 'msi' -> 'application/x-msi'.
  565. 'mvb' -> 'chemical/x-mopac-vib'.
  566. 'mxu' -> 'video/vnd.mpegurl'.
  567. 'nb' -> 'application/mathematica'.
  568. 'nc' -> 'application/x-netcdf'.
  569. 'nwc' -> 'application/x-nwc'.
  570. 'o' -> 'application/x-object'.
  571. 'oda' -> 'application/oda'.
  572. 'odb' -> 'application/vnd.oasis.opendocument.database'.
  573. 'odc' -> 'application/vnd.oasis.opendocument.chart'.
  574. 'odf' -> 'application/vnd.oasis.opendocument.formula'.
  575. 'odg' -> 'application/vnd.oasis.opendocument.graphics'.
  576. 'odi' -> 'application/vnd.oasis.opendocument.image'.
  577. 'odm' -> 'application/vnd.oasis.opendocument.text-master'.
  578. 'odp' -> 'application/vnd.oasis.opendocument.presentation'.
  579. 'ods' -> 'application/vnd.oasis.opendocument.spreadsheet'.
  580. 'odt' -> 'application/vnd.oasis.opendocument.text'.
  581. 'ogg' -> 'application/ogg'.
  582. 'old' -> 'application/x-trash'.
  583. 'oth' -> 'application/vnd.oasis.opendocument.text-web'.
  584. 'oza' -> 'application/x-oz-application'.
  585. 'p' -> 'text/x-pascal'.
  586. 'p7r' -> 'application/x-pkcs7-certreqresp'.
  587. 'pac' -> 'application/x-ns-proxy-autoconfig'.
  588. 'pas' -> 'text/x-pascal'.
  589. 'pat' -> 'image/x-coreldrawpattern'.
  590. 'pbm' -> 'image/x-portable-bitmap'.
  591. 'pcf' -> 'application/x-font'.
  592. 'pcf.Z' -> 'application/x-font'.
  593. 'pcx' -> 'image/pcx'.
  594. 'pdb' -> 'chemical/x-pdb'.
  595. 'pdf' -> 'application/pdf'.
  596. 'pfa' -> 'application/x-font'.
  597. 'pfb' -> 'application/x-font'.
  598. 'pgm' -> 'image/x-portable-graymap'.
  599. 'pgn' -> 'application/x-chess-pgn'.
  600. 'pgp' -> 'application/pgp-signature'.
  601. 'pk' -> 'application/x-tex-pk'.
  602. 'pl' -> 'text/x-perl'.
  603. 'pls' -> 'audio/x-scpls'.
  604. 'pm' -> 'text/x-perl'.
  605. 'png' -> 'image/png'.
  606. 'pnm' -> 'image/x-portable-anymap'.
  607. 'pot' -> 'text/plain'.
  608. 'ppm' -> 'image/x-portable-pixmap'.
  609. 'pps' -> 'application/vnd.ms-powerpoint'.
  610. 'ppt' -> 'application/vnd.ms-powerpoint'.
  611. 'prf' -> 'application/pics-rules'.
  612. 'prt' -> 'chemical/x-ncbi-asn1-ascii'.
  613. 'ps' -> 'application/postscript'.
  614. 'psd' -> 'image/x-photoshop'.
  615. 'psp' -> 'text/x-psp'.
  616. 'py' -> 'text/x-python'.
  617. 'pyc' -> 'application/x-python-code'.
  618. 'pyo' -> 'application/x-python-code'.
  619. 'qt' -> 'video/quicktime'.
  620. 'qtl' -> 'application/x-quicktimeplayer'.
  621. 'ra' -> 'audio/x-realaudio'.
  622. 'ram' -> 'audio/x-pn-realaudio'.
  623. 'rar' -> 'application/rar'.
  624. 'ras' -> 'image/x-cmu-raster'.
  625. 'rd' -> 'chemical/x-mdl-rdfile'.
  626. 'rdf' -> 'application/rdf+xml'.
  627. 'rgb' -> 'image/x-rgb'.
  628. 'rm' -> 'audio/x-pn-realaudio'.
  629. 'roff' -> 'application/x-troff'.
  630. 'ros' -> 'chemical/x-rosdal'.
  631. 'rpm' -> 'application/x-redhat-package-manager'.
  632. 'rss' -> 'application/rss+xml'.
  633. 'rtf' -> 'text/rtf'.
  634. 'rtx' -> 'text/richtext'.
  635. 'rxn' -> 'chemical/x-mdl-rxnfile'.
  636. 'sct' -> 'text/scriptlet'.
  637. 'sd' -> 'chemical/x-mdl-sdfile'.
  638. 'sd2' -> 'audio/x-sd2'.
  639. 'sda' -> 'application/vnd.stardivision.draw'.
  640. 'sdc' -> 'application/vnd.stardivision.calc'.
  641. 'sdd' -> 'application/vnd.stardivision.impress'.
  642. 'sdf' -> 'chemical/x-mdl-sdfile'.
  643. 'sdp' -> 'application/vnd.stardivision.impress'.
  644. 'sdw' -> 'application/vnd.stardivision.writer'.
  645. 'ser' -> 'application/java-serialized-object'.
  646. 'sgf' -> 'application/x-go-sgf'.
  647. 'sgl' -> 'application/vnd.stardivision.writer-global'.
  648. 'sh' -> 'text/x-sh'.
  649. 'shar' -> 'application/x-shar'.
  650. 'shtml' -> 'text/html'.
  651. 'sid' -> 'audio/prs.sid'.
  652. 'sik' -> 'application/x-trash'.
  653. 'silo' -> 'model/mesh'.
  654. 'sis' -> 'application/vnd.symbian.install'.
  655. 'sit' -> 'application/x-stuffit'.
  656. 'skd' -> 'application/x-koan'.
  657. 'skm' -> 'application/x-koan'.
  658. 'skp' -> 'application/x-koan'.
  659. 'skt' -> 'application/x-koan'.
  660. 'smf' -> 'application/vnd.stardivision.math'.
  661. 'smi' -> 'application/smil'.
  662. 'smil' -> 'application/smil'.
  663. 'snd' -> 'audio/basic'.
  664. 'spc' -> 'chemical/x-galactic-spc'.
  665. 'spl' -> 'application/x-futuresplash'.
  666. 'src' -> 'application/x-wais-source'.
  667. 'stc' -> 'application/vnd.sun.xml.calc.template'.
  668. 'std' -> 'application/vnd.sun.xml.draw.template'.
  669. 'sti' -> 'application/vnd.sun.xml.impress.template'.
  670. 'stl' -> 'application/vnd.ms-pki.stl'.
  671. 'stw' -> 'application/vnd.sun.xml.writer.template'.
  672. 'sty' -> 'text/x-tex'.
  673. 'sv4cpio' -> 'application/x-sv4cpio'.
  674. 'sv4crc' -> 'application/x-sv4crc'.
  675. 'svg' -> 'image/svg+xml'.
  676. 'svgz' -> 'image/svg+xml'.
  677. 'sw' -> 'chemical/x-swissprot'.
  678. 'swf' -> 'application/x-shockwave-flash'.
  679. 'swfl' -> 'application/x-shockwave-flash'.
  680. 'sxc' -> 'application/vnd.sun.xml.calc'.
  681. 'sxd' -> 'application/vnd.sun.xml.draw'.
  682. 'sxg' -> 'application/vnd.sun.xml.writer.global'.
  683. 'sxi' -> 'application/vnd.sun.xml.impress'.
  684. 'sxm' -> 'application/vnd.sun.xml.math'.
  685. 'sxw' -> 'application/vnd.sun.xml.writer'.
  686. 't' -> 'application/x-troff'.
  687. 'tar' -> 'application/x-tar'.
  688. 'taz' -> 'application/x-gtar'.
  689. 'tcl' -> 'text/x-tcl'.
  690. 'tex' -> 'text/x-tex'.
  691. 'texi' -> 'application/x-texinfo'.
  692. 'texinfo' -> 'application/x-texinfo'.
  693. 'text' -> 'text/plain'.
  694. 'tgf' -> 'chemical/x-mdl-tgf'.
  695. 'tgz' -> 'application/x-gtar'.
  696. 'tif' -> 'image/tiff'.
  697. 'tiff' -> 'image/tiff'.
  698. 'tk' -> 'text/x-tcl'.
  699. 'tm' -> 'text/texmacs'.
  700. 'torrent' -> 'application/x-bittorrent'.
  701. 'tr' -> 'application/x-troff'.
  702. 'ts' -> 'text/texmacs'.
  703. 'tsp' -> 'application/dsptype'.
  704. 'tsv' -> 'text/tab-separated-values'.
  705. 'txt' -> 'text/plain'.
  706. 'udeb' -> 'application/x-debian-package'.
  707. 'uls' -> 'text/iuls'.
  708. 'ustar' -> 'application/x-ustar'.
  709. 'val' -> 'chemical/x-ncbi-asn1-binary'.
  710. 'vcd' -> 'application/x-cdlink'.
  711. 'vcf' -> 'text/x-vcard'.
  712. 'vcs' -> 'text/x-vcalendar'.
  713. 'vmd' -> 'chemical/x-vmd'.
  714. 'vms' -> 'chemical/x-vamas-iso14976'.
  715. 'vor' -> 'application/vnd.stardivision.writer'.
  716. 'vrm' -> 'x-world/x-vrml'.
  717. 'vrml' -> 'x-world/x-vrml'.
  718. 'vsd' -> 'application/vnd.visio'.
  719. 'wad' -> 'application/x-doom'.
  720. 'wav' -> 'audio/x-wav'.
  721. 'wax' -> 'audio/x-ms-wax'.
  722. 'wbmp' -> 'image/vnd.wap.wbmp'.
  723. 'wbxml' -> 'application/vnd.wap.wbxml'.
  724. 'wk' -> 'application/x-123'.
  725. 'wm' -> 'video/x-ms-wm'.
  726. 'wma' -> 'audio/x-ms-wma'.
  727. 'wmd' -> 'application/x-ms-wmd'.
  728. 'wml' -> 'text/vnd.wap.wml'.
  729. 'wmlc' -> 'application/vnd.wap.wmlc'.
  730. 'wmls' -> 'text/vnd.wap.wmlscript'.
  731. 'wmlsc' -> 'application/vnd.wap.wmlscriptc'.
  732. 'wmv' -> 'video/x-ms-wmv'.
  733. 'wmx' -> 'video/x-ms-wmx'.
  734. 'wmz' -> 'application/x-ms-wmz'.
  735. 'wp5' -> 'application/wordperfect5.1'.
  736. 'wpd' -> 'application/wordperfect'.
  737. 'wrl' -> 'x-world/x-vrml'.
  738. 'wsc' -> 'text/scriptlet'.
  739. 'wvx' -> 'video/x-ms-wvx'.
  740. 'wz' -> 'application/x-wingz'.
  741. 'xbm' -> 'image/x-xbitmap'.
  742. 'xcf' -> 'application/x-xcf'.
  743. 'xht' -> 'application/xhtml+xml'.
  744. 'xhtml' -> 'application/xhtml+xml'.
  745. 'xlb' -> 'application/vnd.ms-excel'.
  746. 'xls' -> 'application/vnd.ms-excel'.
  747. 'xlt' -> 'application/vnd.ms-excel'.
  748. 'xml' -> 'application/xml'.
  749. 'xpi' -> 'application/x-xpinstall'.
  750. 'xpm' -> 'image/x-xpixmap'.
  751. 'xsl' -> 'application/xml'.
  752. 'xtel' -> 'chemical/x-xtel'.
  753. 'xul' -> 'application/vnd.mozilla.xul+xml'.
  754. 'xwd' -> 'image/x-xwindowdump'.
  755. 'xyz' -> 'chemical/x-xyz'.
  756. 'zip' -> 'application/zip'.
  757. 'zmt' -> 'chemical/x-mopac-input'.
  758. '~' -> 'application/x-trash'
  759. }
  760. !
  761. defaultPort
  762. ^ 4000
  763. !
  764. mimeTypeFor: aString
  765. ^ self mimeTypes at: (aString replace: '.*[\.]' with: '') ifAbsent: ['text/plain']
  766. !
  767. mimeTypes
  768. ^ mimeTypes ifNil: [mimeTypes := self defaultMimeTypes]
  769. !
  770. printHelp
  771. console log: 'Available commandline options are:'.
  772. console log: '--help'.
  773. self commandLineSwitches do: [ :each |
  774. console log: each, ' <parameter>']
  775. !
  776. selectorForCommandLineSwitch: aSwitch
  777. "Remove the trailing '--', add ':' at the end
  778. and replace all occurences of a lowercase letter preceded by a '-' with
  779. the Uppercase letter.
  780. Example: --fallback-page becomes fallbackPage:"
  781. ^ ((aSwitch replace: '^--' with: '')
  782. replace: '-[a-z]' with: [ :each | each second asUppercase ]), ':'
  783. ! !
  784. !FileServer class methodsFor: 'initialization'!
  785. createServerWithArguments: options
  786. "If options are empty return a default FileServer instance.
  787. If options are given loop through them and set the passed in values
  788. on the FileServer instance.
  789. Commanline options map directly to methods in the 'accessing' protocol
  790. taking one parameter.
  791. Adding a method to this protocol makes it directly settable through
  792. command line options.
  793. "
  794. | server popFront front optionName optionValue switches |
  795. switches := self commandLineSwitches.
  796. server := self new.
  797. options ifEmpty: [^server].
  798. (options size even) ifFalse: [
  799. console log: 'Using default parameters.'.
  800. console log: 'Wrong commandline options or not enough arguments for: ' , options.
  801. console log: 'Use any of the following ones: ', switches.
  802. ^server].
  803. popFront := [:args |
  804. front := args first.
  805. args remove: front.
  806. front].
  807. [options notEmpty] whileTrue: [
  808. optionName := popFront value: options.
  809. optionValue := popFront value: options.
  810. (switches includes: optionName) ifTrue: [
  811. optionName := self selectorForCommandLineSwitch: optionName.
  812. server perform: optionName withArguments: (Array with: optionValue)]
  813. ifFalse: [
  814. console log: optionName, ' is not a valid commandline option'.
  815. console log: 'Use any of the following ones: ', switches ]].
  816. ^ server.
  817. !
  818. main
  819. "Main entry point for Amber applications.
  820. Creates and starts a FileServer instance."
  821. | fileServer args |
  822. args := process argv.
  823. "Remove the first args which contain the path to the node executable and the script file."
  824. args removeFrom: 1 to: 3.
  825. args detect: [ :each |
  826. (each = '--help') ifTrue: [FileServer printHelp]]
  827. ifNone: [
  828. fileServer := FileServer createServerWithArguments: args.
  829. ^ fileServer start]
  830. ! !
  831. Object subclass: #NodeTestRunner
  832. instanceVariableNames: ''
  833. package: 'AmberCli'!
  834. !NodeTestRunner class methodsFor: 'not yet classified'!
  835. runTestSuite
  836. | suite worker |
  837. suite := OrderedCollection new.
  838. (TestCase allSubclasses select: [ :each | each isAbstract not ])
  839. do: [ :each | suite addAll: each buildSuite ].
  840. worker := TestSuiteRunner on: suite.
  841. worker announcer on: ResultAnnouncement do:
  842. [ :ann | | result |
  843. result := ann result.
  844. result runs = result total ifTrue: [
  845. console log: result runs asString, ' tests run, ', result failures size asString, ' failures, ', result errors size asString, ' errors.'.
  846. result failures isEmpty ifFalse: [
  847. result failures first runCase.
  848. "the line above should throw, normally, but just in case I leave the line below"
  849. self throw: result failures first class name, ' >> ', result failures first selector, ' is failing!!!!' ].
  850. result errors isEmpty ifFalse: [
  851. result errors first runCase.
  852. "the line above should throw, normally, but just in case I leave the line below"
  853. self throw: result errors first class name, ' >> ', result errors first selector, ' has errors!!!!' ].
  854. ]].
  855. worker run
  856. ! !
  857. Object subclass: #Repl
  858. instanceVariableNames: 'readline interface util session resultCount commands'
  859. package: 'AmberCli'!
  860. !Repl commentStamp!
  861. I am a class representing a REPL (Read Evaluate Print Loop) and provide a command line interface to Amber Smalltalk.
  862. On the prompt you can type Amber statements which will be evaluated after pressing <Enter>.
  863. The evaluation is comparable with executing a 'DoIt' in a workspace.
  864. My runtime requirement is a functional Node.js executable with working Readline support.!
  865. !Repl methodsFor: 'accessing'!
  866. commands
  867. ^ commands
  868. !
  869. prompt
  870. ^ 'amber >> '
  871. ! !
  872. !Repl methodsFor: 'actions'!
  873. clearScreen
  874. | esc cls |
  875. esc := String fromCharCode: 27.
  876. cls := esc, '[2J', esc, '[0;0f'.
  877. process stdout write: cls.
  878. interface prompt
  879. !
  880. close
  881. process stdin destroy
  882. !
  883. createInterface
  884. interface := readline createInterface: process stdin stdout: process stdout.
  885. interface on: 'line' do: [:buffer | self processLine: buffer].
  886. interface on: 'close' do: [self close].
  887. self printWelcome; setupHotkeys; setPrompt.
  888. interface prompt
  889. !
  890. eval: buffer
  891. ^ self eval: buffer on: DoIt new.
  892. !
  893. eval: buffer on: anObject
  894. | result |
  895. buffer isEmpty ifFalse: [
  896. [result := Compiler new evaluateExpression: buffer on: anObject]
  897. tryCatch: [:e |
  898. e isSmalltalkError
  899. ifTrue: [ e resignal ]
  900. ifFalse: [ process stdout write: e jsStack ]]].
  901. ^ result
  902. !
  903. printWelcome
  904. Transcript show: 'Type :q to exit.'; cr.
  905. !
  906. setPrompt
  907. interface setPrompt: self prompt
  908. ! !
  909. !Repl methodsFor: 'initialization'!
  910. initialize
  911. super initialize.
  912. session := DoIt new.
  913. readline := require value: 'readline'.
  914. util := require value: 'util'.
  915. self setupCommands
  916. !
  917. setupCommands
  918. commands := Dictionary from: {
  919. {':q'} -> [process exit].
  920. {''} -> [interface prompt]}
  921. !
  922. setupHotkeys
  923. process stdin on: 'keypress' do: [:s :key | key ifNotNil: [self onKeyPress: key]].
  924. ! !
  925. !Repl methodsFor: 'private'!
  926. addVariableNamed: aString to: anObject
  927. | newClass newObject |
  928. newClass := self subclass: anObject class withVariable: aString.
  929. self encapsulateVariable: aString withValue: anObject in: newClass.
  930. newObject := newClass new.
  931. self setPreviousVariablesFor: newObject from: anObject.
  932. ^ newObject
  933. !
  934. assignNewVariable: buffer do: aBlock
  935. "Assigns a new variable and calls the given block with the variable's name and value
  936. if buffer contains an assignment expression. If it doesn't the block is called with nil for
  937. both arguments."
  938. ^ self parseAssignment: buffer do: [ :name :expr || varName value |
  939. varName := name ifNil: [self nextResultName].
  940. session := self addVariableNamed: varName to: session.
  941. [ value := self eval: varName, ' := ', (expr ifNil: [buffer]) on: session ]
  942. on: Error
  943. do: [ :e | ConsoleErrorHandler new logError: e. value := nil].
  944. aBlock value: varName value: value]
  945. !
  946. encapsulateVariable: aString withValue: anObject in: aClass
  947. "Add getter and setter for given variable to session."
  948. | compiler |
  949. compiler := Compiler new.
  950. compiler install: aString, ': anObject ^ ', aString, ' := anObject' forClass: aClass protocol: 'session'.
  951. compiler install: aString, ' ^ ', aString forClass: aClass protocol: 'session'.
  952. !
  953. executeCommand: aString
  954. "Tries to process the given string as a command. Returns true if it was a command, false if not."
  955. self commands keysAndValuesDo: [:names :cmd |
  956. (names includes: aString) ifTrue: [
  957. cmd value.
  958. ^ true]].
  959. ^ false
  960. !
  961. instanceVariableNamesFor: aClass
  962. "Yields all instance variable names for the given class, including inherited ones."
  963. ^ aClass superclass
  964. ifNotNil: [
  965. aClass instanceVariableNames copyWithAll: (self instanceVariableNamesFor: aClass superclass)]
  966. ifNil: [
  967. aClass instanceVariableNames]
  968. !
  969. isIdentifier: aString
  970. ^ aString match: '^[a-z_]\w*$' asRegexp
  971. !
  972. isVariableDefined: aString
  973. ^ (self instanceVariableNamesFor: session class) includes: aString
  974. !
  975. nextResultName
  976. resultCount := resultCount
  977. ifNotNil: [resultCount + 1]
  978. ifNil: [1].
  979. ^ 'res', resultCount asString
  980. !
  981. onKeyPress: key
  982. (key ctrl and: [key name = 'l'])
  983. ifTrue: [self clearScreen]
  984. !
  985. parseAssignment: aString do: aBlock
  986. "Assigns a new variable if the given string is an assignment expression. Calls the given block with name and value.
  987. If the string is not one no variable will be assigned and the block will be called with nil for both arguments."
  988. | assignment |
  989. assignment := (aString tokenize: ':=') collect: [:s | s trimBoth].
  990. ^ (assignment size = 2 and: [self isIdentifier: assignment first])
  991. ifTrue: [ aBlock value: assignment first value: assignment last ]
  992. ifFalse: [ aBlock value: nil value: nil ]
  993. !
  994. presentResultNamed: varName withValue: value
  995. Transcript show: varName, ': ', value class name, ' = ', value asString; cr.
  996. interface prompt
  997. !
  998. processLine: buffer
  999. "Processes lines entered through the readline interface."
  1000. | show |
  1001. show := [:varName :value | self presentResultNamed: varName withValue: value].
  1002. (self executeCommand: buffer) ifFalse: [
  1003. (self isVariableDefined: buffer)
  1004. ifTrue: [show value: buffer value: (session perform: buffer)]
  1005. ifFalse: [self assignNewVariable: buffer do: show]]
  1006. !
  1007. setPreviousVariablesFor: newObject from: oldObject
  1008. (self instanceVariableNamesFor: oldObject class) do: [:each |
  1009. newObject perform: each, ':' withArguments: {oldObject perform: each}].
  1010. !
  1011. subclass: aClass withVariable: varName
  1012. "Create subclass with new variable."
  1013. ^ ClassBuilder new
  1014. addSubclassOf: aClass
  1015. named: (self subclassNameFor: aClass) asSymbol
  1016. instanceVariableNames: {varName}
  1017. package: 'Compiler-Core'
  1018. !
  1019. subclassNameFor: aClass
  1020. ^ (aClass name matchesOf: '\d+$')
  1021. ifNotNil: [ | counter |
  1022. counter := (aClass name matchesOf: '\d+$') first asNumber + 1.
  1023. aClass name replaceRegexp: '\d+$' asRegexp with: counter asString]
  1024. ifNil: [
  1025. aClass name, '2'].
  1026. ! !
  1027. !Repl class methodsFor: 'initialization'!
  1028. main
  1029. self new createInterface
  1030. ! !