1
0

AmberCli.st 36 KB

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