AmberCli.st 38 KB

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