555
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.js 241KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500
  1. // {{!-- https://corporatefinanceinstitute.com/resources/knowledge/accounting/general-ledger-gl/ --}}
  2. "use strict";
  3. // console.log([ 'If this is colorized we have color output...' ])
  4. // console.dir(process.env)
  5. var __g = require('global-this');
  6. var ENV = Object.assign({}, process.env); // Shallow clone so we can set values and reuse for reshelling spawns.
  7. __g.env = ENV
  8. ENV.NODE_ENV = (ENV.NODE_ENV && ENV.NODE_ENV.trim()) || 'development'
  9. const fs = require('fs')
  10. var path = require('path');
  11. var utils = require('bbhverse');
  12. var any = utils.any;
  13. var Tasq = utils.Tasq
  14. var statuslog = utils.Traq
  15. var Traq = utils.Traq
  16. // console.error('EEEEEEEEEEEEEEEEEEEE')
  17. var util = require('util')
  18. var ENV = Object.assign({}, process.env); // Shallow clone so we can set values and reuse for reshelling spawns.
  19. const cliargs = utils.cliargs;
  20. const processedArgs = cliargs(process.argv.slice(2));
  21. const __ALIAS__STAMP__ = '9e7bebe0-1f57-11ec-8f88-778ffeea9d1b'
  22. const BUILD_VERSION = '[VI]Version: {version} - built on {date}[/VI]';
  23. const runtimestamp = processedArgs.runtimestamp ? (new Date(processedArgs.runtimestamp)).getTime() : (new Date()).getTime();
  24. function getVersion() { return BUILD_VERSION; }
  25. // 'use strict';
  26. // PB : TODO -- make sure folder context is proper coz we can now run elxr from anywhere.
  27. // PB : TODO --
  28. // runas bypass non elevated tasks when we request privelege
  29. // runas message is always error needs to be fixed.
  30. // runas wait needs to be parallelized.
  31. // suppress elevation check error messages
  32. // support runas lauched directly from shell.
  33. // pass in environment in hta to shellexecute.
  34. const https = require('https')
  35. const http = require('http');
  36. const { Console } = require('console');
  37. const { env } = require('process');
  38. const PATTERNAPI = require('serververse').PATTERNAPI
  39. // const RESTAPI = require('serververse').RESTAPI
  40. const RESTAPI = (function(){
  41. // Singleton
  42. function RESTAPI(){}
  43. // RESTAPI.create = RESTAPI; // Returns the one singe instance which is the class itself
  44. // const httpsoptions = {
  45. // hostname: 'whatever.com',
  46. // port: 443,
  47. // path: '/todos',
  48. // method: 'POST',
  49. // headers: {
  50. // 'Content-Type': 'application/json',
  51. // 'Content-Length': data.length
  52. // }
  53. // }
  54. RESTAPI.method = function(options, resolve, reject){
  55. options.headers = options.headers || { 'Content-Type': 'application/json' }
  56. const data = options.payload ? new TextEncoder().encode( JSON.stringify(options.payload) ) : null
  57. options.headers = options.payload ? (options.headers || {
  58. 'Content-Type': 'application/json',
  59. 'Content-Length': data.length
  60. }) : (options.headers || {})
  61. !options.headers.Authorization && usertokens[options.username] ? (()=>{
  62. options.headers.Authorization = `token ${usertokens[options.username]}`
  63. delete options.username
  64. onauthenticated()
  65. })() : (()=>{
  66. if(!usertokens[options.username] && !options.isAuthCall) {
  67. RESTAPI.authenticate( utils.assign( {isAuthCall : true}, options ) , onauthenticated, function(err){
  68. // PB : TODO -- Retry without auth...
  69. console.error('Auth failed or not accessible')
  70. reject(err)
  71. })
  72. }
  73. else onauthenticated()
  74. })()
  75. function onauthenticated(){
  76. var acquirer = getHTTPorS(options)
  77. const req = acquirer.request(options, res => {
  78. if (res.statusCode < 200 || res.statusCode >= 300) {
  79. // new Error('statusCode=' + res.statusCode)
  80. return reject('statusCode = ' + res.statusCode);
  81. }
  82. var body = [];
  83. // res.setEncoding('utf8');
  84. res.on('data', (chunk)=>{ body.push(chunk); });
  85. res.on('end', ()=>{
  86. try {
  87. if(res.headers['content-type'] && res.headers['content-type'].split(';').find( (i)=> i.trim() === 'application/json' )) body = JSON.parse(Buffer.concat(body).toString());
  88. else body = Buffer.concat(body).toString();
  89. } catch(e) { return reject(e); }
  90. resolve(body);
  91. });
  92. });
  93. req.on('error', error => { reject(error) })
  94. if(options.payload) req.write(data)
  95. req.end()
  96. }
  97. }
  98. var usertokens = {}
  99. RESTAPI.authenticate = function(options, resolve, reject){
  100. options.headers = options.headers || { 'Content-Type': 'application/json' }
  101. if(!usertokens[options.username]) {
  102. // Authenticate and acquire token.
  103. // https://git.bbh/api/v1/users/<username>/tokens
  104. // curl -XPOST -H "Content-Type: application/json" -k -d '{"name":"demo"}' -u demo:demo123 http://git.bbh/api/v1/users/demo/tokens
  105. var _options = Object.assign({}, options)
  106. // _options.username = 'demo'
  107. // _options.password = 'demo123'
  108. _options.method = 'POST'
  109. _options.headers.Authorization = `Basic ${Buffer.from(`${_options.username}:${_options.password}`).toString('base64')}`
  110. _options.path = `/api/v1/users/${_options.username}/tokens`
  111. var postoptions = { name : _options.username }
  112. delete _options.username
  113. delete _options.password
  114. _options.payload = postoptions
  115. RESTAPI.post( _options, function(tokenresp){
  116. // tokenresp = JSON.parse(tokenresp)
  117. usertokens[options.username] = tokenresp.sha1
  118. resolve(tokenresp)
  119. },
  120. function(err){ reject(err) }
  121. )
  122. }
  123. else resolve(tokenresp.sha1)
  124. }
  125. RESTAPI.put = RESTAPI.get = RESTAPI.post = RESTAPI.method
  126. return RESTAPI
  127. })();
  128. var getHTTPorS = function(options){ return options.protocol.startsWith('https') ? https : http; }
  129. const GITEA = (function(){
  130. function GITEA(){}
  131. GITEA.APIROOT = '/api/v1'
  132. GITEA.repository = {
  133. fork( httpoptions, cmdoptions, giteaoptions, resolve, reject ){
  134. // forkoptions = { owner : httpoptions.username, repo : {{reoptoFork}} }
  135. // giteaoptions = {
  136. // organization string
  137. // --- organization name, if forking into an organization
  138. // }
  139. // http://try.gitea.io/api/v1/repos/{owner}/{repo}/forks
  140. httpoptions.path = `${GITEA.APIROOT}/repos/${cmdoptions.owner}/${cmdoptions.repo}/forks`
  141. httpoptions.method = 'POST'
  142. httpoptions.payload = giteaoptions;
  143. return RESTAPI.post(httpoptions, resolve || function(){}, reject || function(){} )
  144. }
  145. , updateattributes( httpoptions, cmdoptions, giteaoptions, resolve, reject ){
  146. httpoptions.path = `${GITEA.APIROOT}/repos/${cmdoptions.owner}/${cmdoptions.repo}`
  147. httpoptions.method = 'PATCH'
  148. httpoptions.payload = giteaoptions;
  149. return RESTAPI.post(httpoptions, resolve || function(){}, reject || function(){} )
  150. }
  151. , exists( httpoptions, repo, owner ) {
  152. // ​/users​/{username} // Get a user
  153. httpoptions.path = `${GITEA.APIROOT}/repos/${owner}/${repo}`
  154. httpoptions.method = 'GET'
  155. return new Promise( (resolve, reject) => {
  156. RESTAPI.get(httpoptions, function(o){
  157. if(o.id) return resolve(true)
  158. return resolve(false) }, reject || function(){ return false } )
  159. })
  160. }
  161. , addcollaborator( httpoptions, repodef, owner, collaborator, permission ) {
  162. permission = permission || 'Read'
  163. httpoptions.payload = { permission }
  164. httpoptions.path = `${GITEA.APIROOT}/repos/${owner}/${repodef.repo}/collaborators/${collaborator}`
  165. httpoptions.method = 'PUT'
  166. return new Promise( (resolve, reject) => {
  167. RESTAPI.put(httpoptions, function(o){
  168. //
  169. if(o === "") return resolve(true)
  170. return resolve(false) }, reject || function(){ return false } )
  171. })
  172. }
  173. }
  174. GITEA.user = {
  175. getuser( httpoptions, cmdoptions, giteaoptions, resolve, reject ){
  176. // ​/users​/{username} // Get a user
  177. httpoptions.path = `${GITEA.APIROOT}/users/${httpoptions.username}`
  178. httpoptions.method = 'GET'
  179. return RESTAPI.get(httpoptions, giteaoptions, resolve || function(){}, reject || function(){} )
  180. }
  181. }
  182. return GITEA
  183. })();
  184. // Wrapper for Git shell operations. Some meta operations will map to a bunch of GIT commands.
  185. const GIT = (function(){
  186. function GIT(){}
  187. Object.assign(GIT, {
  188. 'switch user'(username){
  189. var httpoptions = new URL(selectedinstance.reposerver);
  190. httpoptions.username = selectedinstance.username
  191. httpoptions.password = selectedinstance.password
  192. return GITEA.user.getuser(httpoptions).then(()=>{
  193. return nodeShellExec('git', ['config', '--replace-all', 'user.name', username],
  194. {
  195. inherit: true, shell: true,
  196. env: ENV
  197. , cwd: instanceroot + '/' + repo
  198. , runas: processedArgs.runas
  199. , title: `'git', ${['config', '--replace-all', 'user.name', username].join(' ')}`
  200. })
  201. }
  202. )
  203. .catch(e => {
  204. console.error(e + 'Could not switch. Probably no such user.')
  205. })
  206. }
  207. })
  208. return GIT
  209. })();
  210. // PB : NOTE -- iife doesnt work if previous statement is not terminated by ;
  211. (function () {
  212. "use strict";
  213. if (!Array.prototype.earlyreduce) {
  214. Array.prototype.earlyreduce = function(eachcallback, initialValue, donecallback){
  215. var iterable = this;
  216. var donecallback = donecallback || (a=>a)
  217. var result = { value : initialValue === undefined ? iterable[0] : initialValue };
  218. initialValue === undefined ? null : result = eachcallback(result, element, i, iterable);
  219. // function *earlyReduceGenerator(acc, v, i, a) {
  220. for(var i = initialValue === undefined ? 0 : 1; i < iterable.length; i++){
  221. var element = iterable[i]
  222. result = eachcallback(result, element, i, iterable)
  223. if(result.done) return donecallback(result)
  224. }
  225. // }
  226. return donecallback(result)
  227. }
  228. }
  229. }());
  230. function isWin(){ return /^win/.test(process.platform) }
  231. if(isWin()) {
  232. var win_verse = require('./win_verse')
  233. var shell_verse = win_verse;
  234. shell_verse.getVersion = getVersion
  235. }
  236. else {
  237. var lin_verse = require('./lin_verse')
  238. var shell_verse = lin_verse;
  239. }
  240. // PB : TODO -- In windows if we are run from an elevated shell we never move forward and simply exits !?.
  241. // -- Currently workaround in windows is to always run from a non-elevated shell.
  242. shell_verse.acquireElevationState().then((isElevated) => {
  243. // PB : TODO -- Implement queues using streams. Specially form bundling all elevated tasks as a single out of proc run with post elevated queue run postponed until the elevated stream and its dependencies are completed....
  244. const { existsSync } = require('fs');
  245. const existslink = function(name, cb){
  246. fs.lstat(name, (error, stats) => {
  247. if (error) {
  248. console.log(error);
  249. cb(error)
  250. }
  251. else {
  252. console.log("Stats object for: example_directory.txt");
  253. console.log(stats);
  254. // Using methods of the Stats object
  255. console.log("Path is file:", stats.isFile());
  256. console.log("Path is directory:", stats.isDirectory());
  257. cb(null, true)
  258. }
  259. });
  260. }
  261. const existsFolderSync = existsSync;
  262. var hasElxr = function(path, options, cb) {
  263. // PB : TOOD -- Navigate up the folder chain to discover the relevant .elxr directory.
  264. options = options || {};
  265. var tasks = [
  266. '/elxr' // Is there a subfolder named elxr
  267. , '/elxr/.git' // which is also a git repository
  268. // , '/elxr/.elxr' // and has .elxr subfolder we now store this in the instanceroot.
  269. , '/elxr/' + __ALIAS__STAMP__ // Which has our stamp.
  270. ]
  271. if(options.sync) { return tasks.earlyreduce((acc, tpath)=>{
  272. var value = existsFolderSync(path + tpath);
  273. return { value, done : acc && !value };
  274. }).value }
  275. if(cb) return cb(null, tasks.earlyreduce((acc, tpath)=>{
  276. var value = existsFolderSync(path + tpath);
  277. return { value, done : acc && !value };
  278. }).value );
  279. return Promise.resolve(tasks.earlyreduce((acc, tpath)=>{
  280. var value = existsFolderSync(path + tpath);
  281. return { value, done : acc && !value };
  282. }).value);
  283. }
  284. var hasElxrSync = function(path){ return hasElxr(path, { sync :true}); }
  285. var uselauncdirasdefaultroot = false;
  286. if( ENV.NODE_ENV === 'production') uselauncdirasdefaultroot = true;
  287. // PB : TODO -- enable for for production.
  288. var thisscriptdir = path.normalize(__dirname); // PB : TODO -- Thisscriptdir could be dislocated when run as a standalone file... We need to detect this where and how
  289. var root = undefined // process.cwd() // Root need not be the launchdir...
  290. // we typicall assume the cwd to be the root. However this should default to
  291. // elxr parent if the root is not recongnizable as an instance root....
  292. // wd is our own environment variable probably corresponding to the root but need not be the same.
  293. // console.log(processedArgs.root)
  294. // console.log('PWD :' + ENV.PWD)
  295. // console.log('cwd : ' + process.cwd())
  296. // console.log('launchscriptdir : ' + path.normalize(__dirname))
  297. console.log('----------------------------------------------------------------')
  298. console.log('BEFORE DISCOVERY')
  299. console.log('version : ' + getVersion());
  300. console.log('process.env.wd : ' + process.env.wd)
  301. console.log('processedArgs.root : ' + processedArgs.root)
  302. console.log('----------------------------------------------------------------')
  303. console.log('wd :' + ENV.wd)
  304. console.log('PWD :' + ENV.PWD)
  305. console.log('cwd : ' + process.cwd())
  306. console.log(`thisscriptdir = ${thisscriptdir}`)
  307. console.log(`root = ${root}`)
  308. console.log(`instanceroot = ${instanceroot}`)
  309. console.log('----------------------------------------------------------------')
  310. if(!processedArgs.root){ // There is no runtime invoke time named args override.
  311. console.log('discovery')
  312. // Script may exists in the same location where we were launched(PWD) but that doesn't mean we r running from elxr.
  313. // script could have been copied tosome random location and run from there.
  314. // check elxr is preinstalled in same location. If so we need to chdir to parent. Else promt for confirmation of root.
  315. var launchdir = /*process.env.PWD ||*/ process.cwd() // mingw + node --inspect-brk behaves differently has a PWD that windows commands cannot recognize /d instead of D:\ and process.chdir fails..
  316. var parentdir = path.dirname( launchdir )
  317. var parentFolderHasElxr = hasElxrSync(parentdir)
  318. var launchFolderHasElxr = hasElxrSync(launchdir)
  319. if( path.normalize(launchdir + '/elxr') === thisscriptdir ) {
  320. // launchFolderHasElxr is false -- and yet thiscriptdir is still proper.
  321. if(!launchFolderHasElxr) {
  322. console.warn('Warning : detected thisscriptdir as subfolder but did not recognize launchdir as a proper root. elxr may not autoupdate...')
  323. // hasElxr checks for git repo status and elxr id stamping etc.
  324. // exlr tool may have been acquired unconventionally and we may not be able to manage it.
  325. // We will run anyway though
  326. }
  327. root = ENV.wd = launchdir;
  328. }
  329. else if( path.normalize(parentdir + '/elxr') === thisscriptdir ) {
  330. if(!parentFolderHasElxr) {
  331. console.warn('Warning : detected thisscriptdir as subfolder but did not recognize parentdir as a proper root. elxr may not autoupdate...')
  332. }
  333. // PB : TODO -- Cleanup this should no longer be needed... selectedinstance is properly initialized...
  334. root = ENV.wd = parentdir; // Default to the parent.
  335. }
  336. else {
  337. if (launchdir === thisscriptdir) {
  338. // Same directory doesn't mean we are being run from elxr sub directory. It could be a dislocated standalone elxr script.
  339. // PB : TODO -- In case elxr is not full elxr we need to locate it and relaunch to switch to the full version...
  340. // if(!parentFolderHasElxr) console.error('Invalid run location in subfolder that looks like elxr. We should probably abort.')
  341. if (BUILD_VERSION.indexOf('Version: {version} - built on {date}') > -1) {
  342. // Confirmed we were run from an Unbuilt ( meaning non standalone ) elxr therefore we are in the elxr sub directory.
  343. root = ENV.wd = parentdir; // Default to the parent.
  344. // instanceroot = root = path.normalize(selectedinstance.root + '/..');
  345. // instanceoptions.splice( 0, 0, detected = { root });
  346. // instanceoptions.splice( 0, 0, detectfromroot(root));
  347. }
  348. else if(!parentFolderHasElxr) {
  349. // Either case we use the launchdir.
  350. // if(launchFolderHasElxr) {
  351. // // Probably a standalone run. Lets just go with it
  352. // root = ENV.wd = launchdir;
  353. // }
  354. // In standalone build script we may or not be in the same location.
  355. // We could have been run from the elxr subfolder. However we cant say for sure.
  356. // Most likely that the built version isn't the full elxr. We assume elxr doesnt exist and create an new elxr under..
  357. console.error('Warning : detected thisscriptdir as elxr subfolder but not recognized as elixir. git updates might fail.')
  358. root = ENV.wd = launchdir;
  359. }
  360. else {
  361. // Built version was run from the full elxr subfolder
  362. root = ENV.wd = parentdir; // Default to the parent.
  363. // instanceoptions.splice( 0, 0, detected = { root })
  364. // instanceoptions.splice( 0, 0, detectfromroot(root))
  365. // Assume current selectedinstance.root is a new instance and create.
  366. // Figure out the instnace name and environment from parent folders as an alternative option with confirmation if not provided in the arguments.
  367. // if(clioverrides.instanceName) {
  368. // if(clioverrides.node_env) {
  369. // instanceroot = root = path.normalize(selectedinstance.root + '/' + clioverrides.instanceName + '/' + clioverrides.node_env)
  370. // instanceoptions.splice( 0, 0, detected = { root, instanceName : clioverrides.instanceName, node_env : clioverrides.node_env })
  371. // // instanceoptions.splice( 0, 0, detectfromroot(root)) // This can be an option but is unnecessary unless a confirmation is provided.
  372. // // also folder names may have no relation to the actual instanceName and instanceType coz we need to have many
  373. // // eg : floder name can be elixir01 but instance name is elixr
  374. // }
  375. // else {
  376. // instanceroot = root = path.normalize(selectedinstance.root + '/' + clioverrides.instanceName + '/' + 'development')
  377. // instanceoptions.splice( 0, 0, detected = { root, instanceName : clioverrides.instanceName, node_env : 'development' })
  378. // instanceoptions.splice( 0, 0, detectfromroot(root)) // A recessive option only.
  379. // }
  380. // }
  381. // else {
  382. // instanceroot = root = selectedinstance.root;
  383. // if(clioverrides.node_env) {
  384. // instanceoptions.splice( 0, 0, detected = { root, node_env : clioverrides.node_env })
  385. // instanceoptions.splice( 0, 0, detectfromroot(root))
  386. // }
  387. // else {
  388. // // Nothing was specified... We only have one option from root.
  389. // instanceoptions.splice( 0, 0, detected = detectfromroot(launcpath))
  390. // }
  391. // }
  392. }
  393. }
  394. else if(launchFolderHasElxr) {
  395. root = ENV.wd = launchdir;
  396. // instanceoptions.splice( 0, 0, detected = { root })
  397. // instanceoptions.splice( 0, 0, detectfromroot(root))
  398. }
  399. else {
  400. // Ambiguous but assume script is standalone in the instanceroot
  401. // Lets defualt to the script parent assuming there is an instanceroot there. Hoever this should probably be a prompt where possible.
  402. // when we r in that mode.
  403. if(uselauncdirasdefaultroot) {
  404. // must be a new install in the selectedinstance.root with script invoked from some random location.
  405. if(!process.env.wd){
  406. // Working directory as a .env variable was not passed in.
  407. root = ENV.wd = launchdir;
  408. }
  409. else root = ENV.wd = process.env.wd
  410. }
  411. else {
  412. var scriptparent = path.dirname( thisscriptdir )
  413. root = ENV.wd = scriptparent;
  414. }
  415. }
  416. }
  417. }
  418. else {
  419. if(process.env.wd && process.env.wd !== processedArgs.root) throw 'wd and root must match.'
  420. root = ENV.wd = process.env.wd = processedArgs.root
  421. }
  422. var instanceroot = root
  423. ENV.PWD = ENV.wd
  424. ENV.NODE_ENV = processedArgs.node_env || (ENV.NODE_ENV && ENV.NODE_ENV.trim()) || 'development'
  425. console.log('----------------------------------------------------------------')
  426. console.log('AFTER DISCOVERY')
  427. console.log('version : ' + getVersion());
  428. console.log('process.env.wd : ' + process.env.wd)
  429. console.log('processedArgs.root : ' + processedArgs.root)
  430. console.log('----------------------------------------------------------------')
  431. console.log('wd :' + ENV.wd)
  432. process.chdir(ENV.wd) // Ensure cwd is the actual working dir.
  433. console.log('PWD :' + ENV.PWD)
  434. console.log('cwd : ' + process.cwd())
  435. console.log(`thisscriptdir = ${thisscriptdir}`)
  436. console.log(`root = ${root}`)
  437. console.log(`instanceroot = ${instanceroot}`)
  438. console.log('----------------------------------------------------------------')
  439. var cli = require('./cliverse')
  440. // throw 'initbreak'
  441. // We no longer use this Folder name may be different from instanceName
  442. // var detectfromroot = function(root){
  443. // return { root, node_env : path.basename(root), instanceName : path.basename( path.dirname(root) ) }
  444. // }
  445. // independent elxr cli operations
  446. var noprerequisites = {
  447. add : true, 'set-url' : true, 'repo-relocate' : true
  448. , remote : true, 'c' : true, 'h' : true
  449. , httpget : true, getuser : true
  450. , 'switch user' : true
  451. , 'switch' : true
  452. // , 'undefined' : true
  453. }
  454. var __default = {
  455. // Common baseline repos for all chess chessinstances.
  456. repos : [
  457. { repo : 'ember-masonry-grid' /*, branch : master*/ } // Default need not be specified.
  458. , { repo : 'bbhverse' }
  459. , { repo : 'clientverse' }
  460. , { repo : 'serververse' }
  461. , { repo : 'elxr' }
  462. , { repo : 'ember-searchable-select' }
  463. , { repo : 'loopback-component-jsonapi' }
  464. , { repo : 'loopback-jsonapi-model-serializer' }
  465. , { repo : 'loopback-connector-mysql' }
  466. , { repo : 'loopback-connector-ds' }
  467. , { repo : 'ember-service-worker' }
  468. , { repo : 'ember-service-worker-asset-cache' }
  469. , { repo : 'ember-service-worker-cache-fallback' }
  470. , { repo : 'ember-service-worker-index' }
  471. , { repo : 'ember-sw-client-route' }
  472. , { repo : 'global-this' }
  473. ]
  474. // Requires elevation only in windows
  475. , elevated : [ { repo : 'chess-server-lib', requiresElevation : true } ]
  476. , exludeMergeRepos : { }
  477. }; // PB : TODO -- Use initialized instance instead of __default everywhere.
  478. var regexreplaceall = function(content, ps){
  479. var repmatches
  480. var replaced = content;
  481. while (repmatches = ps.strOrregexp.exec(content)) {
  482. if(content.length > 0) {
  483. var replacement = repmatches[0]
  484. for(var m = 1; m < repmatches.length; m++) {
  485. replacement = replacement.replace(repmatches[m], ps.substitutes[m-1])
  486. }
  487. replaced = replaced.replace( repmatches[0], replacement )
  488. }
  489. }
  490. return replaced
  491. }
  492. var cmds = {
  493. sqlpreprocess : {
  494. noprerequisites : true
  495. , cmdFn : function(args){
  496. var sqlquery = fs.readFileSync(args._[1], { encoding: 'utf8'})
  497. sqlquery = PATTERNAPI.includesql(sqlquery, path.dirname(args._[1]))
  498. fs.writeFileSync(args._[1] + '.d.sql', sqlquery, { encoding: 'utf8'})
  499. return sqlquery
  500. // // PB : TODO -- move to dsql preprocesor
  501. // // var sqlquery = 'SET @dsql = @dsql + ' + "'" + ('' + fs.readFileSync(args._[1])).replace(/\'/g,"''") + "'"
  502. // var sqlquery = fs.readFileSync(args._[1], { encoding: 'utf8'})
  503. // var regExp = /\-\-\s{{INCLUDE(.*?) ([\s\S]*?)}}\s\-\-/gm;
  504. // var options = {}
  505. // sqlquery = replacepatterns(sqlquery, regExp, (matches, sqlquery)=>{
  506. // if (matches[1] === 'ASDSQL') options.dsql = true
  507. // var replacement = {
  508. // distinctpatterntoreplace : new RegExp("\\-\\-\\s{{INCLUDE\\s" + matches[2] + "}}\\s\\-\\-","gm")
  509. // , detectedvaluepattern : matches[2]
  510. // // escaped dsql... //'SET @dsql = @dsql + ' + "'" + ('' + fs.readFileSync(args._[1])).replace(/\'/g,"''") + "'"
  511. // }
  512. // if(options.dsql) replacement.substituedvalue = ('SET @dsql = @dsql + ' + "'" + ('' + fs.readFileSync(path.dirname(args._[1]) + '/' + matches[2])).replace(/\'/g,"''") + "'")
  513. // else replacement.substituedvalue = fs.readFileSync(path.dirname(args._[1]) + '/' + matches[2])
  514. // sqlquery = sqlquery.replace(replacement.distinctpatterntoreplace, replacement.substituedvalue);
  515. // regExp.lastIndex = 0;
  516. // })
  517. // // console.log(replaced)
  518. // fs.writeFileSync(args._[1] + '.d.sql', sqlquery, { encoding: 'utf8'})
  519. }
  520. , toArgs : function( o ){ return o }
  521. , interpret() { return { cmd : processedArgs._.slice(0, 1) } }
  522. }
  523. , remote : {
  524. interpret() { return utils.assign_core( { keycase: true, arraymergetype : utils.assign_core.DISTINCT_UNION }
  525. , { cmd : processedArgs._.slice(0, 2).join(' '), runchoice : 'c' }) }
  526. , noprerequisites : true
  527. , independentcmd : true
  528. }
  529. , start : {
  530. interpret() { return utils.assign_core( { keycase: true, arraymergetype : utils.assign_core.DISTINCT_UNION }
  531. , { cmd : 'start', runchoice : 'c'
  532. , node_env : ENV.NODE_ENV, root : ENV.wd, instanceType : ENV.NODE_ENV
  533. })}
  534. , toArgs : function( o ){
  535. return o
  536. }
  537. }
  538. , 'remote refresh' : {
  539. // return a interpreted set of arguments for this cmd run context.
  540. interpret() { return utils.assign_core( { keycase: true, arraymergetype : utils.assign_core.DISTINCT_UNION }
  541. , { cmd : 'remote refresh', runchoice : 'c' }) }
  542. , noprerequisites : true
  543. , independentcmd : true
  544. // , requires : [ generateDependencies ]
  545. , toArgs : function( o ){
  546. return o
  547. }
  548. }
  549. , 'remote set-url' : {
  550. // return a interpreted set of arguments for this cmd run context.
  551. interpret() { return utils.assign_core( { keycase: true, arraymergetype : utils.assign_core.DISTINCT_UNION }
  552. , { cmd : 'remote set-url', runchoice : 'c' }) }
  553. , noprerequisites : true
  554. , independentcmd : true
  555. // , requires : [ generateDependencies ]
  556. }
  557. , 'remote add' : {
  558. // return a interpreted set of arguments for this cmd run context.
  559. interpret() { return utils.assign_core( { keycase: true, arraymergetype : utils.assign_core.DISTINCT_UNION }
  560. , { cmd : 'remote add', runchoice : 'c' }) }
  561. , noprerequisites : true
  562. , independentcmd : true
  563. // , requires : [ generateDependencies ]
  564. }
  565. , 'remote remove' : {
  566. // return a interpreted set of arguments for this cmd run context.
  567. interpret() { return utils.assign_core( { keycase: true, arraymergetype : utils.assign_core.DISTINCT_UNION }
  568. , { cmd : 'remote remove', runchoice : 'c' }) }
  569. , noprerequisites : true
  570. , independentcmd : true
  571. }
  572. , 'addcollaborator' : {
  573. // Usage :
  574. // elxr addcollaborator instancename developer
  575. cmdFn : function(args){
  576. var __each = function(args){
  577. var collaborator = args.collaborator;
  578. if(!collaborator) {console.error('Error : collaborator required'); throw 'Error : collaborator required' }
  579. var repo = args.repo
  580. var remotename = 'chess'
  581. var repodef = selectedinstance.reposindexed[repo];
  582. if(!repodef) return
  583. var remotenames = (selectedinstance.selectedremotes || []).concat( selectedinstance.permanentremotes )
  584. var remotes = selectedinstance.reposerverinstances[selectedinstance.reposerver].remotes
  585. // console.log('-----------------------------------------------------')
  586. // console.log(repo)
  587. // // console.dir(remotes)
  588. // console.log('-----------------------------------------------------')
  589. // PB : TODO -- pick up remote definitions per repository...
  590. var reposmanfiest = utils.assign_core( { keycase : true, arraymergetype : utils.assign_core.DISTINCT_UNION }
  591. , {}, selectedinstance, loadmanifest( selectedinstance.root + '/' + repo
  592. , { username : selectedinstance.username, instanceName : selectedinstance.instanceName
  593. , node_env : selectedinstance.node_env, reposerver : selectedinstance.reposerver }
  594. ))
  595. if( !reposmanfiest.error ) {
  596. var reporemotenames = remotenames.concat(reposmanfiest.selectedremotes || []).concat( reposmanfiest.permanentremotes || [] )
  597. var reporemotes = utils.assign(remotes, reposmanfiest.reposerverinstances[selectedinstance.reposerver].remotes)
  598. }
  599. else {
  600. var reporemotenames = remotenames
  601. var reporemotes = remotes
  602. }
  603. var remote = reporemotes[remotename]
  604. var reposerver = repodef.server || remote.server || selectedinstance.reposerver
  605. // selectedinstance.reposerverinstances[reposerver]
  606. var auth = repodef.username ? repodef : remote.username ? remote : selectedinstance.reposerverinstances[reposerver].username ? reposerver : selectedinstance;
  607. var httpoptions = new URL(reposerver);
  608. httpoptions = {
  609. hostname: httpoptions.hostname
  610. , protocol : httpoptions.protocol
  611. }
  612. httpoptions.username = auth.username // PB : TODO -- Handle remotes with different username. Also cache git credentials either globally or per repo...
  613. // PB : TODO -- handle credentials properly. cant mix and match passwords..
  614. httpoptions.password = (auth.password || selectedinstance.password || '') // PB : NOTE URL has some kind of a setter for password which converts to string "undefined" as password which is undesirable.. so we pre resolve and send.
  615. // console.log(___args)
  616. // PB : TODO -- Check valid collaborator before adding...
  617. return GITEA.repository.addcollaborator(httpoptions, repodef, remote.owner, collaborator).then( v => {
  618. if(v === true) {
  619. console.log('-----------------------------------------------------')
  620. console.log('addcollaborator successful for ' + repo + ' ' + collaborator)
  621. console.log('-----------------------------------------------------')
  622. }
  623. } )
  624. }
  625. var promises = []
  626. var repos = Object.keys(selectedinstance.reposindexed)
  627. repos.forEach(repo => { promises.push(__each({ repo, collaborator : args._[2]})) }) // PB : TODO -- Move to toArgs.
  628. return Promise.all(promises).then(pr => { console.log('addcollaborator done') })
  629. }
  630. }
  631. , 'isurlaccessible' : {
  632. noprerequisites : true
  633. , independentcmd : true
  634. , toArgs : function( o ){
  635. return { url : o._[1] }
  636. }
  637. }
  638. , resetgitconfig : {
  639. // return a interpreted set of arguments for this comd run context.
  640. // cmdFn : resetgitconfig,
  641. interpret() { return { cmd : 'resetgitconfig' } }
  642. , noprerequisites : true
  643. , independentcmd : true
  644. }
  645. , reinit : {
  646. // return a interpreted set of arguments for this comd run context.
  647. // cmdFn : reinit
  648. // ,
  649. interpret() { return { cmd : 'reinit' } }
  650. , noprerequisites : true
  651. , independentcmd : true
  652. , requiresElevation : true
  653. // , requires : [ generateDependencies ]
  654. }
  655. , init : {
  656. // return a interpreted set of arguments for this comd run context.
  657. // cmdFn : init
  658. // ,
  659. interpret() { return { cmd : 'init' } }
  660. , noprerequisites : true
  661. , independentcmd : true
  662. , requiresElevation : true
  663. // , requires : [ generateDependencies ]
  664. }
  665. , switch : {
  666. interpret() {
  667. return { cmd : subcommandlabels['switch'], runchoice : 'c', username : processedArgs._[2]
  668. , reposerver : __default.reposerver // .?.?.?
  669. }
  670. }
  671. , getPossiblePrompts(){ return { username : true, reposerver : 'http://git.bbh' } } // Requires only one argument...
  672. }
  673. , 'switch user' : {
  674. interpret() {
  675. return { cmd : subcommandlabels['switch'], runchoice : 'c', username : processedArgs._[2] }
  676. }
  677. , getPossiblePrompts(){ return { username : true } } // Requires only one argument...
  678. }
  679. // Flat linear structure. Every subcommand should have a top level 'label'
  680. , 'users' : {
  681. // default to the users list
  682. subcommands : { list : {} }
  683. , cmdFn : ()=>getCredentials() // default
  684. , cmd : 'users'
  685. , noprerequisites : true
  686. }
  687. , 'users list' : {
  688. cmdFn : ()=>getCredentials()
  689. , cmd : 'users list'
  690. , noprerequisites : true
  691. }
  692. , 'get-upstream' :{
  693. // cmdFn : op['get-upstream'] // default
  694. // ,
  695. cmd : 'get-upstream'
  696. , noprerequisites : true
  697. , independentcmd : true
  698. , interpret() { return { cmd : 'get-upstream' } }
  699. }
  700. , 'g' : {
  701. cmd : 'g'
  702. , noprerequisites : true
  703. }
  704. , 'link' : {
  705. 'cmd' : 'link'
  706. // , cmdFn : function( sourecpath, filename, dir ){
  707. // var afterTargetPath = (dir)=>{
  708. // console.dir(dir);
  709. // // var tasks = [
  710. // // () => {
  711. // // // Use junctions to avoid npm package issues
  712. // // var p = nodeShellExec('mklink', ['/J', filename, sourecpath], {
  713. // // inherit: true, shell: true
  714. // // , cwd : dir || instanceroot
  715. // // , env: ENV
  716. // // }).catch((e) => { console.error(e) })
  717. // // return p;
  718. // // }
  719. // // ];
  720. // }
  721. // // console.dir(ENV)
  722. // if(!dir) getCurrentFolder().then(afterTargetPath);
  723. // else afterTargetPath(dir)
  724. // }
  725. , cmdFn : function( cmdopts ){
  726. // sourecpathandfile should include name of file name
  727. targetfilename = cmdopts.targetfilename || processedArgs._[1]
  728. // console.log(processedArgs)
  729. if(!targetfilename) return Promise.reject('error no file provided for linking')
  730. targetdir = cmdopts.targetdir || ENV.wd
  731. sourecpathandfile = cmdopts.sourecpathandfile || path.normalize(`../../node_modules/chess-server-lib/common/models/${targetfilename}`)
  732. var tasks = [
  733. () => {
  734. // Use junctions to avoid npm package issues
  735. var p = nodeShellExec('mklink', [path.normalize(`${targetdir + '/' + targetfilename}`), sourecpathandfile], {
  736. inherit: true, shell: true
  737. , cwd : targetdir
  738. , env: ENV
  739. }).catch((e) => { console.error(e) })
  740. return p;
  741. }
  742. ];
  743. var etask = ()=>{
  744. return any(tasks).then(() => {
  745. fs.writeFileSync('run.done', 'success')
  746. }).catch(() => {
  747. fs.writeFileSync('run.done', 'error')
  748. })
  749. }
  750. etask.statuslog = statuslog
  751. etask.selectedinstance = selectedinstance
  752. etask.processedArgs = processedArgs
  753. etask.runtimestamp = runtimestamp
  754. etask.ENV = ENV
  755. return shell_verse.runElevated(etask)
  756. }
  757. , noprerequisites : true
  758. , privileged : true
  759. }
  760. }
  761. function interpret() {
  762. var interpreted = this
  763. // Non custom command has universal positiona args.
  764. processedArgs._[1] ? interpreted.instanceName = processedArgs._[1] : null;
  765. interpreted.runchoice = interpreted.cmd ? 'c' : null
  766. // interpreted.runchoice = processedArgs._[0] || selectedinstance.runchoice;
  767. // return clioverrides
  768. // cmds[cmd] = {
  769. // interpret() {
  770. // return Object.assign(clioverrides, { cmd, runchoice : 'c' })
  771. // }
  772. // , getPossiblePrompts(){ return { cmd, username : true, password : true,
  773. // instanceName : true, instanceType : true, reposerver : true } }
  774. // }
  775. // ... PB : TODO -- use cmd.toArgs
  776. // interpreted.cmd = this.cmd
  777. return interpreted
  778. }
  779. var interpretrun = function(){
  780. var cmd = processedArgs._[0];
  781. return cmds[cmd] && cmds[cmd].interpret ? cmds[cmd].interpret() : (function(){
  782. return cmds[cmd] = utils.assign(cmds[cmd] || {}, interpret.call({ cmd, toArgs : function( o ){
  783. // PB : TODO -- need to call this before selectedinstance is built. The instanceName is dependent on the specific cmd.
  784. return o } }))
  785. })()
  786. }
  787. var chessinstances = { current_run : {} };
  788. var clioverrides = interpretrun()
  789. clioverrides = utils.assign( { cmd : processedArgs._[0], node_env : ENV.NODE_ENV, root : ENV.wd, instanceType : ENV.NODE_ENV }
  790. , clioverrides, cmds[clioverrides.cmd].toArgs(processedArgs), { root : ENV.wd } )
  791. function acquirelocalinstances(selected){
  792. // utils.assign is used to cleanup duplicates... assuming it is probably not clean.
  793. // PB : TODO -- if require fails decipher instanceName from findlocalinstances using the root...
  794. try { var existinglocalinstances = require(path.normalize(selected.root + '/chessinstances.js'))}
  795. catch(e){
  796. console.warn( 'Local instances not found.' ) // This is not an error. A new fresh instance is probably being setup.
  797. var existinglocalinstances = { current_run : {}, error : true }
  798. }
  799. chessinstances = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }, existinglocalinstances);
  800. // console.dir(chessinstances)
  801. return chessinstances
  802. }
  803. function findlocalinstances(chessinstances, instanceoptions){
  804. // We can expect a .elxr at each level in folder and 2 levels up. higher up we will find a shared instance chessinstances.js
  805. ['' /* instanceroot */, '../' /* instanceTypes or node_env */, '../../' /* instanceNames */].
  806. earlyreduce( ( reduced, p, i, a )=>{
  807. var localinstancesPath = `${instanceroot}/${p}.elxr`;
  808. if(existsSync( localinstancesPath )) {
  809. try {
  810. acquirelocalinstances( { root : `${instanceroot}/${p}` } )
  811. if(chessinstances.error) {
  812. delete chessinstances.error; delete chessinstances.e
  813. return {}
  814. }
  815. return Object.keys(chessinstances).earlyreduce( ( reduced, instanceName) => {
  816. return Object.keys(chessinstances[instanceName]).earlyreduce( (reduced, instanceType) => {
  817. // Scan to find a matching instanceroot
  818. if( path.normalize(chessinstances[instanceName][instanceType].root) === path.normalize( instanceroot) ) {
  819. instanceoptions.splice( 0, 0, chessinstances[instanceName][instanceType])
  820. return {
  821. value : chessinstances[instanceName][instanceType]
  822. , done : true
  823. };
  824. }
  825. })
  826. })
  827. }
  828. catch(e){
  829. return { }
  830. }
  831. }
  832. else return { }
  833. }
  834. )
  835. }
  836. // PB : TODO -- Move this to utils assign... as an array merge option.
  837. var mergeObjByKey = function(arrOfObjs, keyName) {
  838. var keyedDistinct = {}
  839. var distinctArrOfObjs = []
  840. arrOfObjs.forEach( o => {
  841. if(o) (keyedDistinct[o[keyName]] || (keyedDistinct[o[keyName]] = []) ).push(o)
  842. })
  843. Object.keys(keyedDistinct).forEach(key => {
  844. distinctArrOfObjs.push( utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
  845. , ...keyedDistinct[key] ) ) // PB : TODO -- Shallow use utils.assign
  846. })
  847. return distinctArrOfObjs;
  848. }
  849. var cacheWriteInstanceConfig = function(chessinstances, instanceroot, selectedinstance){
  850. if(selectedinstance) {
  851. var instanceName = selectedinstance.instanceName ;
  852. var node_env = selectedinstance.node_env;
  853. // PB : TODO -- handle current_run switch...
  854. // console.dir(chessinstances)
  855. // PB : TODO -- We should be able to do simply merge at a higher level using assign
  856. chessinstances[instanceName][node_env].repos = mergeObjByKey(chessinstances[instanceName][node_env].repos || [], 'repo') ;
  857. chessinstances[instanceName][node_env].elevated = mergeObjByKey(chessinstances[instanceName][node_env].elevated || [], 'repo') ;
  858. }
  859. fs.writeFileSync(instanceroot + '/chessinstances.js', 'module.exports = ' + JSON.stringify(chessinstances, null, 2) + '', { 'flag': 'w' })
  860. }
  861. var loadmanifest = function( mpath, moverrides ){
  862. try {
  863. // PB : TODO -- pick up remote definitions per repository...
  864. return utils.assign_core( { keycase : true, arraymergetype : utils.assign_core.DISTINCT_UNION }
  865. , {}, require(path.normalize( mpath + '/repo-manifest'))( {utils}, null, moverrides ))
  866. }
  867. catch(e){
  868. // console.warn(e);
  869. return utils.assign_core( { keycase : true, arraymergetype : utils.assign_core.DISTINCT_UNION }, { error : true, e }, moverrides)
  870. }
  871. }
  872. var getReconfirmAll = ()=>{return { instanceName : true, instanceType : true, reposerver : true, username : true, password : true } }
  873. if(clioverrides.reconfirm) {
  874. var reconfirm = getReconfirmAll()
  875. }
  876. else { var reconfirm = {}; }
  877. var shouldPrompt = function(k, possiblePrompts, target){
  878. return ((possiblePrompts[k] !== undefined && possiblePrompts[k] !== null) && target[k] !== possiblePrompts[k]
  879. || (possiblePrompts[k] === undefined || possiblePrompts[k] === null) && (target[k] === undefined || target[k] === null)
  880. || reconfirm[k])
  881. }
  882. var getPromptableAsyncPropDescriptor = function(propName, promptable){
  883. return {
  884. get (){
  885. return any( promptable.dependencies || [] ).then(()=>{
  886. return cli.prompt( promptable.choices, promptable.label, promptable.defaultchoice, promptable.selectedchoice ).then(propValue => {
  887. var asyncprop = Promise.resolve(propValue)
  888. if(promptable.interpret){
  889. asyncprop = promptable.interpret(propValue)
  890. }
  891. return asyncprop.then(
  892. ()=>{
  893. Object.defineProperty(this, propName, {
  894. value: propValue,
  895. writable: true,
  896. configurable : true,
  897. enumerable : true
  898. });
  899. return propValue
  900. }
  901. )
  902. })
  903. } )
  904. }
  905. // , set (propValue){
  906. // Object.defineProperty(this, propName, {
  907. // value: propValue,
  908. // writable: true, // PB : TODO -- Use this to fix value permanently until run is over.
  909. // configurable : true,
  910. // enumerable : true
  911. // })
  912. // return propValue;
  913. // }
  914. , configurable : true
  915. , enumerable : true
  916. }
  917. }
  918. var getBoundEachPrompt = function(target, possiblePrompts, promptables, choices, promptsfilter) {
  919. return function(prompts, k, i, a){
  920. // Reducer for all prompts on targets.
  921. // No local instances config found. We use a default initialized instance available in selectedinstance
  922. // Confirm those that were not supplied as user choices in runtime args and proceed to reattempt.
  923. // PB : TODO -- selectedinstance === __default check to prompt everything...
  924. if( shouldPrompt(k, possiblePrompts, target) ) {
  925. delete reconfirm[k];
  926. // console.log(k)
  927. // console.dir(possiblePrompts); //console.dir(target)
  928. prompts.push(async ()=>{
  929. // PB : NOTE -- Important in async cases when this {{target}} needs to be in the same state as when it was invoked.
  930. // We need to take a snapshot... Shallow.. !! If required deep should be used based on use case.
  931. // var asyncthis = Object.assign(this);
  932. // By default Latest altered state is provided which is an implicit reference directly.
  933. console.log('----------------------------------------------------')
  934. console.log(k)
  935. console.dir(choices[k])
  936. if(!promptables[k]) promptables[k] = {}
  937. promptables[k].choices = choices[k]
  938. Object.defineProperty(target, k, getPromptableAsyncPropDescriptor(k, promptables[k]));
  939. return await target[k]
  940. })
  941. }
  942. delete possiblePrompts[k] // PB : TODO We should keep this around instead of deleting so we can do a second pass if required.
  943. return prompts
  944. }
  945. }
  946. // unbound. Bind before using.
  947. var unbound_interactionpoints = function(selectedinstance){
  948. var self = this;
  949. var _interactionpoints = {
  950. get runchoice() {
  951. return {
  952. label :
  953. `Choose an option :
  954. d) Install the default chess instance.
  955. => elxr i chess node_env=development --default
  956. n) Create your custom new instance interactively
  957. => elxr i {{instanceName}} node_env={{environment}}
  958. i) Choose an instance and environment to install
  959. => elxr i {{instanceName}} node_env={{environment}}
  960. c) Choose a command to run ( pull, use, i, npmi ... ) <= pull
  961. => elxr {{cmd}} {{instanceName}} node_env={{environment}}
  962. h) Help
  963. q) Quit
  964. : `
  965. , choices : []
  966. , defaultchoice : 'c'
  967. , selectedchoice : self.target.runchoice
  968. , interpret : function(choice){
  969. var interpret_map = {
  970. d : function(){
  971. processedArgs._[0] = 'i'
  972. self.target.instanceName = processedArgs._[1] = processedArgs._[1] || 'chess'
  973. self.target.node_env = processedArgs.node_env = (ENV.NODE_ENV && ENV.NODE_ENV.trim()) || processedArgs.node_env || 'development'
  974. self.target.reposerver = 'https://git.bbh.org.in' // PB : TODO -- Read from global defaults...
  975. }
  976. , n : function() { processedArgs._[0] = 'i' }
  977. , i : function() {
  978. processedArgs._[0] = 'i'
  979. // processedArgs._[1] = self.target.instanceName || processedArgs._[1] || 'chess';
  980. }
  981. , c : async function() {
  982. // self here will always be the self.target.
  983. Object.defineProperty(self, 'cmd', getPromptableAsyncPropDescriptor('cmd', {
  984. label : `Enter cmd :
  985. p) pull
  986. Default <= p
  987. : `
  988. , defaultchoice : 'pull'
  989. }
  990. ));
  991. var cmd = await self.target['cmd'];
  992. if (!cmd || cmd === 'p') { self.target['cmd'] = processedArgs._[0] = 'pull' }
  993. else self.target['cmd'] = processedArgs._[0] = cmd
  994. return cmd;
  995. }
  996. , h : function() { console.log(elxr.help()); process.exit() } // PB : TODO -- Why do we need log.
  997. , q : function() { process.exit() }
  998. }
  999. if(Promise.resolve(choice) === choice){
  1000. return choice.then( resolvedchoice => {
  1001. return (interpret_map[choice] || interpret_map['c']).call(self.target)
  1002. })
  1003. }
  1004. else return Promise.resolve( (interpret_map[choice] || interpret_map['c']).call(self.target) )
  1005. // var __interpreter = interpret_map[choice] || interpret_map['c']
  1006. // if(!choice) return interpret_map['c']() // This should not happen prompter should always give us a default choice.
  1007. // if(interpret_map[choice]) __interpreter = interpret_map[choice];
  1008. // return __interpreter.call(self.target)
  1009. }
  1010. }
  1011. }
  1012. , get instanceName() {
  1013. return { label : `Enter Instance Name ( <= ${self.target.instanceName || 'chess'} ) : `
  1014. , choices : self.choices['instanceName'], defaultchoice : 'chess'
  1015. , selectedchoice : self.target.instanceName
  1016. }
  1017. }
  1018. , get instanceType() {
  1019. return { label : `Enter Instance Type ( <= ${self.target.instanceType || 'development'} ) : `
  1020. , choices : self.choices['instanceType'], defaultchoice : 'development'
  1021. , selectedchoice : self.target.instanceType || 'development'
  1022. }
  1023. }
  1024. , get reposerver() {
  1025. return { label : `Enter Repo Server Base Url ( <= ${self.target.reposerver || 'https://git.bbh.org.in'} ) : `
  1026. , get choices() {
  1027. // self.choices['reposerver'].forEach( rs => {
  1028. // var __rs = new URL(rs);
  1029. // __rs.hostname = __rs.host;
  1030. // __rs.path = '/'
  1031. // __rs.method = 'GET'
  1032. // RESTAPI.get(__rs, function(data){ rs.accessibility = 'accessible' }
  1033. // , function(error){ rs.accessibility = 'unaccessible' } )
  1034. // })
  1035. return self.choices['reposerver']
  1036. }
  1037. , set choices(cs) {
  1038. return self.choices['reposerver'].concat([selectedinstance.reposerver]).concat(cs)
  1039. }
  1040. , defaultchoice : selectedinstance.reposerver || 'https://git.bbh.org.in'
  1041. , selectedchoice : self.target.reposerver
  1042. }
  1043. }
  1044. // , 'upstream-remote' : { label : `Enter Remote Name ( <= ${self.target['upstream-remote'] || 'chess'} ) : `
  1045. // , get choices() {
  1046. // var reposerver = self.target['reposerver']
  1047. // var remotes = []
  1048. // var trs = self.target.reposervers || []
  1049. // trs.forEach(rs => {
  1050. // if(rs.server === reposerver){
  1051. // remotes.push(remote)
  1052. // // PB : TODO -- Sort and display highest priority self.target.remotes.sort( )
  1053. // }
  1054. // })
  1055. // return remotes
  1056. // }
  1057. // , set choices(addlchoices){
  1058. // var reposerver = self.target['reposerver']
  1059. // var remotes = []
  1060. // var trs = self.target.reposervers || []
  1061. // trs.forEach(rs => {
  1062. // if(rs.server === reposerver){
  1063. // remotes.push(remote)
  1064. // // PB : TODO -- Sort and display highest priority self.target.remotes.sort( )
  1065. // }
  1066. // })
  1067. // return remotes.concat(addlchoices)
  1068. // }
  1069. // , defaultchoice : 'userfork'
  1070. // , selectedchoice : self.target['upstream-remote'] || 'userfork'
  1071. // // Just using getters resolves dependencies..., dependencies : [ ()=>{ return self.target['reposerver'] } ]
  1072. // }
  1073. // , 'remote-type' : { label : `Enter Remote Type ( <= ${self.target['remote-type'] || 'public'} ) : `
  1074. // , get choices() {
  1075. // return ['external', 'public', 'private', 'github', 'unc']
  1076. // }
  1077. // , set choices(addlchoices){
  1078. // var reposerver = self.target['reposerver']
  1079. // var remotes = []
  1080. // var trs = self.target.reposervers || []
  1081. // trs.forEach(rs => {
  1082. // if(rs.server === reposerver){
  1083. // remotes.push(remote)
  1084. // // PB : TODO -- Sort and display highest priority self.target.remotes.sort( )
  1085. // }
  1086. // })
  1087. // return ['external', 'public', 'private', 'github', 'unc'].concat(addlchoices)
  1088. // }
  1089. // , defaultchoice : 'public'
  1090. // , selectedchoice : self.target['remote-type'] || 'public'
  1091. // // Just using getters resolves dependencies..., dependencies : [ ()=>{ return self.target['reposerver'] } ]
  1092. // }
  1093. // , 'selectedremotes' : { label : `Chose Remote Names ( <= ${self.target['selectedremotes'] || 'chess'} ) : `
  1094. // , get choices() {
  1095. // var reposerver = self.target['reposerver'] // PB : TODO -- We need options to work with multiple selected reposervers at the same time..
  1096. // var remotenames = []
  1097. // Object.entries(self.target.remotes || []).forEach( ([rname, r]) => {
  1098. // if(r.server === reposerver && r.accessibility.find( self.target[ 'remote-type' ] )){
  1099. // remotes.push(rname)
  1100. // // PB : TODO -- Sort and display highest priority self.target.remotes.sort( )
  1101. // }
  1102. // })
  1103. // // PB : TODO -- Need to generate all possible permuted choices nP( 1 -> n )
  1104. // // Currenty handles all combinations without any priority order.
  1105. // var _remotechoices = [] // Array of arrays of choices.
  1106. // remotenames.forEach( r => {
  1107. // var __rcs = []
  1108. // _remotechoices.forEach(rc => {
  1109. // __rcs.push( rc.concat(r) )
  1110. // })
  1111. // Array.prototype.push.apply( _remotechoices, __rcs)
  1112. // _remotechoices.push(r)
  1113. // })
  1114. // return _remotechoices
  1115. // }
  1116. // , defaultchoice : ['userfork', 'chess'] // userfork and chess should imlicitly point to userfork-external and chess-external when external connectivity is dtetected.
  1117. // , selectedchoice : self.target['selectedremotes'] || ['userfork-external', 'chess-external']
  1118. // // , defaultchoice : { 'userfork-external' : self.target.remotes['userfork-external'] , 'chess-external' : self.target.remotes['chess-external'] }
  1119. // // , selectedchoice : self.target['selectedremotes'] || { 'userfork-external' : self.target.remotes['userfork-external'] , 'chess-external' : self.target.remotes['chess-external'] }
  1120. // // Info : Just using getters resolves dependencies..., dependencies : [ ()=>{ return self.target['reposerver'] } ]
  1121. // }
  1122. , get username() { return { label : `Enter User Id for ${self.target.reposerver} ( <= ${self.target.username || 'chess'} ) : `
  1123. , choices : self.choices['username'], defaultchoice : self.target.username || 'chess', selectedchoice : self.target.username } }
  1124. , get password() { return { label : `Enter Password for ${self.target.username} @ ${self.target.reposerver} ( <= ${self.target.password || ''} ) : `
  1125. , choices : self.choices['password'], defaultchoice : '***', selectedchoice : self.target.password } }
  1126. , get email() { return { label : `Enter Email for ${self.target.username} @ ${self.target.reposerver} ( <= ${self.target.email || ''} ) : `
  1127. , choices : self.choices['email'], defaultchoice : 'guest@bbh.org.in', selectedchoice : self.target.email } }
  1128. }
  1129. return _interactionpoints
  1130. }
  1131. var get_interactionpoints_template = function(){
  1132. return {
  1133. instanceName : { label : `Enter Instance Name ( <= ${this.target.instanceName || 'chess'} ) : `
  1134. , choices : this.choices['instanceName'], defaultchoice : 'chess'
  1135. , selectedchoice : this.target.instanceName
  1136. }
  1137. }
  1138. }
  1139. var pending = (function() {
  1140. // PB : TODO -- Override cli prefs and call with undefined selectedinstance only if there is no cli overide or selection.
  1141. acquirelocalinstances( { root : ENV.wd } )
  1142. function createLocalChessInstance( cfg ){
  1143. // return createInstance(cfg)
  1144. reconfirm = getReconfirmAll()
  1145. var inst = {};
  1146. var __new = Object.assign({}, __default, cfg)
  1147. inst[cfg.node_env] = __new; return inst;
  1148. }
  1149. if(chessinstances.error) {
  1150. delete chessinstances.error
  1151. // use installchoices only when we don't find chessinstances.
  1152. try { var installchoices = require(path.normalize(ENV.wd + '/installchoices.js'))
  1153. var instanceName = installchoices.instanceName;
  1154. var reposerver = installchoices.reposerver
  1155. var node_env = clioverrides.node_env || installchoices.node_env
  1156. var __instance = (chessinstances[instanceName] = chessinstances[instanceName] || createLocalChessInstance( {
  1157. instanceName, node_env, root, reposerver /* promptkeys['reposerver'] */ } ))[node_env];
  1158. chessinstances['current_run'] = { instanceName, node_env, reposerver, root }
  1159. // if(path.normalize(selectedinstance.root) !== path.normalize(chessinstances[selectedinstance.instanceName][selectedinstance.node_env].root)) {
  1160. // throw "instanceName and instanceType specified doesn't match whats already present do you want to continue " + chessinstances[instanceName][node_env].root + ' does not match ' + selectedinstance.root
  1161. // }
  1162. // chessinstances[installchoices.instanceName] = chessinstances[installchoices.instanceName] || {}
  1163. // chessinstances[installchoices.instanceName][installchoices.node_env || clioverrides.node_env] = installchoices
  1164. __instance.username = installchoices.username = installchoices.gitUser
  1165. __instance.email = installchoices.email = installchoices.gitEmail
  1166. }
  1167. catch(e){
  1168. console.warn(e)
  1169. console.warn( 'Install choices not found. WIll prompt for choices' ) // This is not an error. A new fresh instance is probably being setup.
  1170. throw 'PROMPT FOR INSTLL CHOICES TO BE IMPLEMENTED'
  1171. // chessinstances[installchoices.instanceName] = chessinstances[installchoices.instanceName] || {}
  1172. // chessinstances[installchoices.instanceName][installchoices.node_env || clioverrides.node_env] = installchoices
  1173. }
  1174. }
  1175. // PB : chessinstances.js update if we are switching repo servers, username etc... Myabe always refresh on each run.
  1176. // root location for instance swithc ?? should not be allowd...
  1177. var instanceName = clioverrides.instanceName || chessinstances.current_run.instanceName
  1178. var instance = {}
  1179. function oninstanceName(instanceName) {
  1180. var instance_ = chessinstances[instanceName]
  1181. if(instance_) {
  1182. instance = instance_[clioverrides.node_env || chessinstances.current_run.node_env] || utils.assign(chessinstances['current_run'], clioverrides, { instanceName })
  1183. }
  1184. else instance = utils.assign(chessinstances['current_run'], clioverrides, { instanceName })
  1185. // PB : TODO We should promt like instanceName create a new one instad of undefined ??
  1186. return instance
  1187. }
  1188. if(!instanceName) {
  1189. var interactionpoints = (function() { return { instanceName : get_interactionpoints_template.bind({target : {}, choices : {}})()['instanceName'] } })()
  1190. var eachPrompt = getBoundEachPrompt(instance, utils.assign({}, interactionpoints), interactionpoints, {})
  1191. var pendingtasks = any( Object.keys(interactionpoints).reduce(eachPrompt, []) ).then(()=>{
  1192. return oninstanceName(instance.instanceName)
  1193. })
  1194. }
  1195. else {
  1196. var pendingtasks = Promise.resolve(oninstanceName(instanceName))
  1197. }
  1198. return pendingtasks.then((instance)=>{
  1199. // PB : TODO -- Embed defaults in the build instead of inlining here...
  1200. // PB : TODO -- All these values instanceName, node_env, username, reposervers should come from instace overridden by a finalized cliovrrides...
  1201. // Also attepmt to load preconfig specially for new chessinstances from ../chess-config/...
  1202. var __repo_manifest_elxr = loadmanifest( instance.root + '/elxr'
  1203. , { username : instance.username /** ??? TODO */ , instanceName : instance.instanceName /** ??? TODO */
  1204. , node_env : clioverrides.node_env, reposerver : instance.reposerver /** ??? TODO */ } // options
  1205. )
  1206. if(__repo_manifest_elxr.error) console.log(__repo_manifest_elxr.e.message)
  1207. var instance_specific_config_manifest = loadmanifest( instance.root + `/${instance.instanceName}-config-${clioverrides.node_env}`
  1208. , { username : instance.username /** ??? TODO */ , instanceName : instance.instanceName /** ??? TODO */
  1209. , node_env : clioverrides.node_env, reposerver : instance.reposerver /** ??? TODO */ } // options
  1210. )
  1211. if(instance_specific_config_manifest.error) console.log(instance_specific_config_manifest.e.message)
  1212. delete __repo_manifest_elxr.error
  1213. delete __repo_manifest_elxr.e
  1214. // delete __repo_manifest_elxr.utils
  1215. delete instance_specific_config_manifest.error
  1216. delete instance_specific_config_manifest.e
  1217. // delete instance_specific_config_manifest.utils
  1218. // selectedinstance is not complete until we load in the following order of priority...
  1219. // 1) inline defaults
  1220. // 2) elxr defaults & manifest
  1221. // 3) ../chess-config/... defaults TODO
  1222. // 4) local cached lastrun or cli selected instance from chessinstances
  1223. // 5) instance specific manifest from {{instanceName}}-config-{{node_env}} ( can work with stale or on demand currently pulled updated version )
  1224. // 5.5) runconfig ??? lastrun vs fixed runconfig for repetitive stuff. TODO -- runconfig overrides lastrun...
  1225. // 6) cli overrides from command promnt
  1226. // 7) promted selections and reconfirms.
  1227. var __pvt = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
  1228. , __default, __repo_manifest_elxr, instance
  1229. , { root : ENV.wd, node_env : ENV.NODE_ENV
  1230. , get instanceName() {
  1231. // FInalize to prevent subsequent overrides...
  1232. return instance.instanceName
  1233. }
  1234. }
  1235. , instance_specific_config_manifest
  1236. , clioverrides
  1237. )
  1238. // console.dir(__pvt)
  1239. // Unmergable server overrides
  1240. Object.keys(instance_specific_config_manifest).forEach( key => {
  1241. __pvt[key] = instance_specific_config_manifest[key]
  1242. })
  1243. var __pub = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }, {}, __pvt
  1244. // Finalized immutables.
  1245. // We don't need pub to prevent immutability.
  1246. , { get root(){ return __pvt.root }
  1247. , get node_env(){ return __pvt.node_env }
  1248. , get instanceName() { return __pvt.instanceName }
  1249. , get reposindexed(){
  1250. // PB : TODO -- Implement -- One time gettor and then cached...
  1251. var indexed = {}
  1252. this.repos.forEach(r => { indexed[r.repo] = r })
  1253. this.elevated.forEach(r => { indexed[r.repo] = r })
  1254. Object.defineProperty(this, 'reposindexed', { value: indexed, writable: false });
  1255. return indexed;
  1256. }
  1257. , set root(val){
  1258. throw 'root changes not yet supported'
  1259. // if the root changes while we r invoked from somewhere else... we need to reload everything from that location...
  1260. if(__pvt.root === val){
  1261. return __pvt.root = val
  1262. }
  1263. else __pvt.root
  1264. }
  1265. }
  1266. )
  1267. chessinstances[__pub.instanceName] = chessinstances[__pub.instanceName] || {}
  1268. chessinstances[__pub.instanceName][__pub.instanceType] = __pub
  1269. // PB : TODO initinstances is now obselete relocated here
  1270. // Upgrade old formats..
  1271. if(__pub?.repos && !__pub?.repos[0]?.repo) {
  1272. console.warn('repo manifest has obsolete format. Attempting upgrade.')
  1273. __pub.repos = __pub.repos.map(function(repo){ return { repo } })
  1274. }
  1275. if(__pub?.elevated && !__pub?.elevated[0]?.repo) {
  1276. console.warn('elevated repo manifest has obsolete format. Attempting upgrade.')
  1277. __pub.elevated = __pub.elevated.map(function(repo){ return { repo } })
  1278. }
  1279. // Config from server always override merges into selection except for the current selection.
  1280. // PB : TODO -- utils.assign Array merges are non-distinct...
  1281. // chessinstances[instanceName][node_env] = selectedinstance;
  1282. // chessinstances[selectedinstance.instanceName][selectedinstance.node_env] = selectedinstance;
  1283. // PB : TODO -- We should probably write the new server config also...
  1284. // PB : TODO -- Attempt first one that is available and online...
  1285. // PB : TODO -- system select may need a reconfirm...
  1286. if(!__pub.reposerver) reconfirm['reposerver'] = true
  1287. __pub.reposerver = __pub.reposerver || __pub.reposervers[0]
  1288. cacheWriteInstanceConfig(chessinstances, __pub.root, __pub )
  1289. Object.defineProperty(__g, 'selectedinstance', {
  1290. get(){ return __pub}
  1291. , set( inst ){
  1292. utils.assign(__pub, inst); return __pub
  1293. }
  1294. })
  1295. return __pub;
  1296. })
  1297. })()
  1298. return pending.then(( selectedinstance)=>{
  1299. // PB : TODO -- Maybe create a new instance so we can switch around for different values...
  1300. shell_verse.init({ statuslog, selectedinstance, processedArgs, runtimestamp, ENV })
  1301. var op = {
  1302. 'h': () => { console.log(elxr.help()); return '-h' }
  1303. , 'clean' : () => {
  1304. // delete all node_module folders and links.
  1305. var tasklist = [];
  1306. dirs( (repodir)=> tasklist.push(getShellTask('rm',['-rf', 'node_modules'], { cwd : instanceroot + '/' + repodir.name })()), instanceroot )
  1307. return Promise.all(tasklist)
  1308. }
  1309. // , 'undefined': () => { return acquireChoices( {} ); }
  1310. , 'isurlaccessible' : function(args){
  1311. // args.url... .. PB : TODO -- Extract from url
  1312. args = args || {}
  1313. var u = new URL(args.url || selectedinstance.reposerver)
  1314. console.log(u)
  1315. var httpoptions = { hostname : u.host || 'git.bbh.org.in', protocol : u.protocol || 'https'
  1316. , method : 'GET'
  1317. , username : args.username || selectedinstance.username || 'chess'
  1318. , password : selectedinstance.password || 'chess'
  1319. }
  1320. httpoptions.path = args.path || `/`
  1321. return new Promise(function( resolve, reject ){
  1322. RESTAPI.get(httpoptions, function(){
  1323. console.log('URL is accessible')
  1324. resolve(true)
  1325. }, function(){
  1326. console.error('URL is not accessible')
  1327. resolve(false)
  1328. })
  1329. })
  1330. }
  1331. , 'reset': () => {
  1332. // Reset NPM packages semver so major versions can be updated.
  1333. const fs = require('fs')
  1334. const wipeDependencies = (__package) => {
  1335. const file = fs.readFileSync(__package + '/package.json')
  1336. const content = JSON.parse(file)
  1337. for (var devDep in content.devDependencies) {
  1338. if (content.devDependencies[devDep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
  1339. content.devDependencies[devDep] = '*';
  1340. }
  1341. }
  1342. for (var dep in content.dependencies) {
  1343. if (content.dependencies[dep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
  1344. content.dependencies[dep] = '*';
  1345. }
  1346. }
  1347. fs.writeFileSync(__package + '/package.json', JSON.stringify(content))
  1348. }
  1349. var repos = ['client'];
  1350. // repos = gitRepos;
  1351. repos.forEach(wipeDependencies)
  1352. // if (require.main === module) {
  1353. // } else {
  1354. // module.exports = wipeDependencies
  1355. // }
  1356. }
  1357. , 'upgrade': () => {
  1358. console.log('upgrade.......')
  1359. var tasks = [
  1360. () => {
  1361. var p = nodeShellExec('npm', ['i', '-g', 'npm-upgrade'], {
  1362. inherit: true, shell: true
  1363. , env: ENV
  1364. }).catch((e) => { console.error(e) })
  1365. p.position = 1;
  1366. console.log('One')
  1367. return p;
  1368. }
  1369. , () => {
  1370. var p = nodeShellExec('npm', ['cache', 'clean', '-f'], {
  1371. inherit: true, shell: true
  1372. , env: ENV
  1373. }).catch((e) => { console.error(e) })
  1374. p.position = 2;
  1375. console.log('Two')
  1376. return p;
  1377. }
  1378. , () => {
  1379. var p = nodeShellExec('npm', ['install', '-g', 'n'], {
  1380. inherit: true, shell: true
  1381. , env: ENV
  1382. }).catch((e) => { console.error(e) })
  1383. p.position = 3;
  1384. console.log('Three')
  1385. return p;
  1386. }
  1387. , () => {
  1388. var p = nodeShellExec('n', ['latest'], {
  1389. inherit: true, shell: true
  1390. , env: ENV
  1391. }).catch((e) => { console.error(e) })
  1392. p.position = 4;
  1393. console.log('Four')
  1394. return p;
  1395. }
  1396. ]
  1397. any(tasks)
  1398. console.log('.......done')
  1399. console.log('Running exlr upgrade in : ' + path.dirname(__dirname))
  1400. console.log('Currently only upgrades ember : ' + path.dirname(__dirname));
  1401. console.info('Uninstalling existing ember globally');
  1402. var step1 = nodeShellExec('cmd', ['/c', 'npm', 'uninstall', '-g', 'ember-cli'], {
  1403. stdio: ['pipe', process.stdout, process.stderr],
  1404. inherit: true,
  1405. shell: true,
  1406. cwd: path.dirname(__dirname),
  1407. env: ENV
  1408. })
  1409. step1.on('close', () => {
  1410. console.info('Installing ember globally');
  1411. var step2 = nodeShellExec('cmd', ['/c', 'npm', 'install', '-g', 'ember-cli'], {
  1412. stdio: ['pipe', process.stdout, process.stderr],
  1413. inherit: true,
  1414. shell: true,
  1415. cwd: path.dirname(__dirname),
  1416. env: ENV
  1417. })
  1418. step2.on('close', () => {
  1419. nodeShellExec('cmd', ['/c', 'ember', '--version'], {
  1420. stdio: ['pipe', process.stdout, process.stderr],
  1421. inherit: true,
  1422. shell: true,
  1423. cwd: path.dirname(__dirname),
  1424. env: ENV
  1425. })
  1426. })
  1427. })
  1428. }
  1429. , 'push': () => {
  1430. if (!processedArgs._[1]) { console.error('push all not supported. Specify repo name'); return }
  1431. // init remote bare from local
  1432. // pushandinitremotebare
  1433. // https://www.jeffgeerling.com/blogs/jeff-geerling/push-your-git-repositories
  1434. // connect to repo server -- net use 172.16.0.27
  1435. // cd 172.16.0.27/repos/
  1436. // mkdir repo.git
  1437. // cd repo.git
  1438. // git init --bare
  1439. // cd localrepo
  1440. // git remote rename origin githubclone
  1441. // git remote add origin //172.16.0.27/repos/repo.git
  1442. // git push origin master
  1443. var repo = processedArgs._[1];
  1444. var remote = 'origin'
  1445. var sequentialTaskShellCommands = [];
  1446. if (!existsSync(`Z:/${repo}.git`)) {
  1447. sequentialTaskShellCommands = [
  1448. // ['net', ['use', 'Z:', selectedinstance.reposerver.replace('/','\\')], {
  1449. // inherit : true, shell: true
  1450. // , env: ENV
  1451. // }]
  1452. ['pwd', { cwd: 'Z:', inherit: true }]
  1453. , ['mkdir', [`${repo}.git`], {
  1454. cwd: `Z:`
  1455. , inherit: true, shell: true
  1456. , env: ENV
  1457. }]
  1458. , ['pwd', { cwd: `Z:/${repo}.git`, inherit: true }]
  1459. , ['git', ['init', '--bare'], {
  1460. cwd: `Z:/${repo}.git`
  1461. , inherit: true, shell: true
  1462. , env: ENV
  1463. }]
  1464. // PB : TODO -- Do this conditionally only...
  1465. , ['git', ['remote', 'rename', remote, 'githubclone'], { cwd: `${instanceroot + '/' + repo}` }, (err) => {
  1466. console.log(`Ignoring ${remote} rename error : ` + err); return true; //return true to continue.
  1467. }] // PB ; Todo -- new repositories created locally will not have origin. Handle this failure.
  1468. , ['git', ['remote', 'add', remote, `${selectedinstance.reposerver}/${repo}.git`], { cwd: `${instanceroot + '/' + repo}` }]
  1469. // PB : TODO -- If threre is a gitbubclone origin
  1470. // Set the master to pull from the local repo.
  1471. ]
  1472. if (!existsSync(`Z:`)) {
  1473. sequentialTaskShellCommands.splice(0, 0, ['net', ['use', 'Z:', selectedinstance.reposerver.replace(/\//gm, '\\')], {
  1474. inherit: true, shell: true
  1475. , env: ENV
  1476. }])
  1477. console.warn('Adding network drive z: for repo server. ' + sequentialTaskShellCommands[0])
  1478. // throw 'done'
  1479. }
  1480. }
  1481. sequentialTaskShellCommands.push(['git', ['push', remote, 'master'], { cwd: `${instanceroot + '/' + repo}` }])
  1482. // console.dir(sequentialTaskShellCommands);
  1483. var tasks = [];
  1484. sequentialTaskShellCommands.forEach(shellcmd => {
  1485. // console.log(shellcmd)
  1486. tasks.push(() => {
  1487. var p = nodeShellExec.apply(null, shellcmd.slice(0, 3)).catch((e) => { if (shellcmd[3]) { return shellcmd[3]() } else { console.error(e); } })
  1488. return p;
  1489. })
  1490. })
  1491. any(tasks);
  1492. }
  1493. , 'is-git-repo': (dir) => {
  1494. return nodeShellExec('git', ['-C', dir.name, 'rev-parse'], { stdio: 'ignore' })
  1495. }
  1496. // git remote equivalents...
  1497. // git branch --set-upstream-to=elixir-unc/master master
  1498. // git push --set-upstream elixir-unc branch..
  1499. , 'remote': (args) => {
  1500. // Subcommands!
  1501. // PB : TODO -- we can now pass in hypehnated args...
  1502. if(!processedArgs.v) return false; // Only -v is supported presently..
  1503. var serial_perform = (repo) => {
  1504. var options = { cwd: instanceroot + '/' + repo }
  1505. return [
  1506. ['git', ['remote', '-v'], options]
  1507. ]
  1508. }
  1509. var x = (args) => {
  1510. var tasq = () => {
  1511. // console.log(args)
  1512. return nodeShellExec.apply(null, args).catch(e => {
  1513. // We continue on failure.
  1514. console.error(tasq.toString())
  1515. })
  1516. }
  1517. tasq.toString = function(){
  1518. return JSON.stringify(args)
  1519. }
  1520. return tasq;
  1521. }
  1522. var perform = (dir) => {
  1523. return any(serial_perform(dir.name).map(x))
  1524. }
  1525. dirs(perform)
  1526. }
  1527. , 'remote set-url': (args) => {
  1528. // git remote set-url elixir-unc //10.10.5.60/gitrepo/chess/bbhverse
  1529. var __args = {
  1530. remotename : args.remotename || processedArgs._[2]
  1531. , url : args.url || processedArgs._[3]
  1532. , branch : args.branch || processedArgs._[4] || 'master'
  1533. }
  1534. __args.upstream = args['upstream'] || processedArgs._[5] || `${__args.remotename}/${__args.branch}`
  1535. // pushable doesn't mean the remote doesn't support being pushed to.
  1536. // Over here it just means we are disabling pushing to that remote by setting the push portion of the url the a junk remote called no-pushing.
  1537. // PB : TODO -- change this to enablepushing.
  1538. // By default pushing should be disabled. Also developers permissions on the remote is a secondary check for pushing.
  1539. var pushable = processedArgs.pushable || (args.remote ? args.remote.pushable : false) || args.pushable;
  1540. var remotename = __args.remotename
  1541. var url = __args.url
  1542. var branch = __args.branch
  1543. var upstream = __args.upstream
  1544. console.log('remotename : ' + args.remotename)
  1545. var serial_perform_git_seturl = (reponame) => {
  1546. var options = { cwd: instanceroot + '/' + reponame }
  1547. // console.log(reponame)
  1548. var serialcmds = [
  1549. ['git', ['remote', 'set-url', remotename, url + '/' + reponame], { cwd: instanceroot + '/' + reponame }]
  1550. ]
  1551. if (!pushable) {
  1552. serialcmds.push(['git', ['remote', `set-url`, '--push', remotename, 'no-pushing'], { cwd: instanceroot + '/' + reponame }])
  1553. }
  1554. var requiresElevation = selectedinstance.elevated.find( r => r.repo === reponame)
  1555. serialcmds.push(['git', ['pull', remotename, branch], { cwd: instanceroot + '/' + reponame, requiresElevation }]) // requires elevation based on repo
  1556. serialcmds.push(['git', ['branch', `--set-upstream-to=${upstream}`, branch], { cwd: instanceroot + '/' + reponame }])
  1557. return serialcmds
  1558. }
  1559. var x = (xargs) => {
  1560. var tasq = () => {
  1561. // console.log(args)
  1562. var task = (onsuccess, onerror)=>{
  1563. return ()=>{
  1564. return nodeShellExec.apply(null, xargs).then( onsuccess ).catch(e => {
  1565. // We continue on failure.
  1566. // No such remote
  1567. if(e.messages[0].search('No such remote') > -1 ){
  1568. console.log(remotename + ' Remote doesnt exist will add.')
  1569. return op['remote add']( args )
  1570. }
  1571. console.error(util.inspect(e) + ' ' + tasq.toString())
  1572. })
  1573. }
  1574. }
  1575. if(xargs[2].requiresElevation){
  1576. if(!isElevated) {
  1577. var etask = task( ()=>{ return remotename } )
  1578. etask.statuslog = statuslog
  1579. etask.selectedinstance = selectedinstance
  1580. etask.processedArgs = processedArgs
  1581. etask.runtimestamp = runtimestamp
  1582. etask.ENV = ENV
  1583. return shell_verse.runElevated(etask)
  1584. }
  1585. }
  1586. return task(
  1587. () => { fs.writeFileSync('run.done', 'success')}
  1588. , () => { fs.writeFileSync('run.done', 'error') }
  1589. )()
  1590. }
  1591. tasq.toString = function(){ return JSON.stringify(args) }
  1592. return tasq;
  1593. }
  1594. var perform_git_seturl = (dir) => {
  1595. return op['is-git-repo'](dir).then((logEntry) => {
  1596. return any(serial_perform_git_seturl(dir.name).map(x))
  1597. }).catch((e) => {
  1598. console.log(e + ' Failed not recognized as a git repo : ' + dir.name)
  1599. })
  1600. }
  1601. if(args.dir) return perform_git_seturl(args.dir) // do this for a specific repo
  1602. else return dirs(perform_git_seturl) // Do for all
  1603. }
  1604. // , 'reset' : ()=>{
  1605. // PB : TODO -- Cant have 2 resets !! | There is an npm reset that should be bundled.
  1606. // // Reset the whole installation pertaining to this elxr folder.
  1607. // }
  1608. , 'remote exists': (args) => {
  1609. var __args = {
  1610. remotename : args.remotename|| processedArgs._[2]
  1611. , url : args.url || processedArgs._[3]
  1612. , branch : args.branch || processedArgs._[4]
  1613. }
  1614. var options = args.repo ? { cwd: instanceroot + '/' + args.repo } : {}
  1615. // PB : TODO -- We should evaluate a whole list of remotes passed in from args instead of just one.
  1616. var commands = [
  1617. // git remote -v| while read remote; do "${remote#origin/}" "$remote"; done
  1618. // ['git', ['remote', '-v', '| while read remote; do "${remote#origin/}" "$remote"; done'], utils.assign( {
  1619. [
  1620. // 'git', ['remote', '-v']
  1621. 'git', ['config', `remote.${__args.remotename}.url`]
  1622. , utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
  1623. , {
  1624. benign : args.benign, ignorefailures : args.ignorefailures,
  1625. evaluateResult : function(err, result){
  1626. return [
  1627. +result.code === 0
  1628. , result
  1629. ]
  1630. }
  1631. } , options) ]
  1632. ]
  1633. var mapped = commands.map(getshelltask) //.map( p => p.catch(e => e)) // Handle errors later.
  1634. mapped.push( function(prevserialtaskresult) {
  1635. var pt = [false , null]
  1636. if(prevserialtaskresult.error) {
  1637. // Previous task has failed.
  1638. pt[1] = prevserialtaskresult.error[1]
  1639. }
  1640. else pt = prevserialtaskresult;
  1641. console.dir(prevserialtaskresult)
  1642. return getshelltask(['git', ['ls-remote', `${__args.url}`], utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
  1643. , {
  1644. benign : args.benign, ignorefailures : args.ignorefailures,
  1645. evaluateResult : function(err, result){
  1646. if(+result.code !== 0) return [pt, [ false, result]]
  1647. // var hasfailed = /^fatal: .*/.test(result.messages.join(' '))
  1648. return [pt, [true, result] ]
  1649. }
  1650. } , options) ])().catch( e => {
  1651. console.error(e)
  1652. return [pt, [ false, null]]
  1653. })
  1654. })
  1655. return any(mapped, true, false, { accumulatedresults : [] }).then( allresolved => {
  1656. console.dir(allresolved)
  1657. !allresolved[0][0] && !allresolved[1][0] ? console.log('was not added as a remote and url is currently inaccessible.')
  1658. : allresolved[0][0] && allresolved[1][0] ? console.log('was added as a remote and url is accessible.')
  1659. : allresolved[0][0] && !allresolved[1][0] ? console.log('was added as a remote but url is currently inaccessible.')
  1660. : console.log('was not added as a remote but url is currently accessible.')
  1661. return !allresolved[0][0] && !allresolved[1][0] ? [0, 0]
  1662. : allresolved[0][0] && allresolved[1][0] ? [1, 1] // => was added as a remote and url is accessible.
  1663. : allresolved[0][0] && !allresolved[1][0] ? [1, 0] // => was added as a remote but url is currently inaccessible.
  1664. : [0, 1] // => was not added and remote and url is accessible.
  1665. }).catch(e => {
  1666. console.log(e)
  1667. return [0, 0]
  1668. })
  1669. }
  1670. , 'remote refresh' : (args) => {
  1671. var url = args._[2] || selectedinstance.reposerver
  1672. return op['isurlaccessible']({ url }).then(( baccess )=>{
  1673. if(!baccess) {
  1674. var reposerver = selectedinstance.reposerverinstances[url]
  1675. if(!reposerver.external) {
  1676. // Internal server not accessible ask to switch to external.
  1677. console.log('Internal server not accsssible. Will switch to external')
  1678. // console.dir(selectedinstance.reposerverinstances)
  1679. url = reposerver.externalreposervers[0]
  1680. }
  1681. else {
  1682. console.log('External server not accsssible. Will switch to interal')
  1683. // PB : TODO -- Prompt and then switch.
  1684. url = reposerver.internalreposervers[0]
  1685. }
  1686. return op['isurlaccessible']({ url }).then(( baccess )=>{
  1687. if(!baccess) {
  1688. console.log('Neither internal nor external servers are accessible.... Presenting choices...')
  1689. console.log('PB : TODO -- Present appropriate choices...')
  1690. // Redo whole command...
  1691. }
  1692. return dorefresh()
  1693. })
  1694. }
  1695. dorefresh()
  1696. console.log(baccess)
  1697. }).catch((err)=>{ console.error(err) })
  1698. function dorefresh(){
  1699. // if(args.url === selectedinstance.reposerver) {
  1700. // // No change. Just refresh with same url anyway. We do not know which of the repos is not up to date and is an outlier.
  1701. // }
  1702. // else {
  1703. // // Also refreshs anyway
  1704. // }
  1705. args = args || {}
  1706. var __args = {
  1707. url : args.url || processedArgs._[2] || selectedinstance.reposerver
  1708. // , branch : args.branch || processedArgs._[4]
  1709. }
  1710. var serial_perform = (repo) => {
  1711. // if(repo === 'setup' || repo === 'chess-server-lib'){
  1712. var options = { cwd: instanceroot + '/' + repo }
  1713. console.log('serial_perform : ' + repo)
  1714. return [
  1715. ['git', ['remote', '-v'], options]
  1716. ]
  1717. // }
  1718. // else return []
  1719. }
  1720. var x = (args) => {
  1721. // console.log('MapX was called')
  1722. var tasq = () => {
  1723. console.log('--------------------------')
  1724. console.log(args)
  1725. return nodeShellExec.apply(null, args).catch(e => {
  1726. console.log('caught error ------------------------' + JSON.stringify(e))
  1727. // We continue on failure.
  1728. console.error(tasq.toString() + args[2].cwd)
  1729. })
  1730. }
  1731. tasq.toString = function(){
  1732. // console.log('sadfasdf------------------------')
  1733. return JSON.stringify(args) // PB : TODO -- Is this needed ?
  1734. }
  1735. return tasq;
  1736. }
  1737. var remotenames = (selectedinstance.selectedremotes || []).concat( selectedinstance.permanentremotes )
  1738. var remotes = selectedinstance.reposerverinstances[__args.url].remotes
  1739. // use the repo manifest to create missing remotes.
  1740. function perform_remote_refresh(dir){
  1741. var repo = dir.name
  1742. var ___args = {url : __args.url, repo}
  1743. if(repo === '.elxr') return Promise.resolve(true)
  1744. if(repo === '.git') return Promise.resolve(true)
  1745. if(repo === 'Downloads') return Promise.resolve(true)
  1746. // PB : TODO -- pick up remote definitions per repository...
  1747. var reposmanfiest = utils.assign_core( { keycase : true, arraymergetype : utils.assign_core.DISTINCT_UNION }
  1748. , {}, selectedinstance, loadmanifest( selectedinstance.root + '/' + repo
  1749. , { username : selectedinstance.username, instanceName : selectedinstance.instanceName
  1750. , node_env : selectedinstance.node_env, reposerver : selectedinstance.reposerver }
  1751. ))
  1752. if( !reposmanfiest.error ) {
  1753. var reporemotenames = remotenames.concat(reposmanfiest.selectedremotes || []).concat( reposmanfiest.permanentremotes || [] )
  1754. var reporemotes = utils.assign([], remotes, reposmanfiest.reposerverinstances[___args.url].remotes)
  1755. }
  1756. else {
  1757. var reporemotenames = remotenames
  1758. var reporemotes = remotes
  1759. }
  1760. return (()=>{
  1761. var promises = []
  1762. return any(serial_perform(repo).map(x)).then(()=>{
  1763. var branch = args.branch || 'master' // PB : TODO -- Dont default branch here.. Let each repos current state define this... ???
  1764. reporemotenames.forEach(rm =>{
  1765. console.log('Processing : ' + rm + ' ' + dir.name)
  1766. // if(repo != 'elxr') return //test
  1767. // if(repo != 'elixir-config-development') return //test
  1768. // if(repo != 'elixir-server') return //test
  1769. promises.push( ((rm) => {
  1770. var remotename = rm
  1771. var repodef = selectedinstance.reposindexed[repo];
  1772. if(!repodef) return
  1773. // if( repo !== 'cihsr-data') return
  1774. // username and owner are two different things. The repository (possibly forked) under the username is when the {{owner}} portion of the repo path is the same as the user.
  1775. // When one user or organiztion shares repos with others through a team without a fork a different user has access to a different {{owner}} path repo.
  1776. var remote = reporemotes[remotename]
  1777. // console.log(repodef)
  1778. // console.log(remote)
  1779. var owner = repodef.owner || remote.owner || defaultRepoOwner // should be based on the server, remote and repo combination.
  1780. var reposerver = repodef.server || remote.server || selectedinstance.reposerver
  1781. // selectedinstance.reposerverinstances[reposerver]
  1782. var auth = repodef.username ? repodef : remote.username ? remote : selectedinstance.reposerverinstances[reposerver].username ? reposerver : selectedinstance;
  1783. var httpoptions = new URL(reposerver);
  1784. httpoptions = {
  1785. hostname: httpoptions.hostname
  1786. , method: 'GET'
  1787. , protocol : httpoptions.protocol
  1788. }
  1789. httpoptions.username = auth.username // PB : TODO -- Handle remotes with different username. Also cache git credentials either globally or per repo...
  1790. httpoptions.password = (auth.password || selectedinstance.password || '') // PB : NOTE URL has some kind of a setter for password which converts to string "undefined" as password which is undesirable.. so we pre resolve and send.
  1791. // console.log(___args)
  1792. var repourl = reporemotes[remotename].url + '/' + repo
  1793. // PB : TOOD -- USE GITTEA API
  1794. // op['isurlaccessible']({ url : repourl }).then((baccess)=>{
  1795. return GITEA.repository.exists( httpoptions, repo, owner ).then((bexists)=>{
  1796. console.log(remotename + ' ' + repourl)
  1797. if(bexists) {
  1798. console.log(remotename + ' ' + repourl + ' is accessible')
  1799. return ((remotename)=>{
  1800. return op['remote set-url']( { dir, remotename, url : reporemotes[remotename].url, remote
  1801. , repodef : selectedinstance.reposindexed[repo] } ) // PB : TODO -- Handle add-url
  1802. })(remotename)
  1803. // get upstream remote choice from user !!!
  1804. // PB : TODO -- Set upstream , ['git', ['branch', `--set-upstream-to=${remotename}/${branch}`, branch], { cwd: instanceroot + '/' + repo }]
  1805. }
  1806. }).catch(e => {
  1807. console.warn(remotename + ' ' + repourl + ' ' + e) // Skip nonexistant not necessarily quietly
  1808. })
  1809. })(rm)
  1810. )
  1811. })
  1812. return Promise.all(promises).then( accessibleremotes => {
  1813. while(!accessibleremotes[accessibleremotes.length -1] && accessibleremotes.length) accessibleremotes.splice(accessibleremotes.length -1, 1)
  1814. if(accessibleremotes.length) {
  1815. ((remotename)=>{
  1816. var upstream = `${remotename}/${branch}`
  1817. var remote = reporemotes[remotename]
  1818. return op['remote set-url']( { dir, remotename, url : reporemotes[remotename].url, remote
  1819. , upstream
  1820. , repodef : selectedinstance.reposindexed[repo] } ) // PB : TODO -- Handle add-url
  1821. })( accessibleremotes[accessibleremotes.length -1] )
  1822. }
  1823. }).catch((e) => { console.log('Processing Error : ' + dir.name); console.error(e); return { error: true, message: repo } })
  1824. })
  1825. })()
  1826. }
  1827. if(isElevated) {
  1828. var elevatedpromises = []
  1829. selectedinstance.elevated.forEach( r => { elevatedpromises.push(perform_remote_refresh({ name : r.repo })) } )
  1830. return Promise.all(elevatedpromises)
  1831. }
  1832. else return dirs(perform_remote_refresh)
  1833. }
  1834. }
  1835. , 'remote add': (args) => {
  1836. // PB : TODO -- set-upstream-to should be chosen and intentionally switched. Coz we can have multiple upstream remotes.
  1837. // Also each upstream remote may need to have is own branch to switch to. We therefore need a branch nomenclature
  1838. // That explicitly has a remote name prefix.
  1839. // git branch branch_name --set-upstream-to your_new_remote/branch_name
  1840. // git branch branch_name -u your_new_remote/branch_name -- older versions
  1841. // git branch -vv -- Detect which branch are we tracking.
  1842. // default upstream should be users own fork.
  1843. // Also need alias branches to
  1844. // define a git alias which would git pull master from one repo, and then git pull master from other remotes.
  1845. // probably git merge from all remotes... and relevant branches...
  1846. // alias pushall='for i in `git remote`; do git push $i; done;'
  1847. // alias pullall='for i in `git remote`; do git pull $i; done;'
  1848. // args === processedArgs ? args = {} : null;
  1849. var __args = {
  1850. remotename : args.remotename|| processedArgs._[2]
  1851. , reponame : args.reponame || (args.repodef ? args.repodef.repo : undefined)
  1852. , url : args.url || processedArgs._[3]
  1853. , branch : args.branch || processedArgs._[4] || 'master'
  1854. }
  1855. __args.upstream = args['upstream'] || processedArgs._[5] || `${remotename}/${branch}`
  1856. var remotename = __args.remotename
  1857. var url = __args.url
  1858. var branch = __args.branch
  1859. var upstream = __args.upstream
  1860. var pushable = processedArgs.pushable || (args.remote ? args.remote.pushable : false) || args.pushable;
  1861. var serial_perform_git_add = (reponame) => {
  1862. var options = { cwd: instanceroot + '/' + reponame }
  1863. // console.log(reponame)
  1864. if (pushable) {
  1865. var gacmds = [
  1866. ['git', ['remote', 'add', remotename, url + '/' + reponame], { cwd: instanceroot + '/' + reponame }]
  1867. , ['git', ['pull', remotename, branch], { cwd: instanceroot + '/' + reponame }]
  1868. // , ['git', ['branch', `--set-upstream-to=${upstream}`, branch], { cwd: instanceroot + '/' + reponame }]
  1869. ]
  1870. }
  1871. else {
  1872. var gacmds = [
  1873. ['git', ['remote', 'add', remotename, url + '/' + reponame], { cwd: instanceroot + '/' + reponame }]
  1874. , ['git', ['remote', `set-url`, '--push', remotename, 'no-pushing'], { cwd: instanceroot + '/' + reponame }]
  1875. , ['git', ['pull', remotename, branch], { cwd: instanceroot + '/' + reponame }]
  1876. // When we add a remote it should not automatically become the upstream. The upstream should be a chosen remote else we do not change
  1877. // , ['git', ['branch', `--set-upstream-to=${upstream}`, branch], { cwd: instanceroot + '/' + reponame }]
  1878. ]
  1879. }
  1880. if(__args['upstream']) gacmds.push(['git', ['branch', `--set-upstream-to=${upstream}`, branch], { cwd: instanceroot + '/' + reponame }])
  1881. return gacmds
  1882. }
  1883. // PB : TODO -- Accumulate using yield... and finally return a set of tasks or promises...
  1884. var perform_git_add = (dir) => {
  1885. return op['is-git-repo'](dir).then((logEntry) => {
  1886. // console.log(code)
  1887. if (logEntry.success) {
  1888. return nodeShellExec('git', ['remote', 'get-url', remotename], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  1889. console.log('skipped : ' + dir.name + ', reason : A remote with same name already exists.')
  1890. return remotename;
  1891. })
  1892. .catch((e) => {
  1893. return perform( serial_perform_git_add, dir.name ).then(()=>{
  1894. return remotename
  1895. })
  1896. })
  1897. }
  1898. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  1899. }).catch((e) => {
  1900. console.log('Failed : ' + dir.name)
  1901. })
  1902. }
  1903. if(__args.reponame) { return perform_git_add( { name : __args.reponame} ) }
  1904. else return dirs(perform_git_add)
  1905. }
  1906. , 'remote remove': (args) => {
  1907. var __args = {
  1908. remotename : args.remotename|| processedArgs._[2]
  1909. }
  1910. var remotename = __args.remotename
  1911. var serial_perform_git_remove = (repo) => {
  1912. var options = { cwd: instanceroot + '/' + repo }
  1913. // console.log(repo)
  1914. return [
  1915. ['git', ['remote', 'remove', remotename], { cwd: instanceroot + '/' + repo }]
  1916. ]
  1917. }
  1918. var perform_git_remove = (dir) => {
  1919. op['is-git-repo'](dir).then((logEntry) => {
  1920. // console.log(code)
  1921. if (logEntry.success) {
  1922. nodeShellExec('git', ['remote', 'get-url', remotename], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  1923. any(serial_perform_git_remove(dir.name).map(getnodeshellexectask))
  1924. })
  1925. .catch((e) => {
  1926. console.log('skipped : ' + dir.name + `, reason : No remote named ${remotename}`)
  1927. })
  1928. }
  1929. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  1930. }).catch((e) => {
  1931. // console.log('Failed : ' + dir.name)
  1932. })
  1933. }
  1934. dirs(perform_git_remove)
  1935. }
  1936. , 'get-remotes' : (args) => {
  1937. // var __args = {
  1938. // repo : args?.repo || processedArgs._[1]
  1939. // }
  1940. var repo = args.repo
  1941. var serial_perform = (repo) => {
  1942. return [
  1943. ['git', ['remote', '-vvvv'], { cwd: instanceroot + '/' + repo,
  1944. evaluateResult : function( issuccess, result){
  1945. if(!issuccess || +result.code !== 0) throw Object.assign( new Error('git branch -vvvv crashed'), result);
  1946. var lines = result.messages.join('').split('\n')
  1947. var remotes = {}
  1948. lines.forEach(line => {
  1949. // pattern = origin https://git.bbh.org.in/chess/elxr (fetch)
  1950. var match = new RegExp(`(\\S+)\\s(\\S+)/${repo}.git\\s\\((\\S+)\\)`).exec(line)
  1951. if(match) {
  1952. var r = remotes[match[1]] || (remotes[match[1]] = { title : match[1] })
  1953. if(match[3] === 'push') { r.push = match[2] }
  1954. else r.url = match[2]
  1955. }
  1956. })
  1957. return remotes
  1958. }}]
  1959. ]
  1960. }
  1961. return perform( serial_perform, repo )
  1962. }
  1963. , 'get-remote' : (upstream) => {
  1964. // var __args = {
  1965. // repo : args?.repo || processedArgs._[1]
  1966. // }
  1967. var repo = upstream.repo
  1968. var serial_perform = (repo) => {
  1969. return [
  1970. ['git', ['remote', '-vvvv'], { cwd: instanceroot + '/' + repo,
  1971. evaluateResult : function( issuccess, result){
  1972. if(!issuccess || +result.code !== 0) throw Object.assign( new Error('git branch -vvvv crashed'), result);
  1973. // origin https://git.bbh.org.in/chess/elxr (fetch)
  1974. var match = new RegExp(`${upstream.remotename}\\\s(\\S+)/${repo}.git\\s\\(fetch\\)`).exec(result.messages.join(' '))
  1975. if(match) { upstream.url = match[1] }
  1976. else throw Object.assign( new Error('No upstream found for active branch'), result)
  1977. return upstream
  1978. }}]
  1979. ]
  1980. }
  1981. return perform( serial_perform, repo )
  1982. }
  1983. , 'get-upstream' : (args) => {
  1984. var __args = {
  1985. repo : args?.repo || processedArgs._[1]
  1986. }
  1987. var repo = __args.repo
  1988. var serial_perform = (repo) => {
  1989. return [
  1990. ['git', ['branch', '-vvvv'], { cwd: instanceroot + '/' + repo,
  1991. evaluateResult : function( issuccess, result){
  1992. if(!issuccess || +result.code !== 0) throw Object.assign( new Error('git branch -vvvv crashed'), result);
  1993. var match = /\*\s(\S+)\s\S+\s\[(\S+)\/(\S+).*?\].*?/.exec(result.messages.join(' '))
  1994. if(match) { var upstream = { remotename : match[2], branch : match[1], remotebranch : match[3] } }
  1995. else throw Object.assign( new Error('No upstream found for active branch'), result)
  1996. if(args?.remotes) {
  1997. var r = args.remotes[upstream.remotename];
  1998. if(!r) return op['get-remote'](upstream)
  1999. r.branch = upstream.branch
  2000. r.remotebranch = upstream.remotebranch
  2001. return r
  2002. }
  2003. return op['get-remote'](upstream)
  2004. }}]
  2005. ]
  2006. }
  2007. return perform( serial_perform, repo )
  2008. }
  2009. , 'init-gitea': (username) => {
  2010. // Change user to an object that has user.username and use here..
  2011. username = username || processedArgs._[1]
  2012. if (!username) throw 'User name required'
  2013. var serial_perform_init_gitea = (repo) => {
  2014. var options = { cwd: instanceroot + '/' + repo }
  2015. // console.log(repo)
  2016. return [
  2017. ['git', ['remote', 'add', 'chess', `${selectedinstance.reposerver}/${username}/${repo}.git`], { cwd: instanceroot + '/' + repo }]
  2018. , ['git', ['remote', 'set-url', '--push', 'chess', 'no-pushing'], { cwd: instanceroot + '/' + repo }]
  2019. , ['git', ['remote', 'set-url', 'userfork', `${selectedinstance.reposerver}/${username}/${repo}.git`], { cwd: instanceroot + '/' + repo }]
  2020. ]
  2021. }
  2022. var perform_init_gitea = (dir) => {
  2023. op['is-git-repo'](dir).then((logEntry) => {
  2024. // console.log(code)
  2025. if (logEntry.success) {
  2026. nodeShellExec('git', ['remote', 'get-url', 'chess'], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  2027. console.log('skipped : ' + dir.name + ', reason : Already has remote chess ')
  2028. })
  2029. .catch((e) => {
  2030. perform( serial_perform_init_gitea, dir.name )
  2031. })
  2032. }
  2033. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  2034. }).catch((e) => {
  2035. // console.log('Failed : ' + dir.name)
  2036. })
  2037. }
  2038. dirs(perform_init_gitea)
  2039. }
  2040. , 'syncmaster': (label) => {
  2041. // Usage :
  2042. // elxr pull -- Defaults to run config
  2043. console.log('Running exlr pull : ' + path.dirname(__dirname))
  2044. if (!processedArgs.runas) gitRepos.map((def) => {
  2045. if (exludeMergeRepos[def.repo]) return Promise.resolve({ 'skipped': true })
  2046. else performPull(def, def.branch || 'master')
  2047. })
  2048. var etask = ()=>{
  2049. return any(elevatedRunasRepos.map((def) =>
  2050. {
  2051. if (exludeMergeRepos[def.repo]) return Promise.resolve({ 'skipped': true })
  2052. else performPull(def, def.branch || 'master')
  2053. })).then(() => {
  2054. fs.writeFileSync('run.done', 'success')
  2055. }).catch(() => {
  2056. fs.writeFileSync('run.done', 'error')
  2057. })
  2058. }
  2059. etask.statuslog = statuslog
  2060. etask.selectedinstance = selectedinstance
  2061. etask.processedArgs = processedArgs
  2062. etask.runtimestamp = runtimestamp
  2063. etask.ENV = ENV
  2064. return shell_verse.runElevated(etask)
  2065. }
  2066. , 'repo-relocate' : function(args){
  2067. // relocate a subfolder in source repo to same subfolder in target repo with history.
  2068. var args = args || {
  2069. remotebase : processedArgs._[4] || 'http://git.bbh/chess/'
  2070. , folder : processedArgs._[3] || 'server'
  2071. , sourcerepo : processedArgs._[2] || 'client'
  2072. , targetrepo : processedArgs._[1] || 'elixir-server'
  2073. }
  2074. var sourcerepooptions = { cwd: `${instanceroot}/relocate/${args.sourcerepo}`
  2075. // , stdio: ['pipe', process.stdout, process.stderr]
  2076. , inherit: true,
  2077. shell: true,
  2078. env: ENV
  2079. , runas: processedArgs.runas
  2080. }
  2081. return op['repo-split'](args).then(()=>{
  2082. return op['repo-merge'](args).then(()=>{
  2083. // cleanup folder from source.
  2084. var cmdseq = [
  2085. ['rm', ['-rf', `${args.folder}`], sourcerepooptions ]
  2086. // commits have to intentional...
  2087. // , ['git', ['commit', '-a', '-m', `relocate folder ${args.folder} to ${targetrepo}`], sourcerepooptions ]
  2088. ]
  2089. return any(cmdseq.map(getshelltask))
  2090. })
  2091. }).catch(e=>{console.error(e)})
  2092. }
  2093. , 'repo-split' : function(args) {
  2094. // https://gist.github.com/smdabdoub/17065c348289158277b5
  2095. /**
  2096. * Eg : folder, remotebase, sourcerepo, targetrepo
  2097. * args.folder = 'server'
  2098. * args.remotebase = 'https://git.bbh/chess/'
  2099. * args.sourcerepo = 'client'
  2100. * args.targetrepo = 'elixir-server'
  2101. */
  2102. var args = args || {
  2103. folder : 'server'
  2104. , remotebase : 'http://git.bbh/chess/'
  2105. , sourcerepo : 'client'
  2106. , targetrepo : 'elixir-server'
  2107. }
  2108. var options = { cwd: `${instanceroot}/relocate`
  2109. // , stdio: ['pipe', process.stdout, process.stderr]
  2110. , inherit: true,
  2111. shell: true,
  2112. env: ENV
  2113. , runas: processedArgs.runas
  2114. }
  2115. var cmdseq = [
  2116. // create a temporary working dir in current folder where we started execution.
  2117. ['mkdir', [ '-p', `${instanceroot}/relocate`]]
  2118. , ['git', ['clone', `${args.remotebase}${args.sourcerepo}`], options ]
  2119. , ['git', ['clone', `${args.sourcerepo}`, `relocate-${args.sourcerepo}-${args.folder}`], options]
  2120. , ['git', ['clone', `${args.remotebase}${args.targetrepo}`, `relocate-${args.targetrepo}-${args.folder}`], options]
  2121. ]
  2122. return any(cmdseq.map(getshelltask)).then(() => {
  2123. // , ['git', ['subtree', 'split', '-P', `${args.folder}`, '-b', `relocate-${args.sourcerepo}-${args.folder}`], sourcerepooptions]
  2124. // split doesnt retain folder structure we need to move and commit ourselves through a branch to retain history...
  2125. // , ['git', [`checkout relocate-${args.sourcerepo}-${args.folder}`], sourcerepooptions]
  2126. // , ['mkdir', [`${args.folder}`], sourcerepooptions]
  2127. // , ['git', ['mv', `!(${args.folder})`, `${args.folder}`], sourcerepooptions ] // requires shopt -s extglob
  2128. // , ['git', ['commit', `-m`, 'Moved to same subfolder after subtree split in branch'] , sourcerepooptions]
  2129. // subtree split and filter-branch are options. We currently use repo-filter.
  2130. return op['filter-repo'](args)
  2131. }).catch(e=>{console.error(e); throw 'failed'})
  2132. }
  2133. , 'repo-merge' : function(args) {
  2134. // Merge source repo into target repo
  2135. var args = args || {
  2136. folder : 'server'
  2137. , remotebase : 'http://git.bbh/chess/'
  2138. , sourcerepo : 'client'
  2139. , targetrepo : 'elixir-server'
  2140. }
  2141. var sourcerepooptions = { cwd: `${instanceroot}/relocate/relocate-${args.sourcerepo}-${args.folder}`
  2142. // , stdio: ['pipe', process.stdout, process.stderr]
  2143. , inherit: true,
  2144. shell: true,
  2145. env: ENV
  2146. , runas: processedArgs.runas
  2147. }
  2148. var targetrepooptions = { cwd: `${instanceroot}/relocate/relocate-${args.targetrepo}-${args.folder}`
  2149. // , stdio: ['pipe', process.stdout, process.stderr]
  2150. , inherit: true,
  2151. shell: true,
  2152. env: ENV
  2153. , runas: processedArgs.runas
  2154. }
  2155. var cmdseq = [
  2156. ['git', ['pull', `../relocate-${args.sourcerepo}-${args.folder}`, `master`, '--allow-unrelated-histories']
  2157. , targetrepooptions ]
  2158. // , ['git', ['push', targetrepooptions ] // manual push for now..
  2159. ]
  2160. return any(cmdseq.map(getshelltask)).catch(e=>{console.error(e)})
  2161. }
  2162. , 'filter-repo' : function(args){
  2163. // Merge source repo into target repo
  2164. var args = args || {
  2165. folder : 'server'
  2166. , remotebase : 'http://git.bbh/chess/'
  2167. , targetrepo : 'elixir-server'
  2168. }
  2169. var targetrepooptions = { cwd: `${instanceroot}/relocate/relocate-${args.sourcerepo}-${args.folder}`
  2170. , inherit: true, shell: true
  2171. , env: ENV
  2172. , runas: processedArgs.runas
  2173. }
  2174. var cmdseq = [
  2175. // git checkout -b feature/merge-old-project
  2176. // git remote add src-project ../src-project
  2177. ['git', ['filter-repo', '--path', `${args.folder}`], targetrepooptions ]
  2178. ]
  2179. return any(cmdseq.map(getshelltask)).catch(e=>{console.error(e); throw 'failed' })
  2180. }
  2181. , 'filter-branch' : function(preservefolder, repo){
  2182. // https://stackoverflow.com/questions/359424/detach-move-subdirectory-into-separate-git-repository
  2183. // git subtree split -P <name-of-folder> -b <name-of-new-branch>
  2184. // Preserve a specific folder.
  2185. // PB : TODO -- filter-branch has known issues. Explore subtree and filter-repo...
  2186. /*
  2187. git clone repo reposplit
  2188. git filter-branch --tag-name-filter cat --prune-empty --subdirectory-filter {{folder}} -- --all
  2189. git remote rm origin
  2190. */
  2191. throw 'filter-repo-history not yet implmented pls refer to manual commands in code.'
  2192. }
  2193. // , 'repo-merge-folder' : function(mergetarget, mergesource, mergefolder){
  2194. // // Merge repo2 into a subfolder in repo1
  2195. // // https://alexharv074.github.io/puppet/2017/10/04/merge-a-git-repository-and-its-history-into-a-subdirectory-of-a-second-git-repository.html
  2196. // // https://thoughts.t37.net/merging-2-different-git-repositories-without-losing-your-history-de7a06bba804
  2197. // /*
  2198. // cd repo1
  2199. // git remote add -f tempmergesource ../{{mergesource}}/.git
  2200. // git merge -s ours --no-commit tempmergesource/master --allow-unrelated-histories
  2201. // git read-tree --prefix={{mergefolder}} -u tempmergesource/master:
  2202. // git commit
  2203. // // Repair History
  2204. // // === git filter-branch --tree-filter '(echo === $GIT_COMMIT:; git ls-tree $GIT_COMMIT) >> /tmp/tree.log'
  2205. // #!/usr/bin/env bash
  2206. // first=ed4f16becc2f03820c164e0617bb98f12ff49ef0
  2207. // last=038e26e21bd60fa265d6637261f3bc918780d2e8
  2208. // subdir=server
  2209. // git filter-branch --tree-filter '
  2210. // first='"$first"'
  2211. // last='"$last"'
  2212. // subdir='"$subdir"'
  2213. // log_file=/tmp/filter.log
  2214. // [ "$GIT_COMMIT" = "$first" ] && seen_first=true
  2215. // if [ "$seen_first" = "true" ] && [ "$seen_last" != "true" ]; then
  2216. // echo "=== $GIT_COMMIT: making changes"
  2217. // files=$(git ls-tree --name-only $GIT_COMMIT)
  2218. // mkdir -p $subdir
  2219. // for i in $files; do
  2220. // mv $i $subdir || echo "ERR: mv $i $subdir failed"
  2221. // done
  2222. // else
  2223. // echo "=== $GIT_COMMIT: ignoring"
  2224. // fi \
  2225. // >> $log_file
  2226. // [ "$GIT_COMMIT" = "$last" ] && seen_last=true
  2227. // status=0 # tell tree-filter never to fail
  2228. // '
  2229. // git remote rm tempmergesource
  2230. // */
  2231. // // better alternative for history
  2232. // /**
  2233. // *
  2234. // git clone git@server.com:old-project.git
  2235. // git clone git@server.com:new-project.git
  2236. // cd old-project
  2237. // mkdir old-project
  2238. // git mv !(old-project) old-project
  2239. // ls -la and gt mv hidden files ....
  2240. // git commit -a -S -m “Moving old project into its own subdirectory”
  2241. // cd ../new-project
  2242. // git remote add old-project ../old-project
  2243. // git fetch old-project
  2244. // git checkout -b feature/merge-old-project
  2245. // git merge -S --allow-unrelated-histories old-project/master
  2246. // git push origin feature/merge-old-project
  2247. // git remote rm old-project
  2248. // */
  2249. // throw 'merge-repos not yet implmented pls refer to manual commands in code.'
  2250. // }
  2251. , 'pull' : (label) => {
  2252. // Usage :
  2253. // elxr pull -- Defaults to run config
  2254. return elxr.getpulltask(selectedinstance)
  2255. }
  2256. , 'isInstalled': () => {
  2257. return nodeShellExec('where', [processedArgs._[1]], { inherit: true }).then(() => {
  2258. console.log(processedArgs._[1] + ' exists.')
  2259. return true;
  2260. });
  2261. }
  2262. , 'c' : ()=>{
  2263. }
  2264. , 'i' : () => {
  2265. var tasks = []
  2266. // tasks.push(op['pull']);
  2267. tasks.push(getShellTask.apply(null, ['rm', [instanceroot + '/run.js'], { ignorefailures: true }]))
  2268. tasks.push(op['use']) // Will pull repos...
  2269. op['npmi'].statuslog = statuslog
  2270. tasks.push(shell_verse.getNonElevatedTask(op['npmi'])) // We do not run npm i with elevated privilege for security reasons.
  2271. // var tasksdefs = [
  2272. // ['elxr', ['pull']]
  2273. // , ['elxr', ['use', 'elixir']]
  2274. // , ['elxr', ['npmi']]
  2275. // ]
  2276. // tasksdefs.forEach(tasksdef=>{
  2277. // tasks.push( ()=> nodeShellExec.apply(null, tasksdef) )
  2278. // })
  2279. return any(tasks);
  2280. }
  2281. , 'npmi': () => {
  2282. var tasks = [];
  2283. // Build fails without babel...
  2284. tasks.push(getShellTask(
  2285. 'npm',[ 'i', '-g', 'babel-cli' ]
  2286. ) )
  2287. var npmbuildrepos = ['loopback-jsonapi-model-serializer']
  2288. // npmbuildrepos = []
  2289. npmbuildrepos.forEach(repo => {
  2290. tasks.push(() => {
  2291. return nodeShellExec('npm', ['i --force'], {
  2292. inherit: true, shell: true
  2293. , cwd: instanceroot + '/' + repo
  2294. , env: ENV
  2295. , title: `npm i for ${repo}`
  2296. }).catch((e) => {
  2297. console.error('Ignoring Benign Error'); console.error(e);
  2298. }).then(() => {
  2299. console.log(`--npm run build for ${repo}--------------------`)
  2300. return nodeShellExec('npm', ['run build'], {
  2301. inherit: true, shell: true
  2302. , cwd: instanceroot + '/' + repo
  2303. , env: ENV
  2304. , title: `npm run build for ${repo}`
  2305. }).then(Tasq.then).catch(Tasq.catch)
  2306. })
  2307. })
  2308. })
  2309. return any(tasks).then(() => {
  2310. gitRepos.push({ repo : 'chess-server-lib/server'});
  2311. gitRepos = gitRepos.concat(elevatedRunasRepos);
  2312. // console.dir(gitRepos)
  2313. // throw ""
  2314. // gitRepos = [
  2315. // // 'bbhverse', 'serververse', 'elixir-server',
  2316. // // 'clientverse',
  2317. // 'client'
  2318. // ];
  2319. var rmtasks = []
  2320. var repotasks = []
  2321. var env = Object.assign({}, ENV)
  2322. delete env.NODE_ENV // PB : TODO -- Why delete ??? npm i fails with NODE_ENV...
  2323. gitRepos.forEach(repodef => {
  2324. rmtasks.push(
  2325. // () => {
  2326. // console.log(`--rm package-lock.json for ${repodef.repo}--------------------`)
  2327. // return nodeShellExec(`"${gitbash}"`, ['-c', '"rm package-lock.json"'], {
  2328. callshelltask(['rm', ['package-lock.json'], {
  2329. inherit: true, shell: true
  2330. , cwd: instanceroot + '/' + repodef.repo
  2331. , env: ENV
  2332. , title: `rm 'package-lock.json' for ${repodef.repo}`
  2333. }])
  2334. .then(()=>{
  2335. console.log(`--rm package-lock.json for ${repodef.repo}--------------------`)
  2336. }).catch((e) => { console.error(e) })
  2337. // }
  2338. )
  2339. if (npmbuildrepos.indexOf(repodef.repo) < 0) {
  2340. repotasks.push(
  2341. () => {
  2342. console.log(`--npm i for ${repodef.repo}--------------------`)
  2343. var p = nodeShellExec('npm', ['i', '--force'], {
  2344. inherit: true, shell: true
  2345. , cwd: instanceroot + '/' + repodef.repo
  2346. , env
  2347. , title: `npm i for ${repodef.repo}`
  2348. }).then(Tasq.then).catch(Tasq.catch)
  2349. return p;
  2350. })
  2351. }
  2352. })
  2353. // NODE_ENV=development DEBUG=loopback:connector:mssql node --tls-min-v1.0 --inspect elixir/server.js
  2354. // PB : NOTE -- npm i for client does not complete when NODE_ENV=production
  2355. // therefore bower doesn't get installed !!! which then fails installing the bower dependenciew !!!
  2356. // We work around this by running npm i for client without any NODE_ENV which probably defualts to development.
  2357. // PB : TODO -- Investigate why NODE_ENV has an impact on npm i !??
  2358. // Second time try also doesnt work.
  2359. // repotasks.push(
  2360. // () => {
  2361. // var env = Object.assign({}, process.env)
  2362. // delete env.NODE_ENV
  2363. // console.log(`--------------------second time npm i for client--------------------`)
  2364. // return nodeShellExec(`"${gitbash}"`, ['-c', '"npm i --force"'], {
  2365. // // return nodeShellExec('npm', ['i --force'], {
  2366. // inherit: true, shell: true
  2367. // , cwd: instanceroot + '/' + 'client'
  2368. // , env
  2369. // , title: `npm i for client`
  2370. // }).then(Tasq.then).catch(Tasq.catch)
  2371. // })
  2372. var bowerRepos = [{ repo : 'client'}]
  2373. var bowertasks = []
  2374. bowerRepos.forEach(repodef => {
  2375. bowertasks.push(() => {
  2376. console.log(instanceroot + '/' + repodef.repo + '/node_modules/bower/bin/bower')
  2377. // var p = nodeShellExec('node_modules/bower/bin/bower', ['install'], {
  2378. var p = nodeShellExec(`"${gitbash}"`, ['-c', '"node_modules/bower/bin/bower i"'], {
  2379. inherit: true, shell: true
  2380. , cwd: instanceroot + '/' + repodef.repo
  2381. , env: ENV
  2382. , title: `bower i for ${repodef.repo}`
  2383. }).then(Tasq.then).catch(Tasq.catch)
  2384. return p;
  2385. })
  2386. })
  2387. // console.log('rmtasks.length : ' + rmtasks.length)
  2388. return Promise.all(rmtasks).then(() => any(repotasks)).then(()=>any(bowertasks));
  2389. }).catch(e => {
  2390. console.error(e)
  2391. }).finally(statuslog.finally)
  2392. }
  2393. , 'start': (args) => {
  2394. // Usage : elxr start {{instanceName=elixir}} {{all||server||client||{{microserviceName=elixir||express}}}}
  2395. var label = clioverrides.cmd
  2396. var env = Object.assign({}, ENV); // Shallow clone it.
  2397. var nodecmd = clioverrides.node_env === 'development' ? 'nodemon' : 'node';
  2398. function startFn( o ){
  2399. var cmd = [nodecmd, [`--inspect=${o.debugport}`, '--preserve-symlinks', o.script]]
  2400. console.log(`Starting ${o.name}.`);
  2401. if(shell_verse.iswin()){
  2402. var __cmd = 'cmd'
  2403. var a1 = '/k'
  2404. }
  2405. else if(shell_verse.islin()) {
  2406. var __cmd = 'sh'
  2407. var a1 = '-c'
  2408. }
  2409. if(o.cmd) {
  2410. cmd = o.cmd
  2411. var childPromise = nodeShellExec(...o.cmd, {
  2412. // inherit : true,
  2413. shell: true,
  2414. detached: true,
  2415. stdio: 'ignore',
  2416. cwd: instanceroot + o.path
  2417. , env
  2418. })
  2419. }
  2420. else {
  2421. var childPromise = nodeShellExec(__cmd, [a1, getCmdString(cmd) ], {
  2422. // inherit : true,
  2423. shell: true,
  2424. detached: true,
  2425. stdio: 'ignore',
  2426. cwd: instanceroot + o.path
  2427. , env
  2428. })
  2429. }
  2430. var child = childPromise.process;
  2431. var cpid = child.pid
  2432. childPromise.then(()=>{
  2433. console.log(` *** started ${o.name} PID(${cpid}) ${cmd}`);
  2434. fs.writeFileSync(o.pidstore, '' + cpid)
  2435. })
  2436. .catch(e => console.error(e) )
  2437. }
  2438. if(clioverrides.node_env === 'development') {
  2439. env.DEBUG = 'loopback:connector:' + dbForLabel(label)
  2440. if(!processedArgs._[2]) processedArgs._[2] = 'all'
  2441. if(processedArgs._[2] === 'server' || processedArgs._[2] === 'all'
  2442. || processedArgs._[2] === 'elixir' // specific microservice name.
  2443. ) {
  2444. startFn( { debugport : 9228, script : 'elixir/server.js', name : 'Elixir Loopback Server', path : '/' + 'elixir-server'
  2445. , pidstore : '.elixir-server.elixir.server.pid'
  2446. } )
  2447. }
  2448. if(processedArgs._[2] === 'server' || processedArgs._[2] === 'all'
  2449. || processedArgs._[2] === 'express' // specific microservice name.
  2450. ) {
  2451. startFn( { debugport : 9227, script : 'bin/www', name : 'Express Server', path : '/' + 'chess-server-lib/server'
  2452. , pidstore : '.express.server.pid'
  2453. } )
  2454. }
  2455. if(processedArgs._[2] === 'client' || processedArgs._[2] === 'all') {
  2456. startFn( {
  2457. name : 'Elixir Ember Client', path : '/' + 'client'
  2458. , cmd : ['node_modules/ember-cli/bin/ember', ['s']]
  2459. , pidstore : '.client.server.pid'
  2460. } )
  2461. }
  2462. }
  2463. }
  2464. , 'stop': (label) => {
  2465. const kill = require('tree-kill');
  2466. try{
  2467. var serverPid = fs.readFileSync('.elixir-server.elixir.server.pid', { encoding: 'utf8'})
  2468. fs.unlinkSync('.elixir-server.elixir.server.pid')
  2469. console.log(serverPid)
  2470. kill(serverPid)
  2471. }
  2472. catch(e){ console.error(e) }
  2473. try{
  2474. serverPid = fs.readFileSync('.express.server.pid', { encoding: 'utf8' })
  2475. fs.unlinkSync('.express.server.pid')
  2476. console.log(serverPid)
  2477. kill(serverPid)
  2478. }
  2479. catch(e){ console.error(e) }
  2480. try{
  2481. serverPid = fs.readFileSync('.client.server.pid', { encoding: 'utf8' })
  2482. fs.unlinkSync('.client.server.pid')
  2483. console.log(serverPid)
  2484. kill(serverPid)
  2485. }
  2486. catch(e){ console.error(e) }
  2487. }
  2488. , 'model' : () => {
  2489. var etask = ()=>{
  2490. var tasks = [
  2491. () => {
  2492. var p = nodeShellExec('mklink', [ `${processedArgs._[2]}.json`
  2493. , `..\\..\\node_modules\\chess-server-lib\\common\\models\\${processedArgs._[2]}.json`], {
  2494. inherit: true, shell: true
  2495. , cwd : instanceroot + `/${selectedinstance.instanceName}-server/${selectedinstance.instanceName}/models`
  2496. , title: `mklink ${processedArgs._[2]}.json ..\\..\\node_modules\\chess-server-lib\\common\\models\\${processedArgs._[2]}.json`
  2497. , env: ENV
  2498. }).catch((e) => { console.error(e) })
  2499. return p;
  2500. }
  2501. ];
  2502. return any(tasks).then(() => {
  2503. fs.writeFileSync('run.done', 'success') // PB : TODO -- IPC through files is needed only for windows.
  2504. }).catch(() => {
  2505. fs.writeFileSync('run.done', 'error')
  2506. })
  2507. }
  2508. etask.statuslog = statuslog
  2509. etask.selectedinstance = selectedinstance
  2510. etask.processedArgs = processedArgs
  2511. etask.runtimestamp = runtimestamp
  2512. etask.ENV = ENV
  2513. return shell_verse.runElevated(etask)
  2514. }
  2515. , 'use' : () => {
  2516. // use a certain named instance.
  2517. // Eg :
  2518. // 1) elxr use elixir
  2519. // 2) elxr use cihsr
  2520. // If environment is not specified defaults to development.
  2521. // 1) NODE=test elxr use elixir
  2522. /*// Steps
  2523. 1) Delete Config and Data symlinks
  2524. 2) Make Links for config ({{name}}-config-{{node_env}}) and data with the NODE_ENV specified or default to dev
  2525. 3) Iterates all repos and pull all. 'git', ['pull', '--all'].
  2526. 4) Iterates all repos and checkout to the ENV specified. 'git', ['checkout', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  2527. 5) Iterates all repos and merge from source configured in mergesource. 'git', ['merge', mergesource],
  2528. */
  2529. // We no longer need to check ruans.. ??? if we were initiated from self invoked privileged shell ?
  2530. if (( /*processedArgs.runas && processedArgs.runas !== 'self' &&*/ !processedArgs.force) &&
  2531. runconfig.NODE_ENV && runconfig.NODE_ENV === (selectedinstance.node_env || runconfig.NODE_ENV) &&
  2532. selectedinstance.instanceName && runconfig.use === selectedinstance.instanceName) {
  2533. console.log(`No change detected. Already using requested specs : ${runconfig.NODE_ENV} ${runconfig.use}`)
  2534. if (processedArgs.runas) { fs.writeFileSync('run.done', 'success') } // PB : TODO -- IPC through files is needed only for windows.
  2535. if (existsSync('config') && existsSync('data')){
  2536. return
  2537. }
  2538. }
  2539. var tasks = [
  2540. () => {
  2541. var promise = new Promise((resolve, reject)=>{
  2542. existslink('config', function(err, data){
  2543. if(data) {
  2544. var p = shell_verse.removeJuncionOrLink('config')
  2545. .then(()=>{resolve(true)})
  2546. .catch((err) => { console.log('Ignoring benign error : ' + err); return resolve(true); })
  2547. }
  2548. else resolve(false)
  2549. })
  2550. })
  2551. return promise;
  2552. },
  2553. () => {
  2554. var promise = new Promise((resolve, reject)=>{
  2555. existslink('data', function(err, data){
  2556. if(data) {
  2557. var p = shell_verse.removeJuncionOrLink('data')
  2558. .then(()=>{resolve(true)})
  2559. .catch((err) => { console.log('Ignoring benign error : ' + err); return resolve(true); })
  2560. }
  2561. else resolve(false)
  2562. })
  2563. })
  2564. return promise;
  2565. },
  2566. ];
  2567. runconfig.NODE_ENV = ENV.NODE_ENV = ENV.NODE_ENV || runconfig.NODE_ENV || 'development';
  2568. if (processedArgs._[1] && runconfig.use !== processedArgs._[1]) runconfig.use = processedArgs._[1];
  2569. if (!runconfig.use && selectedinstance.instanceName) runconfig.use = selectedinstance.instanceName;
  2570. if (!runconfig.use) { throw 'unspecifed use not allowed. Please specify chess instance name.' }
  2571. fs.writeFileSync(instanceroot + '/run.js', 'module.exports = ' + JSON.stringify(runconfig))
  2572. var branch = checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV
  2573. var performPullOrCloneForBranch = (def)=>{
  2574. var promise = Promise.resolve(true)
  2575. if (!branch) {
  2576. var dscoverbranchcmd = gitops.getdiscoverbranchcmd(repo)
  2577. promise = nodeShellExec.apply(null, dscoverbranchcmd).then(__branch=>{ branch = __branch})
  2578. .catch((e) => { console.error(e); return { error: true, message: repo } })
  2579. }
  2580. return promise = promise.then(()=>{ return elxr.getpulltask(def)() }).catch(e => { console.error( 'performPullOrCloneForBranch : Failed ' + e )})
  2581. }
  2582. var performCloneAndCheckout = null;
  2583. // cant use git checkout -b it fails when branch already exists.
  2584. var performCheckout = performCloneAndCheckout = (def) => {if (excludeCheckouts[def.repo]) return Promise.resolve({ 'skipped': true })
  2585. return performPullOrCloneForBranch(def).then(()=>{
  2586. nodeShellExec('git', ['checkout', def.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  2587. // return nodeShellExec('git', ['switch', '-m', '-C', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  2588. // inherit : true, shell: true,
  2589. cwd: instanceroot + '/' + def.repo
  2590. // , stdio : ignore // Use when we want to silence output completely.
  2591. , runas: processedArgs.runas
  2592. , title: `git checkout ${def.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} for ${def.repo}`
  2593. }).then(()=>{ console.log( `SUCCESS : git checkout ${def.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} for ${def.repo}` ) }).catch((e) => { console.error(e); return { error: true, message: def.repo } })
  2594. })
  2595. }
  2596. // var enqueueCheckout = function(def){ enqueue(elevatedqueue, performCheckout, def) }
  2597. // var enqueueMerge = function(def){ enqueue(elevatedqueue, performMerge, def) }
  2598. var elevatedqueue = [];
  2599. var enqueueOnce = (queue, task, def) => {
  2600. var found = queue.find(element => {
  2601. var keys = Object.keys( element )
  2602. for(var k=0; k < keys.length; k++) {
  2603. if(element[keys[k]] !== def[k]) return false;
  2604. }
  2605. })
  2606. queue.push(function(){ return task(this)}.bind(def));
  2607. }
  2608. var enqueue = (queue, task, def) => {
  2609. queue.push(function(){ return task(def)}.bind(def));
  2610. }
  2611. var mergeSources = {
  2612. 'development': null,
  2613. 'test': 'master',
  2614. 'production': 'master'
  2615. }
  2616. var mergesource = mergeSources[checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  2617. // Checkout is reduced to pull provided the current branch is the targetbranch
  2618. if(branch === mergesource) performCheckout = (def) => {
  2619. var dscoverbranchcmd = gitops.getdiscoverbranchcmd(repo)
  2620. return nodeShellExec.apply(null, dscoverbranchcmd).then(__branch=>{
  2621. if(branch === __branch) return performCloneAndCheckout(def)
  2622. return performPullOrCloneForBranch(def)
  2623. })
  2624. .catch((e) => { console.error(e); return { error: true, message: repo } })
  2625. }
  2626. // else performCheckout = (def) => { return performPullOrCloneForBranch(def) }
  2627. var performPullAll = (def) => {
  2628. if (excludeCheckouts[def.repo]) return Promise.resolve({ 'skipped': true })
  2629. return nodeShellExec('git', ['pull', '--all'], {
  2630. // inherit : true, shell: true,
  2631. cwd: instanceroot + '/' + def.repo
  2632. , runas: processedArgs.runas
  2633. , title: `git pull -all for ${checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} ${def.repo}`
  2634. }).catch((e) => { console.error(e); return { error: true, message: def.repo } })
  2635. }
  2636. var excludeCheckouts = Object.assign(exludeMergeRepos)
  2637. delete excludeCheckouts[`elixir-config-${runconfig.NODE_ENV}`]
  2638. // delete excludeCheckouts[`cihsr-config-${runconfig.NODE_ENV}`]
  2639. var performMerge = (def) => {
  2640. if (exludeMergeRepos[def.repo]) return Promise.resolve({ 'skipped': true })
  2641. return nodeShellExec('git', ['merge', mergesource], {
  2642. inherit: true, shell: true,
  2643. cwd: instanceroot + '/' + def.repo
  2644. , runas: processedArgs.runas
  2645. }).catch((e) => { console.error(e) })
  2646. }
  2647. if(!mergesource || branch === mergesource) performMerge = () => { return Promise.resolve(true) }
  2648. // var performRepoOperation = function(def) {
  2649. // elevatedRunasRepos.map((repo) => enqueueCheckout({ repo, branch: def.branch, requiresElevation : true }))
  2650. // return any(gitRepos.map((repo) => performCheckout({ repo, branch: def.branch})))
  2651. // }
  2652. return any(tasks).then(() => {
  2653. var task = ()=>{
  2654. // Default target is developent. if some other target is specified in NODE_ENV in for shell call for the 'use' command we will switch to that target..
  2655. //Switch to target branch
  2656. return any(gitRepos.map((repodef) => { return performCheckout({ repo : repodef.repo, branch}).catch(e=>{ console.log(e); }) } ))
  2657. // pull or clone target branch
  2658. .then(() => {
  2659. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  2660. return any(gitRepos.map((repo) => performPullAll(repo)))
  2661. })
  2662. // switch to source branch
  2663. .then( () => {
  2664. if(!mergesource || branch === mergesource ) return Promise.resolve(true) // Dont do anything if there is no source to merge from.
  2665. return any(gitRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch: mergesource})))
  2666. })
  2667. //Pull on merge source branch
  2668. .then( () => {
  2669. if(!mergesource || branch === mergesource ) return Promise.resolve(true)
  2670. return any(gitRepos.map((repo) => performPullAll(repo)))
  2671. })
  2672. //Switch to target branch
  2673. .then( () => {
  2674. if(!mergesource || branch === mergesource ) return Promise.resolve(true)
  2675. return any(gitRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch})))
  2676. })
  2677. .then( //Merge source branch to target branch
  2678. () => {
  2679. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  2680. return any(gitRepos.map((repo) => performMerge( repo ))).catch(err => { console.error('error in performMerge ' + err) })
  2681. })
  2682. }
  2683. task.statuslog = statuslog
  2684. var netask = shell_verse.getNonElevatedTask(task)
  2685. var eltask = ()=> {
  2686. var opts = {
  2687. inherit: true, shell: true
  2688. , cwd : instanceroot
  2689. , env: ENV
  2690. }
  2691. var tasks = [
  2692. () => {
  2693. // Use junctions to avoid npm package issues
  2694. var target = runconfig.use + '-' + 'config' + '-' + ENV.NODE_ENV
  2695. var p = shell_verse.createJuntionOrLink('config', target, opts)
  2696. return p;
  2697. }
  2698. ];
  2699. // if (processedArgs._[1]) {
  2700. tasks = tasks.concat( [
  2701. () => {
  2702. var dataToLink = runconfig.use + '-data' + '-' + ENV.NODE_ENV
  2703. if(!existsSync(dataToLink)) dataToLink = runconfig.use + '-data';
  2704. var p = shell_verse.createJuntionOrLink('data', dataToLink, opts)
  2705. return p;
  2706. }
  2707. ]
  2708. )
  2709. // }
  2710. return any(tasks).then(()=>{
  2711. // checkout target branch
  2712. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch, requiresElevation : true})))
  2713. // pull or clone target branch
  2714. .then(() => {
  2715. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  2716. return any(elevatedRunasRepos.map((repo) => performPullAll(repo)))
  2717. })
  2718. // switch to source branch
  2719. .then( () => {
  2720. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  2721. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch: mergesource, requiresElevation : true})))
  2722. })
  2723. //Pull on merge source branch
  2724. .then( () => {
  2725. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  2726. return any(elevatedRunasRepos.map((repodef) => performPullAll({repo : repodef.repo, requiresElevation : true })))
  2727. })
  2728. //Switch to target branch
  2729. .then( () => {
  2730. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  2731. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch, requiresElevation : true})))
  2732. })
  2733. .then( //Merge source branch to target branch
  2734. () => {
  2735. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  2736. return any(elevatedRunasRepos.map((repodef) => performMerge({ repo : repodef.repo, requiresElevation : true }))).catch(err => { console.error('error in performMerge ' + err) })
  2737. })
  2738. .then(() => {
  2739. fs.writeFileSync('run.done', 'success')
  2740. }).catch(() => {
  2741. fs.writeFileSync('run.done', 'error')
  2742. })
  2743. })
  2744. }
  2745. eltask.statuslog = statuslog
  2746. eltask.selectedinstance = selectedinstance
  2747. eltask.processedArgs = processedArgs
  2748. eltask.runtimestamp = runtimestamp
  2749. var eltask = shell_verse.getElevatedTask(eltask)
  2750. return eltask().then( ()=>{ return netask() })
  2751. }).catch((e) => {
  2752. fs.writeFileSync('run.done', 'error : ' + e)
  2753. })
  2754. // Antibiotic stewardship program.
  2755. // 1st use is fine.
  2756. // Max vials dispense
  2757. // 2nd use Pharmacy needs justification Form.
  2758. // Approval after a certain period of time.
  2759. }
  2760. , 'g' : () => {
  2761. if (processedArgs.h) {
  2762. console.log('elxr g model [modelname] => generate a model named [modelname]');
  2763. console.log('elxr g vmodel [modelname] => generate a model named [modelname]');
  2764. console.log('elxr g vmodel [modelname] --server=true => generate only a server model named [modelname]');
  2765. console.log('elxr g vmodel [modelname] --all=true => default generate server and client model named [modelname]');
  2766. console.log('elxr g => regenerate all known models');
  2767. return
  2768. }
  2769. // var child = nodeShellExec('mkdir', ['-p', label], { inherit : true} );
  2770. // try {
  2771. // child = child.on('close', () => { process.chdir(label) } );
  2772. // }
  2773. // catch (err) {
  2774. // console.log('chdir: ' + err);
  2775. // }
  2776. // child.on('close', function(){
  2777. // var options = {
  2778. // shell : true
  2779. // , inherit : true
  2780. // // , cwd : '' + process.cwd
  2781. // // , env : ENV
  2782. // };
  2783. // nodeShellExec('git', ['init'], { inherit : true});
  2784. if (0) {
  2785. // PB : TODO -- Special google chrome profile for tests etc.
  2786. nodeShellExec('pwd', { inherit: true });
  2787. // /c/Program\ Files\ \(x86\)/Google/Chrome/Application/chrome.exe --user-data-dir=/c/chess/instances/elixir_01/data/Google/Chrome/User\ Data --profile-directory="chess"
  2788. // "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --user-data-dir="C:\chess\instances\elixir_01\data\Google\Chrome\User Data" --profile-directory="chess" http://localhost:4200/admin/crud/create/item
  2789. // "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --user-data-dir="C:\chess\instances\elixir_01\data\Google\Chrome\User Data" --profile-directory="chess" http://localhost:4200/tests/index.html?grep=loopback
  2790. nodeShellExec("C:/Program Files (x86)/Google/Chrome/Application/chrome.exe", [
  2791. "--profile-directory=Profile 1"
  2792. , 'http://localhost:4200/tests/index.html?grep=model convert ember to loopback' + '&filter=none' /*+ '&filter=model convert ember to loopback'*/]);
  2793. }
  2794. // nodeShellExec('npm', ['init', '-y'], options);
  2795. // nodeShellExec('npm', ['init', '-y'], options);
  2796. // })
  2797. var g = {
  2798. 'client': () => {
  2799. // ember new --skip-bower --no-welcome --skip-git -b {{blueprint}}
  2800. console.info('Creating new ember client named : ' + processedArgs._[2]);
  2801. var step1 = nodeShellExec('cmd', ['/c', 'ember', 'new', processedArgs._[2]], {
  2802. stdio: ['pipe', process.stdout, process.stderr],
  2803. inherit: true,
  2804. shell: true,
  2805. cwd: path.dirname(__dirname),
  2806. env : ENV
  2807. })
  2808. },
  2809. 'modelr': () => {
  2810. var tasks = [
  2811. () => {
  2812. var p = nodeShellExec('"ember"', [
  2813. 'g'
  2814. , 'modelr'
  2815. , processedArgs._[2]], {
  2816. inherit: true, shell: true, env: ENV
  2817. }).then(() => {
  2818. console.log('Blueprint generation complete for : ' + processedArgs._[2])
  2819. return true;
  2820. }).catch((e) => { console.error(e) })
  2821. return p;
  2822. },
  2823. () => {
  2824. var chromePrefsFile = "C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data\\chess\\Preferences";
  2825. var chromeprefs = fs.readFileSync(chromePrefsFile, { encoding: 'utf8' })
  2826. chromeprefs = JSON.parse(chromeprefs)
  2827. var previous = chromeprefs.download.default_directory;
  2828. var parentDir = path.dirname(__dirname);
  2829. chromeprefs.download.default_directory = parentDir + "\\client\\app\\templates\\components\\resource";
  2830. fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs))
  2831. // PB : TODO -- detect where chrome is installed.
  2832. // PB : TODO -- set the download dir to the place where files are needed.
  2833. var p = nodeShellExec('"C:/Program Files (x86)/Google/Chrome/Application/chrome.exe"', [
  2834. '--user-data-dir="C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data"'
  2835. , '--profile-directory="chess"'
  2836. , 'http://localhost:4200/admin/crud/create/' + processedArgs._[2]], {
  2837. inherit: true, shell: true
  2838. , env: ENV
  2839. }).then(() => {
  2840. chromeprefs.download.default_directory = previous;
  2841. fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs))
  2842. return true;
  2843. }).catch((e) => { console.error(e) })
  2844. return p;
  2845. }
  2846. ,
  2847. () => {
  2848. console.log('Browser process should have closed here....')
  2849. return true;
  2850. }
  2851. ]
  2852. any(tasks)
  2853. }
  2854. , 'undefined' : ()=>{
  2855. console.warn('Are you sure you want to refresh all the models.');
  2856. throw 'NOT YET IMPLMENTED'
  2857. }
  2858. , 'vmodel' : (options)=>{
  2859. // node --inspect-brk elxr/index.js g vmodel qlabresults --server=true
  2860. options = options || {
  2861. generate : processedArgs['all'] ? 'all' : processedArgs['server'] ? 'server' : processedArgs['client'] ? 'client' : null
  2862. }
  2863. if(!options.generate) return 'Nothing specified for generation'
  2864. var name = processedArgs._[2];
  2865. if(!name) return 'No name specified for generation'
  2866. var templateverse = `${selectedinstance.root}/bbhverse/__universe__/vmodel`
  2867. // var templateverse = `${selectedinstance.root}/bbhverse/__universe__/vmodel/__base__-server-lib/common/lib`
  2868. var workingtarget = `${selectedinstance.root}/.elxr/run-${runtimestamp}/temp/vmodelworkingdir`
  2869. var destination = `${selectedinstance.root}`
  2870. // Create a tmp working copy for staging the changes.
  2871. return copyrecursive(templateverse, workingtarget).then( r => {
  2872. var base = 'chess' // -- The server base from where this instance was dervied from.
  2873. var patternsubstitutions = [
  2874. { strOrregexp : /(__name__)/g, substitutes : [name]}
  2875. , { strOrregexp : /(__instance__)/g, substitutes : [selectedinstance.instanceName]}
  2876. , { strOrregexp : /(__base__)/g, substitutes : [base]}
  2877. , { strOrregexp : /(__microservice__)/g, substitutes : [selectedinstance.microservice || selectedinstance.instanceName]}
  2878. , { strOrregexp : /(__microclient__)/g, substitutes : [selectedinstance.microclient || `${selectedinstance.instanceName}-client` || 'client']} // PB : TODO -- elixir-client etc... use a config to find the microclient..
  2879. ]
  2880. var options = { source : templateverse, target : workingtarget
  2881. , base , destinationroot : destination, workingtarget
  2882. , processingtype : 'inplace', sourcetype : 'filesystem', patternsubstitutions }
  2883. var actions = [
  2884. fswalk( workingtarget, options
  2885. , [ function(t, o){
  2886. // A series of tasks to be executed on each pattern in patternsubstitutions.
  2887. return any([
  2888. // PB : TODO -- Contentreplace is better addressed in memory instead of file IO so do all regexps in sequence in one shot and then rename.
  2889. ()=>{ return fscontentreplace( t, o ) }
  2890. , ()=>{ return fsrename( t, o ) }
  2891. ])
  2892. }] )
  2893. // Post process links in place.
  2894. , () => dirs((innernode, s, t, o ) => fswalk( path.join(workingtarget, innernode.name), utils.assign({}, o, { innernode }), [ templatelink ] )
  2895. , workingtarget, null, options)
  2896. // Move to the final destination. Whole tree should move only top level folders are required.
  2897. // , () => fswalk( workingtarget, options, [ fsrename ])
  2898. // , () => dirs( ( child, src, target, options )=>{ return fs.renameSync(path.join(src, child.name), path.join(target, child.name) ) }
  2899. // , workingtarget, destination )
  2900. ]
  2901. return any(actions);
  2902. })
  2903. }
  2904. }
  2905. g[processedArgs._[1]]();
  2906. }
  2907. , 'launchui' : () => {
  2908. console.log('-----------------------------')
  2909. console.log('Launching Elxir Admin Console')
  2910. console.log('-----------------------------')
  2911. // shell_verse.getchrome()
  2912. processedArgs.awaitrun = true;
  2913. return shell_verse.launchui()
  2914. // shell_verse.getchrome().then( chrome => {
  2915. // nodeShellExec( `"${chrome}"`, [
  2916. // '--profile-directory="chess"'
  2917. // , `${selectedinstance.root}/elixir-client/elxr-admin-console/html/index.html`], {
  2918. // inherit: true, shell: true
  2919. // , env: ENV
  2920. // })
  2921. // .catch(e => console.dir(e))
  2922. // })
  2923. }
  2924. , 'create' : () => { return createInstance(selectedinstance) }
  2925. , 'httpget' : () => {
  2926. // RESTAPI.get({
  2927. // hostname: 'git.bbh',
  2928. // // port: 443,
  2929. // protocol : 'http:',
  2930. // path: '/',
  2931. // method: 'GET'
  2932. // }, function(data){ console.log(data)}, function(error){ console.log(error)} )
  2933. return createInstance(selectedinstance)
  2934. }
  2935. , 'getuser' : ()=>{ return prerequisites.git.getuser().then(u=>{ console.log(u)}) }
  2936. , 'switch user' : (tousername)=>{ return GIT['switch user'](tousername) }
  2937. }
  2938. Object.keys(op).forEach( oper => {
  2939. if(cmds[oper]) return
  2940. cmds[oper] = {}
  2941. // cmds[oper] = {
  2942. // // return a interpreted set of arguments for this cmd run context.
  2943. // interpret() { return { cmd : oper, runchoice : 'c' } }
  2944. // }
  2945. })
  2946. var elxrcmd = (function(){
  2947. var __cmdprototype = function(){}
  2948. function subcommandlabelFor(cmd, sub){ return (`${cmd} ${sub || ''}`).trim() }
  2949. var __cmd = {
  2950. interpret() {
  2951. var interpreted = {}
  2952. // Non custom command has universal positiona args.
  2953. processedArgs._[1] ? interpreted.instanceName = processedArgs._[1] : null;
  2954. interpreted.runchoice = processedArgs._[0] || selectedinstance.runchoice;
  2955. // return clioverrides
  2956. // cmds[cmd] = {
  2957. // interpret() {
  2958. // return Object.assign(clioverrides, { cmd, runchoice : 'c' })
  2959. // }
  2960. // , getPossiblePrompts(){ return { cmd, username : true, password : true,
  2961. // instanceName : true, instanceType : true, reposerver : true } }
  2962. // }
  2963. // ... PB : TODO -- use cmd.toArgs
  2964. interpreted.cmd = this.cmd
  2965. return interpreted
  2966. }
  2967. , getPossiblePrompts(){ return { username : true, password : true, instanceName : true, instanceType : true, reposerver : true } }
  2968. , cmdFn : ()=>{ throw "Elxr Unknown command."}
  2969. , finalized : true
  2970. , toArgs : function( o ){
  2971. // PB : TODO -- need to call this before selectedinstance is built. The instanceName is dependent on the specific cmd.
  2972. return o }
  2973. }
  2974. function __createO(o){
  2975. if(o.finalized) return o;
  2976. var subs = Object.keys(cmds[o.cmd].subcommands || {})
  2977. // console.log(subs)
  2978. // console.log(o)
  2979. subs.forEach(sub=>elxrcmd.create( cmds[subcommandlabelFor(o.cmd, sub)] ))
  2980. var created = utils.assign_core( { keycase: true, arraymergetype : utils.assign_core.DISTINCT_UNION }
  2981. , {}, __cmd, cmds[o.cmd], o)
  2982. cmds[o.cmd] = created;
  2983. created.cmdFn = op[o.cmd] || o.cmdFn || created.cmdFn
  2984. op[o.cmd] = created.cmdFn;
  2985. noprerequisites[o.cmd] = created.noprerequisites
  2986. return created.cmdFn;
  2987. }
  2988. function create(o){ return __createO(o) }
  2989. __cmdprototype.create = create;
  2990. return __cmdprototype;
  2991. })()
  2992. var cmdFns = {
  2993. resetgitconfig, reinit, init, g : op['g'], 'get-upstream' : op['get-upstream']
  2994. }
  2995. Object.entries(cmds).forEach( ca => {
  2996. ca[1].cmd = ca[0]
  2997. ca[1].cmdFn = ca[1].cmdFn || cmdFns[ca[0]]
  2998. elxrcmd.create( ca[1] )
  2999. })
  3000. shell_verse.cmds = cmds;
  3001. var __default = selectedinstance; // PB : TODO -- Eliminate __default references.
  3002. Tasq.addlistener(statuslog.statuslog)
  3003. // Instead of waiting for the root to be establised we start working at the current locatoin and then relocate when root changes.
  3004. var runlogjson = `${selectedinstance.root}/.elxr/run-${runtimestamp}/run.log`
  3005. ensureDirectoryExistence(runlogjson)
  3006. fs.writeFileSync(runlogjson, JSON.stringify( { message : `Started ${runtimestamp}`, success:true})) // Initialize a new log file with "logrotate" for every run
  3007. Tasq.addlistener((e)=>{ fs.writeFileSync(runlogjson, ', ' + JSON.stringify( e ), { 'flag': 'a+' }) })
  3008. var nodeShellExec = cli.nodeShellExec;
  3009. var chalk = require('chalk')
  3010. const homedir = require('os').homedir();
  3011. function sysAddPathVar(addpath){
  3012. // Object.assign({
  3013. // inherit: true, shell: true, env: ENV, title: `${command} ${args}`
  3014. // }, options)
  3015. // powershell $env:Path -split ';'
  3016. var etask = ()=>{
  3017. return nodeShellExec('Powershell.exe', [
  3018. `$path = [Environment]::GetEnvironmentVariable('PATH', 'Machine')
  3019. $newpath = $path + ';${addpath}'
  3020. [Environment]::SetEnvironmentVariable("PATH", $newpath, 'Machine')`
  3021. ]).then(() => {
  3022. fs.writeFileSync('run.done', 'success') // PB : TODO -- IPC through files is needed only for windows.
  3023. }).catch(() => {
  3024. fs.writeFileSync('run.done', 'error')
  3025. })
  3026. }
  3027. etask.statuslog = statuslog
  3028. etask.selectedinstance = selectedinstance
  3029. etask.processedArgs = processedArgs
  3030. etask.runtimestamp = runtimestamp
  3031. etask.ENV = ENV
  3032. return shell_verse.runElevated(etask)
  3033. // var newpath = addpath.split(';');
  3034. // newpath.push(addpath)
  3035. // newpath = Array.from(new Set(newpath)).join(';')
  3036. // // addpath.split(';').forEach(pel => { var kv = pel.split('='); kv[0] === key ? null : newpath.push(pel); } )
  3037. // // setx /M PATH "%PATH%;<path-to-executable-folder>"
  3038. // // %AppData%\npm
  3039. // return nodeShellExec('setx', ['/m', 'PATH', `%PATH%;${addpath}` ]);
  3040. }
  3041. // singleton one time lazy
  3042. var getCredentials = function(){
  3043. // try {
  3044. // First call
  3045. var creds = fs.readFileSync(path.normalize(`${homedir}/.elxrcredentials`), { encoding: 'utf8' });
  3046. var creds = creds.split('\n').map( c => c.trim() && new URL(c));
  3047. console.log(creds);
  3048. creds.forEach(cred => {console.log( cred.hostname ); console.log( cred.username )} );
  3049. // }
  3050. // catch(e){
  3051. // console.warn('Credentials not cached. You will be prompted for username and password.')
  3052. // }
  3053. // Subsequent calls
  3054. getCredentials = ()=>{ return creds }
  3055. return getCredentials();
  3056. }
  3057. // console.dir(processedArgs)
  3058. // PB : TODO -- defaults for valuless arguments if passed.
  3059. // Object.keys(processedArgs).forEach(a=>{
  3060. // if(Object.prototype.toString.call(processedArgs[a]) === '[object Undefined]' || !processedArgs[a]) || trim(processedArgs[a])) == '') {
  3061. // }
  3062. // })
  3063. const { readdir } = require("fs").promises
  3064. // Directory shallow walk and do perform on each dir.
  3065. const dirs = async (perform, src, target, options) => {
  3066. var rs = []
  3067. for (const dir of await readdir(src || selectedinstance.root, { withFileTypes: true })) {
  3068. if (dir.isDirectory()) rs.push( perform(dir, src, target, options) )
  3069. }
  3070. return any(rs)
  3071. }
  3072. var fsMove = async function(from, to, options) {
  3073. if(!options?.innernode) {
  3074. var exists = fs.existsSync(from);
  3075. var stats = exists && fs.statSync(from);
  3076. var isDirectory = exists && stats.isDirectory();
  3077. }
  3078. else {
  3079. var isDirectory = options.innernode.isDirectory()
  3080. }
  3081. if(!isDirectory) return fs.renameSync(from, to)
  3082. fs.mkdirSync(to, { recursive : true })
  3083. var rs = [];
  3084. for (const innernode of await readdir(from, { withFileTypes: true })) {
  3085. rs.push( fsMove( path.join(from, innernode.name), path.join(to, innernode.name), { innernode } ) )
  3086. }
  3087. return any(rs)
  3088. };
  3089. // PB : TODO -- Should return a bunch of promises to wait for...
  3090. var copyrecursive = async function(src, target, options) {
  3091. if(!options?.innernode) {
  3092. var exists = fs.existsSync(src);
  3093. var stats = exists && fs.statSync(src);
  3094. var isDirectory = exists && stats.isDirectory();
  3095. }
  3096. else {
  3097. var isDirectory = options.innernode.isDirectory()
  3098. }
  3099. if(!isDirectory) return fs.copyFileSync(src, target)
  3100. fs.mkdirSync(target, { recursive : true })
  3101. var rs = [];
  3102. for (const innernode of await readdir(src, { withFileTypes: true })) {
  3103. rs.push( copyrecursive( path.join(src, innernode.name), path.join(target, innernode.name), { innernode } )
  3104. // .then(()=>{
  3105. // return any(actions.map( a => ()=>a(dir, { isDirectory : true}) ))
  3106. // })
  3107. )
  3108. }
  3109. return any(rs)
  3110. // return fswalk( src, {}, [
  3111. // (src, options)=> {
  3112. // if(options.innernode.isDirectory()) fs.mkdirSync(options.target, { recursive : true })
  3113. // else fs.copyFileSync(src, options.target)
  3114. // }
  3115. // ])
  3116. // var exists = fs.existsSync(src);
  3117. // var stats = exists && fs.statSync(src);
  3118. // var isDirectory = exists && stats.isDirectory();
  3119. // if (isDirectory) {
  3120. // fs.mkdirSync(dest, { recursive : true });
  3121. // return dirs( function(childItemName) {
  3122. // return copyrecursive(path.join(src, childItemName.name),
  3123. // path.join(dest, childItemName.name));
  3124. // }, src )
  3125. // } else {
  3126. // fs.copyFileSync(src, dest);
  3127. // }
  3128. };
  3129. // var renamerecursive = function(from, to){
  3130. // var exists = fs.existsSync(from);
  3131. // var stats = exists && fs.statSync(from);
  3132. // var isDirectory = exists && stats.isDirectory();
  3133. // if (isDirectory) {
  3134. // fs.mkdirSync(to);
  3135. // dirs( function(childItemName) {
  3136. // renamerecursive(path.join(from, childItemName),
  3137. // path.join(to, childItemName));
  3138. // }, from )
  3139. // // fs.readdirSync(from).forEach(function(childItemName) {
  3140. // // copyrecursive(path.join(from, childItemName),
  3141. // // path.join(to, childItemName));
  3142. // // });
  3143. // } else {
  3144. // fsrename(from, to);
  3145. // }
  3146. // }
  3147. // filesystem walk
  3148. const fswalk = async (pathToWalk, options, actions) => {
  3149. // options = options || { depthfirst : true }
  3150. if(!options.innernode) {
  3151. var exists = fs.existsSync(pathToWalk);
  3152. var stats = exists && fs.statSync(pathToWalk);
  3153. var isDirectory = exists && stats.isDirectory();
  3154. }
  3155. else {
  3156. var isDirectory = options.innernode.isDirectory()
  3157. }
  3158. if(!isDirectory) return any(actions.map( a => ()=>a( pathToWalk, utils.assign({}, options
  3159. , { pathToWalk, innernode : options.innernode || { isDirectory : function(){ return true } } }) ) ))
  3160. var rs = [];
  3161. for (const innernode of await readdir(pathToWalk, { withFileTypes: true })) {
  3162. rs.push( fswalk( path.join(pathToWalk, innernode.name), utils.assign({}, options, {pathToWalk, innernode }), actions )
  3163. // .then(()=>{
  3164. // return any(actions.map( a => ()=>a(innernode, { isDirectory : true}) ))
  3165. // })
  3166. )
  3167. }
  3168. // Wait for the walk to complete before renaming directories.
  3169. Array.prototype.push.apply(rs, actions.map( a => ()=>a( pathToWalk, utils.assign({}, options
  3170. , { pathToWalk, innernode : options.innernode || { isDirectory : function(){ return true } } } ) ) ))
  3171. return any(rs)
  3172. }
  3173. var fsrecurse = function(target, options, actions, root) {
  3174. var exists = fs.existsSync(target);
  3175. var stats = exists && fs.statSync(target);
  3176. var isDirectory = exists && stats.isDirectory();
  3177. if (isDirectory) {
  3178. var tasks = []
  3179. tasks.push( dirs( function(childItemName) {
  3180. return fsrecurse(path.join(target, childItemName.name)
  3181. , options, actions, root);
  3182. }, target ))
  3183. return any(tasks)
  3184. } else {
  3185. var prevActionResult = null;
  3186. return any( actions.map( (action) => prevActionResult = action.apply(null, target, options) ))
  3187. }
  3188. };
  3189. // var fslink = function(to, options){ try { fs.linkSync( to, options.from ) } catch(e) { throw e } }
  3190. var fslink = function(to, options){ fs.symlinkSync( to, options.from /*, type = "junction"*/ ) }
  3191. var fsrename = function(target, options){
  3192. // PB : TODO -- streaming and async.. target could be a stream a string or a filesystem item or a tree node...
  3193. var targetname = options.innernode?.name || path.parse(target).base;
  3194. var replaced = targetname;
  3195. options.patternsubstitutions.forEach( ps => { replaced = regexreplaceall( replaced, ps ) })
  3196. if(replaced && replaced !== targetname) {
  3197. var tr = target.replace( targetname, replaced )
  3198. fs.renameSync(target, tr)
  3199. return tr;
  3200. }
  3201. else return replaced
  3202. }
  3203. var fscontentreplace = function( target, options ){
  3204. // do many replacements in one shot in the file.
  3205. if(options.processingtype === 'inplace' && options.sourcetype === 'filesystem' && !options.innernode.isDirectory() ) {
  3206. var content = fs.readFileSync(target, { encoding: 'utf8' }) // PB : TODO -- streaming and async..
  3207. options.patternsubstitutions.forEach( ps => { content = regexreplaceall( content, ps ) })
  3208. fs.writeFileSync(target, content)
  3209. }
  3210. }
  3211. var templatelink = function(target, options){
  3212. var targetSubPath = target.replace(options.workingtarget + '/', '' );
  3213. var targetSubPathsplit = targetSubPath.split("/")
  3214. var targetPathBaseDir = `${targetSubPathsplit[0]}/${targetSubPathsplit[1]}`
  3215. var linkToSubPathReplacement = `${options.base}-server-lib/common`
  3216. // var rgxp = new RegExp(`(__link__)${options.base}-server-lib`, "g")
  3217. var rgxp = new RegExp(`(__link__${options.base}-server-lib)`, "g")
  3218. var linkToSubPath = targetSubPath
  3219. var b = target.match(rgxp)
  3220. var linkFromName = regexreplaceall( target, { strOrregexp : rgxp, substitutes : [ '' ] } )
  3221. linkFromName = linkFromName.replace(options.workingtarget, options.destinationroot)
  3222. if( b ) {
  3223. // Only if the pattern matches which is link instruction.
  3224. linkToSubPath = regexreplaceall( linkToSubPath, { strOrregexp : rgxp, substitutes : [ '' ] } )
  3225. }
  3226. options.patternsubstitutions.forEach( ps => { linkToSubPath = regexreplaceall( linkToSubPath, ps ) })
  3227. var linkToName = `${options.destinationroot}/${linkToSubPath}`
  3228. if(b){
  3229. linkToSubPath = linkToSubPath.replace( targetPathBaseDir, linkToSubPathReplacement)
  3230. // PB : DONT DELETE EVERYTHING ??? Only the linkable ones... Or use an add strategy without deleting...
  3231. fs.unlinkSync( target );
  3232. fslink( `${options.destinationroot}/${linkToSubPath}`, { from : linkFromName } )
  3233. }
  3234. else {
  3235. fsMove( `${options.workingtarget}/${linkToSubPath}`, linkToName )
  3236. // fsMove( `${options.workingtarget}/${linkToSubPath}`, linkFromName )
  3237. }
  3238. }
  3239. // Source and Target are files or folders. We need another version or a unifed version for strings..
  3240. var processpatterns = function(target, options){
  3241. // Accept a set of patterns and substitutions and operate on a target and apply all patterns substitutions.
  3242. // options = options || { targettype : 'inplace', sourcetype : 'filesystem' }
  3243. // options.source, options.target sourcetype = 'string' | 'filesystem' options.targettype = 'inplace' | 'copy'
  3244. if(options.processingtype === 'inplace' && options.sourcetype === 'filesystem' ) {
  3245. options.patternsubstitutions.forEach( ps => {
  3246. // var replacement = regexreplaceall( from, ps.strOrregexp, ps.substitutes )
  3247. // if(targetname) { // Porcess all files. Even if file names dont have patterns the content needs to be replaced.
  3248. return options.tasks.map( t => { return t( target, ps ) } )
  3249. // }
  3250. // return str.replace(regex, function(match, key) {
  3251. // console.log(`Found match, group ${match}: ${key}`);
  3252. // return substitutes[key] || match;
  3253. // })
  3254. })
  3255. }
  3256. // while ((m = regex.exec(str)) !== null) {
  3257. // // This is necessary to avoid infinite loops with zero-width matches
  3258. // if (m.index === regex.lastIndex) {
  3259. // regex.lastIndex++;
  3260. // }
  3261. // var rstr = str;
  3262. // // The result can be accessed through the `m`-variable.
  3263. // m.forEach((match, groupIndex) => {
  3264. // // rstr = rstr.replace( groupIndex
  3265. // console.log(`Found match, group ${groupIndex}: ${match}`);
  3266. // if(groupIndex === 0) return
  3267. // });
  3268. // }
  3269. }
  3270. function copyFileSync( source, target , options) {
  3271. var targetFile = target;
  3272. // If target is a directory, a new file with the same name will be created
  3273. if ( fs.existsSync( target ) ) {
  3274. if ( fs.lstatSync( target ).isDirectory() ) {
  3275. targetFile = path.join( target, path.basename( source ) );
  3276. }
  3277. }
  3278. fs.writeFileSync(targetFile, fs.readFileSync(source));
  3279. }
  3280. function copyFolderRecursiveSync( source, target, options ) {
  3281. var files = [];
  3282. // Check if folder needs to be created or integrated
  3283. var targetFolder = path.join( target, path.basename( source ) );
  3284. if ( !fs.existsSync( targetFolder ) ) {
  3285. fs.mkdirSync( targetFolder );
  3286. }
  3287. // Copy
  3288. if ( fs.lstatSync( source ).isDirectory() ) {
  3289. files = fs.readdirSync( source );
  3290. files.forEach( function ( file ) {
  3291. var curSource = path.join( source, file );
  3292. if ( fs.lstatSync( curSource ).isDirectory() ) {
  3293. copyFolderRecursiveSync( curSource, targetFolder );
  3294. } else {
  3295. copyFileSync( curSource, targetFolder );
  3296. }
  3297. } );
  3298. }
  3299. }
  3300. var getShellTask = (command, args, options) => {
  3301. options = options || {}
  3302. var callshell = command === 'rm' ? getgitbashtask : getshelltask;
  3303. return () => {
  3304. var p = callshell( [command, args, Object.assign({
  3305. inherit: true, shell: true, env: ENV, title: `${command} ${args}`
  3306. }, options)
  3307. ])()
  3308. if (options.ignorefailures) {
  3309. return p.catch(e => {
  3310. // Ignore. Not a major error.
  3311. })
  3312. }
  3313. else return p;
  3314. }
  3315. }
  3316. var callshelltask = (args) => {
  3317. // console.dir(args)
  3318. if( Object.prototype.toString.call(args) === '[object Function]' ) {
  3319. return args;
  3320. }
  3321. return getshelltask(args)()
  3322. }
  3323. var getCmdString = function(args){ return `"${args[0]} ${args[1].join(' ')}"` }
  3324. var getshelltask = (args) => {
  3325. return args[0] === 'rm' ? getgitbashtask(args) : () => {
  3326. return nodeShellExec.apply(null, args).catch(function(e){
  3327. e.benign = args[2].benign;
  3328. if(!e.benign) { console.error(e); }
  3329. throw e
  3330. })
  3331. }
  3332. }
  3333. var getgitbashtask = (args, onEachError) => { return () => {
  3334. return nodeShellExec( `"${gitbash}"`, ['-c', getCmdString(args)], args[2]).catch( onEachError || function(e){ console.error(e) }) }
  3335. }
  3336. var getnodeshellexectask = (args) => { return () => { return nodeShellExec.apply(null, args) }}
  3337. var perform = function( serailtasks, taskvector ){ return any( serailtasks(taskvector).map(getnodeshellexectask)) }
  3338. var getTaskCheckExists = shell_verse.getTaskCheckExists
  3339. // var getTaskWithElevation = function(tasdef){ return shell_verse.getElevatedTask( tasdef.elevatedpulltasks ) }
  3340. // var getTaskWithoutElevation = function(tasdef){
  3341. // return ()=>{
  3342. // if(!processedArgs.runas) { return tasdef.regularpulltasks(); }
  3343. // else Promise.resolve(true)
  3344. // }
  3345. // }
  3346. var gitops = {
  3347. getdiscoverbranchcmd : function(repo){
  3348. var parameters = ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  3349. var cmd = [gitbash
  3350. , ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  3351. , { cwd: instanceroot + '/' + repo, title: 'discoverbranch for ' + repo + ' ' + parameters.join(' ') }]
  3352. return cmd
  3353. }
  3354. }
  3355. var getPullCmd = (repodef, branch) => {
  3356. // console.log(useGitPull)var getPullCmd = (repo, branch) => {
  3357. // console.log(useGitPull)
  3358. var repo = repodef.repo
  3359. var pullCmd = []
  3360. if(!branch) {
  3361. // console.warn('No branch was specified detecting from working client.')
  3362. // First check if working client exists.
  3363. // if (existsSync(instanceroot + '/' + repo)) {
  3364. pullCmd= gitops.getdiscoverbranchcmd(repo)
  3365. // }
  3366. // else performpull
  3367. }
  3368. // var pullCmd = [gitInstallDir
  3369. // , ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  3370. // , { cwd: instanceroot + '/' + repo, title: 'pull all remotes for ' + repo }]
  3371. if(branch) {
  3372. var parameters = ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  3373. var pullCmd = [ gitbash
  3374. , ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  3375. , { cwd: instanceroot + '/' + repo, title : 'pull all remotes for ' + branch + ' ' + repo + ' ' + parameters.join(' ') }]
  3376. }
  3377. // var pullCmd = ['pullall', [], { cwd : repo }]
  3378. if (useGitPull) pullCmd = ['git', ['pull'], {
  3379. inherit: true, shell: true,
  3380. cwd: instanceroot + '/' + repo
  3381. // , env: ENV
  3382. , runas: processedArgs.runas
  3383. , title: `git pull ${repo}`
  3384. }]
  3385. return pullCmd
  3386. }
  3387. // PB : TODO -- Use queueing with async tasks..
  3388. var performPull = (repodef, branch, repoowner, errHandler, elevatedBatch, regularBatch) => {
  3389. var __inelevatedBatch = elevatedBatch, __inregularBatch = regularBatch;
  3390. var pT = getPullTask(repodef, branch, repoowner, errHandler, elevatedBatch, regularBatch)
  3391. // var waitForBatchAdditions = function(){
  3392. // return pT;
  3393. // }
  3394. // Execute is implied.
  3395. // if(false && (__inelevatedBatch || __inregularBatch) ) return waitForBatchAdditions() // PB : Todo Implemnt a trigger which starts execution.
  3396. // else
  3397. return pT() // Execute it.
  3398. }
  3399. var getPullTask = (repodef, branch, repoowner, errHandler, elevatedBatch, regularBatch) => {
  3400. // PB : TODO -- Handle no branch passed in case.
  3401. // if(!branch) { throw 'No branch specified' }
  3402. var repo = repodef.repo;
  3403. elevatedBatch = elevatedBatch || [];
  3404. regularBatch = regularBatch || [];
  3405. try{
  3406. // PB : TODO -- local repo folder named the same as the remote repository name is not enough to establish existence.
  3407. // This remote repo and branch may have been or may need to be added as a local tracking branch
  3408. // to any other local repo folder (with a different name)
  3409. var exists = existsSync(instanceroot + '/' + repo)
  3410. }
  3411. catch(e){
  3412. exists = false
  3413. console.log(e)
  3414. }
  3415. function initTask(etask){
  3416. etask.info = { repo }
  3417. etask.errHandler = errHandler
  3418. etask.statuslog = statuslog
  3419. etask.processedArgs = processedArgs
  3420. etask.selectedinstance = selectedinstance
  3421. etask.runtimestamp = runtimestamp
  3422. etask.ENV = ENV
  3423. }
  3424. function initElevatedBatch(){
  3425. elevatedBatch.info = { repo }
  3426. elevatedBatch.errHandler = errHandler
  3427. elevatedBatch.statuslog = statuslog
  3428. elevatedBatch.processedArgs = processedArgs
  3429. elevatedBatch.selectedinstance = selectedinstance
  3430. elevatedBatch.runtimestamp = runtimestamp
  3431. elevatedBatch.ENV = ENV
  3432. }
  3433. if (exists) {
  3434. var tasks = [];
  3435. return (()=>{
  3436. // PB : TODO -- We need a non cacheable set of properties that need to default to something but then need to escplicitly specified in each run.
  3437. if(selectedinstance.addremotes) {
  3438. return op['get-remotes']({repo}).then(( remotes )=>{
  3439. return op['get-upstream']({repo, remotes}).then(( upstream ) => {
  3440. return __addremotesandpull({ upstream, remotes})
  3441. })
  3442. })
  3443. }
  3444. else return __pull();
  3445. })()
  3446. function __pull(){
  3447. var branchprint = branch ? ' branch :' + branch : '';
  3448. var task = ()=>{
  3449. console.log('pulling ' + instanceroot + '/' + repo + branchprint )
  3450. return any(tasks).then( ()=>{
  3451. return nodeShellExec.apply(null, getPullCmd(repodef, branch)).then(() => {
  3452. return true;
  3453. })
  3454. })
  3455. }
  3456. initTask(task)
  3457. if(repodef.requiresElevation) {
  3458. elevatedBatch.push(shell_verse.getElevatedTaskInBatch( task ));
  3459. if(elevatedBatch.length === 1) { initElevatedBatch(); initTask(elevatedBatch[0]) } // PB : TDOO -- Make sure first task also has run context. May need to be moved to win_verse
  3460. else initTask(elevatedBatch[elevatedBatch.length-1])
  3461. return elevatedBatch[elevatedBatch.length-1]
  3462. }
  3463. else {
  3464. regularBatch.push(shell_verse.getNonElevatedTask( task ))
  3465. return regularBatch[regularBatch.length-1]
  3466. }
  3467. }
  3468. function __addremotesandpull(options){
  3469. // Add the remotes
  3470. var tasks = []
  3471. // selectedinstance.selectedremotes are optional and need not be enforced to be chosen. The selection for hte selected remotes
  3472. // could also be derived from a crossfilter of remote-type selected for this run and the current chosen and operating reposervers.
  3473. var selectedremotes = Array.from( new Set(selectedinstance.selectedremotes.concat(Object.keys(repodef.remotes || {}))));
  3474. if(selectedremotes.length > 0) var selectedremoteFilter = function(rs) { return selectedremotes.find( rs.server ) }
  3475. else var selectedremoteFilter = function(){ return true }
  3476. var repoRemotes = Object.assign( {}, selectedinstance.remotes, options.remotes, options.upstream, repodef.remotes );
  3477. // We need a most permissive filtered list to use as an efficient starting point to further reduce to whats actually needed.
  3478. // However if such a cached list is not available we need to build it by scaning and apply all the filters anyway on the whole world.
  3479. Object.keys(repoRemotes).forEach((remotename)=>{
  3480. // PB : TODO -- ai prefix for all apis that require an answer amongst many choices.
  3481. var ai_RemoteAddNeeded = (r)=>{
  3482. if(r.server === reposerver && selectedremoteFilter() && r.accessibility.find( selectedinstance[ 'remote-type' ] )){ // currently chosen remotetype...
  3483. var exists = false;
  3484. if(exists = (options.remotes[r.remotename] || Object.keys(options.remotes).find( lrn => {
  3485. var exists = options.remotes[lrn].server === r.server && !options.remotes[r.remotename]
  3486. if(exists) console.warn('Found duplicate remote with a different name for the same server...')
  3487. return exists
  3488. } )) ) {
  3489. return false // Already a remote not required.
  3490. }
  3491. return true // PB : TODO -- Sort and display highest priority target.remotes.sort( )
  3492. }
  3493. return false
  3494. };
  3495. tasks.push(
  3496. ()=>{
  3497. return op['remote exists']({
  3498. remotename, repo, benign : true, ignorefailures : true
  3499. , url : repoRemotes[remotename].url + repo
  3500. , branch : checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV
  3501. }).then( (r) => {
  3502. if(!r[1]) return false; // PB : TODO -- Not accessible skip for now probably should remove.
  3503. else if(r[0]) return true; // Already added nothing to do
  3504. else if(ai_RemoteAddNeeded( repoRemotes[remotename] )) return op['remote add']( { remotename,
  3505. 'set-upstream' : (selectedinstance['upstream'] || `${remotename}/${branch}`) // ??? when url accessible... in order of highest priority
  3506. , reponame : repo
  3507. , url : repoRemotes[remotename].url , branch : checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV
  3508. })
  3509. // else skipped as remote is not relevant for this repo...
  3510. })
  3511. }
  3512. )
  3513. })
  3514. __pull()
  3515. }
  3516. }
  3517. else {
  3518. // PB : TODO -- detect if a clonable repo exists within the context of currentGitAuthUser on remote reposerver...
  3519. console.log('cloning ' + repo)
  3520. // PB : TODO -- add additional remotes after cloning and pull again...
  3521. var task = ()=>{
  3522. return nodeShellExec('git', ['clone', '-c', 'core.symlinks=true', selectedinstance.reposerver + `/${repodef.owner || repoowner || defaultRepoOwner}/` + repo + '.git'],
  3523. {
  3524. inherit: true, shell: true,
  3525. env: ENV
  3526. , cwd : instanceroot
  3527. , runas: processedArgs.runas
  3528. }).then(() => {
  3529. var task = ()=>{
  3530. return nodeShellExec('git', ['config', '--replace-all', 'core.symlinks', true],
  3531. {
  3532. inherit: true, shell: true,
  3533. env: ENV
  3534. , cwd: instanceroot + '/' + repo
  3535. , runas: processedArgs.runas
  3536. , title: `'git', ${['config', '--replace-all', 'core.symlinks', selectedinstance.username].join(' ')}`
  3537. })
  3538. }
  3539. initTask(task)
  3540. if(repodef.requiresElevation) {
  3541. elevatedBatch.push(shell_verse.getElevatedTaskInBatch( task ));
  3542. return elevatedBatch[elevatedBatch.length-1]
  3543. }
  3544. else {
  3545. regularBatch.push(shell_verse.getNonElevatedTask( task ))
  3546. return regularBatch[regularBatch.length-1]
  3547. }
  3548. })
  3549. }
  3550. initTask(task)
  3551. if(repodef.requiresElevation) {
  3552. elevatedBatch.push(shell_verse.getElevatedTaskInBatch( task ));
  3553. return elevatedBatch[elevatedBatch.length-1]
  3554. }
  3555. else {
  3556. regularBatch.push(shell_verse.getNonElevatedTask( task ))
  3557. return regularBatch[regularBatch.length-1]
  3558. }
  3559. }
  3560. }
  3561. var currentGitAuthUser; // nodeShellExec('git', ['config', 'user.email']) ... PB : TODO-- get the current GITEA username
  3562. var defaultRepoOwner = 'chess';
  3563. var elevatedRunasRepos = null
  3564. var gitRepos = null
  3565. // grep -qxF 'alias elxr="node elxr/index.js"' ~/.bash_profile || echo 'alias elxr="node elxr/index.js"' >> ~/.bash_profile
  3566. // nodeShellExec('echo', ['elxr'], { inherit : true}) //, {stdio: "inherit"}
  3567. var dbForLabel = function (label) {
  3568. var dbsForLabel = {
  3569. devmysql: 'mysql'
  3570. , development: 'mssql'
  3571. , production: 'mssql'
  3572. }
  3573. return dbsForLabel[label] || 'mysql'
  3574. }
  3575. // Maps an environment to a branch. Not required if the branch is appropriately named.
  3576. var checkoutMap = { 'development': 'master' }
  3577. // SAM : TODO Use nodeshellexec where to detect git installation dir
  3578. var gitbash = shell_verse.getbash()
  3579. // var gitbash = "G:\\Installed\\Git\\bin\\sh.exe"
  3580. // Relevant git repos
  3581. var exludeMergeRepos = [];
  3582. var useGitPull = processedArgs.useGitPull || false;
  3583. var configPromise = null
  3584. var reconfirmcmds = { create : true }
  3585. var subcommandlabels = {
  3586. switch : (`switch ${processedArgs._[1] || ''}`).trim()
  3587. }
  3588. var independentcmd = function(){
  3589. return false;
  3590. }
  3591. var util = require('util');
  3592. var cliname = 'elxr';
  3593. var ver = '1.1';
  3594. var readme = `
  3595. Command syntax examples
  3596. elxr
  3597. Displays help. Same as elxr h
  3598. elxr i
  3599. Runs interactive propmts to help choose installation options.
  3600. NODE_ENV={{yourenvironment}} elxr {{cmd}} {{instancename}} {{otheroptions}}
  3601. General command syntax.
  3602. Eg: NODE_ENV=development elxr pull elixir
  3603. Note : Although {{instancename}} is generally a positional parameter supplied immediately after the cmd for most cmd's.
  3604. The specific cmd defines what the value is interpreted as.
  3605. There are several cmds that do not require an {{instancename}} parameter.
  3606. Eg: elxr remote remove origin
  3607. Git operations or passthrough external commands on all repository folders in you working directory.
  3608. Main objectives.
  3609. elxr cli is a wrapper around other shell commands and api based operations.
  3610. One of the main objetives it achives is ease of use of repeating an individual cmd multiple times on all targets.
  3611. Eg: A git operation like pull can be repeated consistently on a set of git repositories.
  3612. `;
  3613. var help = `
  3614. ${readme}
  3615. # list of commands... please refer dveloper documentation for ${cliname}
  3616. \r\n\t${
  3617. Object.keys(op).join('\r\n\t')
  3618. }
  3619. `;
  3620. var elxr = {
  3621. help() {
  3622. return chalk.cyanBright(`
  3623. -------------------------------------------------------------------------------
  3624. *** BBH Elixir ***
  3625. -------------------------------------------------------------------------------
  3626. elxr ${ver}
  3627. A cli tool for chess
  3628. ${help}
  3629. -------------------------------------------------------------------------------
  3630. `)
  3631. }
  3632. , info() {
  3633. return chalk.cyanBright(`
  3634. -------------------------------------------------------------------------------
  3635. *** BBH Elixir ***
  3636. -------------------------------------------------------------------------------
  3637. elxr ${ver}
  3638. A cli tool for chess
  3639. -------------------------------------------------------------------------------
  3640. `)
  3641. }
  3642. , getpulltask(args){
  3643. // def can be an instance config
  3644. // Or an object with many repos and elevated repos
  3645. // Or a single repo ( Either Elevated or normal. )
  3646. // USAGE
  3647. // elxr pull elixir origin master
  3648. // elxr pull
  3649. // not all remote branches are setup to be tracked locally (respective remotes and branches).
  3650. // pull --all is useless. As it fetches all remotes and branches but only merges current branch.
  3651. // apart from remote tracking branches We are interested in pulling from all remotes and relavant branches.
  3652. // The branch pipline should feed back to master
  3653. // master -> test -> stage -> release[nnnn] -> production
  3654. // (master) <= git merge [all remotes] production && git merge [all remotes] release[nnnn]
  3655. // git merge [all remotes] stage && git merge [all remotes] test && git merge [all remotes] master
  3656. var __args = {
  3657. remotename : args.remotename|| processedArgs._[2]
  3658. , url : args.url || processedArgs._[3]
  3659. , branch : args.branch || processedArgs._[4] // If branch not specified opearte on the current branch of each working directorys
  3660. }
  3661. // var commands = [
  3662. // // ['git', ['checkout', __args.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]]
  3663. // ,
  3664. // ]
  3665. // var parameters = ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  3666. // var pullCmd = [ gitbash
  3667. // , ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  3668. // , { cwd: instanceroot + '/' + repo, title : 'pull all remotes for ' + branch + ' ' + repo + ' ' + parameters.join(' ') }]
  3669. var def = args || {
  3670. repos : selectedinstance.repos,
  3671. elevated : selectedinstance.elevated
  3672. }
  3673. var elevatedpulltasks = null;
  3674. if(def.repo) {
  3675. // Single repo case.
  3676. if(def.repo.requiresElevation) {
  3677. var t1 = function() {
  3678. return performPull(def).then(() => {
  3679. return true;
  3680. }).catch((e) => {
  3681. console.error(e)
  3682. }).finally(Traq.finally)
  3683. }
  3684. t1.statuslog = statuslog
  3685. t1.selectedinstance = selectedinstance
  3686. t1.processedArgs = processedArgs
  3687. elevatedpulltasks = shell_verse.getElevatedTask( t1 )
  3688. }
  3689. else {
  3690. var t2 = function(){
  3691. return performPull(def).then(() => {
  3692. console.log('pulled ' + JSON.stringify(def.repo))
  3693. return true;
  3694. }).catch((e) => {
  3695. console.error(e)
  3696. })
  3697. // .finally(Traq.finally)
  3698. }
  3699. t2.statuslog = statuslog
  3700. var regularpulltasks = shell_verse.getNonElevatedTask( t2 )
  3701. }
  3702. if(elevatedpulltasks) return elevatedpulltasks //getTaskWithElevation( { elevatedpulltasks, regularpulltasks} )
  3703. else return regularpulltasks // getTaskWithoutElevation({ regularpulltasks})
  3704. }
  3705. // console.log(`-------------------Processing pull for : ${def.repo} ${def.branch}`)
  3706. console.dir(def)
  3707. console.log('Running exlr pull : ' + path.dirname(__dirname))
  3708. var useGitPull = processedArgs.useGitPull || false;
  3709. if(def.elevated || def.repos) {
  3710. if(def.elevated) def.requiresElevation = true;
  3711. else delete def.requiresElevation;
  3712. }
  3713. else {
  3714. if(def.requiresElevation) def.elevated = [def]
  3715. else def.repos = [def]
  3716. }
  3717. var regularpulltasks = function(){ return Promise.resolve(true) }
  3718. if(def.elevated){
  3719. elevatedpulltasks = function() {
  3720. var eBatch = []
  3721. def.elevated.map((def) => getPullTask(def, null, null, null, eBatch))
  3722. if(eBatch.length<1) return Promise.resolve(true);
  3723. eBatch[0].processedArgs = processedArgs
  3724. return shell_verse.runElevatedBatch(eBatch).then(() => {
  3725. return true;
  3726. }).catch((e) => {
  3727. console.error(e)
  3728. })
  3729. }
  3730. elevatedpulltasks.statuslog = statuslog
  3731. }
  3732. if(def.repos) {
  3733. var regularpulltasks = function(){
  3734. var pendingpulls = [];
  3735. def.repos.forEach((def) => {
  3736. pendingpulls.push(
  3737. // PB : TODO serializing to prevent out of memory.
  3738. // Need to optimize as batches and streams...
  3739. function(){
  3740. // if(def.repo === 'setup') return;
  3741. // if(def.repo !== 'chess-client-lib') return;
  3742. return performPull(def).then(()=>{ console.log('pulled ' + JSON.stringify(def.repo)) })
  3743. .catch(e => {
  3744. console.error(util.inspect(e)); throw e })
  3745. }
  3746. )
  3747. })
  3748. return any(pendingpulls).finally(Traq.finally)
  3749. }
  3750. regularpulltasks.statuslog = statuslog
  3751. }
  3752. // if(elevatedpulltasks) return getTaskWithElevation( { elevatedpulltasks, regularpulltasks} )
  3753. // else return getTaskWithoutElevation({ regularpulltasks})
  3754. return elevatedpulltasks().then(()=>{
  3755. if(isWin() && isElevated) return Promise.resolve(true);
  3756. return regularpulltasks()
  3757. })
  3758. }
  3759. }
  3760. function preworkerconfig(){
  3761. // Everything runs after this check is completed. Elevation occurs out of process when needed.
  3762. gitRepos = selectedinstance.repos
  3763. // gitRepos = ['chess-server-lib'];
  3764. // Repositiories that have symlinks that require elevated priviletes in windows to create symlinks
  3765. elevatedRunasRepos = selectedinstance.elevated
  3766. // Repos that should excluded from merge for releases...
  3767. exludeMergeRepos = selectedinstance.exludeMergeRepos
  3768. // mysqldump --add-drop-table --no-data -u root -p db_name | grep 'DROP TABLE' ) > drop_all_tables.sql
  3769. // mysql -u root -p db_name < drop_all_tables.sql
  3770. var mysql = '../xampp/mysql/bin/mysql'
  3771. var mysqldump = '../xampp/mysql/bin/mysqldump'
  3772. }
  3773. // The main elxr cli process
  3774. function elxrworker() {
  3775. var __runcmd = function (label) {
  3776. var distinquishedlabel = subcommandlabels[label] || label
  3777. return op[distinquishedlabel] ? op[distinquishedlabel](processedArgs) : null;
  3778. }
  3779. return __runcmd(processedArgs.label || processedArgs._[0] || 'undefined');
  3780. }
  3781. // function acquireChoices(selectedinstance) {
  3782. // var hasconfig = false;
  3783. // console.warn(chalk.cyan(`
  3784. // -------------------------------------------------------------------------------
  3785. // Could not locate your preferred configuration (you may not specified it)
  3786. // You should fork the default chess configuration to customize and make it
  3787. // your own instance with a named config as
  3788. // {{yourowninstancename}}-config-{{yourchosenenvironment}}
  3789. // And then run this tool as follows
  3790. // NODE_ENV={{yourchosenenvironment}} elxr i {{yourowninstancename}}
  3791. // OR
  3792. // Run this tool with the following command to use a quick start default.
  3793. // elxr --default
  3794. // OR
  3795. // Choose one of the options below to run interactively.
  3796. // We will run your choice at the next prompt.
  3797. // -------------------------------------------------------------------------------
  3798. // `))
  3799. // var choices = getInteractionPoints(detectedinstanceoptions, __interactive_prompts)
  3800. // var todo = any( __interactive_prompts(selectedinstance, choices) ).then(()=>{
  3801. // return initinstances(selectedinstance)
  3802. // })
  3803. // // var prompt = cli.prompter;
  3804. // // return prompt.ask(`Choose an option :
  3805. // // d) Install the default chess instance.
  3806. // // => elxr i chess node_env=development --default
  3807. // // n) Create your custom new instance interactively
  3808. // // => elxr i {{instanceName}} node_env={{environment}}
  3809. // // i) Choose an instance and environment to install
  3810. // // => elxr i {{instanceName}} node_env={{environment}}
  3811. // // c) Choose a command to run ( pull, use, i, npmi ... ) <= pull
  3812. // // => elxr {{cmd}} {{instanceName}} node_env={{environment}}
  3813. // // h) Help
  3814. // // q) Quit
  3815. // // Default <= d
  3816. // // : `).then((choice) => {
  3817. // // if (choice && choice === 'd' || !choice) {
  3818. // // processedArgs._[0] = 'i'
  3819. // // selectedinstance.instanceName = processedArgs._[1] = processedArgs._[1] || 'chess'
  3820. // // selectedinstance.node_env = processedArgs.node_env = (ENV.NODE_ENV && ENV.NODE_ENV.trim()) || processedArgs.node_env || 'development'
  3821. // // selectedinstance.reposerver = 'https://git.bbh.org.in'
  3822. // // }
  3823. // // else if (choice === 'h') {
  3824. // // processedArgs._[0] = 'h'
  3825. // // fs.writeFileSync('run.done', 'noop help');
  3826. // // console.log(elxr.help()); process.exit()
  3827. // // }
  3828. // // else if (choice === 'n' || choice === 'i') {
  3829. // // var p1 = cli.prompter;
  3830. // // return p1.ask(`Enter Instance Name ( <= ${selectedinstance.instanceName} ) : `).then(function (instanceName) {
  3831. // // processedArgs._[0] = 'i'
  3832. // // selectedinstance.instanceName = processedArgs._[1] = instanceName || selectedinstance.instanceName;
  3833. // // return p1.ask(`Enter Environment ( <= ${selectedinstance.node_env} ) : `).then(function (node_env) {
  3834. // // selectedinstance.node_env = processedArgs.node_env = node_env || selectedinstance.node_env
  3835. // // if (choice === 'n') {
  3836. // // selectedinstance.reposerver = 'https://git.bbh.org.in'
  3837. // // console.warn(
  3838. // // chalk.magenta('No Option Available. Your account may not have privileges. You can request here http://git.bbh.org.in/chess'))
  3839. // // process.exit();
  3840. // // }
  3841. // // return p1.ask(`Enter preferred repo server ( <= ${selectedinstance.reposerver || selectedinstance.reposervers[0]} ) : `).then(function (reposerver) {
  3842. // // selectedinstance.reposerver = reposerver || selectedinstance.reposervers[0] || 'https://git.bbh.org.in'
  3843. // // })
  3844. // // })
  3845. // // })
  3846. // // } else if (choice === 'c') {
  3847. // // var p1 = cli.prompter;
  3848. // // return p1.ask(`Enter Instance Name ( <= ${selectedinstance.instanceName} ) : `).then(function (instanceName) {
  3849. // // selectedinstance.instanceName = processedArgs._[1] = instanceName || selectedinstance.instanceName
  3850. // // return p1.ask(`Enter Environment ( <= ${selectedinstance.node_env} ) : `).then(function (node_env) {
  3851. // // selectedinstance.node_env = processedArgs.node_env = node_env || selectedinstance.node_env
  3852. // // return p1.ask(`Enter cmd :
  3853. // // p) pull
  3854. // // Default <= p
  3855. // // : `).then(function (cmd) {
  3856. // // if (!cmd || cmd === 'p') {
  3857. // // processedArgs._[0] = 'pull'
  3858. // // }
  3859. // // else processedArgs._[0] = cmd
  3860. // // return p1.ask(`Enter preferred repo server ( <= ${selectedinstance.reposerver || selectedinstance.reposervers[0]} ) : `).then(function (reposerver) {
  3861. // // selectedinstance.reposerver = reposerver || selectedinstance.reposerver || selectedinstance.reposervers[0] || 'https://git.bbh.org.in'
  3862. // // })
  3863. // // })
  3864. // // })
  3865. // // })
  3866. // // } else {
  3867. // // console.log(chalk.gray(`Default option not exercised. Please follow manual instructions to customize your instance here http://git.bbh.org.in/chess and try again.`));
  3868. // // fs.writeFileSync('run.log', ', ' + JSON.stringify({ success: 'quit without execution' }), { 'flag': 'a+' })
  3869. // // fs.writeFileSync('run.done', 'noop quit');
  3870. // // process.exit()
  3871. // // }
  3872. // // })
  3873. // }
  3874. var os = require("os");
  3875. var hostname = os.hostname();
  3876. var clustername = null; // PB : TODO -- Prompt to acquire.
  3877. var configs = (function(){
  3878. // We need to discover and use the most specialized config available.
  3879. // Two passes are required as the config currently cloned may be switched by the discovery.
  3880. // If the repo name is the same but has different remotes the newly acquired config from multiple remotes may
  3881. // iteself redefine the remotes, repos and servers for the config which we need to honor..
  3882. return {
  3883. ownerClusterNodeConfig(selected) {
  3884. // Hostname and therefore clusternodename can be anything and can participate in many clusters.
  3885. // Also many cluster node instance can be running as a set of services on the same host on the same port with ( specific domain names )
  3886. var clusternodename = hostname || `CHESS0001${selected.username}`; // Cluster node names need to be unique accross all clusters to avoid collitions.
  3887. clustername = clustername || `${selected.username}-CHESS-${selected.node_env}`;
  3888. return __acquireConfig(selected, { remote : 'userfork' } // PB : TODO -- accessiblity state should switch to public etc..
  3889. , selected.instanceName + '-config-' + selected.node_env + `-${clusternodename}`
  3890. , function(e){ console.info('Customized node level config not found. This is not an Error. Will attempt with owner level config.');
  3891. e.benign = true
  3892. return e; }
  3893. )
  3894. }
  3895. , ownerInstnace(selected) { return __acquireConfig(selected, { remote : 'userfork' }
  3896. , selected.instanceName + '-config-' + selected.node_env
  3897. , function(e){ console.info('Customized user level config not found. This is not an Error. Will attempt global common instance config.');
  3898. e.benign = true
  3899. return e }
  3900. )
  3901. }
  3902. // PB : TODO -- Use the ORG level instance before falling back to common Instance coz common instance may not exist for certain orgs.
  3903. , commonInstance(selected) { return __acquireConfig(selected, { repoOwner : defaultRepoOwner }
  3904. , undefined
  3905. , function(e){
  3906. // PB : TODO -- console.info('This is probably an error unless the user is asking to create a new instance with this name.')
  3907. statuslog.statuslog(e, e)
  3908. var manifestpath = path.normalize(selected.root + '/' + selected.instanceName + '-config-' + selected.node_env + '/repo-manifest');
  3909. utils.assign_core( { keycase : true, arraymergetype : utils.assign_core.DISTINCT_UNION }
  3910. , selectedinstance, require(manifestpath)( {utils}, null, { username : selectedinstance.username, instanceName : selectedinstance.instanceName
  3911. , node_env : selectedinstance.node_env, reposerver : 'https://git.bbh.org.in' } ))
  3912. console.dir(selectedinstance.repos)
  3913. // Config from server always override merges into selection except for the current selection.
  3914. // PB : TODO -- utils.assign Array merges are non-distinct...
  3915. if(selectedinstance?.repos && !selectedinstance.repos[0].repo) {
  3916. console.warn('repo manifest has obsolete format. Attempting upgrade.')
  3917. selectedinstance.repos = selectedinstance.repos.map(function(repo){ return { repo } })
  3918. }
  3919. if(selectedinstance?.elevated && !selectedinstance.elevated[0]?.repo) {
  3920. console.warn('elevated repo manifest has obsolete format. Attempting upgrade.')
  3921. selectedinstance.elevated = selectedinstance.elevated.map(function(repo){ return { repo } })
  3922. }
  3923. chessinstances[selected.instanceName][selected.node_env] = selectedinstance = __g.selectedinstance = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
  3924. , selected, selectedinstance)
  3925. chessinstances[selected.instanceName][selected.node_env].reposervers = Array.from(new Set(chessinstances[selected.instanceName][selected.node_env].reposervers))
  3926. selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online...
  3927. cacheWriteInstanceConfig(chessinstances, selectedinstance.root, selectedinstance)
  3928. // ENV.NODE_ENV = selectedinstance.node_env;
  3929. throw e
  3930. }
  3931. ) }
  3932. // , genericChessInstance(selected) { return __acquireConfig(selected, { repoOwner : defaultRepoOwner }) }
  3933. }
  3934. })()
  3935. var eNotImplemented = function(){
  3936. console.error('Not yet implemented')
  3937. process.exit()
  3938. }
  3939. // PB : TODO -- accept additional arg - an array specifying custom configPriority.
  3940. var acquireConfig = function(slections){
  3941. var configPriority = [ 'ownerClusterNodeConfig', 'ownerInstnace', 'commonInstance' /*, 'genericChessInstance'*/ ]
  3942. return any(configPriority.map(cfg => { return function() { return configs[cfg](slections) } } ), true, true).then(()=>{
  3943. return acquireData(slections)
  3944. })
  3945. }
  3946. var instanceData = (function(){
  3947. return {
  3948. ownerClusterNodeData(selected) {
  3949. var clusternodename = hostname || `CHESS0001${selected.username}`; // Cluster node names need to be unique accross all clusters to avoid collitions.
  3950. clustername = clustername || `${selected.username}-CHESS-${selected.node_env}`;
  3951. return __acquireData(selected, { remote : 'userfork' }
  3952. , selected.instanceName + '-data-' + selected.node_env + `-${clusternodename}`
  3953. , function(e){ console.info('Customized node level data not found. This is not an Error. Will attempt with owner level config.');
  3954. e.benign = true
  3955. return e; }
  3956. )
  3957. }
  3958. , ownerInstnace(selected) { return __acquireData(selected, { remote : 'userfork' }
  3959. , selected.instanceName + '-data-' + selected.node_env
  3960. , function(e){ console.info('Customized user level data not found. This is not an Error. Will attempt global common instance config.');
  3961. e.benign = true
  3962. return e }
  3963. )
  3964. }
  3965. // PB : TODO -- Use the ORG level instance before falling back to common Instance coz common instance may not exist for certain orgs.
  3966. , commonInstance(selected) { return __acquireData(selected, { repoOwner : defaultRepoOwner }
  3967. // , function(e){ console.info('This is probably an error unless the user is asking to create a new instance with this name.') }
  3968. ) }
  3969. , genericChessInstance(selected) { return __acquireData(selected, { repoOwner : defaultRepoOwner }) }
  3970. }
  3971. })()
  3972. var acquireData = function(slections){
  3973. var configPriority = [ 'ownerClusterNodeData', 'ownerInstnace', 'commonInstance' /*, 'genericChessInstance'*/ ]
  3974. return any(configPriority.map(cfg => { return function() { return instanceData[cfg](slections) } } ), true, true)
  3975. }
  3976. function reinit(){
  3977. sysAddPathVar('%AppData%\\npm')
  3978. resetgitconfig()
  3979. }
  3980. function init(){
  3981. sysAddPathVar('%AppData%\\npm')
  3982. resetgitconfig()
  3983. }
  3984. function resetgitconfig(){
  3985. // https://stackoverflow.com/questions/37182847/how-do-i-disable-git-credential-manager-for-windows
  3986. // use git config --edit --system to remove the helper = manager line so that it is no longer registered as a credential helper.
  3987. // For bonus points, use git config --edit --global and insert:
  3988. // [core]
  3989. // askpass =
  3990. // https://git-scm.com/book/en/v2/Git-Tools-Credential-Storage
  3991. // Git Credential storage...
  3992. // git config --global credential.helper 'store --file ~/.elxrcredentials'
  3993. // git credential fill
  3994. // protocol=https
  3995. // host=git.bbh.org.in
  3996. // username=bob
  3997. // password=pppp
  3998. // git credential-store --file ~/.gitcredentials store
  3999. // // notepad C:/Program Files/Git/etc/gitconfig
  4000. // git config --edit --system
  4001. // git credential-store --file ~/git.store store
  4002. // Find system git config
  4003. // git config --global --edit
  4004. // git config --list --show-origin
  4005. // git config --list --show-origin --show-scope
  4006. // https://stackoverflow.com/questions/35942754/how-can-i-save-username-and-password-in-git
  4007. // Recipie
  4008. // git config --global --unset credentials.helper
  4009. // cd /path/to/my/repo
  4010. // git config --unset credential.helper
  4011. // git config credential.helper 'store --file ~/.git_repo_credentials'
  4012. // git config credential.*.username my_user_name
  4013. // git config credential.https://gitlab.com.username my_user_name
  4014. // git credential fill
  4015. // git config --global credential.modalprompt false // doesnst work.
  4016. // core askpass = ;;; https://stackoverflow.com/questions/37182847/how-do-i-disable-git-credential-manager-for-windows
  4017. var options = {
  4018. inherit: true, shell: true, env: ENV
  4019. , cwd: instanceroot
  4020. , runas: processedArgs.runas
  4021. }
  4022. var task = ['git', ['config'], options]
  4023. var tasklist = [
  4024. // ['--global', '--unset credentials.helper']
  4025. // ['--unset', 'credentials.helper']
  4026. // ,
  4027. // ['credential.helper', `'store --file git_repo_credentials'`]
  4028. ['--global', 'credential.helper', "'store --file ~/.git_repo_credentials'"]
  4029. , ['--global', '--replace-all', 'user.name', 'pb']
  4030. , ['--global', '--replace-all', 'user.email', 'pradeep@bbh.org.in']
  4031. // , ['--list']
  4032. // , ['credential', 'fill']
  4033. ]
  4034. var onEachError = e => console.error( e.messages.join('\n') + e.result + '\n' + util.inspect(e) + '\n')
  4035. var shellT = (args) => { return getgitbashtask(args, onEachError)
  4036. // .catch(e => console.error( e.messages.join('\n') + e.result + '\n' + util.inspect(e) + '\n' + tasq.toString()) )
  4037. }
  4038. execserial(tasklist, task, shellT, onEachError )
  4039. }
  4040. var createTasq = (args, shellT, onEachError) => {
  4041. var tasq = shellT ? shellT(args) : (() => { return nodeShellExec.apply(null, args).catch( onEachError || function(e){ console.error(e) } ) })
  4042. tasq.toString = function(){ return JSON.stringify(args)}
  4043. return tasq;
  4044. }
  4045. var execserial = function(tasklist, task, shellT){
  4046. var exec = (taskArgs)=>{
  4047. var thistask = task.concat();
  4048. thistask[1] = thistask[1].concat()
  4049. thistask[1].push.apply(thistask[1], taskArgs)
  4050. return createTasq(thistask, shellT)
  4051. }
  4052. return any(tasklist.map(exec))
  4053. }
  4054. var execonce = function(taskArgs, task){ return any([task[1].push.apply(task[1], taskArgs)].map(createTasq)) }
  4055. var __acquireConfig = function (selected, options, configrepo, errHandler) {
  4056. configrepo = configrepo || selected.instanceName + '-config-' + selected.node_env;
  4057. var repoOwner = options.repoOwner || selected.username || options.defaultRepoOwner
  4058. var errorHandler = (e) => {
  4059. if(e.messages.join(' ').match(new RegExp (`fatal: unable to access '${selectedinstance.reposerver}/${repoOwner}/${configrepo}.git/': Failed to connect to .*? port .*? after .*? ms: Timed out`))){
  4060. // console.error('Could not connect to repo server. Timed Out')
  4061. return cli.prompt( ['(y)es', '(n)o', '(r)etry'], 'Could not connect to repo server. Timed Out. Would you like to switch server ? (y/n) ', 'y' ).then(propValue => {
  4062. if(propValue === 'y') {
  4063. reconfirm = getReconfirmAll()
  4064. return startElxr()
  4065. }
  4066. else if(propValue === 'r'){
  4067. return acquireConfig(selected)
  4068. }
  4069. else process.exit()
  4070. })
  4071. }
  4072. if(e.messages.join(' ').match(new RegExp (`fatal: repository '${selectedinstance.reposerver}/${repoOwner}/${configrepo}.git/' not found`))){
  4073. var choices = {
  4074. t : `install a new temporary local instance with this name ( will not persist ).
  4075. Use your own username for additional options. You can request for a username at chess@bbh.org.in )`
  4076. , e : 'exit' }
  4077. if(selectedinstance.username !== 'guest' && selectedinstance.username !== 'demo') {
  4078. choices = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
  4079. , {
  4080. i : 'create a new instance with this name => will fork the default config under your username'
  4081. , f : 'fork a new instance with this name for yourself for this node from another instance'
  4082. , o : 'fork a new instance with this name for your organization from another instance' // prompt organization name...
  4083. , c : 'create a custom config for yourself for this node' // prompt hostname as nodename
  4084. , p : 'create a custom config for yourself '
  4085. }, choices)
  4086. }
  4087. return cli.prompt( choices
  4088. , 'Config for instance not found. Would you like to ', 'e' ).then(propValue => {
  4089. if(propValue === 't') {
  4090. selectedinstance.local = true; return createInstance(selectedinstance)
  4091. }
  4092. if(propValue === 'i') return eNotImplemented()
  4093. if(propValue === 'f') return eNotImplemented()
  4094. if(propValue === 'o') return eNotImplemented()
  4095. if(propValue === 'c') return eNotImplemented() // return createLocalChessInsance(selectedinstance)
  4096. if(propValue === 'p') return eNotImplemented() // return createChessInstance(selectedinstance)
  4097. // if(propValue === 'o') createChessInstance(selectedinstance, orgname)
  4098. else process.exit()
  4099. })
  4100. }
  4101. console.warn(e)
  4102. throw e; //('Config acquisition failed.')
  4103. }
  4104. var successHandler = () => {
  4105. var manifestpath = path.normalize(selected.root + '/' + selected.instanceName + '-config-' + selected.node_env + '/repo-manifest');
  4106. utils.assign_core( { keycase : true, arraymergetype : utils.assign_core.DISTINCT_UNION }
  4107. , selectedinstance, require(manifestpath)( {utils}, null, { username : selectedinstance.username, instanceName : selectedinstance.instanceName
  4108. , node_env : selectedinstance.node_env, reposerver : selectedinstance.reposerver }))
  4109. console.dir(selectedinstance.repos)
  4110. // Config from server always override merges into selection except for the current selection.
  4111. // PB : TODO -- utils.assign Array merges are non-distinct...
  4112. if(!selectedinstance.repos[0].repo) {
  4113. console.warn('repo manifest has obsolete format. Attempting upgrade.')
  4114. selectedinstance.repos = selectedinstance.repos.map(function(repo){ return { repo } })
  4115. }
  4116. if(selectedinstance.elevated[0] && !selectedinstance.elevated[0].repo) {
  4117. console.warn('elevated repo manifest has obsolete format. Attempting upgrade.')
  4118. selectedinstance.elevated = selectedinstance.elevated.map(function(repo){ return { repo } })
  4119. }
  4120. chessinstances[selected.instanceName][selected.node_env] = selectedinstance = __g.selectedinstance = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
  4121. , selected, selectedinstance)
  4122. chessinstances[selected.instanceName][selected.node_env].reposervers = Array.from(new Set(chessinstances[selected.instanceName][selected.node_env].reposervers))
  4123. selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online...
  4124. cacheWriteInstanceConfig(chessinstances, selectedinstance.root)
  4125. ENV.NODE_ENV = selectedinstance.node_env;
  4126. }
  4127. return performPull( selected.reposindexed[configrepo] || { repo : configrepo }
  4128. , null, repoOwner, errHandler || errorHandler || ((e)=>{ throw e })).then( successHandler )
  4129. .catch( (e)=>{
  4130. // if(e){
  4131. if(Promise.resolve(e) === e) return e;
  4132. // console.error(e)
  4133. e.benign = true;
  4134. throw e; // Not a hard error but we need this for bcontinueonfailure as we still want to stop on firstsuccess.
  4135. // }
  4136. })
  4137. }
  4138. var __acquireData = function (selected, options, datarepo, errHandler) {
  4139. datarepo = datarepo || selected.instanceName + '-data';
  4140. var repoOwner = options.repoOwner || selected.username || options.defaultRepoOwner
  4141. var errorHandler = (e) => {
  4142. if(e.messages.join(' ').match(new RegExp (`fatal: unable to access '${selectedinstance.reposerver}/${repoOwner}/${datarepo}.git/': Failed to connect to .*? port .*? after .*? ms: Timed out`))){
  4143. // console.error('Could not connect to repo server. Timed Out')
  4144. return cli.prompt( ['(y)es', '(n)o', '(r)etry'], 'Could not connect to repo server. Timed Out. Would you like to switch server ? (y/n) ', 'y' ).then(propValue => {
  4145. if(propValue === 'y') {
  4146. reconfirm = getReconfirmAll()
  4147. return startElxr()
  4148. }
  4149. else if(propValue === 'r'){
  4150. return acquireConfig(selected)
  4151. }
  4152. else process.exit()
  4153. })
  4154. }
  4155. if(e.messages.join(' ').match(new RegExp (`fatal: repository '${selectedinstance.reposerver}/${repoOwner}/${datarepo}.git/' not found`))){
  4156. var choices = {
  4157. t : `install a temporary local data folder.
  4158. For more options. Request and use a personal username at chess@bbh.org.in )`
  4159. , e : 'exit' }
  4160. if(selectedinstance.username !== 'guest' && selectedinstance.username !== 'demo') {
  4161. choices = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
  4162. , {
  4163. i : 'create a new instance with this name => will fork the default config under your username'
  4164. , f : 'fork a new instance with this name for yourself for this node from another instance'
  4165. , o : 'fork a new instance with this name for your organization from another instance' // prompt organization name...
  4166. , c : 'create a custom config for yourself for this node' // prompt hostname as nodename
  4167. , p : 'create a custom config for yourself '
  4168. }, choices)
  4169. }
  4170. return cli.prompt( choices
  4171. , 'Data repo for instance not found. Would you like to ', 'e' ).then(propValue => {
  4172. if(propValue === 't') {
  4173. selectedinstance.local = true; return createInstanceData(selectedinstance)
  4174. }
  4175. if(propValue === 'i') return eNotImplemented()
  4176. if(propValue === 'f') return eNotImplemented()
  4177. if(propValue === 'o') return eNotImplemented()
  4178. if(propValue === 'c') return eNotImplemented() // return createLocalChessInsance(selectedinstance)
  4179. if(propValue === 'p') return eNotImplemented() // return createChessInstance(selectedinstance)
  4180. // if(propValue === 'o') createChessInstance(selectedinstance, orgname)
  4181. else process.exit()
  4182. })
  4183. }
  4184. console.warn(e)
  4185. throw e; //('Config acquisition failed.')
  4186. }
  4187. var successHandler = () => {
  4188. }
  4189. return performPull( selected.reposindexed[datarepo] || { repo : datarepo }
  4190. , null, repoOwner, errHandler || errorHandler || ((e)=>{ throw e })).then( successHandler )
  4191. .catch( (e)=>{
  4192. // if(e){
  4193. if(Promise.resolve(e) === e) return e;
  4194. // console.error(e)
  4195. e.benign = true;
  4196. throw e; // Not a hard error but we need this for bcontinueonfailure
  4197. // }
  4198. })
  4199. }
  4200. // ----------------------------------------------------------------
  4201. // PB : TODO -- Review and obsolete...
  4202. // ----------------------------------------------------------------
  4203. // var launchpath = path.resolve(path.normalize(ENV.wd))
  4204. var launchpath = selectedinstance.root
  4205. // // we were run.
  4206. // // The easisest would be to ask for a target directory and default to current dir....
  4207. // // path.dirname(launchpath).split(path.sep).pop()
  4208. // var parent = path.dirname(launchpath);
  4209. // var pp = launchpath;
  4210. // var instancediscoverytasks = [];
  4211. // while(parent !== pp){
  4212. // instancediscoverytasks.push(
  4213. // ((pa)=>{
  4214. // var p = pa;
  4215. // return function(){
  4216. // return hasElxr(p).then((value)=>{
  4217. // if(value) return p
  4218. // // PB : TODO -- Using throw like this is not friendly with any...
  4219. // throw Object.assign( new Error('Benign Failure in Batch')
  4220. // , { value : false, benign : true });
  4221. // })
  4222. // }
  4223. // })(pp)
  4224. // )
  4225. // pp = parent;
  4226. // parent = path.dirname(parent);
  4227. // }
  4228. // var instanceroot = null
  4229. // var detectInstanceRoot = any(instancediscoverytasks, true, true).then( ir => {
  4230. // if(ir.error) { instanceroot = path.normalize(thisscriptdir) === path.normalize(launchpath) ? path.normalize(thisscriptdir + '/..') : launchpath ; }
  4231. // else instanceroot = ir.pVal
  4232. // return instanceroot
  4233. // }).catch(()=>{
  4234. // instanceroot = path.normalize(thisscriptdir) === path.normalize(launchpath) ? path.normalize(thisscriptdir + '/..') : launchpath ;
  4235. // })
  4236. // We first load the default and then override with a runconfig if it exists else we override with the interactive prompts.
  4237. // Then acquire and reload and replace this default.
  4238. var __interactive_prompts = function( target, choices, promptsfilter ){
  4239. Object.defineProperty(target, 'node_env', { get : function(){ return this.instanceType } });
  4240. var interactionpoints = unbound_interactionpoints.bind({target, choices})(selectedinstance)
  4241. function getPromptKeys() {
  4242. // PB : TODO -- get interactionpoints
  4243. if(! (processedArgs.label || processedArgs._[0]) ) return Object.assign({}, interactionpoints);
  4244. return promptkeys // PB : TODO __ Convert pormptkeys to filtered interactionpoints.
  4245. }
  4246. var eachPrompt = getBoundEachPrompt( target, getPromptKeys() , interactionpoints, choices, promptsfilter)
  4247. return Object.keys(promptsfilter || interactionpoints).reduce(eachPrompt, [])
  4248. }
  4249. var downloadsdir = shell_verse.downloadsdir;
  4250. var prerequisites = [
  4251. {
  4252. shellcmd: 'git',
  4253. name : 'git',
  4254. url: 'https://github.com/git-for-windows/git/releases/download/v2.31.0.windows.1/Git-2.31.0-64-bit.exe'
  4255. , installer: 'Git-2.31.0-64-bit.exe'
  4256. , installcmd: ['cmd', ['/c', 'start',
  4257. '/WAIT', path.resolve(downloadsdir + '/' + 'Git-2.31.0-64-bit.exe')
  4258. , '/VERYSILENT'
  4259. // , '/MERGETASKS=!runcode' // This is required only for vscode...
  4260. ]]
  4261. , preinstallsteps: function() {
  4262. var steps = [
  4263. () => {
  4264. if (!existsSync(downloadsdir + '/' + this.installer)) {
  4265. return nodeShellExec(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`, [this.url, downloadsdir + '/' + this.installer])
  4266. }
  4267. else return Promise.resolve(true)
  4268. }
  4269. ]
  4270. var prompts = this.getuser(null, ()=>{
  4271. // console.log('preinstallsteps')
  4272. // var gitUser = 'guest';
  4273. // var gitEmail = 'guest@bbh.org.in';
  4274. // var prompts = [];
  4275. // prompts.push( ()=>{ return cli.prompt(choices['username'], 'git user name').then(gituser => gitUser = gituser) } )
  4276. // prompts.push( ()=>{ return cli.prompt(choices['useremail'], 'git user email').then(gitemail => gitEmail = gitemail) } )
  4277. // console.log('prompting in preinstallsteps')
  4278. // return any(prompts).then(()=>{
  4279. // var steps = [
  4280. // ['git', ['config', '--global', '--add', 'user.name', `${gitUser}`]]
  4281. // , ['git', ['config', '--global', '--add', 'user.email', `${gitEmail}`]]
  4282. // ]
  4283. // return any(steps.map(getshelltask)).then(() => {
  4284. // })
  4285. // });
  4286. return Promise.resolve(true)
  4287. })
  4288. return any([any(steps), prompts])
  4289. }
  4290. , installsteps: function () {
  4291. return any([this.installcmd].map(getshelltask))
  4292. }
  4293. , postinstallsteps: function(err, users){
  4294. return this.getuser(null, (err, data)=>{
  4295. // ignore err and proceed with data as guest.
  4296. console.dir(data)
  4297. if(data && data.length === 1 && !shouldPrompt('username', promptkeys, selectedinstance) ) {
  4298. return username = data[0];
  4299. }
  4300. data = data || ['guest']
  4301. choices['username'] = Array.from( new Set( data.concat( (choices['username'] || []) )) )
  4302. console.log('prompting in postinstallsteps')
  4303. var username = 'guest';
  4304. var email = 'guest@bbh.org.in';
  4305. var password = '***';
  4306. return any( getInteractionPoints([selectedinstance], promptkeys, { username, password, email}) ).then(()=>{
  4307. if(!data.find(e => e === selectedinstance.username)) {
  4308. var steps = [
  4309. ['git', ['config', '--global', '--add', 'user.name', `${username}`]]
  4310. , ['git', ['config', '--global', '--add', 'user.email', `${email}`]]
  4311. ]
  4312. return any(steps.map(getshelltask)).then(() => {
  4313. })
  4314. }
  4315. else {
  4316. return Promise.resolve(true)
  4317. }
  4318. });
  4319. })
  4320. }
  4321. , install: function () {
  4322. return any([ /*this.preinstallsteps,*/ this.installsteps.bind(this), this.postinstallsteps.bind(this)])
  4323. }
  4324. , verifyAndInstall : function(){
  4325. return getTaskCheckExists(this.shellcmd, { ignorefailures: true })().then((exists) => {
  4326. if(exists) {
  4327. // return any(['git', ['config', '--global', '-l']].map(getshelltask))
  4328. return this.postinstallsteps.bind(this)()
  4329. }
  4330. return this.install();
  4331. });
  4332. }
  4333. , getuser : function(repo, onResult){
  4334. var __onResult = onResult || function(e, data){
  4335. data = data || []
  4336. choices['username'] = Array.from( new Set( data.concat( (choices['username'] || []) )) )
  4337. // console.dir(choices)
  4338. return data[0]
  4339. }
  4340. var globalOrLocal = '--global';
  4341. if(repo) globalOrLocal = '--local'
  4342. return any([['git', ['config', globalOrLocal, '--get-all', 'user.name']]].map(getshelltask)).then((result)=>{
  4343. // not yet configured.
  4344. if(!result.success) return __onResult(result)
  4345. else {
  4346. var users = result.messages[0].trim().split('\n');
  4347. if(users.length === 0 ||
  4348. users.length === 1 && users[0] === 'guest') {
  4349. return __onResult(result)
  4350. }
  4351. else {
  4352. return __onResult(null, Array.from( new Set( users ) ) ); }// PB : TODO == We should probably prompt with all the users available for selection !
  4353. }
  4354. })
  4355. .catch((e)=>{
  4356. console.error(e)
  4357. return __onResult(e)
  4358. })
  4359. }
  4360. }
  4361. ,
  4362. {
  4363. shellcmd: 'node',
  4364. name : 'node',
  4365. url: 'https://nodejs.org/dist/v14.16.0/node-v14.16.0-x64.msi'
  4366. , installer: 'node-v14.16.0-x64.msi'
  4367. , installcmd: ['MSIEXEC.exe', ['/i'
  4368. , path.resolve(downloadsdir + '/' + 'node-v14.16.0-x64.msi')
  4369. , 'ACCEPT=YES', '/passive']]
  4370. , install : function() { return any([this.installcmd].map(getshelltask)).then(() => { }) }
  4371. }
  4372. ]
  4373. for(var i=0; i<prerequisites.length; i++) {
  4374. prerequisites[prerequisites[i].name] = prerequisites[i];
  4375. }
  4376. prerequisites.forEach(p=>{ prerequisites[p.shellcmd] = p })
  4377. function ensureDirectoryExistence(filePath) { return shell_verse.ensureDirectoryExistence(filePath) }
  4378. var mainTasks = [];
  4379. function verifyAndInstallPrerequisites() {
  4380. var downloadtasks = [];
  4381. var installtasks = [];
  4382. prerequisites.forEach(preq => {
  4383. downloadtasks.push(getTaskCheckExists(preq.shellcmd, { ignorefailures: true })().then((exists) => {
  4384. if (exists) console.log(`${preq.shellcmd} exists`)
  4385. else {
  4386. console.log(`${preq.shellcmd} is not installed`)
  4387. return preq.preinstallsteps.call(preq).then(() => {
  4388. installtasks.push(preq.install.bind(preq))
  4389. })
  4390. }
  4391. }))
  4392. })
  4393. return Promise.all(downloadtasks).then(() => { return any(installtasks) })
  4394. }
  4395. // function updateselection(selected) { selectedinstance = utils.assign(selectedinstance, selected) }
  4396. var runconfig = null;
  4397. var promptkeys = {
  4398. cmd : processedArgs._[0] || 'pull'
  4399. // Try not to prompt anything unless absolutely necessary or reconfirm is forced.
  4400. // 'instanceName' : true
  4401. // , 'node_env' : true
  4402. // , username : ''
  4403. // , runchoice : 'c'
  4404. }
  4405. // promptkeys.runchoice = promptkeys.cmd ? 'c' : undefined
  4406. var choices = {
  4407. 'instanceName' : []
  4408. , 'reposerver' : []
  4409. , 'upstream-remote' : []
  4410. , 'instanceType' : []
  4411. , username : ['guest', 'chessdemo', 'demo']
  4412. }
  4413. var getInteractionPoints = function(detectedinstanceoptions, possiblePrompts, promptsfilter){
  4414. var instances = []
  4415. var reposervers = [];
  4416. var remotes = [];
  4417. var instanceNames = []
  4418. var instanceTypes = ['development', 'production'];
  4419. // Accumulate all known choices from every possible instance...
  4420. Object.keys( chessinstances).forEach(instanceName => {
  4421. if(instanceName === 'current_run') return ;
  4422. Object.keys( chessinstances[instanceName] ).forEach(node_env=>{
  4423. var instance = chessinstances[instanceName][node_env];
  4424. reposervers = reposervers.concat(instance.reposervers)
  4425. if(instance.reposerver) reposervers.push(instance.reposerver)
  4426. instances.push(instance)
  4427. instanceTypes.push(instance.node_env)
  4428. instanceNames.push(instance.instanceName)
  4429. var otherremotes = instance?.reposerverinstances
  4430. if(otherremotes) otherremotes = otherremotes[instance?.reposerver]?.remotes
  4431. otherremotes = otherremotes || {}
  4432. Array.prototype.push.apply(remotes, Object.keys(otherremotes))
  4433. })
  4434. })
  4435. instances = instances.concat(detectedinstanceoptions)
  4436. if(selectedinstance['instanceName']) instanceNames.push(selectedinstance['instanceName'])
  4437. if(possiblePrompts['instanceName']) instanceNames.push(possiblePrompts['instanceName'])
  4438. if(selectedinstance['reposervers']) reposervers = reposervers.concat(selectedinstance['reposervers'])
  4439. choices['instanceName'] = Array.from( new Set(instanceNames.concat(choices['instanceName'])) )
  4440. choices['reposerver'] = Array.from( new Set(reposervers.concat(choices['reposerver'])) )
  4441. // choices['upstream-remote'] = Array.from( new Set(remotes.concat(choices['upstream-remote'])) )
  4442. choices['instanceType'] = Array.from( new Set(instanceTypes.concat(choices['instanceType'])) )
  4443. return __interactive_prompts(selectedinstance, choices, promptsfilter)
  4444. }
  4445. var detection_state = {
  4446. localInstanceDetected : false
  4447. }
  4448. function createInstanceData(target, source) {
  4449. var sourceinstance = source || target;
  4450. console.dir(sourceinstance)
  4451. var args = {
  4452. remotebase : sourceinstance.reposerver + '/chess/'
  4453. , sourcerepo : sourceinstance.repo || 'chess-data'
  4454. , targetrepo : `${target.instanceName}-data-${target.instanceType}${target.nodeName ? ('-' + target.nodeName) : ''}`
  4455. }
  4456. if(sourceinstance.local) {
  4457. var options = {
  4458. inherit: true, shell: true,
  4459. env: ENV
  4460. , cwd : instanceroot
  4461. , runas: processedArgs.runas
  4462. }
  4463. var cmdseq = [
  4464. ['git', ['clone', `${args.remotebase}${args.sourcerepo}`, `${args.targetrepo}`], options]
  4465. ]
  4466. return any(cmdseq.map(getshelltask)).then(() => { return true })
  4467. }
  4468. else {
  4469. // http://try.gitea.io/api/v1/org/{org}/repos
  4470. if(source.reposerver !== target.reposerver && source.username !== target.username) {
  4471. throw 'createInstanceData is possible only within the same repository server.'
  4472. }
  4473. var server = new URL(target.reposerver);
  4474. return GITEA.repository.fork( { hostname : server.host, protocol : server.protocol
  4475. , username : target.username, password : target.password
  4476. }
  4477. // , { repo : `${selectedinstance.instanceName}-config-${selectedinstance.instanceType}`}
  4478. , { repo : `${args.sourcerepo}`, owner : `${target.username}` }, {}, function( repository ){
  4479. return GITEA.repository.updateattributes( {
  4480. hostname : server.host, protocol : server.protocol
  4481. , username : target.username, password : target.password
  4482. }
  4483. , { repo : `${args.sourcerepo}`, owner : `${target.username}` }
  4484. , { name : `${args.targetrepo}`}
  4485. )
  4486. }
  4487. )
  4488. }
  4489. // GITEA.repository.updateattributes( {
  4490. // hostname : server.host, protocol : server.protocol
  4491. // , username : selectedinstance.username, password : selectedinstance.password
  4492. // }
  4493. // , { repo : `chess-config`, owner : selectedinstance.username }
  4494. // , { name : `${selectedinstance.instanceName}-config-${selectedinstance.instanceType}${selectedinstance.nodeName ? '-' + selectedinstance.nodeName : ''}`}
  4495. // )
  4496. // return selectedinstance
  4497. }
  4498. function createInstance(target, source) {
  4499. var sourceinstance = source || target;
  4500. console.dir(sourceinstance)
  4501. var args = {
  4502. remotebase : sourceinstance.reposerver + '/chess/'
  4503. , sourcerepo : sourceinstance.repo || 'chess-config'
  4504. , targetrepo : `${target.instanceName}-config-${target.instanceType}${target.nodeName ? ('-' + target.nodeName) : ''}`
  4505. }
  4506. if(sourceinstance.local) {
  4507. var options = {
  4508. inherit: true, shell: true,
  4509. env: ENV
  4510. , cwd : instanceroot
  4511. , runas: processedArgs.runas
  4512. }
  4513. var cmdseq = [
  4514. ['git', ['clone', `${args.remotebase}${args.sourcerepo}`, `${args.targetrepo}`], options]
  4515. ]
  4516. return any(cmdseq.map(getshelltask)).then(() => { return true })
  4517. }
  4518. else {
  4519. // http://try.gitea.io/api/v1/org/{org}/repos
  4520. if(source.reposerver !== target.reposerver && source.username !== target.username) {
  4521. throw 'createInstance is possible only within the same repository server.'
  4522. }
  4523. var server = new URL(target.reposerver);
  4524. return GITEA.repository.fork( { hostname : server.host, protocol : server.protocol
  4525. , username : target.username, password : target.password
  4526. }
  4527. // , { repo : `${selectedinstance.instanceName}-config-${selectedinstance.instanceType}`}
  4528. , { repo : `${args.sourcerepo}`, owner : `${target.username}` }, {}, function( repository ){
  4529. return GITEA.repository.updateattributes( {
  4530. hostname : server.host, protocol : server.protocol
  4531. , username : target.username, password : target.password
  4532. }
  4533. , { repo : `${args.sourcerepo}`, owner : `${target.username}` }
  4534. , { name : `${args.targetrepo}`}
  4535. )
  4536. }
  4537. )
  4538. }
  4539. // GITEA.repository.updateattributes( {
  4540. // hostname : server.host, protocol : server.protocol
  4541. // , username : selectedinstance.username, password : selectedinstance.password
  4542. // }
  4543. // , { repo : `chess-config`, owner : selectedinstance.username }
  4544. // , { name : `${selectedinstance.instanceName}-config-${selectedinstance.instanceType}${selectedinstance.nodeName ? '-' + selectedinstance.nodeName : ''}`}
  4545. // )
  4546. // return selectedinstance
  4547. }
  4548. var skipprerequisites = false;
  4549. function initinstances() {
  4550. // var root = selectedinstance.root
  4551. var instanceName = selectedinstance.instanceName
  4552. var node_env = selectedinstance.node_env
  4553. var reposerver = selectedinstance.reposerver
  4554. // var instanceName = selectedinstance.instanceName
  4555. // || clioverrides.instanceName
  4556. // // || processedArgs._[1]
  4557. // || chessinstances.current_run.instanceName
  4558. // var node_env = selectedinstance.node_env
  4559. // || clioverrides.node_env
  4560. // // || processedArgs.node_env
  4561. // || chessinstances.current_run.node_env
  4562. // var reposerver = selectedinstance.reposerver
  4563. // || clioverrides.reposerver
  4564. // // || processedArgs.node_env
  4565. // || chessinstances.current_run.reposerver
  4566. // if(!instanceName) {
  4567. // promptkeys['instanceName'] = instanceName = chessinstances.current_run.instanceName = promptkeys['instanceName'] || __default.instanceName;
  4568. // promptkeys['node_env'] = node_env = chessinstances.current_run.node_env = promptkeys['node_env'] || __default.node_env;
  4569. // promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
  4570. // }
  4571. // if(!node_env) {
  4572. // promptkeys['node_env'] = node_env = chessinstances.current_run.node_env = promptkeys['node_env'] || __default.node_env;
  4573. // promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
  4574. // }
  4575. // if(!reposerver) {
  4576. // promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
  4577. // }
  4578. // chessinstances[instanceName] = chessinstances[instanceName] || createLocalChessInstance( {
  4579. // instanceName, node_env, root : selectedinstance.root, reposerver : selectedinstance.reposerver /* promptkeys['reposerver'] */ } );
  4580. // chessinstances['current_run'] = { instanceName: selectedinstance.instanceName, node_env : selectedinstance.node_env, reposerver : selectedinstance.reposerver, root }
  4581. // if(path.normalize(selectedinstance.root) !== path.normalize(chessinstances[selectedinstance.instanceName][selectedinstance.node_env].root)) {
  4582. // throw "instanceName and instanceType specified doesn't match whats already present do you want to continue " + chessinstances[instanceName][node_env].root + ' does not match ' + selectedinstance.root
  4583. // }
  4584. // Override sequence.
  4585. // __default, chessinstances[current_run], instanceName-config-development, cliargs, interactve_promts
  4586. // PB : TODO -- Undefined keys are overriding and deleting values. We should not allow that.
  4587. // This is ordinary utils.assign behavior. The key should not exist as undefined in the override.
  4588. // PB : TODO -- We now have options that can be passed into assign_core to control this behavior.
  4589. if(selectedinstance.node_env === undefined) delete selectedinstance.node_env
  4590. // selectedinstance = __g.selectedinstance = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
  4591. // , __default
  4592. // , chessinstances[instanceName][node_env]
  4593. // , clioverrides
  4594. // , selectedinstance
  4595. // // , __interactive_prompts -- Cant just override. Also need selectedinstance to be ready...
  4596. // );
  4597. // chessinstances[instanceName] = chessinstances[instanceName] || {}
  4598. // chessinstances[instanceName][node_env] = chessinstances[instanceName][node_env] || {}
  4599. // if(!selectedinstance.repos || selectedinstance.instanceName) {
  4600. // // Brand New.
  4601. // selectedinstance = Object.assign( __default, selectedinstance )
  4602. // }
  4603. // Upgrade old formats..
  4604. if(selectedinstance?.repos && !selectedinstance?.repos[0]?.repo) {
  4605. console.warn('repo manifest has obsolete format. Attempting upgrade.')
  4606. selectedinstance.repos = selectedinstance.repos.map(function(repo){ return { repo } })
  4607. }
  4608. if(selectedinstance?.elevated && !selectedinstance?.elevated[0]?.repo) {
  4609. console.warn('elevated repo manifest has obsolete format. Attempting upgrade.')
  4610. selectedinstance.elevated = selectedinstance.elevated.map(function(repo){ return { repo } })
  4611. }
  4612. // Config from server always override merges into selection except for the current selection.
  4613. // PB : TODO -- utils.assign Array merges are non-distinct...
  4614. // chessinstances[instanceName][node_env] = selectedinstance;
  4615. // chessinstances[selectedinstance.instanceName][selectedinstance.node_env] = selectedinstance;
  4616. cacheWriteInstanceConfig(chessinstances, selectedinstance.root)
  4617. // PB : TODO -- We should probably write the new server config also...
  4618. selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online...
  4619. return chessinstances
  4620. }
  4621. var skipprereqs = {}
  4622. var maintask = () => {
  4623. // Default cmd to run !
  4624. processedArgs._[0] === processedArgs._[0] || 'pull';
  4625. // selectedinstance.reposerver = selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online from all that are available.
  4626. if(!noprerequisites[processedArgs._[0]]
  4627. && !skipprereqs[processedArgs._[0]]
  4628. ) {
  4629. return prerequisites.git.verifyAndInstall().then(()=>{
  4630. var e = { message : 'verifyAndInstall', success : true}
  4631. var inittasks = []
  4632. var commontask = () => { preworkerconfig(); return elxrworker(true) }
  4633. if(!detection_state.localInstanceDetected) {
  4634. var t1 = ()=>{ return createInstance(selectedinstance) };
  4635. t1.statuslog = statuslog
  4636. var specifictask = shell_verse.getNonElevatedTask(t1)
  4637. }
  4638. else {
  4639. var t2 = ()=>{ return acquireConfig(selectedinstance) };
  4640. t2.statuslog = statuslog
  4641. var specifictask = shell_verse.getNonElevatedTask(t2)
  4642. }
  4643. inittasks.push( specifictask().catch((err) => {
  4644. e = err;
  4645. console.error('Chosen cofiguraton failed or not found. Fix config and rerun or chose another.')
  4646. console.error(err)
  4647. }).then( commontask )
  4648. // .finally(()=>{
  4649. // fs.writeFileSync('run.log', ', ' + JSON.stringify({ error: e.message }), { 'flag': 'a+' })
  4650. // if(!e.success) fs.writeFileSync('run.done', 'error');
  4651. // // return process.exit()
  4652. // }))
  4653. )
  4654. return any(inittasks)
  4655. })
  4656. }
  4657. else {
  4658. console.log('cmd has no preqs or has been configured to skip preqs')
  4659. preworkerconfig()
  4660. return elxrworker()
  4661. }
  4662. }
  4663. function generateDependencies(){ return shell_verse.generateDependencies() }
  4664. var startElxr = function() {
  4665. const retaincount = 2
  4666. var min = runtimestamp;
  4667. var collect = []
  4668. if(reconfirmcmds[processedArgs.label || processedArgs._[0]]) {
  4669. reconfirm = getReconfirmAll()
  4670. }
  4671. // detectedinstanceoptions.splice(0,0, __default) // PB : TODO -- Merge multiple...
  4672. var detectedinstanceoptions = [selectedinstance]
  4673. var cmdinstance = cmds[clioverrides.cmd]
  4674. var cmdprompts = cmdinstance.getPossiblePrompts()
  4675. // selectedinstance.node_env ? selectedinstance.node_env : selectedinstance.node_env = clioverrides.node_env
  4676. // PB : TODO -- Most recent should be at the tip ! at index 0 so utils.reverseassign is required !!!
  4677. utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }, selectedinstance, promptkeys )
  4678. // promptkeys = utils.assign(promptkeys, clioverrides)
  4679. // startElxr requires instance // Independent cmds should have already been bypassed.
  4680. // if(cmdprompts.instanceName) {
  4681. // not an instanceless cmd.
  4682. // console.dir(selectedinstance)
  4683. try {
  4684. // chessinstances = acquirelocalinstances(selectedinstance);
  4685. // findlocalinstances(chessinstances, detectedinstanceoptions)
  4686. initinstances(selectedinstance) // use the local instances for defaults if at all possible.
  4687. var todo = any( getInteractionPoints(detectedinstanceoptions, promptkeys) ).then(()=>{
  4688. var inst = initinstances(selectedinstance)
  4689. detection_state.localInstanceDetected = true;
  4690. return inst;
  4691. })
  4692. }
  4693. catch (e) {
  4694. // PB : TODO -- verbose mode warning.. console.warn(e) // Missing chessinstances is not an error...
  4695. var todo = any( getInteractionPoints(detectedinstanceoptions, promptkeys) ).then(()=>{
  4696. return initinstances(selectedinstance)
  4697. })
  4698. // if(!processedArgs._[0] || !selectedinstance.node_env || !selectedinstance.instanceName){
  4699. // // Weve not been told what to do.
  4700. // todo = todo.then(() => { return acquireChoices(selectedinstance) })
  4701. // }
  4702. todo = todo.then(() => {
  4703. try {
  4704. // chessinstances = acquirelocalinstances(selectedinstance)
  4705. // findlocalinstances(chessinstances, detectedinstanceoptions)
  4706. // detectedinstanceoptions.splice(0,0, __default)
  4707. initinstances(selectedinstance)
  4708. detection_state.localInstanceDetected = true;
  4709. }
  4710. catch (e) {
  4711. // console.error(e)
  4712. console.log('No local instances config found in current root = ' + selectedinstance.root);
  4713. console.log('A config will be createed with the instance and environment chosen...')
  4714. // return (async ()=>{return await __default.reposerver})().then(()=>{
  4715. // // selectedinstance = Object.assign(detectedInstance, clioverrides);
  4716. // return selectedinstance = Object.assign(__default, selectedinstance);
  4717. // })
  4718. detection_state.localInstanceDetected = false;
  4719. return selectedinstance
  4720. }
  4721. })
  4722. }
  4723. return todo.then( ()=>{
  4724. // PB : TODO -- Embed this in the build instead of inlining it.
  4725. // PB : TODO -- Also attepmt to load from ../chess-config/... as base for new instances...
  4726. initinstances(selectedinstance) // PB : TODO Review Initinstancess... and cleanup
  4727. // ---------------------------
  4728. runconfig = { NODE_ENV: selectedinstance.node_env }
  4729. try { runconfig = Object.assign(runconfig, require(instanceroot + '/run.js')) } catch (e) { }
  4730. generateDependencies();
  4731. if(noprerequisites[processedArgs._[0]]
  4732. || skipprereqs[processedArgs._[0]]
  4733. ) {
  4734. return elxrworker()
  4735. }
  4736. var neTask = ()=>{
  4737. ensureDirectoryExistence(`${selectedinstance.root}/.elxr/${__ALIAS__STAMP__}`)
  4738. // collect garbage
  4739. return dirs( (dir)=>{
  4740. var matches = /run-(.*)/gm.exec(dir.name)
  4741. if(matches) {
  4742. if(+(matches[1]) < min) {
  4743. min = matches[1]
  4744. collect.splice( 0, 0, matches[1] )
  4745. }
  4746. else collect.push(matches[1])
  4747. }
  4748. return Promise.resolve(collect);
  4749. }, `${selectedinstance.root}/.elxr` )
  4750. .then(()=>{
  4751. // delete garbage
  4752. if(collect.length > retaincount) {
  4753. var asyncs = [];
  4754. while((collect.length - asyncs.length) > retaincount) {
  4755. asyncs.push(getShellTask('rm',['-rf', `run-${collect[asyncs.length]}`], { cwd : `${selectedinstance.root}/.elxr` })());
  4756. }
  4757. return Promise.all(asyncs)
  4758. }
  4759. else return true
  4760. })
  4761. .catch(e => {
  4762. console.error
  4763. })
  4764. }
  4765. neTask.statuslog = statuslog
  4766. shell_verse.getNonElevatedTask( neTask )()
  4767. var commonTask = ()=>{
  4768. verifyAndInstallPrerequisites.statuslog = statuslog
  4769. if((!skipprerequisites || processedArgs.forceprereqs)) mainTasks.push(verifyAndInstallPrerequisites);
  4770. mainTasks.push(maintask)
  4771. return any(mainTasks);
  4772. }
  4773. return commonTask()
  4774. })
  4775. // }
  4776. // else return Promise.resolve(true)
  4777. }
  4778. // return detectInstanceRoot.then(()=>{
  4779. var cmdobj = cmds[selectedinstance.cmd]
  4780. return Promise.all((cmdobj.requires || []).map( (r) => utils.promisify(null, r) ) ).then(()=>{
  4781. if(cmdobj.independentcmd) {
  4782. if(cmdobj.requiresElevation) {
  4783. return cmdobj.cmdFn(cmdobj.toArgs(processedArgs))
  4784. }
  4785. else return cmdobj.cmdFn(cmdobj.toArgs(processedArgs))
  4786. }
  4787. else return startElxr()
  4788. })
  4789. .catch(e => {
  4790. if(typeof e === 'symbol') console.log('error : ' + 'symbol')
  4791. else console.log('error : ' + e)
  4792. })
  4793. // })
  4794. })
  4795. })
  4796. // .then( () => {
  4797. // console.log(process._getActiveHandles());
  4798. // console.log(process._getActiveRequests());
  4799. // })
  4800. // detect if alread installed -> Take no action.
  4801. // download if no installer avalable -> next()
  4802. // install
  4803. function checkandinstall(items) {
  4804. var tasks = []
  4805. items.forEach(item => {
  4806. tasks.push(getTaskCheckExists(item.shellcommand || prerequisites[item]))
  4807. })
  4808. return Promise.all(tasks).then(existances => {
  4809. existances.forEach((exists, i) => {
  4810. if (!exists) {
  4811. return downloadandinstall([items[i]])
  4812. }
  4813. })
  4814. })
  4815. }
  4816. function downloadandinstall(items) {
  4817. var tasks = []
  4818. items.forEach(item => {
  4819. tasks.push(getTaskDownload(item))
  4820. })
  4821. return Promise.all(tasks)
  4822. }
  4823. // Sample instances config.
  4824. // var instances = {
  4825. // "elixir": {
  4826. // "production": {
  4827. // "reposervers": ["http://git.bbh", "https://git.bbh.org.in"]
  4828. // , "repos": ["ember-masonry-grid", "client", "elixir-client"]
  4829. // , "exludeMergeRepos": {
  4830. // "elixir-config-development": true, "elixir-config-test": true
  4831. // , "elixir-config-production": true, "elixir-data": true
  4832. // }
  4833. // , "instanceName": "elixir", "node_env": "production"
  4834. // }
  4835. // },
  4836. // "current_run": { "instanceName": "elixir", "node_env": "production" }
  4837. // }
  4838. // ,([^\}^\S\r]*?\}) // Regexp to eliminate extra comma at the end of an array or an object...