Repository: conan-io/conan

Issue:
Error when trying to read the `conanfile.txt`
In our Jenkins-system, jenkins created a projectdirectory, that contains an "@". After we generated the conanfile.txt, we cannot run conan, cause it doesn't find the "@ folder=True" at the end of the line.

The conanfile.txt parser, splits at the first "@" and when we habe an "@" in our directory name, the parsing fails.

Example:
/home/jenkins/workspace/conan_test@2/conanfile.txt
```
[generators]
cmake

[requires]
OpenSSL/1.1.1@conan/stable

[options]
OpenSSL:shared=True
OpenSSL:no_zlib=True

[imports]
"., LICENSE -> /home/jenkins/workspace/conan_test@2/install/licenses @ folder=True"
lib, * -> /home/jenkins/workspace/conan_test@2/g/install/lib
bin, * -> /home/jenkins/workspace/conan_test@2/install/bin
include, * -> /home/jenkins/workspace/conan_test@2/install/include
```

Run conan install:
`conan install . -g cmake -s build_type=Debug -s os=Linux -s arch=x86_64 -s compiler=gcc -s compiler.version=7 -s compiler.libcxx=libstdc++11 --build=missing`

Error:
ERROR: Invalid imports line: "., LICENSE -> /home/jenkins/workspace/conan_test@2/install/licenses @ folder=True"
EX: OpenCV/lib, * -> ./lib
Invalid imports. Unknown argument 2install/licenses @ folder


Code with error:
/conans/client/loader_txt.py:
https://github.com/conan-io/conan/blob/ab15630bf0675eb2b787b4aaad8f79a53b3580f6/conans/client/loader_txt.py#L75

Possible Solution:
Split it at the last "@" if possible or ignore things, that are inside `"` or `'`.


Discussion:

Patch:
diff --git a/conans/client/build/cmake.py b/conans/client/build/cmake.py
index f6f2727ce..b9dc3c6e8 100644
--- a/conans/client/build/cmake.py
+++ b/conans/client/build/cmake.py
@@ -45,6 +45,8 @@ class CMake(object):
         self._cmake_program = os.getenv("CONAN_CMAKE_PROGRAM") or cmake_program or "cmake"
 
         self.generator = generator or get_generator(conanfile.settings)
+        if not self.generator:
+            self._conanfile.output.warn("CMake generator could not be deduced from settings")
         self.parallel = parallel
         # Initialize definitions (won't be updated if conanfile or any of these variables change)
         builder = CMakeDefinitionsBuilder(self._conanfile,
diff --git a/conans/client/build/cmake_flags.py b/conans/client/build/cmake_flags.py
index f3df58ec3..2bc7dbb09 100644
--- a/conans/client/build/cmake_flags.py
+++ b/conans/client/build/cmake_flags.py
@@ -36,7 +36,8 @@ def get_generator(settings):
 
     if not compiler or not compiler_version or not arch:
         if os_build == "Windows":
-            return "MinGW Makefiles"
+            logger.warning("CMake generator could not be deduced from settings")
+            return None
         return "Unix Makefiles"
 
     if compiler == "Visual Studio":
@@ -64,6 +65,8 @@ def get_generator(settings):
 
 
 def is_multi_configuration(generator):
+    if not generator:
+        return False
     return "Visual" in generator or "Xcode" in generator
 
 
diff --git a/conans/client/loader_txt.py b/conans/client/loader_txt.py
index 1462684a0..75ba25e2f 100644
--- a/conans/client/loader_txt.py
+++ b/conans/client/loader_txt.py
@@ -8,7 +8,8 @@ class ConanFileTextLoader(object):
     def __init__(self, input_text):
         # Prefer composition over inheritance, the __getattr__ was breaking things
         self._config_parser = ConfigParser(input_text,  ["requires", "generators", "options",
-                                                         "imports", "build_requires"], parse_lines=True)
+                                                         "imports", "build_requires"],
+                                           parse_lines=True)
 
     @property
     def requirements(self):
@@ -33,8 +34,13 @@ class ConanFileTextLoader(object):
         def _parse_args(param_string):
             root_package, ignore_case, folder, excludes, keep_path = None, False, False, None, True
             params = param_string.split(",")
-            params = [p.split("=") for p in params if p]
-            for (var, value) in params:
+            params = [p.strip() for p in params if p.strip()]
+            for param in params:
+                try:
+                    var, value = param.split("=")
+                except ValueError:
+                    raise ConanException("Wrong imports argument '%s'. "
+                                         "Need a 'arg=value' pair." % param)
                 var = var.strip()
                 value = value.strip()
                 if var == "root_package":
@@ -52,11 +58,15 @@ class ConanFileTextLoader(object):
             return root_package, ignore_case, folder, excludes, keep_path
 
         def _parse_import(line):
-            pair = line.split("->")
-            source = pair[0].strip().split(',', 1)
-            dest = pair[1].strip()
-            src, pattern = source[0].strip(), source[1].strip()
-            return pattern, dest, src
+            try:
+                pair = line.split("->", 1)
+                source = pair[0].strip().split(',', 1)
+                dest = pair[1].strip()
+                src, pattern = source[0].strip(), source[1].strip()
+                return pattern, dest, src
+            except Exception:
+                raise ConanException("Wrong imports line: %s\n"
+                                     "Use syntax: path, pattern -> local-folder" % line)
 
         ret = []
         local_install_text = self._config_parser.imports
@@ -72,7 +82,7 @@ class ConanFileTextLoader(object):
                 raise ConanException("%s\n%s" % (invalid_line_msg,
                                                  "Import's paths can't begin with '/' or '..'"))
             try:
-                tokens = line.split("@", 1)
+                tokens = line.rsplit("@", 1)
                 if len(tokens) > 1:
                     line = tokens[0]
                     params = tokens[1]
@@ -80,7 +90,8 @@ class ConanFileTextLoader(object):
                     params = ""
                 root_package, ignore_case, folder, excludes, keep_path = _parse_args(params)
                 pattern, dest, src = _parse_import(line)
-                ret.append((pattern, dest, src, root_package, folder, ignore_case, excludes, keep_path))
+                ret.append((pattern, dest, src, root_package, folder, ignore_case, excludes,
+                            keep_path))
             except Exception as e:
                 raise ConanException("%s\n%s" % (invalid_line_msg, str(e)))
         return ret


Test patch:
diff --git a/conans/test/functional/build_helpers/cmake_flags_test.py b/conans/test/functional/build_helpers/cmake_flags_test.py
index 4254e085a..dcb11c5a0 100644
--- a/conans/test/functional/build_helpers/cmake_flags_test.py
+++ b/conans/test/functional/build_helpers/cmake_flags_test.py
@@ -1,10 +1,12 @@
 import os
 import platform
 import unittest
+from textwrap import dedent
 
 from nose.plugins.attrib import attr
 from parameterized.parameterized import parameterized
 
+from conans import load
 from conans.client.build.cmake import CMake
 from conans.model.version import Version
 from conans.test.utils.tools import TestClient
@@ -431,3 +433,39 @@ conan_basic_setup()
         client.save({"CMakeLists.txt": tmp, "conanfile.py": conanfile}, clean_first=True)
         client.run("create . user/channel -o MyLib:fPIC=True")
         self.assertNotIn("Conan: Adjusting fPIC flag", client.out)
+
+    def header_only_generator_test(self):
+        """ Test cmake.install() is possible although Generetaor could not be deduced from
+        settings
+        """
+        conanfile = dedent("""
+        from conans import ConanFile, CMake
+
+        class TestConan(ConanFile):
+            name = "kk"
+            version = "1.0"
+            exports = "*"
+
+            def package(self):
+                cmake = CMake(self)
+                self.output.info("Configure command: %s" % cmake.command_line)
+                cmake.configure()
+                cmake.install()
+        """)
+        cmakelists = dedent("""
+        cmake_minimum_required(VERSION 3.3)
+        project(test)
+
+        install(DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/include"
+            DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}")
+        """)
+        client = TestClient()
+        client.save({"conanfile.py": conanfile, "CMakeLists.txt": cmakelists, "include/file.h": ""})
+        client.run("create . danimtb/testing")
+        if platform.system() == "Windows":
+            self.assertIn("WARN: CMake generator could not be deduced from settings", client.out)
+            self.assertIn('Configure command: -DCONAN_EXPORTED="1" -DCONAN_IN_LOCAL_CACHE="ON" '
+                          '-DCMAKE_INSTALL_PREFIX=', client.out)
+        else:
+            self.assertIn('Configure command: -G "Unix Makefiles" -DCONAN_EXPORTED="1" '
+                          '-DCONAN_IN_LOCAL_CACHE="ON" -DCMAKE_INSTALL_PREFIX=', client.out)
diff --git a/conans/test/functional/conanfile/imports_tests.py b/conans/test/functional/conanfile/imports_tests.py
index 85e7bb473..f521364fb 100644
--- a/conans/test/functional/conanfile/imports_tests.py
+++ b/conans/test/functional/conanfile/imports_tests.py
@@ -97,6 +97,46 @@ LibC/0.1@lasote/testing
         self.assertEqual(load(os.path.join(client.current_folder, "licenses/LibC/license.txt")),
                          "LicenseC")
 
+    def imports_wrong_args_txt_test(self):
+        client = TestClient()
+        conanfile = """
+[imports]
+., license* -> lic@myfolder @ something
+"""
+        client.save({"conanfile.txt": conanfile})
+        client.run("install .", assert_error=True)
+        self.assertIn("Wrong imports argument 'something'. Need a 'arg=value' pair.", client.out)
+
+    def imports_wrong_line_txt_test(self):
+        client = TestClient()
+        conanfile = """
+[imports]
+., license*
+"""
+        client.save({"conanfile.txt": conanfile})
+        client.run("install .", assert_error=True)
+        self.assertIn("Wrong imports line: ., license*", client.out)
+        self.assertIn("Use syntax: path, pattern -> local-folder", client.out)
+
+    def imports_folders_extrachars_txt_test(self):
+        # https://github.com/conan-io/conan/issues/4524
+        client = self._set_up()
+
+        conanfile = """[requires]
+LibC/0.1@lasote/testing
+[imports]
+., license* -> lic@myfolder @ folder=True, ignore_case=True, excludes=*.md # comment
+., *.md -> lic@myfolder @ # This is mandatory, otherwise it will fail
+"""
+        client.save({"conanfile.txt": conanfile}, clean_first=True)
+        client.run("install . --build=missing")
+        self.assertEqual(load(os.path.join(client.current_folder, "lic@myfolder/LibA/LICENSE.txt")),
+                         "LicenseA")
+        self.assertEqual(load(os.path.join(client.current_folder, "lic@myfolder/LICENSE.md")),
+                         "LicenseB")
+        self.assertEqual(load(os.path.join(client.current_folder, "lic@myfolder/LibC/license.txt")),
+                         "LicenseC")
+
     def conanfile_txt_multi_excludes_test(self):
         # https://github.com/conan-io/conan/issues/2293
         client = TestClient()
@@ -138,14 +178,14 @@ bin, *.dll ->  @ excludes=Foo/*.dll Baz/*.dll
         client.save({"conanfile.py": testconanfile}, clean_first=True)
         client.run("install . --build=missing")
         self.assertTrue(os.path.exists(os.path.join(client.current_folder,
-                                                     "licenses/path/to/license.txt")))
+                                                    "licenses/path/to/license.txt")))
 
         # keep_path = False AND conanfile.py
         testconanfile = testconanfile.replace("keep_path=True", "keep_path=False")
         client.save({"conanfile.py": testconanfile}, clean_first=True)
         client.run("install . --build=missing")
         self.assertTrue(os.path.exists(os.path.join(client.current_folder,
-                                                     "licenses/license.txt")))
+                                                    "licenses/license.txt")))
 
         # keep_path = True AND conanfile.txt
         testconanfile = conanfile_txt % "LibC/0.1@lasote/testing"
@@ -156,7 +196,7 @@ bin, *.dll ->  @ excludes=Foo/*.dll Baz/*.dll
         client.save({"conanfile.txt": testconanfile}, clean_first=True)
         client.run("install . --build=missing")
         self.assertTrue(os.path.exists(os.path.join(client.current_folder,
-                                                     "licenses/path/to/license.txt")))
+                                                    "licenses/path/to/license.txt")))
 
         # keep_path = False AND conanfile.txt
         testconanfile = testconanfile.replace("keep_path=True", "keep_path=False")
diff --git a/conans/test/functional/generators/cmake_generator_test.py b/conans/test/functional/generators/cmake_generator_test.py
index 80b88bd6f..091b18512 100644
--- a/conans/test/functional/generators/cmake_generator_test.py
+++ b/conans/test/functional/generators/cmake_generator_test.py
@@ -52,16 +52,20 @@ class CMakeGeneratorTest(unittest.TestCase):
         client.run("install . -p my_profile")
         client.run("build .")
 
-        self.assertIn('cmake -G "{}"'.format(generator), client.out)
-        self.assertTrue(os.path.isfile(os.path.join(client.current_folder, "Makefile")))
+        if generator:
+            self.assertIn('cmake -G "{}"'.format(generator), client.out)
+            self.assertTrue(os.path.isfile(os.path.join(client.current_folder, "Makefile")))
+        else:
+            self.assertNotIn("cmake -G", client.out)
+            self.assertFalse(os.path.isfile(os.path.join(client.current_folder, "Makefile")))
 
     @unittest.skipUnless(tools.os_info.is_linux, "Compilation with real gcc needed")
     def test_cmake_default_generator_linux(self):
         self._check_build_generator("Linux", "Unix Makefiles")
 
-    @unittest.skipUnless(tools.os_info.is_windows, "MinGW is only supported on Windows")
+    @unittest.skipUnless(tools.os_info.is_windows, "Windows does not support default compiler")
     def test_cmake_default_generator_windows(self):
-        self._check_build_generator("Windows", "MinGW Makefiles")
+        self._check_build_generator("Windows", None)
 
     @unittest.skipUnless(tools.os_info.is_macos, "Compilation with real clang is needed")
     def test_cmake_default_generator_osx(self):
diff --git a/conans/test/unittests/client/build/cmake_test.py b/conans/test/unittests/client/build/cmake_test.py
index 478be4521..0d179a860 100644
--- a/conans/test/unittests/client/build/cmake_test.py
+++ b/conans/test/unittests/client/build/cmake_test.py
@@ -17,7 +17,7 @@ from conans.errors import ConanException
 from conans.model.build_info import CppInfo, DepsCppInfo
 from conans.model.ref import ConanFileReference
 from conans.model.settings import Settings
-from conans.test.utils.conanfile import ConanFileMock
+from conans.test.utils.conanfile import ConanFileMock, MockSettings
 from conans.test.utils.test_files import temp_folder
 from conans.util.files import load, save
 
@@ -1037,7 +1037,7 @@ build_type: [ Release]
         self.assertEquals(cmake.generator, "Unix Makefiles")
 
         cmake = instance_with_os_build("Windows")
-        self.assertEquals(cmake.generator, "MinGW Makefiles")
+        self.assertEquals(cmake.generator, None)
 
         with tools.environment_append({"CONAN_CMAKE_GENERATOR": "MyCoolGenerator"}):
             cmake = instance_with_os_build("Windows")
@@ -1231,3 +1231,14 @@ build_type: [ Release]
             self.assertEquals(conanfile.captured_env["CTEST_OUTPUT_ON_FAILURE"], "1")
             self.assertEquals(conanfile.captured_env["CTEST_PARALLEL_LEVEL"], "666")
 
+    def test_unkown_generator_does_not_raise(self):
+        # https://github.com/conan-io/conan/issues/4265
+        settings = MockSettings({"os_build": "Windows", "compiler": "random",
+                                 "compiler.version": "15", "build_type": "Release"})
+        conanfile = ConanFileMock()
+        conanfile.settings = settings
+        cmake = CMake(conanfile)
+        self.assertIsNone(cmake.generator)
+        self.assertIn("WARN: CMake generator could not be deduced from settings", conanfile.output)
+        cmake.configure()
+        cmake.build()