Best JavaScript code snippet using appium-xcuitest-driver
manage-metadata-component.js
Source:manage-metadata-component.js
1myApp.component('manageMetadataComponent', {2 // isolated scope binding3 bindings: {4 },5 templateUrl: '/Views/Admin/manage-metadata-component.html',67 // The controller that handles our component logic8 controller: ['$rootScope', '$http', 'authorizeService', 'layerService', 'ngIntroService', 'commonService', function ($rootScope, $http, authorizeService, layerService, ngIntroService, commonService ) {9 var $ctrl = this;10 $ctrl.setting = {};11 $ctrl.$onInit = function () {1213 var getOtherSetting = function () {14 $rootScope.errorMessage = "";15 $rootScope.isLoading = true;16 $http.get("/admin/GetOtherSetting").success(function (res) {17 if (!res.Error) {18 $ctrl.setting.IsCatalogDisabled = res.IsCatalogDisabled;19 $ctrl.setting.MapboxToken = res.MapboxToken;20 }21 else {22 $rootScope.errorMessage = res.Message;23 }24 $rootScope.isLoading = false;25 });26 };27 getOtherSetting();2829 };30 $ctrl.isTreeCollapsed = false;31 $ctrl.toggleTree = function () {32 $ctrl.isTreeCollapsed = !$ctrl.isTreeCollapsed;33 }34 $ctrl.menuOptions = [35 ['<span class="glyphicon glyphicon-remove"></span> Delete', function ($itemScope, $event) {36 $ctrl.removeMetadata($itemScope)37 }]38 ]39 $ctrl.layerTabs = [{ Id: 0, Name: 'Layer' },40 { Id: 1, Name: 'Fields' },41 { Id: 2, Name: 'Styles' },42 { Id: 3, Name: 'Labels' },43 { Id: 4, Name: 'HTML' },44 { Id: 5, Name: 'Related Records' },45 { Id: 6, Name: 'Events' },46 { Id: 7, Name: 'Versions' }47 ];48 $ctrl.currentLayerTab = 0;49 $ctrl.serviceTabs = [{ Id: 0, Name: 'Service' },50 { Id: 1, Name: 'Build Tiles' },51 ];52 $ctrl.currentServiceTab = 0;53 $ctrl.activeLayerTab = function (id) {54 if ($rootScope.canDeactivate && !$rootScope.canDeactivate()) {55 return; // can't navigate away if have unsaved change56 }57 $ctrl.currentLayerTab = id;58 }59 $ctrl.activeServiceTab = function (id) {60 if ($rootScope.canDeactivate && !$rootScope.canDeactivate()) {61 return; // can't navigate away if have unsaved change62 }63 $ctrl.currentServiceTab = id;64 }6566 var getLayerSetting = function () {67 $rootScope.errorMessage = "";68 $rootScope.isLoading = true;69 $http.get("/admin/GetLayerSetting", { params: { layerId: $rootScope.currentLayerId } }).success(function (res) {70 if (!res.Error) {71 $ctrl.layerTabs = [72 { Id: 0, Name: 'Layer' },73 { Id: 1, Name: 'Fields' },74 { Id: 2, Name: 'Styles' },75 { Id: 3, Name: 'Labels' },76 { Id: 4, Name: 'HTML' },77 { Id: 5, Name: 'Related Records' },78 { Id: 6, Name: 'Events' }79 ];80 if (res.LayerSetting.ServiceType === 1 && res.LayerSetting.ServerType == "mssql") {81 $ctrl.layerTabs.push({ Id: 7, Name: 'Versions' });82 } else {83 $ctrl.currentLayerTab = $ctrl.currentLayerTab === 7 ? 0 : $ctrl.currentLayerTab;84 }85 }86 else {87 $rootScope.errorMessage = res.Message;88 }89 $rootScope.isLoading = false;90 });91 }9293 $ctrl.activeNode = function (scope, idx) {94 if ($rootScope.canDeactivate&&!$rootScope.canDeactivate()) {95 return; // can't navigate away if have unsaved change96 }97 $rootScope.currentNodeIndex = idx;98 $rootScope.currentScope = scope;99 $rootScope.currentNode = scope.node;100 editNode(scope);101 if ($rootScope.currentNode.MetadataType === 2) {102 getLayerSetting();103 }104 }105 var activeNodeManually = function (node) {106 setTimeout(function () {107 var currentScope = angular.element("#node" + node.MetadataType + "_" + node.Id).scope();108 $ctrl.activeNode(currentScope.$nodeScope, currentScope.$index);109 $rootScope.$digest();110 });111 };112 var inactiveNode = function (scope, idx) {113 $rootScope.currentNodeIndex = -1;114 $rootScope.currentScope = {};115 $rootScope.currentNode = {}; 116 }117 $ctrl.introOptions = {118 steps: [119 {120 element: '#intro1',121 intro: "To get started add a folder. Folders help you organize Map Services and Feature Services.",122 position: 'left'123 },124 {125 element: '#intro2',126 intro: "Now you can add a Map Service or Feature Service.",127 },128 {129 element: '#intro3',130 intro: "You can add a layer to a service by uploading a file or by connecting to a table in a database."131 }132 ]133 }134 $rootScope.callIntro = function (step) {135 if ($rootScope.isIntro) {136 setTimeout(function () {137 $ctrl.callIntro(step);138 }, 500);139 }140 }141 $ctrl.single = {};142 $ctrl.single.NewFolder = {};143 $ctrl.single.NewService = {};144 $ctrl.connections = [];145 // get connection146 var getConnections = function () {147 $rootScope.errorMessage = "";148 $rootScope.isLoading = true;149 $http.get("/Connection/GetConnections").success(function (res) {150 if (!res.Error) {151 $ctrl.connections = res.Connections; 152153 }154 else {155 $rootScope.errorMessage = res.Message;156 };157 $rootScope.isLoading = false;158 }).error(authorizeService.onError);159 }160 getConnections();161 162 163 164 165 166 $ctrl.getNodeLink = function (scope, idx) {167 var getServiceLink = function (serviceScope) {168 var folderName = serviceScope.$parentNodeScope.$modelValue.Name;169 var serviceName = serviceScope.node.Name;170 var serviceType = serviceScope.node.ServiceType ? "FeatureServer" : "MapServer"; // 1 for feature server171 links.push(folderName);172 links.push(serviceName);173 links.push(serviceType);174 }175 var links = ["/bluespatial/rest/services"];176 switch (scope.node.MetadataType) {177 case 0:178 links.push(scope.node.Name);179 break;180 case 1:181 if (scope.$parentNodeScope) { // fix bug when parrent node null182 getServiceLink(scope);183 }184 break;185 case 2:186 if (scope.$parentNodeScope) { // fix bug when parrent node null187 getServiceLink(scope.$parentNodeScope);188 links.push(idx);189 }190 break;191 }192 return links.join("/");193 }194 $ctrl.getNodeTypeName = function (scope, idx) {195 switch (scope.node.MetadataType) {196 case 1: return scope.node.ServiceType ? "(Feature Service)" : "(Map Service)"; //1 for feature service197 //case 2: return "(Layer " + idx + ")";198 default: return "";199 }200 }201 $ctrl.removeMetadata = function (scope) {202 if (!authorizeService.isAuthorize()) return;203 var confirmMessage = "Are you sure you want to delete layer '" + scope.node.Name + "'?";204 205 if (scope.node.MetadataType == 0) {206 confirmMessage = "Are you sure you want to delete folder '" + scope.node.Name + "'? This will also delete all child services, all child layers."; 207 }208 else if (scope.node.MetadataType == 1) {209 confirmMessage = "Are you sure you want to delete service '" + scope.node.Name + "'? This will also delete all child layers.";210 };211 212 if (confirm(confirmMessage)) {213 $("#dialog-confirm").dialog({214 resizable: false,215 height: "auto",216 width: 400,217 modal: true,218 buttons: {219 "Yes": function () {220 $rootScope.errorMessage = "";221 $rootScope.isLoading = true;222 $http.post("/Admin/DeleteMetadata", { id: scope.node.Id, type: scope.node.MetadataType, needDeleteTable: true }223 ).success(function (res) {224 if (!res.Error) {225 scope.remove();226 if (scope.node.MetadataType == 2 && scope.node.Id == $rootScope.currentLayerId) {227 $rootScope.currentLayerId = null;228 }229 inactiveNode();230 }231 else {232 $rootScope.errorMessage = res.Message;233 };234 $rootScope.isLoading = false;235 })236 .error(authorizeService.onError);237 $(this).dialog("close");238 },239 "No": function () {240 $rootScope.errorMessage = "";241 $rootScope.isLoading = true;242 $http.post("/Admin/DeleteMetadata", { id: scope.node.Id, type: scope.node.MetadataType, needDeleteTable: false }243 ).success(function (res) {244 if (!res.Error) {245 scope.remove();246 if (scope.node.MetadataType == 2 && scope.node.Id == $rootScope.currentLayerId) {247 $rootScope.currentLayerId = null;248 }249 inactiveNode();250 }251 else {252 $rootScope.errorMessage = res.Message;253 };254 $rootScope.isLoading = false;255 })256 .error(authorizeService.onError);257 $(this).dialog("close");258 }259 }260 });261 262 }263 };264265 $ctrl.changeStatusService = function (serviceId, isStopped) {266 if (!authorizeService.isAuthorize()) return;267268 if (isStopped) {269 confirmMessage = "Are you sure you want to stop this service?";270 } 271272 if ((isStopped && confirm(confirmMessage)) || (!isStopped)) {273 $rootScope.errorMessage = "";274 $rootScope.isLoading = true;275 $http.post("/Admin/UpdateServiceStatus", { serviceId: serviceId, status: isStopped }276 ).success(function (res) {277 if (!res.Error) {278 $ctrl.single.NewService.IsStopped = isStopped;279280 // update breadcrumb 281 $rootScope.$emit('changeBreadcrumbServiceIsStopped', $ctrl.single.NewService);282283 // update metadata tree284 getMetadataTree();285 }286 else {287 $rootScope.errorMessage = res.Message;288 };289 $rootScope.isLoading = false;290 })291 .error(authorizeService.onError);292 }293 };294295 $ctrl.toggle = function (scope) {296 scope.toggle();297 };298299300 $ctrl.collapseAll = function () {301 $rootScope.$broadcast('angular-ui-tree:collapse-all');302 };303304 $ctrl.expandAll = function () {305 $rootScope.$broadcast('angular-ui-tree:expand-all');306 };307 var getMetadataTree = function () {308 $rootScope.errorMessage = "";309 $rootScope.isLoading = true;310 return $http.get("/Admin/GetMetadataTree").success(function (res) {311 if (!res.Error) {312 $ctrl.data = res.Data;313 if (!$ctrl.data.length) {314 $ctrl.callIntro();315 $rootScope.isIntro = true;316 }317 $ctrl.havePreview = res.HavePreview;318 }319 else {320 $rootScope.errorMessage = res.Message;321 };322 $rootScope.isLoading = false;323 }).error(authorizeService.onError);324 }325 getMetadataTree();326 $ctrl.importServiceCallBack = getMetadataTree;327328 $ctrl.pushFolder = null; // this function difference for create and update329 $ctrl.pushService = null;330331 $ctrl.addNewFolder = function () {332 if ($rootScope.canDeactivate && !$rootScope.canDeactivate()) {333 return; // can't navigate away if have unsaved change334 }335 $ctrl.single.IsEditMode = false;336 $ctrl.single.NewFolder = {};337 $rootScope.currentNode = { Id: 0, MetadataType: 0 }; // MetadataType:0 for folder338 $rootScope.currentScope = {};339 340 $ctrl.pushFolder = function (folder) {341 var folderNode = {342 Id: folder.Id,343 Name: folder.Name,344 MetadataType: 0,// 0 for foler345 Nodes: []346 };347 $ctrl.data.push(folderNode);348 activeNodeManually(folderNode); 349 // copy current node to continue edit350 $ctrl.single.NewFolder.Id = folderNode.Id; 351 $rootScope.successMessage = "Folder \"" + folder.Name + "\" was generated successfully.";352 // update the pushFolder function, since after first push the second time is edit353 //$ctrl.pushFolder = function (folder) {354 // folderNode.Name = folder.Name;355 //}356 }357 };358 $ctrl.showLayerModal = function (scope) {359 var nodeService = scope.$modelValue; 360 361 $ctrl.single.Layer = { ServiceId:nodeService.Id };362 var $layerModal = $("#creatLayerModal");363 $layerModal.modal('show');364 $ctrl.saveLayerCallback = function (layer) {365 layer.Nodes = [];366 layer.MetadataType = 2;// 2 for layer 367 nodeService.Nodes.push(layer);368 activeNodeManually(layer);369 370 }371 }372 var generateFolderBreadcrumb = function (scope) {373 $ctrl.folderBreadcrumb = [{374 Url: $ctrl.getNodeLink(scope, 0),375 MetadataType: 0,376 Name: scope.$modelValue.Name,377 }];378 }379 var attrsToMerge = ['Id', 'Name', 'ServiceType','IsDisabled'];380 $ctrl.addNewService = function (scope) {381 382 $ctrl.single.IsEditMode = false;383 $ctrl.single.NewService = { IsCached: false, IsWMSEnabled: false, IsAllowAnonymous: false, MaxRecordCount: 1000, MinScale: 0, MaxScale: 0, IsStopped: false, SpatialReference: 102100 };384 if ($rootScope.isNotFullVersion()) {385 // auto select the default connection for basic version386 //if ($rootScope.isBasicVersion()) {387 // $ctrl.connections.forEach(function (item, index) {388 // if (item.IsDefault) {389 // $ctrl.single.NewService.ConnectionId = item.Id;390 // }391 // });392 //}393 // map service for all not full version394 $ctrl.single.NewService.ServiceType = 0;395 }396 397 // select the first connection if have only one connection398 if ($ctrl.connections.length == 1) {399 $ctrl.single.NewService.ConnectionId = $ctrl.connections[0].Id;400 }401 $rootScope.currentNode = { Id: 0, MetadataType:1 };// MetadataType=1 for service402 403 var nodeFolder = scope.$modelValue;404 $ctrl.single.NewService.FolderId = nodeFolder.Id;405 generateFolderBreadcrumb(scope);406 $ctrl.pushService = function (service) {407 service.MetadataType = 1;408 service.Nodes = [];409 nodeFolder.Nodes.push(service);410 activeNodeManually(service); 411 $rootScope.successMessage = "Service \"" + service.Name + "\" was generated successfully.";412 // the second time this will be edit service413 414 //$ctrl.pushService = function (s) {415 // commonService.mergeObject(s, service, attrsToMerge);416 // service.MetadataType = 1;417 // service.Nodes = [];418 // $rootScope.successMessage = "Service \"" + service.Name + "\" was updated successfully.";419 //}420421 }422 423 };424 425426 var editNode = function (scope) {427 $ctrl.single.IsEditMode = true;428 var currentNode = scope.node;429 $rootScope.currentFolderId = 0;430 $rootScope.currentLayerId = 0;431 $rootScope.currentServiceId = 0;432 if (currentNode.MetadataType == 0) {// folder 433 434 $ctrl.pushFolder=function(folder){435 currentNode.Name = folder.Name;436 }437 $rootScope.currentFolderId = currentNode.Id;438 }439 else if (currentNode.MetadataType == 1) {// service440 441 442 //$("#creatServiceModel").modal('show');443 $ctrl.pushService = function (service) {444 commonService.mergeObject(service, currentNode, attrsToMerge);445 $rootScope.successMessage = "Service \"" + service.Name + "\" was updated successfully.";446 };447 $rootScope.currentServiceId = currentNode.Id;448 if (currentNode.ServiceType==1){ // for feature service active tab 0 b/c we don't have tab 1449 $ctrl.currentServiceTab = 0;450 }451 }452 else if (currentNode.MetadataType == 2) {// layer453 $ctrl.single.NewLayer = {};454 $ctrl.single.NewLayer.Id = currentNode.Id;455 $ctrl.single.NewLayer.Name = currentNode.Name;456 $ctrl.single.NewLayer.IsODataEnabled = currentNode.IsODataEnabled;457 $ctrl.single.NewLayer.IsStopped = currentNode.IsStopped;458459 //("#editLayerModal").modal('show');460 $ctrl.pushLayer = function (layerName) {461 currentNode.Name = layerName;462 };463 $rootScope.currentLayerId = currentNode.Id;464 }465 };466 467 $ctrl.isFeatureLayer = function (scope) {468 if (scope.node.MetadataType != 2) { // !layer469 return false;470 };471 if (scope.$parentNodeScope.$modelValue.ServiceType == 1) {// if service is feature service472 return true;473 };474 return false;475476 }477 478 $ctrl.getDisableTitle = function (node) {479 if (!node.IsDisabled) {480 return "";481 }482 else {483 var metaName = "";484 if (node.MetadataType == 2) {485 metaName = "layer";486 }487 else if (node.MetadataType == 1) {488 metaName = "service";489 }490 return ["This ", metaName, " was disabled, please upgrade to PRO version to unlock it"].join("");491 }492 }; 493 $ctrl.openImportServiceDialog = function (scope) {494 $('#importServiceModal').modal('show');495 generateFolderBreadcrumb(scope);496 };497 setTimeout(function () {498 $("#tree-root").slimScroll({499 height: 'calc(100vh - 120px)'500 });501 });502503 this.$routerCanDeactivate = $rootScope.canDeactivate;504 505 }]
...
document.js
Source:document.js
...85 filesName = filesName.slice(0,-1);86 let index = filesName.lastIndexOf("/") + 1;87 filesName = filesName.slice(index, filesName.length);88 return getHtml([89 '<input type="checkbox" onclick="objectOps.pushFolder(\'' + file.Prefix + '\')"/>',90 '<span onclick="prefix_add(\'' + filesName + '\');objectOps.clear();listFolder();">',91 filesName,92 '</span>',93 '<br>'94 ]);95 });96 var files = data.Contents.map(function(file) {97 var fileKey = file.Key;98 if(file.Size==0) return;99 var fileUrl = bucketUrl + encodeURIComponent(fileKey);100 var fileName = fileKey.replace(path, '');101 return getHtml([102 '<span>',103 '<div>',104 '<input type="checkbox" onclick="objectOps.push(\'' + fileKey + '\')"/>',105 '<a href="' + fileUrl + '">',106 fileName,107 '</a>',108 '</div>',109 '</span>'110 ]);111 });112 var htmlTemplate = [113 getHtml(folder),114 getHtml(files)115 ];116 document.getElementById('list-item').innerHTML = getHtml(htmlTemplate);117 });118}119120function uploadOps(){121 var pushedItems;122 var counter;123 function initialize(){124 pushedItems = [];125 counter = 0;126 uploadOps.inputClicked = inputClicked;127 uploadOps.push = push;128 uploadOps.upload = upload;129 uploadOps.uploadFile = uploadFile;130 uploadOps.haveUploadItems = haveUploadItems;131 uploadOps.postOperation = postOperation;132 uploadOps.addCounter = addCounter;133 document.getElementById('dropDiv').addEventListener('dragover', dragHover);134 document.getElementById('dropDiv').addEventListener('dragleave', dragHover);135 document.getElementById('dropDiv').addEventListener('drop', drop_Handler);136 document.getElementById('upload-Modal').style.display = 'block';137 }138 function finalize(){139 pushedItems = null;140 counter = null;141 delete uploadOps;142 document.getElementById('dropDiv').removeEventListener('dragover', dragHover);143 document.getElementById('dropDiv').removeEventListener('dragleave', dragHover);144 document.getElementById('dropDiv').removeEventListener('drop', drop_Handler);145 }146 function dragHover(event) {147 event.stopPropagation();148 event.preventDefault();149 event.target.className = (event.type === 'dragover')? 'over':'';150 }151 function drop_Handler(event){152 event.stopPropagation();153 event.preventDefault();154 event.target.className = '';155 let items = event.dataTransfer.items;156 (Array.from(items)).forEach(item=>{157 item = item.webkitGetAsEntry();158 if(item)159 {160 uploadOps.push(item);161 }162 });163 if(uploadOps.haveUploadItems())164 {165 document.getElementById("upload-modal-initial").style.display = "none";166 document.getElementById("upload-modal").style.display = "block";167 }168 }169 async function scanFiles(item, folderPath) {170 async function getFile(fileEntry) {171 try {172 return await new Promise((resolve, reject) => fileEntry.file(resolve, reject));173 } catch (err) {174 console.log(err);175 }176 }177 if (item.isDirectory) {178 let folderKey = path + item.fullPath.slice(1,item.fullPath.length) + "/";179 objectOps.createFolder(folderKey, true);180 let directoryReader = item.createReader();181 directoryReader.readEntries(function(entries) {182 entries.forEach(function(entry) {183 scanFiles(entry, folderKey);184 });185 });186 }187 else {188 counter++;189 let file = (item.constructor.name=='File')?item:await getFile(item);190 let fileKey = folderPath + file.name;191 uploadFile(fileKey, file);192 }193 }194195 function inputClicked(){196 let files = document.getElementById('uploadInput').files;197 (Array.from(files)).forEach(file=>{198 push(file);199 });200 document.getElementById('uploadInput').value = "";201 if(haveUploadItems())202 {203 document.getElementById("upload-modal-initial").style.display = "none";204 document.getElementById("upload-modal").style.display = "block";205 }206 }207 function push(item){208 if(!haveUploadItems()||(!pushedItems.some(pushedItem=>{209 if(pushedItem.name==item.name)210 {211 alert('The file\'s name duplicates with existed file. ')212 return true;213 }214 })))215 {216 pushedItems.push(item);217 const bodyRow = document.getElementById('upload-tbody').insertRow();218 const bodyCell = bodyRow.insertCell();219 bodyCell.innerHTML = item.name;220 const deleteSpan = document.createElement('span');221 deleteSpan.innerHTML = 'x';222 deleteSpan.onclick = () => {223 bodyRow.remove();224 pushedItems = pushedItems.filter(pushedItem=>pushedItem.name!=item.name);225 };226 bodyRow.appendChild(deleteSpan);227 }228 }229 function upload(){230 pushedItems.forEach(pushedItem => {231 scanFiles(pushedItem, path);232 });233 }234 function uploadFile(key, file){235 s3.upload({236 Key: key,237 Body: file,238 ACL: 'public-read'239 }, function(err, data) {240 if (err) {241 return alert('There was an error uploading your file: ', err.message);242 }243 postOperation(false);244 });245 }246 function haveUploadItems(){247 return pushedItems.length!=0;248 }249 function postOperation(cancel){250 if ( counter-- == pushedItems.length ) {251 pushedItems.pop();252 }253 if ( cancel || counter == 0 ) {254 let tableBody = document.getElementById('upload-tbody');255 let items = document.querySelectorAll('#upload-tbody tr');256 pushedItems.splice(0, pushedItems.length);257 items.forEach(item=>{258 tableBody.removeChild(item);259 })260 document.getElementById("upload-modal-initial").style.display = "block";261 document.getElementById("upload-modal").style.display = "none";262 document.getElementById('upload-Modal').style.display = "none";263 finalize();264 if(!cancel){265 listFolder();266 }267 }268 }269 function addCounter(){270 counter++;271 }272273 initialize();274}275276function objectOps(){277 var pushedKeys;278 var cutKeys;279 var _remove;280 function initialize(){281 pushedKeys = [];282 cutKeys = [];283 _remove = false;284 objectOps.push = push;285 objectOps.pushAll = pushAll;286 objectOps.pushFolder = pushFolder;287 objectOps.createFolder = createFolder;288 objectOps.handle_createFolder = handle_createFolder;289 objectOps.cut = cut;290 objectOps.paste = paste;291 objectOps.remove = remove;292 objectOps.rename = rename;293 objectOps.clear = pushedKeys_Clear;294 objectOps.dropDown = dropDown;295 }296 function push(key){297 if(pushedKeys.includes(key))298 {299 if(key!=pushedKeys[0])300 {301 pushedKeys = pushedKeys.filter(pushedKey=>pushedKey!=key);302 }303 }304 else305 {306 pushedKeys.push(key);307 }308 }309 function pushAll(){310 let checked = document.getElementById('selectAllBoxes').checked;311 let all = document.querySelectorAll('input[type=checkbox]:not(#selectAllBoxes)');312 (Array.from(all)).map((box)=>{313 if(checked!=box.checked)314 {315 box.click();316 }317 });318 }319 function pushFolder(key){320 s3.listObjects({ Delimiter: '/', Prefix: key }, function(err, data) {321 data.CommonPrefixes.map(function(file){322 pushFolder(file.Prefix);323 });324 data.Contents.map(function(file) {325 push(file.Key);326 });327 });328 }329 function createFolder(key, upload){330 s3.headObject({Key: key}, function(err, data) {331 if(upload){332 uploadOps.addCounter();333 }334 else{335 if (!err) {336 return alert('Folder already exists.');
...
checkstyleUtil.js
Source:checkstyleUtil.js
...428 return fileName.substring(0, idx);429 }430 431 // Add a folder to the list of folders.432 function pushFolder(folderName){433 if(!allFolders[folderName]){434 allFolders[folderName] = true;435 json.push("{id: '" +(ids++) + "', file: '" + folderName + "', folder: 1}");436 }437 }438 439 for(i = 0; i < checkstyleUtil.errors.length; i++){440 err = checkstyleUtil.errors[i];441 var message = err.message;442 var messageId = messageIds[message];443 if(!messageId){444 messageId = "m" + messageCounter++;445 messageIds[message] = messageId;446 447 json.push("{id:'" + messageId + 448 "',msg:'" + message + 449 "'}");450 }451 }452 453 pushFolder("All");454 455 // Create the JSON records for each error.456 for(i = 0; i < checkstyleUtil.errors.length; i++){457 err = checkstyleUtil.errors[i];458 var folderName = getFolderName(err.file);459 pushFolder(folderName);460 461 json.push("{id:'" +(ids++) + 462 "', file:'" + err.file + 463 "',line:" + err.line + 464 ",msg:{'_reference':'" + messageIds[err.message] + 465 //"'},folder:'" + folderName +466 "'},folder: 0" +467 "}");468 469 }470 // Add the date that the check was run to the store.471 json.push("{id:'" +(ids++) + "', date: " +(new Date()).getTime() + "}");472 473 // Save the file....
User.spec.js
Source:User.spec.js
...82 })83 describe('pushFolder', () => {84 it('æ£å¸¸ã« Folder ã追å ã§ãã (Folder ã 0 â 1 ã®ã¨ã)', () => {85 const userObj = cloneDeep(demoUserObj)86 const expectUser = User.pushFolder(new User(userObj), cloneDeep(demoFolderObj))87 expect(userObj.attributes.folders).toHaveLength(0) // éç ´å£ã88 expect(expectUser).toBeInstanceOf(User) // Objectã«ãã£ã¹ãããã¦ããªãã89 expect(expectUser.folders).toHaveLength(1)90 expect(expectUser.folders[0]).toBeInstanceOf(Folder)91 })92 it('æ£å¸¸ã« Folder ã追å ã§ãã (Folder ã 1 â 2 ã®ã¨ã)', () => {93 const userObj = cloneDeep(demoUserObj)94 userObj.attributes.folders.push(cloneDeep(demoFolderObj)) // æåã«1ã¤ç®ã®Folderãå
¥ãã95 const expectUser = User.pushFolder(new User(userObj), cloneDeep(demoFolderObj2))96 expect(userObj.attributes.folders).toHaveLength(1) // éç ´å£ã97 expect(expectUser).toBeInstanceOf(User) // Objectã«ãã£ã¹ãããã¦ããªãã98 expect(expectUser.folders).toHaveLength(2)99 expect(expectUser.folders.every(v => Folder.isFolder(v))).toBeTruthy()100 })101 })102 describe('updatePost', () => {103 it('æ£å¸¸ã« Post ãæ´æ°ã§ãã', () => {104 const userObj = cloneDeep(demoUserObj)105 const postObj = cloneDeep(demoPostObj)106 // æåã«1ã¤ç®ã®Postãå
¥ãã107 const user = User.pushPost(new User(userObj), cloneDeep(demoPostObj))108 const updatePostObj = cloneDeep(demoPostObj)109 updatePostObj.attributes.name = "ããã¿ã«ã®æ稿ãæ´æ°"110 const expectUser = User.updatePost(user, postObj.id, updatePostObj)111 expect(user.posts).toHaveLength(1) // å
ã®Userã«å½±é¿ãä¸ãã¦ããªããã¨ã確èª112 expect(expectUser).toBeInstanceOf(User)113 expect(expectUser.posts).toHaveLength(1)114 expect(expectUser.posts[0]).toBeInstanceOf(Post)115 expect(expectUser.posts[0].name).toBe("ããã¿ã«ã®æ稿ãæ´æ°")116 })117 it('æå®ãã id ããªãã¨ããå
¥åå¤ãè¿å´ãã', () => {118 const userObj = cloneDeep(demoUserObj)119 const postObj = cloneDeep(demoPostObj)120 // æåã«1ã¤ç®ã®Postãå
¥ãã121 const user = User.pushPost(new User(userObj), postObj)122 const updatePostObj = cloneDeep(demoPostObj)123 updatePostObj.attributes.name = "ããã¿ã«ã®æ稿ãæ´æ°"124 const expectUser = User.updatePost(user, postObj.id + 1000, updatePostObj)125 expect(user.posts).toHaveLength(1) // å
ã®Userã«å½±é¿ãä¸ãã¦ããªããã¨ã確èª126 expect(expectUser).toBeInstanceOf(User)127 expect(expectUser.posts).toHaveLength(1)128 expect(expectUser.posts[0]).toBeInstanceOf(Post)129 expect(expectUser.posts[0].name).toBe(postObj.attributes.name)130 })131 })132 describe('updateFolder', () => {133 it('æ£å¸¸ã« Folder ãæ´æ°ã§ãã', () => {134 const userObj = cloneDeep(demoUserObj)135 // æåã«1ã¤ç®ã®Folderãå
¥ãã136 const user = User.pushFolder(new User(userObj), cloneDeep(demoFolderObj))137 const updateFolderObj = cloneDeep(demoFolderObj)138 updateFolderObj.attributes.name = "ããã¿ã«ã®ãã©ã«ãã¼ãæ´æ°"139 const expectUser = User.updateFolder(user, 1, updateFolderObj)140 expect(user.folders).toHaveLength(1) // å
ã®Userã«å½±é¿ãä¸ãã¦ããªããã¨ã確èª141 expect(expectUser).toBeInstanceOf(User)142 expect(expectUser.folders).toHaveLength(1)143 expect(expectUser.folders[0]).toBeInstanceOf(Folder)144 expect(expectUser.folders[0].name).toBe("ããã¿ã«ã®ãã©ã«ãã¼ãæ´æ°")145 })146 it('æå®ãã id ããªãã¨ããå
¥åå¤ãè¿å´ãã', () => {147 const userObj = cloneDeep(demoUserObj)148 const folderObj = cloneDeep(demoFolderObj)149 // æåã«1ã¤ç®ã®Postãå
¥ãã150 const user = User.pushFolder(new User(userObj), folderObj)151 const updateFolderObj = cloneDeep(demoFolderObj)152 updateFolderObj.attributes.name = "ããã¿ã«ã®ãã©ã«ãã¼ãæ´æ°"153 const expectUser = User.updatePost(user, folderObj.id + 1000, updateFolderObj)154 expect(user.folders).toHaveLength(1) // å
ã®Userã«å½±é¿ãä¸ãã¦ããªããã¨ã確èª155 expect(expectUser).toBeInstanceOf(User)156 expect(expectUser.folders).toHaveLength(1)157 expect(expectUser.folders[0]).toBeInstanceOf(Folder)158 expect(expectUser.folders[0].name).toBe(folderObj.attributes.name)159 })160 })161 describe('deletePost', () => {162 it('æ£å¸¸ã« Post ãåé¤ã§ãã', () => {163 const userObj = cloneDeep(demoUserObj)164 const postObj = cloneDeep(demoPostObj)165 // æåã«1ã¤ç®ã®Postãå
¥ãã166 const user = User.pushPost(new User(userObj), postObj)167 const expectUser = User.deletePost(user, postObj.id)168 expect(user.posts).toHaveLength(1) // å
ã®Userã«å½±é¿ãä¸ãã¦ããªããã¨ã確èª169 expect(expectUser).toBeInstanceOf(User)170 expect(expectUser.posts).toHaveLength(0)171 })172 it('æå®ãã id ããªãã¨ããå
¥åå¤ãè¿å´ãã', () => {173 const userObj = cloneDeep(demoUserObj)174 const postObj = cloneDeep(demoPostObj)175 // æåã«1ã¤ç®ã®Postãå
¥ãã176 const user = User.pushPost(new User(userObj), postObj)177 const expectUser = User.deletePost(user, postObj.id + 1000)178 expect(user.posts).toHaveLength(1) // å
ã®Userã«å½±é¿ãä¸ãã¦ããªããã¨ã確èª179 expect(expectUser).toBeInstanceOf(User)180 expect(expectUser.posts).toHaveLength(1)181 expect(expectUser.posts[0]).toBeInstanceOf(Post)182 })183 })184 describe('deleteFolder', () => {185 it('æ£å¸¸ã« Folder ãåé¤ã§ãã', () => {186 const userObj = cloneDeep(demoUserObj)187 const folderObj = cloneDeep(demoFolderObj)188 // æåã«1ã¤ç®ã®Folderãå
¥ãã189 const user = User.pushFolder(new User(userObj), folderObj)190 const expectUser = User.deleteFolder(user, folderObj.id)191 expect(user.folders).toHaveLength(1) // å
ã®Userã«å½±é¿ãä¸ãã¦ããªããã¨ã確èª192 expect(expectUser).toBeInstanceOf(User)193 expect(expectUser.folders).toHaveLength(0)194 })195 it('æå®ãã id ããªãã¨ããå
¥åå¤ãè¿å´ãã', () => {196 const userObj = cloneDeep(demoUserObj)197 const folderObj = cloneDeep(demoFolderObj)198 // æåã«1ã¤ç®ã®Folderãå
¥ãã199 const user = User.pushFolder(new User(userObj), folderObj)200 const expectUser = User.deleteFolder(user, folderObj.id + 1000)201 expect(user.folders).toHaveLength(1) // å
ã®Userã«å½±é¿ãä¸ãã¦ããªããã¨ã確èª202 expect(expectUser).toBeInstanceOf(User)203 expect(expectUser.folders).toHaveLength(1)204 expect(expectUser.folders[0]).toBeInstanceOf(Folder)205 })206 })...
mapper.js
Source:mapper.js
1var parseUrl = require ('url').parse,2 cradle = require ('cradle'),3 _ = require ('lodash'),4 EventEmitter = require ('events').EventEmitter,5 fs = require ('./fs'),6 Promises = require ('vow'),7 mime = require ('mime'),8 syncDelay = 4000;9function parseRev (rev) {10 return parseInt (rev.split ('-') [0] || 0);11}12function docFileName (doc) {13 var id = encodeURIComponent (doc._id.split ('/') [1]);14 return doc.title15 ? doc.title + ' (' + id + ')'16 : id;17}18module.exports = function (connstr, folder) {19 var parsed = parseUrl (connstr),20 auth = parsed.auth.split (':'),21 database = decodeURIComponent (parsed.path.substring (1));22 this.connection = new (cradle.Connection) (parsed.protocol + '//' + parsed.hostname, parsed.port, {23 cache: false,24 auth: {25 username: auth [0],26 password: auth [1]27 }28 });29 this.database = this.connection.database (database);30 this.folder = folder;31 this.cache = {};32};33_.extend (module.exports.prototype, EventEmitter.prototype);34_.extend (module.exports.prototype, {35 pushing: false, pulling: false,36 pull: function () {37 if (this.pulling || this.pushing) {38 return;39 } else {40 this.pulling = true;41 console.log ('pull');42 }43 var self = this;44 return this.fetchDocs ()45 .then (function (result) {46 return Promises.all (47 _.map (result, function (row) {48 return self.pullDoc (row.doc);49 })50 )51 })52 .always (function () {53 _.delay (function () {54 self.pulling = false;55 }, syncDelay);56 });57 },58 push: function () {59 if (this.pulling || this.pushing) {60 return;61 } else {62 console.log ('push')63 this.pushing = true;64 }65 var folder = this.folder,66 self = this;67 // Find all document folders68 return fs.readdir (folder)69 .then (function (list) {70 // For each found fs node71 return Promises.all (72 _.map (list, self.pushFolder)73 );74 })75 .always (function () {76 _.delay (function () {77 self.pushing = false;78 }, syncDelay);79 });80 },81 pushFolder: function (name, is_field) {82 var path = this.folder + '/' + name,83 self = this,84 singlePush = false;85 if (!this.pushing) {86 if (this.pulling) {87 return;88 } else {89 this.pushing = true;90 singlePush = true;91 }92 }93 // Check, if it's a folder94 return fs.stat (path)95 .then (function (stat) {96 if (!stat.isDirectory ()) return;97 // Get attachments from local fs98 return fs.scanfiles (path + '/_attachments')99 .then (function (files) {100 return self.assembleDocument (path, is_field)101 .then (function (doc) {102 // if (doc._attachments) {103 // delete doc._attachments;104 // }105 delete doc._rev;106 return self.saveDoc (doc)107 .then (function () {108 // Save each attachment one-by-one109 var save = function () {110 if (files.length) {111 var name = files.pop ();112 return self.saveAttachment (doc._id, name, path + '/_attachments/' + name)113 .then (save);114 }115 }116 return save ();117 })118 .fail (function (error) {119 console.error ('Failed to save doc', doc._id, error);120 });121 });122 });123 })124 .always (function () {125 if (singlePush) {126 _.delay (function () {127 self.pushing = false;128 }, syncDelay);129 }130 });131 },132 assembleDocument : function (path, is_field) { 133 if (is_field) {134 return fs.scanfiles (path + '/_fields')135 .then (function (files) {136 var doc = {};137 return Promises.all (138 _.map (files, function (field_file) {139 return fs.readFile (path + '/_fields/' + field_file)140 .then (function (buffer) {141 var value = buffer.toString ('utf-8');142 try {143 value = JSON.parse (value);144 } catch (e) {}145 doc [field_file.replace (/\.js$/, '')] = value;146 });147 })148 )149 .then (function () {150 return doc;151 });152 });153 } else {154 return fs.readFile (path + '/index.js')155 .then (function (buffer) {156 return JSON.parse (buffer.toString ('utf-8'));157 });158 }159 },160 saveDoc: function (doc) {161 var promise = Promises.promise (),162 cache = this.cache;163 this.database.save (doc, function (error, result) {164 if (error) {165 promise.reject (error);166 } else {167 cache [result.id] = result.rev;168 promise.fulfill (result);169 }170 });171 return promise;172 },173 watch: function () {174 return Promises.all ([175 this.watchDB (),176 this.watchFS ()177 ]);178 },179 watchDB: function () {180 var promise = Promises.promise (),181 database = this.database,182 self = this,183 cache = this.cache;184 database.info (function (error, result) {185 if (error) {186 promise.reject (error);187 } else {188 var feed = database.changes ({since: result.update_seq, include_docs: true});189 feed.on ('change', function (event) {190 if (!self.pulling && !self.pushing && self.cache [event.id]) {191 cache [event.id] = event.seq;192 193 var promise = self.pullDoc (event.doc);194 if (promise) {195 promise196 .fail (console.error)197 .done ();198 }199 200 }201 });202 promise.fulfill ();203 }204 });205 return promise;206 },207 watchFS: function () {208 var self = this;209 fs.watch (this.folder, function (event, path) {210 if (self.pushing || self.pulling) {211 return;212 }213 path = path.replace (/\\/g, '/');214 self.pushing = true;215 var is_field = Boolean(~ path.indexOf ('/_fields/'));216 var name = path.substring (self.folder.replace (/^\.\//, '').length + 1);217 name = name.substring (0, name.indexOf ('/'));218 self.pushFolder (name, is_field)219 .then (function () {220 console.log ('Pushed', name, 'because', path, 'has changed');221 }, function (error) {222 console.error ('Failed to push', path, error);223 })224 .always (function () {225 _.delay (function () {226 self.pushing = false;227 }, syncDelay);228 })229 .done ();230 });231 },232 pullDoc: function (doc) {233 var folder = this.folder + '/' + docFileName (doc),234 file = folder + '/index.js',235 self = this,236 singlePull = false;237 if (!this.pulling) {238 if (this.pushing) {239 return false;240 } else {241 this.pulling = true;242 singlePull = true;243 }244 }245 console.log ('Pull', doc._id);246 delete this.cache [doc._id];247 var stringify = function (doc) {248 var data = _.extend ({}, doc);249 delete data._rev;250 delete data._attachments;251 return JSON.stringify (data, null, '\t');252 };253 this.cache [doc._id] = doc._rev;254 return fs.mkdir (folder)255 .then (function () {256 return fs.writeFile (file, stringify (doc), 'utf8');257 })258 .then (function () {259 return fs.mkdir (folder + '/_fields');260 })261 .then (function () {262 return fs.readFile (folder + '/index.js')263 .then (function (buffer) {264 var doc = JSON.parse (buffer.toString ('utf-8')),265 fields_folder = folder + '/_fields/';266 return Promises.all (267 _.map (_.keys (doc), function (field) {268 var value = doc [field];269 if (typeof value == 'object') {270 value = JSON.stringify (value, null, '\t');271 }272 return fs.writeFile (fields_folder + field + '.js', value, 'utf8');273 })274 );275 })276 })277 .then (function () {278 return fs.mkdir (folder + '/_attachments');279 })280 .then (function () {281 return fs.scanfiles (folder + '/_attachments');282 })283 .then (function (list) {284 var needed = _.keys (doc._attachments),285 needless = _.difference (list, needed);286 return Promises.all (287 _.union (288 _.map (needless, function (name) {289 return fs.unlink (folder + '/_attachments/' + name);290 }),291 _.map (needed, function (name) {292 var path = folder + '/_attachments/' + name293 return self.getAttachment (doc._id, name)294 .then (function (buffer) {295 return fs.writeBuffer (path, buffer);296 })297 .fail (function (error) {298 console.error ('Could not get attachment', doc._id, name, error);299 });300 })301 )302 );303 })304 .then (function () {305 return self.getCurrentRevision (doc._id);306 })307 .then (function (rev) {308 self.cache [doc._id] = rev;309 })310 .always (function () {311 if (singlePull) {312 _.delay (function () {313 self.pulling = false;314 }, syncDelay);315 }316 });317 },318 fetchDocs: function (callback) {319 var promise = Promises.promise ();320 321 this.database.all ({startkey: 'a', include_docs: true}, function (error, result) {322 if (error) {323 promise.reject (error);324 } else {325 promise.fulfill (result);326 }327 });328 329 return promise;330 },331 getAttachment: function (id, name) {332 var promise = Promises.promise ();333 this.database.getAttachment (id, name, function (error, result) {334 if (error) {335 promise.reject (error);336 } else {337 promise.fulfill (result.body);338 }339 });340 return promise;341 },342 getCurrentRevision: function (id) {343 var promise = Promises.promise ();344 this.database.get (id, function (error, result) {345 if (error) {346 promise.reject (error);347 } else {348 promise.fulfill (result._rev);349 }350 });351 return promise;352 },353 saveAttachment: function (id, name, path) {354 var promise = Promises.promise (),355 cache = this.cache;356 fs.createReadStream (path).pipe (357 this.database.saveAttachment ({358 _id: id,359 _rev: this.cache [id]360 }, {361 name: name,362 'Content-Type': mime.lookup (path)363 }, function (error, result) {364 if (error) {365 promise.reject (error);366 } else {367 cache [id] = result.rev;368 promise.fulfill (result);369 }370 })371 );372 return promise;373 }...
exporter.js
Source:exporter.js
...14 },15 16 buildStructure: function() {17 this.feeds = app.user.createFeedContainer();18 this.feeds.pushFolder("Feeds");19 20 // Add Google Feeds21 if ( this.googleSubscription && this.googleSubscription.order && this.googleSubscription.order.root )22 this.googleSubscription.order.root.forEach(this.addGoogleOrderSubscription);23 24 this.nestedFolders = [];25 26 // Merge current structure into it27 app.user.structure.base.forEachItem(this.addCurrentItem);28 29 // Add nested folders to bottom folder30 this.nestedFolders.forEach(function(folder) {31 this.feeds.pushFolder(folder.name);32 folder.getFeeds().forEach(this.addCurrentFeed);33 this.feeds.popFolder();34 }, this);35 },36 37 addGoogleOrderSubscription: function(item) {38 if ( item.isFeed )39 this.addGoogleFeedSubscription(item);40 else41 this.addGoogleFolderSubscription(item);42 },43 44 addGoogleFeedSubscription: function(feed) {45 if ( ! feed.isFeed )46 return;47 48 this.feeds.addFeed({49 path: feed.href,50 guid: feed.id,51 link: feed.htmlUrl,52 title: feed.title,53 type: 'google'54 });55 },56 57 addGoogleFolderSubscription: function(folder) {58 var category = this.googleSubscription.order.categories.filter(function(a) {59 return a.id == folder.id;60 })[0];61 62 if ( ! category )63 return;64 65 this.feeds.pushFolder(folder.label);66 67 // Only add feeds since we can't have nested folders in Google Reader68 category.order.forEach(this.addGoogleFeedSubscription);69 70 this.feeds.popFolder();71 },72 73 addCurrentItem: function(item) {74 if ( item.isFeed )75 this.addCurrentFeed(item);76 else {77 // If in base folder (since we don't support nested folders)78 if ( this.feeds.base === this.feeds.currentFolder )79 this.addCurrentFolder(item);80 else81 this.addNestedFolder(item);82 }83 },84 85 addCurrentFeed: function(feed) {86 if ( this.feeds.currentFolder.feedBy('path', feed.path) )87 return;88 this.feeds.addFeed(feed);89 },90 91 addCurrentFolder: function(folder) {92 var folderInstance = this.feeds.currentFolder.folderBy('name', folder.name);93 94 this.feeds.pushFolder(folderInstance || folder.name);95 folder.items().forEach(this.addCurrentItem);96 this.feeds.popFolder();97 },98 99 addNestedFolder: function(folder) {100 this.nestedFolders.push(folder);101 folder.getFolders().forEach(this.addNestedFolder);102 }...
component.js
Source:component.js
1/*2 * @Author: Luoxd3 * @Description: 对ç»ä»¶çæ¹æ³4 * @Date: 2019-10-13 18:21:345 * @LastEditTime: 2020-03-02 15:32:466 * @LastEditors: Luoxd7 */8const fs = require('fs')9const generateTemplate = require('./codeTemplate')10/**11 * å°ç»ä»¶æå
¥å°æ件夹ï¼sql12 */13function pushFolder (connection, folderId, componentId) {14 connection.query(`SELECT * from folder_list WHERE folderId='${folderId}'`, (err, data) => {15 if (err) {16 console.log('æ¥æ¾æ件夹失败ï¼' + err)17 return18 }19 if (!data.length) {20 console.log('æªæ¾å°æ件夹')21 return22 }23 const componentIds = JSON.parse(data[0].componentIds)24 componentIds.push(componentId)25 connection.query(`UPDATE folder_list SET componentIds='${JSON.stringify(componentIds)}' WHERE folderId='${folderId}'`, (err) => {26 if (err) {27 console.log('æå
¥æ件夹失败ï¼' + err)28 return29 }30 })31 })32}33/**34 * æ¥è¯¢æ件夹ä¸çç»ä»¶35 */36function getFolderComponentList (connection, componentIds) {37 let sql = `SELECT componentId, componentName, componentImgUrl, componentDesc from component_list`38 componentIds.forEach((componentId, index) => {39 if (index === 0) {40 sql += ` Where componentId='${componentId}'`41 } else {42 sql += ` or componentId='${componentId}'`43 }44 })45 const promise = new Promise((resolve, reject) => {46 connection.query(sql, (err, data) => {47 if (err) {48 reject()49 }50 resolve(data)51 })52 })53 return promise54}55/**56 * çææ件57 */58function generateFiled (url, data, cb) {59 fs.writeFile(url, data, { encoding: 'utf-8' }, (err) => {60 typeof cb === 'function' ? cb(err) : null61 })62}63/**64 * çæ代ç 65 */66function generateCode (codeInfo, curId, status, layout, data) {67 let code = '', path = `assets/component/${curId}-${codeInfo.type}`68 try {69 fs.mkdirSync(path)70 } catch (err) {71 }72 switch(codeInfo.type) {73 case 'Vue':74 code = new generateTemplate.GenerateVueCode().init(layout, data)75 break76 case 'React':77 let formatCode = new generateTemplate.GenerateReactCode().init(layout, data)78 code = formatCode.html79 generateFiled(`${path}/style.css`, formatCode.css)80 break81 }82 generateFiled(`${path}/index${codeInfo.suffix}`, code)83 return code84}85const CODE_INFO = {86 React: {87 type: 'React',88 suffix: '.jsx'89 },90 Vue: {91 type: 'Vue',92 suffix: '.vue'93 }94}95module.exports = {96 generateCode,97 CODE_INFO,98 pushFolder,99 generateFiled,100 getFolderComponentList...
folder_history.js
Source:folder_history.js
...5 storage.put("folderHistoryArray", ha.serialize(), false);6 //}7}89function pushFolder(folder) {10 var ha = Object.deserialize(storage.get("folderHistoryArray"));11 if (ha == null)12 ha = new Array();13 14 ha.push(folder);15 storage.put("folderHistoryArray", ha.serialize(), false);16}1718function popFolder(folder) {19 var ha = Object.deserialize(storage.get("folderHistoryArray"));20 if (ha == null)21 ha = new Array();2223 if (ha.length > 0) {
...
Using AI Code Generation
1var wd = require('wd');2var assert = require('assert');3var serverConfig = {4};5var desiredCaps = {6};7var driver = wd.promiseChainRemote(serverConfig);8driver.init(desiredCaps)9 .then(function () {10 return driver.pushFolder('/Users/username/Documents/Apps/MyApp.app');11 })12 .then(function () {13 return driver.quit();14 })15 .done();16var wd = require('wd');17var assert = require('assert');18var serverConfig = {19};20var desiredCaps = {21};22var driver = wd.promiseChainRemote(serverConfig);23driver.init(desiredCaps)24 .then(function () {25 return driver.pullFolder('/Documents/Apps/MyApp.app');26 })27 .then(function () {28 return driver.quit();29 })30 .done();31var wd = require('wd');32var assert = require('assert');33var serverConfig = {34};35var desiredCaps = {36};37var driver = wd.promiseChainRemote(serverConfig);38driver.init(desiredCaps)39 .then(function () {
Using AI Code Generation
1var XCUITestDriver = require('appium-xcuitest-driver').XCUITestDriver;2var xCUITestDriver = new XCUITestDriver();3var driver = xCUITestDriver.createSession({4});5driver.pushFolder('/Users/username/Downloads/MyApp.app', '/Users/username/Downloads/MyApp.app');6driver.quit();7var XCUITestDriver = require('appium-xcuitest-driver').XCUITestDriver;8var xCUITestDriver = new XCUITestDriver();9var driver = xCUITestDriver.createSession({10});11driver.pushFile('/Users/username/Downloads/MyApp.app', '/Users/username/Downloads/MyApp.app');12driver.quit();13var XCUITestDriver = require('appium-xcuitest-driver').XCUITestDriver;14var xCUITestDriver = new XCUITestDriver();15var driver = xCUITestDriver.createSession({16});17driver.pullFolder('/Users/username/Downloads/MyApp.app', '/Users/username/Downloads/MyApp.app');18driver.quit();
Using AI Code Generation
1let { remote } = require('webdriverio');2let opts = {3 capabilities: {4 }5};6async function main () {7 let client = await remote(opts);8 await client.pushFolder('/Users/maheshkumar/Desktop/MyFolder', '/Documents/MyFolder');9 await client.deleteSession();10}11main();12let { remote } = require('webdriverio');13let opts = {14 capabilities: {15 }16};17async function main () {18 let client = await remote(opts);19 await client.pullFolder('/Documents/MyFolder', '/Users/maheshkumar/Desktop/MyFolder');20 await client.deleteSession();21}22main();23let { remote } = require('webdriverio');24let opts = {25 capabilities: {26 }27};28async function main () {29 let client = await remote(opts);30 await client.pushFile('/Documents/MyFolder/MyFile.txt', 'This is my file content');31 await client.deleteSession();32}33main();34let { remote } = require('webdriverio');35let opts = {36 capabilities: {
Using AI Code Generation
1const wd = require('wd');2const path = require('path');3const fs = require('fs');4const { exec } = require('child_process');5const { execSync } = require('child_process');6const { spawn } = require('child_process');7const { spawnSync } = require('child_process');8const { execFile } = require('child_process');9const { execFileSync } = require('child_process');10const { spawnFile } = require('child_process');11const { spawnFileSync } = require('child_process');12const { execFileSync } = require('child_process');13const { execFile } = require('child_process');14const { spawnFile } = require('child_process');15const { spawnFileSync } = require('child_process');16const app = require('./app.json');17const appPath = path.resolve(__dirname, app.path);18const appBundleId = app.bundleId;19const device = require('./device.json');20const deviceName = device.name;21const devicePlatformVersion = device.platformVersion;22const devicePlatformName = device.platformName;23const serverConfig = require('./serverConfig.json');24const serverHost = serverConfig.host;25const serverPort = serverConfig.port;26const pushFolder = require('./pushFolder.json');27const pushFolderName = pushFolder.name;28const pushFolderPath = path.resolve(__dirname, pushFolder.path);29const desiredCaps = {30};31const driver = wd.promiseChainRemote(serverHost, serverPort);32driver.on('status', function (info) {33 console.log('\x1b[36m%s\x1b[0m', info);34});35driver.on('command', function (meth, path, data) {36 console.log(' > \x1b[33m%s\x1b[0m: %s', meth, path, data || '');37});38driver.on('http', function
Using AI Code Generation
1const wd = require('wd');2const { exec } = require('child_process');3const { fs } = require('appium-support');4const { logger } = require('appium-support');5const chai = require('chai');6const chaiAsPromised = require('chai-as-promised');7const B = require('bluebird');8const { getSimulator } = require('appium-ios-simulator');9const { getDevices }
Using AI Code Generation
1try {2 await driver.pushFolder('/var/mobile/Containers/Data/Application/5A8F5A5D-DC5A-4B7C-8F8D-7F9F9B2D7E8B/Documents/Inbox', 'test');3} catch (e) {4 console.log(e);5}6try {7 await driver.pullFolder('/var/mobile/Containers/Data/Application/5A8F5A5D-DC5A-4B7C-8F8D-7F9F9B2D7E8B/Documents/Inbox');8} catch (e) {9 console.log(e);10}
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!