import.js (3422B)
1 const csv = require("csv"); 2 const fs = require("fs"); 3 4 const { createIssue } = require("./helpers.js"); 5 6 const importFile = (octokit, file, values) => { 7 fs.readFile(file, "utf8", (err, data) => { 8 if (err) { 9 console.error("Error reading file."); 10 process.exit(1); 11 } 12 csv.parse( 13 data, 14 { 15 trim: true, 16 bom: true, 17 delimiter: values.csvDelimiter, 18 }, 19 (err, csvRows) => { 20 if (err) throw err; 21 const cols = csvRows[0].map((col) => col.toLowerCase()); 22 csvRows.shift(); 23 24 // get indexes of the fields we need 25 const titleIndex = cols.indexOf("title"); 26 const bodyIndex = cols.indexOf("body"); 27 const labelsIndex = cols.indexOf("labels"); 28 const milestoneIndex = cols.indexOf("milestone"); 29 const assigneeIndex = cols.indexOf("assignee"); 30 const stateIndex = cols.indexOf("state"); 31 32 if (titleIndex === -1) { 33 console.error("Title required by GitHub, but not found in CSV."); 34 process.exit(1); 35 } 36 const createPromises = csvRows.map((row) => { 37 const sendObj = { 38 issue: {}, 39 }; 40 41 sendObj.issue.title = row[titleIndex]; 42 43 // if we have a body column, pass that. 44 if (bodyIndex > -1 && row[bodyIndex] !== "") { 45 sendObj.issue.body = row[bodyIndex]; 46 } 47 48 // if we have a labels column, pass that. 49 if (labelsIndex > -1 && row[labelsIndex] !== "") { 50 sendObj.issue.labels = row[labelsIndex].split(","); 51 } 52 53 // if we have a milestone column, pass that. 54 if (milestoneIndex > -1 && row[milestoneIndex] !== "") { 55 sendObj.issue.milestone = Number(row[milestoneIndex]); 56 } 57 58 // if we have an assignee column, pass that. 59 if (assigneeIndex > -1 && row[assigneeIndex] !== "") { 60 sendObj.issue.assignee = row[assigneeIndex]; 61 } 62 63 if (stateIndex > -1 && row[stateIndex].toLowerCase() === "closed") { 64 sendObj.issue.closed = true; 65 } 66 return createIssue( 67 octokit, 68 sendObj, 69 values.userOrOrganization, 70 values.repo 71 ); 72 }); 73 74 Promise.all(createPromises).then( 75 (res) => { 76 const successes = res.filter((cr) => { 77 return ( 78 cr.status === 200 || cr.status === 201 || cr.status === 202 79 ); 80 }); 81 const fails = res.filter((cr) => { 82 return ( 83 cr.status !== 200 && cr.status !== 201 && cr.status !== 202 84 ); 85 }); 86 87 console.log( 88 `Created ${successes.length} issues, and had ${fails.length} failures.` 89 ); 90 console.log( 91 "❤ ❗ If this project has provided you value, please ⭐ star the repo to show your support: ➡ https://github.com/gavinr/github-csv-tools" 92 ); 93 94 if (fails.length > 0) { 95 console.error("ERROR - some of the imports have failed"); 96 console.log(fails); 97 } 98 99 process.exit(0); 100 }, 101 (err) => { 102 console.error("Error"); 103 console.error(err); 104 process.exit(0); 105 } 106 ); 107 } 108 ); 109 }); 110 }; 111 112 module.exports = { importFile };