AmberCli.st 38 KB

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