AmberCli.st 38 KB

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