How to use no-restricted-imports to prevent any import file that starts with underline (_) - eslint

I'm trying to prevent any import from "private files" that are specified by prefixing them with an underscore.
As an example, I would like to prevent importing file patters as follows:
import {foo} from '_file';
import {foo} from './_file';
import {foo} from './dialog/_file';
import {foo} from '#alias_root/src/framework/dialog/_file';
To do so, I've used the following rules:
{
'no-restricted-imports': ['error', {
patterns: [{
group: ['_*'],
message: 'Import files starting with an underline are private',
}],
}],
}
Unfortunately this does not seem to catch all the cases I would like to prevent and I'm wondering what I'm missing or how to exactly use this rule.

Related

React app start error due to react refresh

So I am trying run a react app locally that was originally developed on windows, on my system which is running Ubuntu 18.04. I use npm install --legacy-peer-deps as suggested by the original developer and the run npm start/npm run start. I encounter the following error from a whole bunch of files,
ERROR in ./src/components/ui/Task/Template/ReturnHomeTemplate.js
1:40-111 Module not found: Error: You attempted to import
/home/praneet/SevenHub/node_modules/react-refresh/runtime.js which
falls outside of the project src/ directory. Relative imports outside
of src/ are not supported. You can either move it inside src/, or add
a symlink to it from project's node_modules/.
In most of the files, the first line is
import React from "react";
and in some files it's not even that. Apparently the app does not use react-refresh explicitly anywhere.
There are warnings with npm install, but I was told that I can safely ignore them and don't have to audit fix them (I am new to react so I am not sure). I have tried reinstalling various node versions, removing node_modules and package-lock.json but am still unsuccessful in resolving the issue. Any pointers on this would be great, and happy to provide more information if necessary.
A few files where the error is thrown from for reference:
Index.js
import React from "react";
import ReactDOM from "react-dom";
import App from "./components/App";
import Header from "./components/ui/Header";
import { WorldProvider } from "./components/ui/ToolContext";
import { ROSProvider } from "./components/RosContext";
import { DndProvider } from "react-dnd";
import { HTML5Backend } from "react-dnd-html5-backend";
import UniversMap from "./components/ui/UniversMap/UniversMap";
import { Login } from "./components/ui/Login/Login";
import { FormantProvider } from "#formant/ui-sdk";
ReactDOM.render(
<WorldProvider>
<DndProvider backend={HTML5Backend}>
{/* <Login /> */}
<FormantProvider>
<App />
</FormantProvider>
</DndProvider>
</WorldProvider>,
document.getElementById("root")
);
Navigation.js
import React from "react";
import LiveTvSharpIcon from "#material-ui/icons/LiveTvSharp";
import EditSharpIcon from "#material-ui/icons/EditSharp";
import BorderHorizontalSharpIcon from "#material-ui/icons/BorderHorizontalSharp";
import StreetViewSharpIcon from "#material-ui/icons/StreetviewSharp";
import EqualizerSharpIcon from "#material-ui/icons/EqualizerSharp";
import ListAltSharpIcon from "#material-ui/icons/ListAltSharp";
import TodayOutlinedIcon from "#material-ui/icons/TodayOutlined";
import robotIcon from "../../assets/robotlogo.png";
import MapOutlinedIcon from "#material-ui/icons/MapOutlined";
import TaskItem from "./Taskitem";
import TaskTabs from "./../ui/TaskTabs";
import RobotList from "./Robots/RobotList";
import { userDemoData } from "./User/Users";
import Users from "./User/Users";
const routes = [
"/dashboard",
"/robots",
"/maps",
"/tasks",
"/users",
"/settings",
"/newmap",
];
const taskTabs = [{ id: 1 }];
const dashboardMappings = {
Live: <LiveTvSharpIcon />,
Layout: <EditSharpIcon />,
test: <EditSharpIcon />,
Zones: <BorderHorizontalSharpIcon />,
Streams: <StreetViewSharpIcon />,
Stats: <EqualizerSharpIcon />,
Logs: <ListAltSharpIcon />,
};
const taskList = [
{ id: 1, task: "sort", user: "A" },
{ id: 2, task: "Collaboration", user: "B" },
{ id: 3, task: "queue", user: "C" },
];
const robotList = [
{ id: 1, name: "Robot1" },
{ id: 2, name: "Robot2" },
];
const drawerMappings = {
dashboard: dashboardMappings,
robots: {
list: [<RobotList />],
icon: <img src={robotIcon} style={{ maxWidth: "24px" }} />,
active: [],
},
maps: {
list: ["Map1", "Map2", "Map3", "Map4"],
icon: <MapOutlinedIcon />,
active: [],
},
tasks: {
list: [<TaskTabs />], //taskTabs.map((item) => <TaskTabs />),
active: [],
},
// tasks: {
// list: taskList.map((item) => (
// <TaskItem task={item.task} id={item.id} user={item.user} />
// )),
// icon: <TodayOutlinedIcon />,
// disabled: true,
// active: [],
// },
users: {
list: [<Users />],
icon: <MapOutlinedIcon />,
active: [],
},
};
export { routes, dashboardMappings, drawerMappings, robotList };
It's hard to provide you with a proper solution, but we can investigate. Try these 3 things:
I) Reinstall node.
Remove node_modules, package-lock.json, yarn.lock (if you have it) from your project. Clear cache (npm cache clean --force).
Completely remove node from your computer (How to completely remove node.js from Windows).
Install node. Try the one that you have now (I may assume that the problem is not related to the node version).
Install packages in your project.
II) Issue with the path
Remove the line import robotIcon from "../../assets/robotlogo.png";. The error is related to importing the data outside of ./src directory, maybe the issue is here. If the number of errors will decrease, please, let me know.
III) Replace:
ReactDOM.render(
<WorldProvider>
<DndProvider backend={HTML5Backend}>
{/* <Login /> */}
<FormantProvider>
<App />
</FormantProvider>
</DndProvider>
</WorldProvider>,
document.getElementById("root")
);
with
ReactDOM.render(
<div>text</div>,
document.getElementById("root")
);
If the errors are left, provide the list. If the errors disappeared, try:
ReactDOM.render(
<WorldProvider>
<DndProvider backend={HTML5Backend}>
<FormantProvider>
<div>text</div>
</FormantProvider>
</DndProvider>
</WorldProvider>,
document.getElementById("root")
);
Removing the parts of the code, you will localize the error(s).
Also:
Provide the contents of the files where the errors appear (UniversMap.tsx, UserDetails.js, etc). So far, just index.js and Navigation.js are provided, they don't have the errors following your screenshot and they are less useful rather than files with the errors.
Text of all errors including the details provided with the number of the errors (not on a screenshot, but in a text format).

unable to initialize snowflake data source

I am trying to access the snowflake datasource using "great_expectations" library.
The following is what I tried so far:
from ruamel import yaml
import great_expectations as ge
from great_expectations.core.batch import BatchRequest, RuntimeBatchRequest
context = ge.get_context()
datasource_config = {
"name": "my_snowflake_datasource",
"class_name": "Datasource",
"execution_engine": {
"class_name": "SqlAlchemyExecutionEngine",
"connection_string": "snowflake://myusername:mypass#myaccount/myDB/myschema?warehouse=mywh&role=myadmin",
},
"data_connectors": {
"default_runtime_data_connector_name": {
"class_name": "RuntimeDataConnector",
"batch_identifiers": ["default_identifier_name"],
},
"default_inferred_data_connector_name": {
"class_name": "InferredAssetSqlDataConnector",
"include_schema_name": True,
},
},
}
print(context.test_yaml_config(yaml.dump(datasource_config)))
I initiated great_expectation before executing above code:
great_expectations init
but I am getting the error below:
great_expectations.exceptions.exceptions.DatasourceInitializationError: Cannot initialize datasource my_snowflake_datasource, error: 'NoneType' object has no attribute 'create_engine'
What am I doing wrong?
Your configuration seems to be ok, corresponding to the example here.
If you look at the traceback you should notice that the error propagates starting at the file great_expectations/execution_engine/sqlalchemy_execution_engine.py in your virtual environment.
The actual line where the error occurs is:
self.engine = sa.create_engine(connection_string, **kwargs)
And if you search for that sa at the top of that file:
import sqlalchemy as sa
make_url = import_make_url()
except ImportError:
sa = None
So sqlalchemy is not installed, which you
don't get automatically in your environement if you install greate_expectiations. The thing to do is to
install snowflake-sqlalchemy, since you want to use sqlalchemy's snowflake
plugin (assumption based on your connection_string).
/your/virtualenv/bin/python -m pip install snowflake-sqlalchemy
After that you should no longer get an error, it looks like test_yaml_config is waiting for the connection
to time out.
What worries me greatly is the documented use of a deprecated API of ruamel.yaml.
The function ruamel.yaml.dump is going to be removed in the near future, and you
should use the .dump() method of a ruamel.yaml.YAML() instance.
You should use the following code instead:
import sys
from ruamel.yaml import YAML
import great_expectations as ge
context = ge.get_context()
datasource_config = {
"name": "my_snowflake_datasource",
"class_name": "Datasource",
"execution_engine": {
"class_name": "SqlAlchemyExecutionEngine",
"connection_string": "snowflake://myusername:mypass#myaccount/myDB/myschema?warehouse=mywh&role=myadmin",
},
"data_connectors": {
"default_runtime_data_connector_name": {
"class_name": "RuntimeDataConnector",
"batch_identifiers": ["default_identifier_name"],
},
"default_inferred_data_connector_name": {
"class_name": "InferredAssetSqlDataConnector",
"include_schema_name": True,
},
},
}
yaml = YAML()
yaml.dump(datasource_config, sys.stdout, transform=context.test_yaml_config)
I'll make a PR for great-excpectations to update their documentation/use of ruamel.yaml.

eslint no-restricted-imports - prevent an import from from path ending with pattern

According to the eslint no-restricted-imports documentation
When using the object form, you can also specify an array of
gitignore-style patterns:
"no-restricted-imports": ["error", {
"paths": ["import1", "import2"],
"patterns": ["import1/private/*", "import2/*", "!import2/good"] }]
(Emphasis mine)
What I'm trying to do is restrict imports from parent index files - as this is causing issues with cyclical dependencies (I am also using the import/no-cycle rule, but it makes sense to also explicitly use this rule.)
That is, I want to ban imports like:
import foo from "../..";
import bar from "../../..";
I also want to ban imports like:
import a from "../Components";
but not like
import b from "../Components/Foo";
I have tried using this rule:
'no-restricted-imports': [
'error',
{
patterns: [
'**/..',
'**/Components'
]
},
But this causes on errors on imports of:
import b from "../Components/Foo";
Is there a way to specify 'end of string' in a gitignore style pattern?
First, make sure you don't have set import/no-relative-parent-imports, or any ../ import would fail.
Second, if this really follows .gitignore rules, you cannot have rules for folders (like **/.. or **/Components).
Because, once you ignore a folder, any other rule for elements inside that folder would be ignored.
Try:
'no-restricted-imports': [
'error',
{
patterns: [
'**/../*',
'!**/../Components',
'**/../Components/*',
'!**/../Components/Foo',
]
},

Expected 'multiple' syntax before 'single' syntax

I am trying to import files like this but getting error: Expected 'multiple' syntax before 'single' syntax
import { Component, Prop, Vue } from 'vue-property-decorator';
import { getModule } from 'vuex-module-decorators';
import { ApiException, IProduct, IProductCategory } from '#/services'; // error here
import { INavs } from '#/types';
Rule config:
'sort-imports': ['error', {
'ignoreCase': false,
'ignoreDeclarationSort': false,
'ignoreMemberSort': false,
'memberSyntaxSortOrder': ['none', 'all', 'multiple', 'single']
}]
import { ApiException, IProduct, IProductCategory } from '#/services'; is importing multiple (three) exports.
Both import { getModule } from 'vuex-module-decorators'; and import { INavs } from '#/types'; are only importing a single named export.
That error will go way if you move import { ApiException, IProduct, IProductCategory } up one line so it's above the single imports.
This is configured in your settings where it says 'memberSyntaxSortOrder': ['none', 'all', 'multiple', 'single'] because 'multiple' is listed before 'single'.
You can read more about it in the eslint documentation here https://eslint.org/docs/rules/sort-imports
Ran into this too looking for a CI solution for reordering multiple imports, since ESLint --fix only supports multiple members on a single line; i.e. autofixing unsupported when spread over multiple lines - e.g. from a low Prettier printWidth of ~80.
eslint-plugin-simple-import-sort works great, fixed the errors after amending config from the docs:
Make sure not to use other sorting rules at the same time:
[sort-imports]
[import/order]
To resolve this issue I'll recommend modifying your .eslintrc.json setting
"sort-imports": ["error", {
"ignoreCase": false,
"ignoreDeclarationSort": false,
"ignoreMemberSort": false,
"memberSyntaxSortOrder": ["none", "all", "multiple", "single"],
"allowSeparatedGroups": false // <-- Change this to true
}],
Which prevents you from reordering local imports and third party imports that are in different groups but violate the memberSyntaxSortOrder as earlier suggested

How using Vim alphabetically sort JS es6 imports

I use vim as IDE for typescript project.
import { FlightInfo } from './FlightInfo'
import { InfoBlockProps, InfoRowProps, INavigationFlightOfferDataProps } from './interfaces'
import { getDiscountData, formatDataByServicesType, selectAdministrationFee } from './functions'
Also, I use ts-lint rule for check sorting:
...
ordered-imports": [
true,
{
"import-sources-order": "lowercase-first",
"named-imports-order": "lowercase-first"
}
],
...
And get errors:
ERROR: 11:1 ordered-imports Import sources within a group must be alphabetized.
ERROR: 11:10 ordered-imports Named imports must be alphabetized.
ERROR: 12:1 ordered-imports Import sources within a group must be alphabetized.
ERROR: 12:10 ordered-imports Named imports must be alphabetized.
I am searching for a solution or plugin for fix this sorting errors.
In this situation, for me very well works ts-lint --fix -c ./ts-congig.json my-file.ts command.

Resources