From 7902fcd296ee076c80ec41b9a8e7835a76f0defc Mon Sep 17 00:00:00 2001 From: Johnathan Martin Date: Thu, 1 Aug 2019 14:22:06 -0700 Subject: [PATCH 01/16] remove unnecessary await statement (fix issue #2) --- src/getGroupRDF.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/getGroupRDF.js b/src/getGroupRDF.js index 7492011..34d9ed6 100644 --- a/src/getGroupRDF.js +++ b/src/getGroupRDF.js @@ -48,7 +48,8 @@ const getResourceTextFromServer = async(groupName, resourceName) => { const saveResourceTextFromServer = async(savePathString, groupName, resourceName) => { - await fs.writeFileSync(`${savePathString}/${resourceName}`, (await getResourceTextFromServer(groupName, resourceName))) + // alternatively, could await https://nodejs.org/api/fs.html#fs_fspromises_writefile_file_data_options + fs.writeFileSync(`${savePathString}/${resourceName}`, (await getResourceTextFromServer(groupName, resourceName))) } const downloadAllRdfForGroup = async (groupName) => { From 691c8b4177a7fe0a3031aff897d862e40daf5bed Mon Sep 17 00:00:00 2001 From: Johnathan Martin Date: Thu, 1 Aug 2019 14:25:16 -0700 Subject: [PATCH 02/16] fix map statement to save entity RDF to correct filename, and to return an array of promises resulting from saveResourceTextFromServer calls (instead of undefined) (fix issue #3) --- src/getGroupRDF.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/getGroupRDF.js b/src/getGroupRDF.js index 34d9ed6..00beb04 100644 --- a/src/getGroupRDF.js +++ b/src/getGroupRDF.js @@ -58,7 +58,7 @@ const downloadAllRdfForGroup = async (groupName) => { savePathString = getSavePathString(groupName) fs.mkdirSync(savePathString) - await Promise.all(entityNames.map((entityName) => { saveResourceTextFromServer(savePathString, groupName, entityNames) })) + await Promise.all(entityNames.map((entityName) => saveResourceTextFromServer(savePathString, groupName, entityName))) const completionMsg = `completed export of ${groupName} at ${getDateString()}` fs.writeFileSync(`${savePathString}/complete.log`, completionMsg) From a287c1c160ed8e66dd0925756b000682bd5624de Mon Sep 17 00:00:00 2001 From: Johnathan Martin Date: Thu, 1 Aug 2019 14:25:49 -0700 Subject: [PATCH 03/16] add copyright statement and LICENSE file (fixes #5) --- LICENSE | 52 ++++++++++++++++++++++++++++++++++++++++++++++ src/getGroupRDF.js | 2 ++ 2 files changed, 54 insertions(+) create mode 100644 LICENSE diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..133cf6d --- /dev/null +++ b/LICENSE @@ -0,0 +1,52 @@ +Apache License + +Version 2.0, January 2004 + +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + +"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: + + You must give any other recipients of the Work or Derivative Works a copy of this License; and + You must cause any modified files to carry prominent notices stating that You changed the files; and + You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and + If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. + + You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. diff --git a/src/getGroupRDF.js b/src/getGroupRDF.js index 00beb04..7b320b8 100644 --- a/src/getGroupRDF.js +++ b/src/getGroupRDF.js @@ -1,3 +1,5 @@ +// Copyright 2019 Stanford University see LICENSE for license + const fs = require('fs'); const path = require('path'); const SinopiaServer = require('sinopia_server') From cf83dcb004a7e68e886bd68e1e04f62e1b19fd7b Mon Sep 17 00:00:00 2001 From: Johnathan Martin Date: Thu, 1 Aug 2019 14:51:55 -0700 Subject: [PATCH 04/16] add config package dependency, along with default configuration --- config/default.json | 5 +++++ package-lock.json | 18 ++++++++++++++++++ package.json | 1 + 3 files changed, 24 insertions(+) create mode 100644 config/default.json diff --git a/config/default.json b/config/default.json new file mode 100644 index 0000000..2d8dba1 --- /dev/null +++ b/config/default.json @@ -0,0 +1,5 @@ +{ + "trellis": { + "basePath": "https://trellis.sinopia.io" + } +} diff --git a/package-lock.json b/package-lock.json index 4bc4601..3b0f660 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1888,6 +1888,24 @@ "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=", "dev": true }, + "config": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/config/-/config-3.2.2.tgz", + "integrity": "sha512-rOsfIOAcG82AWouK4/vBS/OKz3UPl2T/kP0irExmXJJOoWg2CmdfPLdx56bCoMUMFNh+7soQkQWCUC8DyemiwQ==", + "requires": { + "json5": "^1.0.1" + }, + "dependencies": { + "json5": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/json5/-/json5-1.0.1.tgz", + "integrity": "sha512-aKS4WQjPenRxiQsC93MNfjx+nbF4PAdYzmd/1JIj8HYzqfbu86beTuNgXDzPknWk0n0uARlyewZo4s++ES36Ow==", + "requires": { + "minimist": "^1.2.0" + } + } + } + }, "contains-path": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/contains-path/-/contains-path-0.1.0.tgz", diff --git a/package.json b/package.json index 3a343f6..315b366 100644 --- a/package.json +++ b/package.json @@ -26,6 +26,7 @@ "@babel/node": "^7.5.5", "@babel/preset-env": "^7.5.5", "@babel/runtime": "^7.5.5", + "config": "^3.2.2", "sinopia_server": "^3.0.0-beta5" }, "devDependencies": { From 5d687c2f575fcade9c12d397b32d03d1c0db5972 Mon Sep 17 00:00:00 2001 From: Johnathan Martin Date: Thu, 1 Aug 2019 16:51:00 -0700 Subject: [PATCH 05/16] make the export functionality more easily runnable as a single command (fixes #4) --- .babelrc | 8 ++++++++ bin/export | 3 +++ src/cli/exportAndSave.js | 31 +++++++++++++++++++++++++++++++ src/getGroupRDF.js | 37 +++++++++---------------------------- 4 files changed, 51 insertions(+), 28 deletions(-) create mode 100644 .babelrc create mode 100755 bin/export create mode 100644 src/cli/exportAndSave.js diff --git a/.babelrc b/.babelrc new file mode 100644 index 0000000..de77da7 --- /dev/null +++ b/.babelrc @@ -0,0 +1,8 @@ +{ + "presets": [ + "@babel/preset-env" + ], + "plugins": [ + "@babel/plugin-transform-runtime", + ] +} \ No newline at end of file diff --git a/bin/export b/bin/export new file mode 100755 index 0000000..60c62a5 --- /dev/null +++ b/bin/export @@ -0,0 +1,3 @@ +#!/usr/bin/env bash + +npx babel-node src/cli/exportAndSave.js $@ diff --git a/src/cli/exportAndSave.js b/src/cli/exportAndSave.js new file mode 100644 index 0000000..3dab112 --- /dev/null +++ b/src/cli/exportAndSave.js @@ -0,0 +1,31 @@ +// Copyright 2019 Stanford University see LICENSE for license + +import sinopiaExporter from '../../package' +import { downloadAllRdfForGroup } from '../getGroupRDF' + + +const helpText = ` +> ./bin/export 'ucdavis' + +and you should end up with something like: + +$ tree sinopia_export/ +sinopia_export/ +└── ucdavis_2019-07-26T01:41:00.002Z + ├── 0c9895ff-9470-4c70-bee4-b791ee179b34 + └── complete.log + +each RDF resource will have its own file. complete.log will be written at the end of a successful run. +` + + +console.debug(`arguments: ${process.argv}`) +console.info(`sinopia_exporter v${sinopiaExporter.version}`) + + +const groupName = process.argv[2] +if(groupName) { + downloadAllRdfForGroup(groupName) +} else { + console.error(helpText) +} diff --git a/src/getGroupRDF.js b/src/getGroupRDF.js index 7b320b8..3c93adc 100644 --- a/src/getGroupRDF.js +++ b/src/getGroupRDF.js @@ -1,12 +1,14 @@ // Copyright 2019 Stanford University see LICENSE for license -const fs = require('fs'); -const path = require('path'); -const SinopiaServer = require('sinopia_server') +import fs from 'fs' +import path from 'path' +import config from 'config' +import SinopiaServer from 'sinopia_server' -instance = new SinopiaServer.LDPApi() -instance.apiClient.basePath = 'https://trellis.sinopia.io' +const instance = new SinopiaServer.LDPApi() +instance.apiClient.basePath = config.get('trellis.basePath') +console.info(`Sinopia Server base URL: ${instance.apiClient.basePath}`) const resourceToName = (uri) => { @@ -54,10 +56,10 @@ const saveResourceTextFromServer = async(savePathString, groupName, resourceName fs.writeFileSync(`${savePathString}/${resourceName}`, (await getResourceTextFromServer(groupName, resourceName))) } -const downloadAllRdfForGroup = async (groupName) => { +export const downloadAllRdfForGroup = async (groupName) => { const entityNames = await listGroupRdfEntityNames(groupName) - savePathString = getSavePathString(groupName) + const savePathString = getSavePathString(groupName) fs.mkdirSync(savePathString) await Promise.all(entityNames.map((entityName) => saveResourceTextFromServer(savePathString, groupName, entityName))) @@ -66,24 +68,3 @@ const downloadAllRdfForGroup = async (groupName) => { fs.writeFileSync(`${savePathString}/complete.log`, completionMsg) console.log(completionMsg) } - -/* -TODO: make this something that's usable in a single invocation from the command line. - -for now, open a node console, paste the above code in, and then do something like the following: -> downloadPromise = downloadAllRdfForGroup('ucdavis') - -and you should end up with something like: - -$ tree sinopia_export/ -sinopia_export/ -└── ucdavis_2019-07-26T01:41:00.002Z - ├── 0c9895ff-9470-4c70-bee4-b791ee179b34 - └── complete.log - -each RDF resource will have its own file. complete.log will be written at the end of a successful run. - -also TODO: any error handling at all! -*/ - - From 5a2176ca6df57c7212403af42bd69470cb015ac1 Mon Sep 17 00:00:00 2001 From: Johnathan Martin Date: Fri, 2 Aug 2019 17:28:14 -0700 Subject: [PATCH 06/16] start adding tests (connects to #6) * add test scripts to package.json * make getGroupRDF.js more testable by lazily instantiating the sinopia server client, to make mocking it easier * add a test for the basic success case of getResourceTextFromServer, using a mock instance of the sinopia server client to avoid the need for network interactions --- __tests__/getGroupRDF.test.js | 23 +++++++++++++++++++++++ package.json | 5 ++++- src/getGroupRDF.js | 21 +++++++++++++++------ 3 files changed, 42 insertions(+), 7 deletions(-) create mode 100644 __tests__/getGroupRDF.test.js diff --git a/__tests__/getGroupRDF.test.js b/__tests__/getGroupRDF.test.js new file mode 100644 index 0000000..0f3b45b --- /dev/null +++ b/__tests__/getGroupRDF.test.js @@ -0,0 +1,23 @@ +import * as getGroupRDF from '../src/getGroupRDF' +import SinopiaServer from 'sinopia_server' + +const mockSinopiaClient = jest.fn() +mockSinopiaClient.getGroupWithHttpInfo = jest.fn() +mockSinopiaClient.getResourceWithHttpInfo = jest.fn() +mockSinopiaClient.apiClient = jest.fn() //TODO: test that .basePath gets set correctly on this + +jest.spyOn(SinopiaServer, 'LDPApi').mockImplementation(() => mockSinopiaClient) + +describe('getGroupRDF', () => { + describe('getResourceTextFromServer', () => { + it('retrieves the specified resource from the server and returns the RDF as text', async () => { + const groupResources = { 'group1': ['resource1', 'resource2', 'resource3'] } + const resourceContent = { 'resource1': 'resource1content', 'resource2': 'resource2content', 'resource3': 'resource3content' } + + mockSinopiaClient.getGroupWithHttpInfo = async (groupName) => { return (!groupResources[groupName] ? null : { response: { body: {contains: resourceList } } }) } + mockSinopiaClient.getResourceWithHttpInfo = async (groupName, resourceName) => { return (!groupResources[groupName] ? null : { response: { text: resourceContent[resourceName] } }) } + + expect(await getGroupRDF.getResourceTextFromServer('group1', 'resource2')).toEqual('resource2content') + }) + }) +}) diff --git a/package.json b/package.json index 315b366..b10961b 100644 --- a/package.json +++ b/package.json @@ -3,7 +3,10 @@ "version": "0.1.0", "description": "Export RDF entities from a group in Sinopia Server (Sinopia's particular configuration of trellis-ext-db)", "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" + "jest-cov": "jest --coverage --colors --silent --runInBand", + "jest-ci": "jest --colors --silent --ci --runInBand --coverage --reporters=default --reporters=jest-junit && cat ./coverage/lcov.info | coveralls", + "test": "jest --colors --silent --runInBand --detectOpenHandles", + "test-verbose": "jest --colors --runInBand" }, "engines": { "node": "10.12.x" diff --git a/src/getGroupRDF.js b/src/getGroupRDF.js index 3c93adc..2d4510c 100644 --- a/src/getGroupRDF.js +++ b/src/getGroupRDF.js @@ -6,9 +6,18 @@ import config from 'config' import SinopiaServer from 'sinopia_server' -const instance = new SinopiaServer.LDPApi() -instance.apiClient.basePath = config.get('trellis.basePath') -console.info(`Sinopia Server base URL: ${instance.apiClient.basePath}`) +var clientInstance = null + +// lazy instantiation of the client makes mocking its behavior easier +export const sinopiaClient = () => { + if(!clientInstance) { + clientInstance = new SinopiaServer.LDPApi() + clientInstance.apiClient.basePath = config.get('trellis.basePath') + console.debug(`Sinopia Server client lazily instantiated. base URL: ${clientInstance.apiClient.basePath}`) + } + + return clientInstance +} const resourceToName = (uri) => { @@ -27,7 +36,7 @@ const getSavePathString = (groupName) => { const listGroupRdfEntityUris = async (groupName) => { - const groupResponse = await instance.getGroupWithHttpInfo(groupName) + const groupResponse = await sinopiaClient().getGroupWithHttpInfo(groupName) if(!groupResponse.response.body.contains) { return } @@ -42,10 +51,10 @@ const listGroupRdfEntityNames = async (groupName) => { const getRdfResourceFromServer = async (groupName, resourceName, accept = 'application/ld+json') => { // TODO: do we need to do any error handling in case we request a resource that's not RDF? - return await instance.getResourceWithHttpInfo(groupName, resourceName, { accept }) + return await sinopiaClient().getResourceWithHttpInfo(groupName, resourceName, { accept }) } -const getResourceTextFromServer = async(groupName, resourceName) => { +export const getResourceTextFromServer = async(groupName, resourceName) => { return (await getRdfResourceFromServer(groupName, resourceName)).response.text } From dbbe381a7cd1930fd31964f0b975026b1002d028 Mon Sep 17 00:00:00 2001 From: Johnathan Martin Date: Sun, 4 Aug 2019 18:18:35 -0700 Subject: [PATCH 07/16] test getGroupRDF.sinopiaClient() --- __tests__/getGroupRDF.test.js | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/__tests__/getGroupRDF.test.js b/__tests__/getGroupRDF.test.js index 0f3b45b..96e8b76 100644 --- a/__tests__/getGroupRDF.test.js +++ b/__tests__/getGroupRDF.test.js @@ -1,14 +1,21 @@ +import config from 'config' import * as getGroupRDF from '../src/getGroupRDF' import SinopiaServer from 'sinopia_server' const mockSinopiaClient = jest.fn() mockSinopiaClient.getGroupWithHttpInfo = jest.fn() mockSinopiaClient.getResourceWithHttpInfo = jest.fn() -mockSinopiaClient.apiClient = jest.fn() //TODO: test that .basePath gets set correctly on this +mockSinopiaClient.apiClient = jest.fn() jest.spyOn(SinopiaServer, 'LDPApi').mockImplementation(() => mockSinopiaClient) describe('getGroupRDF', () => { + describe('sinopiaClient', () => { + it('returns a client that is properly configured', () => { + expect(getGroupRDF.sinopiaClient().apiClient.basePath).toEqual(config.get('trellis.basePath')) + }) + }) + describe('getResourceTextFromServer', () => { it('retrieves the specified resource from the server and returns the RDF as text', async () => { const groupResources = { 'group1': ['resource1', 'resource2', 'resource3'] } From fc92916f6a1be747628e6b7aa8418b833da7c693 Mon Sep 17 00:00:00 2001 From: Johnathan Martin Date: Sun, 4 Aug 2019 23:47:54 -0700 Subject: [PATCH 08/16] make export base directory configurable, and don't assume it exists already. add unit test specific config. --- config/default.json | 3 ++- config/test.json | 6 ++++++ src/getGroupRDF.js | 13 +++++++++---- 3 files changed, 17 insertions(+), 5 deletions(-) create mode 100644 config/test.json diff --git a/config/default.json b/config/default.json index 2d8dba1..2d34cb9 100644 --- a/config/default.json +++ b/config/default.json @@ -1,5 +1,6 @@ { "trellis": { "basePath": "https://trellis.sinopia.io" - } + }, + "exportBasePath": "./exported_rdf" } diff --git a/config/test.json b/config/test.json new file mode 100644 index 0000000..02e8a61 --- /dev/null +++ b/config/test.json @@ -0,0 +1,6 @@ +{ + "trellis": { + "basePath": "https://trellis.sinopia.test" + }, + "exportBasePath": "./test_exported_rdf" +} diff --git a/src/getGroupRDF.js b/src/getGroupRDF.js index 2d4510c..a31c03f 100644 --- a/src/getGroupRDF.js +++ b/src/getGroupRDF.js @@ -30,8 +30,14 @@ const getDateString = () => { return (new Date()).toISOString() } -const getSavePathString = (groupName) => { - return `./sinopia_export/${groupName}_${getDateString()}/` +const initAndGetSavePath = (groupName) => { + // the { recursive: true } option did not work for me with mkdirSync (JM), so DIYing it + if(!fs.existsSync(config.get('exportBasePath'))) + fs.mkdirSync(config.get('exportBasePath')) + + const savePathString = `${config.get('exportBasePath')}/${groupName}_${getDateString()}` + fs.mkdirSync(savePathString) + return savePathString } @@ -68,8 +74,7 @@ const saveResourceTextFromServer = async(savePathString, groupName, resourceName export const downloadAllRdfForGroup = async (groupName) => { const entityNames = await listGroupRdfEntityNames(groupName) - const savePathString = getSavePathString(groupName) - fs.mkdirSync(savePathString) + const savePathString = initAndGetSavePath(groupName) await Promise.all(entityNames.map((entityName) => saveResourceTextFromServer(savePathString, groupName, entityName))) From d8fb11b9c83219d1e0fd75a9d3fa3cb9f44f076c Mon Sep 17 00:00:00 2001 From: Johnathan Martin Date: Sun, 4 Aug 2019 23:51:47 -0700 Subject: [PATCH 09/16] add test for basic success case of getGroupRDF.downloadAllRdfForGroup() pull up some mockSinopiaClient setup code that can be shared from a prior test, and import fs functions --- __tests__/getGroupRDF.test.js | 43 ++++++++++++++++++++++++++++------- 1 file changed, 35 insertions(+), 8 deletions(-) diff --git a/__tests__/getGroupRDF.test.js b/__tests__/getGroupRDF.test.js index 96e8b76..71c6f57 100644 --- a/__tests__/getGroupRDF.test.js +++ b/__tests__/getGroupRDF.test.js @@ -1,11 +1,15 @@ import config from 'config' +import fs from 'fs' import * as getGroupRDF from '../src/getGroupRDF' import SinopiaServer from 'sinopia_server' +const groupResources = { 'group1': ['resource1', 'resource2', 'resource3'] } +const resourceContent = { 'resource1': 'resource1content', 'resource2': 'resource2content', 'resource3': 'resource3content' } + const mockSinopiaClient = jest.fn() -mockSinopiaClient.getGroupWithHttpInfo = jest.fn() -mockSinopiaClient.getResourceWithHttpInfo = jest.fn() -mockSinopiaClient.apiClient = jest.fn() +mockSinopiaClient.apiClient = jest.fn() // need this field present so sinopiaClient() function can set .basePath on it. +mockSinopiaClient.getGroupWithHttpInfo = async (groupName) => { return (!groupResources[groupName] ? null : { response: { body: {contains: groupResources[groupName] } } }) } +mockSinopiaClient.getResourceWithHttpInfo = async (groupName, resourceName) => { return (!groupResources[groupName] ? null : { response: { text: resourceContent[resourceName] } }) } jest.spyOn(SinopiaServer, 'LDPApi').mockImplementation(() => mockSinopiaClient) @@ -18,13 +22,36 @@ describe('getGroupRDF', () => { describe('getResourceTextFromServer', () => { it('retrieves the specified resource from the server and returns the RDF as text', async () => { - const groupResources = { 'group1': ['resource1', 'resource2', 'resource3'] } - const resourceContent = { 'resource1': 'resource1content', 'resource2': 'resource2content', 'resource3': 'resource3content' } + expect(await getGroupRDF.getResourceTextFromServer('group1', 'resource2')).toEqual('resource2content') + }) + }) - mockSinopiaClient.getGroupWithHttpInfo = async (groupName) => { return (!groupResources[groupName] ? null : { response: { body: {contains: resourceList } } }) } - mockSinopiaClient.getResourceWithHttpInfo = async (groupName, resourceName) => { return (!groupResources[groupName] ? null : { response: { text: resourceContent[resourceName] } }) } + describe('downloadAllRdfForGroup', () => { + it('retrieves the RDF resources for the specified group, and saves the RDF text (on file per resource, in a dated sub-directory)', async () => { + const dlDateLowerBound = new Date() + await getGroupRDF.downloadAllRdfForGroup('group1') + const dlDateUpperBound = new Date() - expect(await getGroupRDF.getResourceTextFromServer('group1', 'resource2')).toEqual('resource2content') + // assume we just want the latest output dir in the export base dir, since we should be the only ones writing there + const exportBaseDirContents = fs.readdirSync(`./${config.get('exportBasePath')}`) + const groupDirName = exportBaseDirContents[exportBaseDirContents.length-1] + + // RDF for group exported to subdirectory with name like 'group1_2019-08-05T01:34:13.143Z' + const groupDirDate = new Date(/^group1_(.*)$/.exec(groupDirName)[1]) + // .toBeGreaterThan and .toBeLessThan only work for numbers + expect(dlDateLowerBound < groupDirDate && groupDirDate < dlDateUpperBound).toBeTruthy() + + const groupDirPath = `./${config.get('exportBasePath')}/${groupDirName}` + const groupDirContents = fs.readdirSync(groupDirPath) + expect(groupDirContents).toEqual(['complete.log', 'resource1', 'resource2', 'resource3']) + + expect(fs.readFileSync(`${groupDirPath}/resource1`).toString()).toEqual('resource1content') + expect(fs.readFileSync(`${groupDirPath}/resource2`).toString()).toEqual('resource2content') + expect(fs.readFileSync(`${groupDirPath}/resource3`).toString()).toEqual('resource3content') + const completionLogText = fs.readFileSync(`${groupDirPath}/complete.log`).toString() + // completion log text should have date, should fall between group dir creation and downloadAllRdfForGroup resolving + const completionLogDate = new Date(/^completed export of group1 at (.*)$/.exec(completionLogText)[1]) + expect(groupDirDate <= completionLogDate && completionLogDate <= dlDateUpperBound).toBeTruthy() }) }) }) From b384e8074ce8f0d91e08b023157202bc7c4ed589 Mon Sep 17 00:00:00 2001 From: Johnathan Martin Date: Mon, 5 Aug 2019 11:25:42 -0700 Subject: [PATCH 10/16] add eslint scripts and configuration, clean up a bit of lint discovered by eslint --- .eslintrc.js | 77 ++++++++++++++++++++++++++++++++++++++++++++++ package.json | 3 ++ src/getGroupRDF.js | 1 - 3 files changed, 80 insertions(+), 1 deletion(-) create mode 100644 .eslintrc.js diff --git a/.eslintrc.js b/.eslintrc.js new file mode 100644 index 0000000..01b5e98 --- /dev/null +++ b/.eslintrc.js @@ -0,0 +1,77 @@ +// Copyright 2019 Stanford University see Apache2.txt for license +module.exports = { + plugins: [ + "import", + "jest", + "security" + ], + extends: [ + "eslint:recommended", + "plugin:node/recommended", + "plugin:import/errors", + "plugin:import/warnings", + "plugin:security/recommended", + "plugin:jest/recommended" + ], + env: { + "es6": true, + "jest": true, + "node": true + }, + parserOptions: { + ecmaVersion: 2019, + sourceType: "module" + }, + overrides: [ + { + "files": ["src/**/*.js", + "__mocks__/**/*.js", + "__tests__/**/*.js"], + "rules": { + // Indent `case` statements within `switch` blocks + "indent": ["error", 2, { + "SwitchCase": 1 + }], + // See https://github.com/mysticatea/eslint-plugin-node/blob/master/docs/rules/no-unsupported-features/es-syntax.md + // rule supposedly matches ECMA version with node + // we get: "Import and export declarations are not supported yet" + "node/no-unsupported-features/es-syntax": "off", + // Avoiding: "warning Found fs.readFileSync with non literal argument ..." + "security/detect-non-literal-fs-filename": "off", + // Avoiding: "warning Found non-literal argument to RegExp Constructor" + "security/detect-non-literal-regexp": "off", + // this is a CLI tool; we DO want to send output to console + "no-console": "off", + // allow unused variables that begin with underscore + "no-unused-vars": [ + "error", + { + "argsIgnorePattern": "^_" + } + ] + } + }, + { + // We aren't concerned about this in our tests, see: + // https://github.com/nodesecurity/eslint-plugin-security#detect-object-injection + // https://github.com/nodesecurity/eslint-plugin-security/blob/master/docs/the-dangers-of-square-bracket-notation.md + // https://security.stackexchange.com/questions/170648/variable-assigned-to-object-injection-sink-security-detect-object-injection + // specifically, the variables in square brackets do not come from user input + files: [ + '__tests__/**/*.js' + ], + rules: { + 'security/detect-object-injection': 'off', + } + }, + { + // Allow skipped tests in test suite + files: [ + '__tests__/**/*.js' + ], + rules: { + 'jest/no-disabled-tests': 'off', + } + } + ] +} diff --git a/package.json b/package.json index b10961b..d9be83a 100644 --- a/package.json +++ b/package.json @@ -3,6 +3,9 @@ "version": "0.1.0", "description": "Export RDF entities from a group in Sinopia Server (Sinopia's particular configuration of trellis-ext-db)", "scripts": { + "eslint": "eslint --max-warnings 5 --color -c .eslintrc.js --ext js,jsx .", + "eslint-fix": "eslint --max-warnings 5 --color -c .eslintrc.js --ext js,jsx --fix .", + "eslint-fix-single": "eslint --color -c .eslintrc.js --fix", "jest-cov": "jest --coverage --colors --silent --runInBand", "jest-ci": "jest --colors --silent --ci --runInBand --coverage --reporters=default --reporters=jest-junit && cat ./coverage/lcov.info | coveralls", "test": "jest --colors --silent --runInBand --detectOpenHandles", diff --git a/src/getGroupRDF.js b/src/getGroupRDF.js index a31c03f..9ff0bdb 100644 --- a/src/getGroupRDF.js +++ b/src/getGroupRDF.js @@ -1,7 +1,6 @@ // Copyright 2019 Stanford University see LICENSE for license import fs from 'fs' -import path from 'path' import config from 'config' import SinopiaServer from 'sinopia_server' From b444c03f75221c599add5d302674be09a18add52 Mon Sep 17 00:00:00 2001 From: Johnathan Martin Date: Mon, 5 Aug 2019 11:30:37 -0700 Subject: [PATCH 11/16] add circleci configuration --- .circleci/config.yml | 61 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 .circleci/config.yml diff --git a/.circleci/config.yml b/.circleci/config.yml new file mode 100644 index 0000000..c2afcc0 --- /dev/null +++ b/.circleci/config.yml @@ -0,0 +1,61 @@ +# Copyright 2019 Stanford University see LICENSE file +# CircleCI 2.0 configuration file + +defaults: &defaults + docker: + - image: circleci/node:10.15.3 + working_directory: ~/sinopia_exporter + +version: 2 +jobs: + dependencies: + <<: *defaults + steps: + - run: + name: update-npm + command: 'sudo npm install -g npm@5' + - checkout + - restore_cache: + key: dependency-cache-prod-{{ checksum "package.json" }} + - run: npm install --only=production + - save_cache: + key: dependency-cache-prod-{{ checksum "package.json" }} + paths: + - node_modules + - restore_cache: + key: dependency-cache-ci-{{ checksum "package.json" }} + - run: npm install # including CI/Test dependencies + - save_cache: + key: dependency-cache-ci-{{ checksum "package.json" }} + paths: + - node_modules + build: + <<: *defaults + steps: + - checkout + - setup_remote_docker + - restore_cache: + key: dependency-cache-ci-{{ checksum "package.json" }} + - run: + name: Run linter (eslint) + command: npm run eslint + - run: + name: Setup Code Climate test-reporter + command: | + curl -L https://codeclimate.com/downloads/test-reporter/test-reporter-latest-linux-amd64 > ./cc-test-reporter + chmod +x ./cc-test-reporter + - run: + name: Run jest unit tests + command: | + ./cc-test-reporter before-build + npm run jest-ci + ./cc-test-reporter after-build --exit-code $? + +workflows: + version: 2 + build: + jobs: + - dependencies + - build: + requires: + - dependencies From 727724504fcddb17189c628736091a3192d9d718 Mon Sep 17 00:00:00 2001 From: Johnathan Martin Date: Mon, 5 Aug 2019 16:20:33 -0700 Subject: [PATCH 12/16] improved help text and logging --- src/cli/exportAndSave.js | 24 ++++++++++++++++-------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/src/cli/exportAndSave.js b/src/cli/exportAndSave.js index 3dab112..7f0584e 100644 --- a/src/cli/exportAndSave.js +++ b/src/cli/exportAndSave.js @@ -5,27 +5,35 @@ import { downloadAllRdfForGroup } from '../getGroupRDF' const helpText = ` -> ./bin/export 'ucdavis' +Invoke the bin/export script with the name of the group to be exported +as a parameter. E.g. to export RDF for the ucdavis group: -and you should end up with something like: +$ ./bin/export 'ucdavis' -$ tree sinopia_export/ -sinopia_export/ -└── ucdavis_2019-07-26T01:41:00.002Z +...which should leave you with output like: + +$ tree exported_rdf/ +exported_rdf/ +└── ucdavis_2019-08-05T23:11:54.601Z ├── 0c9895ff-9470-4c70-bee4-b791ee179b34 └── complete.log -each RDF resource will have its own file. complete.log will be written at the end of a successful run. +* The output will land in the configured exportBasePath (defaults to + './exported_rdf'), in a subdirectory named for the exported group and + the time at which the export was run. +* Each RDF resource will have its own file (named for the resource). +* complete.log will be written at the end of a successful run. ` -console.debug(`arguments: ${process.argv}`) console.info(`sinopia_exporter v${sinopiaExporter.version}`) - const groupName = process.argv[2] if(groupName) { + console.info(`beginning export of RDF from group: ${groupName}`) downloadAllRdfForGroup(groupName) + console.info(`finished export of RDF from group: ${groupName}`) } else { console.error(helpText) + console.error('\nIt appears that no group name was specified.') } From 496323286f8a753117a3dee5bc657f1baf268afa Mon Sep 17 00:00:00 2001 From: Johnathan Martin Date: Mon, 5 Aug 2019 16:21:05 -0700 Subject: [PATCH 13/16] bump version --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index d9be83a..d0862a4 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "sinopia_exporter", - "version": "0.1.0", + "version": "0.2.0", "description": "Export RDF entities from a group in Sinopia Server (Sinopia's particular configuration of trellis-ext-db)", "scripts": { "eslint": "eslint --max-warnings 5 --color -c .eslintrc.js --ext js,jsx .", From 0ae846557e2de6d5399355a4b816547d89b336b4 Mon Sep 17 00:00:00 2001 From: Johnathan Martin Date: Mon, 5 Aug 2019 17:19:05 -0700 Subject: [PATCH 14/16] fix jest-cov and jest-ci script defs --- package.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index d0862a4..e94a76f 100644 --- a/package.json +++ b/package.json @@ -6,8 +6,8 @@ "eslint": "eslint --max-warnings 5 --color -c .eslintrc.js --ext js,jsx .", "eslint-fix": "eslint --max-warnings 5 --color -c .eslintrc.js --ext js,jsx --fix .", "eslint-fix-single": "eslint --color -c .eslintrc.js --fix", - "jest-cov": "jest --coverage --colors --silent --runInBand", - "jest-ci": "jest --colors --silent --ci --runInBand --coverage --reporters=default --reporters=jest-junit && cat ./coverage/lcov.info | coveralls", + "jest-cov": "jest --colors --coverage --runInBand", + "jest-ci": "jest --colors --ci --coverage --runInBand", "test": "jest --colors --silent --runInBand --detectOpenHandles", "test-verbose": "jest --colors --runInBand" }, From 1e9eaf5c9e4c6f8b60913e2eeda1874aaff78087 Mon Sep 17 00:00:00 2001 From: Johnathan Martin Date: Mon, 5 Aug 2019 23:19:49 -0700 Subject: [PATCH 15/16] add copyright statement --- __tests__/getGroupRDF.test.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/__tests__/getGroupRDF.test.js b/__tests__/getGroupRDF.test.js index 71c6f57..a6eb7a1 100644 --- a/__tests__/getGroupRDF.test.js +++ b/__tests__/getGroupRDF.test.js @@ -1,3 +1,5 @@ +// Copyright 2019 Stanford University see LICENSE for license + import config from 'config' import fs from 'fs' import * as getGroupRDF from '../src/getGroupRDF' From b75240f640b96011bb671fa979d6531c1d9e6120 Mon Sep 17 00:00:00 2001 From: Johnathan Martin Date: Mon, 5 Aug 2019 23:29:54 -0700 Subject: [PATCH 16/16] prevent flappy test results while files are written too quicly --- __tests__/getGroupRDF.test.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/__tests__/getGroupRDF.test.js b/__tests__/getGroupRDF.test.js index a6eb7a1..a42a736 100644 --- a/__tests__/getGroupRDF.test.js +++ b/__tests__/getGroupRDF.test.js @@ -41,7 +41,7 @@ describe('getGroupRDF', () => { // RDF for group exported to subdirectory with name like 'group1_2019-08-05T01:34:13.143Z' const groupDirDate = new Date(/^group1_(.*)$/.exec(groupDirName)[1]) // .toBeGreaterThan and .toBeLessThan only work for numbers - expect(dlDateLowerBound < groupDirDate && groupDirDate < dlDateUpperBound).toBeTruthy() + expect(dlDateLowerBound <= groupDirDate && groupDirDate <= dlDateUpperBound).toBeTruthy() const groupDirPath = `./${config.get('exportBasePath')}/${groupDirName}` const groupDirContents = fs.readdirSync(groupDirPath)