We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
`dvc init` prints analytics warning even if has been disabled
**When** a new repository is initialized and the `core.analytics` has been set to `False` either globally or system-wide
**Then** a the analytics warning message is still printed
**Causing** a bit of irritation and actually checking the code what's really going on 

Seems like the `_welcome_message` function in `dvc/repo/init.py` has no check if analytics is still enabled.

---
**DVC version**: 0.51.2
**Method of installation**: `pip`



--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `dvc/repo/init.py`
Content:
```
1 import os
2 import colorama
3 import logging
4 
5 from dvc.repo import Repo
6 from dvc.scm import SCM, NoSCM
7 from dvc.config import Config
8 from dvc.exceptions import InitError
9 from dvc.utils import boxify, relpath, remove
10 
11 logger = logging.getLogger(__name__)
12 
13 
14 def _welcome_message():
15     logger.info(
16         boxify(
17             "DVC has enabled anonymous aggregate usage analytics.\n"
18             "Read the analytics documentation (and how to opt-out) here:\n"
19             "{blue}https://dvc.org/doc/user-guide/analytics{nc}".format(
20                 blue=colorama.Fore.BLUE, nc=colorama.Fore.RESET
21             ),
22             border_color="red",
23         )
24     )
25 
26     msg = (
27         "{yellow}What's next?{nc}\n"
28         "{yellow}------------{nc}\n"
29         "- Check out the documentation: {blue}https://dvc.org/doc{nc}\n"
30         "- Get help and share ideas: {blue}https://dvc.org/chat{nc}\n"
31         "- Star us on GitHub: {blue}https://github.com/iterative/dvc{nc}"
32     ).format(
33         yellow=colorama.Fore.YELLOW,
34         blue=colorama.Fore.BLUE,
35         nc=colorama.Fore.RESET,
36     )
37 
38     logger.info(msg)
39 
40 
41 def init(root_dir=os.curdir, no_scm=False, force=False):
42     """
43     Creates an empty repo on the given directory -- basically a
44     `.dvc` directory with subdirectories for configuration and cache.
45 
46     It should be tracked by a SCM or use the `--no-scm` flag.
47 
48     If the given directory is not empty, you must use the `--force`
49     flag to override it.
50 
51     Args:
52         root_dir: Path to repo's root directory.
53 
54     Returns:
55         Repo instance.
56 
57     Raises:
58         KeyError: Raises an exception.
59     """
60     root_dir = os.path.realpath(root_dir)
61     dvc_dir = os.path.join(root_dir, Repo.DVC_DIR)
62     scm = SCM(root_dir)
63     if isinstance(scm, NoSCM) and not no_scm:
64         raise InitError(
65             "{repo} is not tracked by any supported scm tool (e.g. git). "
66             "Use '--no-scm' if you don't want to use any scm.".format(
67                 repo=root_dir
68             )
69         )
70 
71     if os.path.isdir(dvc_dir):
72         if not force:
73             raise InitError(
74                 "'{repo}' exists. Use '-f' to force.".format(
75                     repo=relpath(dvc_dir)
76                 )
77             )
78 
79         remove(dvc_dir)
80 
81     os.mkdir(dvc_dir)
82 
83     config = Config.init(dvc_dir)
84     proj = Repo(root_dir)
85 
86     scm.add([config.config_file])
87 
88     if scm.ignore_file:
89         scm.add([os.path.join(dvc_dir, scm.ignore_file)])
90         logger.info("\nYou can now commit the changes to git.\n")
91 
92     _welcome_message()
93 
94     return proj
95
```

Path: `dvc/analytics.py`
Content:
```
1 """Collect and send usage analytics"""
2 
3 from __future__ import unicode_literals
4 
5 from dvc.utils.compat import str
6 
7 import os
8 import json
9 import errno
10 import logging
11 
12 from dvc import __version__
13 
14 
15 logger = logging.getLogger(__name__)
16 
17 
18 class Analytics(object):
19     """Class for collecting and sending usage analytics.
20 
21     Args:
22         info (dict): optional existing analytics report.
23     """
24 
25     URL = "https://analytics.dvc.org"
26     TIMEOUT_POST = 5
27 
28     USER_ID_FILE = "user_id"
29 
30     PARAM_DVC_VERSION = "dvc_version"
31     PARAM_USER_ID = "user_id"
32     PARAM_SYSTEM_INFO = "system_info"
33 
34     PARAM_OS = "os"
35 
36     PARAM_WINDOWS_VERSION_MAJOR = "windows_version_major"
37     PARAM_WINDOWS_VERSION_MINOR = "windows_version_minor"
38     PARAM_WINDOWS_VERSION_BUILD = "windows_version_build"
39     PARAM_WINDOWS_VERSION_SERVICE_PACK = "windows_version_service_pack"
40 
41     PARAM_MAC_VERSION = "mac_version"
42 
43     PARAM_LINUX_DISTRO = "linux_distro"
44     PARAM_LINUX_DISTRO_VERSION = "linux_distro_version"
45     PARAM_LINUX_DISTRO_LIKE = "linux_distro_like"
46 
47     PARAM_SCM_CLASS = "scm_class"
48     PARAM_IS_BINARY = "is_binary"
49     PARAM_CMD_CLASS = "cmd_class"
50     PARAM_CMD_RETURN_CODE = "cmd_return_code"
51 
52     def __init__(self, info=None):
53         from dvc.config import Config
54         from dvc.lock import Lock
55 
56         if info is None:
57             info = {}
58 
59         self.info = info
60 
61         cdir = Config.get_global_config_dir()
62         try:
63             os.makedirs(cdir)
64         except OSError as exc:
65             if exc.errno != errno.EEXIST:
66                 raise
67 
68         self.user_id_file = os.path.join(cdir, self.USER_ID_FILE)
69         self.user_id_file_lock = Lock(cdir, self.USER_ID_FILE + ".lock")
70 
71     @staticmethod
72     def load(path):
73         """Loads analytics report from json file specified by path.
74 
75         Args:
76             path (str): path to json file with analytics report.
77         """
78         with open(path, "r") as fobj:
79             analytics = Analytics(info=json.load(fobj))
80         os.unlink(path)
81         return analytics
82 
83     def _write_user_id(self):
84         import uuid
85 
86         with open(self.user_id_file, "w+") as fobj:
87             user_id = str(uuid.uuid4())
88             info = {self.PARAM_USER_ID: user_id}
89             json.dump(info, fobj)
90             return user_id
91 
92     def _read_user_id(self):
93         if not os.path.exists(self.user_id_file):
94             return None
95 
96         with open(self.user_id_file, "r") as fobj:
97             try:
98                 info = json.load(fobj)
99             except ValueError as exc:
100                 logger.debug("Failed to load user_id: {}".format(exc))
101                 return None
102 
103             return info[self.PARAM_USER_ID]
104 
105     def _get_user_id(self):
106         from dvc.lock import LockError
107 
108         try:
109             with self.user_id_file_lock:
110                 user_id = self._read_user_id()
111                 if user_id is None:
112                     user_id = self._write_user_id()
113                 return user_id
114         except LockError:
115             msg = "Failed to acquire '{}'"
116             logger.debug(msg.format(self.user_id_file_lock.lock_file))
117 
118     def _collect_windows(self):
119         import sys
120 
121         version = sys.getwindowsversion()  # pylint: disable=no-member
122         info = {}
123         info[self.PARAM_OS] = "windows"
124         info[self.PARAM_WINDOWS_VERSION_MAJOR] = version.major
125         info[self.PARAM_WINDOWS_VERSION_MINOR] = version.minor
126         info[self.PARAM_WINDOWS_VERSION_BUILD] = version.build
127         info[self.PARAM_WINDOWS_VERSION_SERVICE_PACK] = version.service_pack
128         return info
129 
130     def _collect_darwin(self):
131         import platform
132 
133         info = {}
134         info[self.PARAM_OS] = "mac"
135         info[self.PARAM_MAC_VERSION] = platform.mac_ver()[0]
136         return info
137 
138     def _collect_linux(self):
139         import distro
140 
141         info = {}
142         info[self.PARAM_OS] = "linux"
143         info[self.PARAM_LINUX_DISTRO] = distro.id()
144         info[self.PARAM_LINUX_DISTRO_VERSION] = distro.version()
145         info[self.PARAM_LINUX_DISTRO_LIKE] = distro.like()
146         return info
147 
148     def _collect_system_info(self):
149         import platform
150 
151         system = platform.system()
152 
153         if system == "Windows":
154             return self._collect_windows()
155 
156         if system == "Darwin":
157             return self._collect_darwin()
158 
159         if system == "Linux":
160             return self._collect_linux()
161 
162         raise NotImplementedError
163 
164     def collect(self):
165         """Collect analytics report."""
166         from dvc.scm import SCM
167         from dvc.utils import is_binary
168         from dvc.repo import Repo
169         from dvc.exceptions import NotDvcRepoError
170 
171         self.info[self.PARAM_DVC_VERSION] = __version__
172         self.info[self.PARAM_IS_BINARY] = is_binary()
173         self.info[self.PARAM_USER_ID] = self._get_user_id()
174 
175         self.info[self.PARAM_SYSTEM_INFO] = self._collect_system_info()
176 
177         try:
178             scm = SCM(root_dir=Repo.find_root())
179             self.info[self.PARAM_SCM_CLASS] = type(scm).__name__
180         except NotDvcRepoError:
181             pass
182 
183     def collect_cmd(self, args, ret):
184         """Collect analytics info from a CLI command."""
185         from dvc.command.daemon import CmdDaemonAnalytics
186 
187         assert isinstance(ret, int) or ret is None
188 
189         if ret is not None:
190             self.info[self.PARAM_CMD_RETURN_CODE] = ret
191 
192         if args is not None and hasattr(args, "func"):
193             assert args.func != CmdDaemonAnalytics
194             self.info[self.PARAM_CMD_CLASS] = args.func.__name__
195 
196     def dump(self):
197         """Save analytics report to a temporary file.
198 
199         Returns:
200             str: path to the temporary file that contains the analytics report.
201         """
202         import tempfile
203 
204         with tempfile.NamedTemporaryFile(delete=False, mode="w") as fobj:
205             json.dump(self.info, fobj)
206             return fobj.name
207 
208     @staticmethod
209     def _is_enabled_config(config):
210         from dvc.config import Config
211 
212         core = config.config.get(Config.SECTION_CORE, {})
213         return core.get(Config.SECTION_CORE_ANALYTICS, True)
214 
215     @staticmethod
216     def _is_enabled(cmd=None):
217         from dvc.config import Config
218         from dvc.repo import Repo
219         from dvc.exceptions import NotDvcRepoError
220         from dvc.command.daemon import CmdDaemonBase
221 
222         if os.getenv("DVC_TEST"):
223             return False
224 
225         if isinstance(cmd, CmdDaemonBase):
226             return False
227 
228         if cmd is None or not hasattr(cmd, "config"):
229             try:
230                 dvc_dir = Repo.find_dvc_dir()
231                 config = Config(dvc_dir)
232                 assert config is not None
233             except NotDvcRepoError:
234                 config = Config(validate=False)
235                 assert config is not None
236         else:
237             config = cmd.config
238             assert config is not None
239 
240         enabled = Analytics._is_enabled_config(config)
241         logger.debug(
242             "Analytics is {}.".format("enabled" if enabled else "disabled")
243         )
244         return enabled
245 
246     @staticmethod
247     def send_cmd(cmd, args, ret):
248         """Collect and send analytics for CLI command.
249 
250         Args:
251             args (list): parsed args for the CLI command.
252             ret (int): return value of the CLI command.
253         """
254         from dvc.daemon import daemon
255 
256         if not Analytics._is_enabled(cmd):
257             return
258 
259         analytics = Analytics()
260         analytics.collect_cmd(args, ret)
261         daemon(["analytics", analytics.dump()])
262 
263     def send(self):
264         """Collect and send analytics."""
265         import requests
266 
267         if not self._is_enabled():
268             return
269 
270         self.collect()
271 
272         logger.debug("Sending analytics: {}".format(self.info))
273 
274         try:
275             requests.post(self.URL, json=self.info, timeout=self.TIMEOUT_POST)
276         except requests.exceptions.RequestException as exc:
277             logger.debug("Failed to send analytics: {}".format(str(exc)))
278
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/dvc/analytics.py b/dvc/analytics.py
--- a/dvc/analytics.py
+++ b/dvc/analytics.py
@@ -213,10 +213,20 @@
         return core.get(Config.SECTION_CORE_ANALYTICS, True)
 
     @staticmethod
-    def _is_enabled(cmd=None):
+    def _get_current_config():
         from dvc.config import Config
         from dvc.repo import Repo
         from dvc.exceptions import NotDvcRepoError
+
+        try:
+            dvc_dir = Repo.find_dvc_dir()
+            config = Config(dvc_dir)
+        except NotDvcRepoError:
+            config = Config(validate=False)
+        return config
+
+    @staticmethod
+    def is_enabled(cmd=None):
         from dvc.command.daemon import CmdDaemonBase
 
         if os.getenv("DVC_TEST"):
@@ -225,17 +235,13 @@
         if isinstance(cmd, CmdDaemonBase):
             return False
 
-        if cmd is None or not hasattr(cmd, "config"):
-            try:
-                dvc_dir = Repo.find_dvc_dir()
-                config = Config(dvc_dir)
-                assert config is not None
-            except NotDvcRepoError:
-                config = Config(validate=False)
-                assert config is not None
-        else:
-            config = cmd.config
-            assert config is not None
+        config = (
+            Analytics._get_current_config()
+            if cmd is None or not hasattr(cmd, "config")
+            else cmd.config
+        )
+
+        assert config is not None
 
         enabled = Analytics._is_enabled_config(config)
         logger.debug(
@@ -253,7 +259,7 @@
         """
         from dvc.daemon import daemon
 
-        if not Analytics._is_enabled(cmd):
+        if not Analytics.is_enabled(cmd):
             return
 
         analytics = Analytics()
@@ -264,7 +270,7 @@
         """Collect and send analytics."""
         import requests
 
-        if not self._is_enabled():
+        if not self.is_enabled():
             return
 
         self.collect()
diff --git a/dvc/repo/init.py b/dvc/repo/init.py
--- a/dvc/repo/init.py
+++ b/dvc/repo/init.py
@@ -7,21 +7,23 @@
 from dvc.config import Config
 from dvc.exceptions import InitError
 from dvc.utils import boxify, relpath, remove
+from dvc.analytics import Analytics
 
 logger = logging.getLogger(__name__)
 
 
 def _welcome_message():
-    logger.info(
-        boxify(
-            "DVC has enabled anonymous aggregate usage analytics.\n"
-            "Read the analytics documentation (and how to opt-out) here:\n"
-            "{blue}https://dvc.org/doc/user-guide/analytics{nc}".format(
-                blue=colorama.Fore.BLUE, nc=colorama.Fore.RESET
-            ),
-            border_color="red",
+    if Analytics.is_enabled():
+        logger.info(
+            boxify(
+                "DVC has enabled anonymous aggregate usage analytics.\n"
+                "Read the analytics documentation (and how to opt-out) here:\n"
+                "{blue}https://dvc.org/doc/user-guide/analytics{nc}".format(
+                    blue=colorama.Fore.BLUE, nc=colorama.Fore.RESET
+                ),
+                border_color="red",
+            )
         )
-    )
 
     msg = (
         "{yellow}What's next?{nc}\n"

{"golden_diff": "diff --git a/dvc/analytics.py b/dvc/analytics.py\n--- a/dvc/analytics.py\n+++ b/dvc/analytics.py\n@@ -213,10 +213,20 @@\n         return core.get(Config.SECTION_CORE_ANALYTICS, True)\n \n     @staticmethod\n-    def _is_enabled(cmd=None):\n+    def _get_current_config():\n         from dvc.config import Config\n         from dvc.repo import Repo\n         from dvc.exceptions import NotDvcRepoError\n+\n+        try:\n+            dvc_dir = Repo.find_dvc_dir()\n+            config = Config(dvc_dir)\n+        except NotDvcRepoError:\n+            config = Config(validate=False)\n+        return config\n+\n+    @staticmethod\n+    def is_enabled(cmd=None):\n         from dvc.command.daemon import CmdDaemonBase\n \n         if os.getenv(\"DVC_TEST\"):\n@@ -225,17 +235,13 @@\n         if isinstance(cmd, CmdDaemonBase):\n             return False\n \n-        if cmd is None or not hasattr(cmd, \"config\"):\n-            try:\n-                dvc_dir = Repo.find_dvc_dir()\n-                config = Config(dvc_dir)\n-                assert config is not None\n-            except NotDvcRepoError:\n-                config = Config(validate=False)\n-                assert config is not None\n-        else:\n-            config = cmd.config\n-            assert config is not None\n+        config = (\n+            Analytics._get_current_config()\n+            if cmd is None or not hasattr(cmd, \"config\")\n+            else cmd.config\n+        )\n+\n+        assert config is not None\n \n         enabled = Analytics._is_enabled_config(config)\n         logger.debug(\n@@ -253,7 +259,7 @@\n         \"\"\"\n         from dvc.daemon import daemon\n \n-        if not Analytics._is_enabled(cmd):\n+        if not Analytics.is_enabled(cmd):\n             return\n \n         analytics = Analytics()\n@@ -264,7 +270,7 @@\n         \"\"\"Collect and send analytics.\"\"\"\n         import requests\n \n-        if not self._is_enabled():\n+        if not self.is_enabled():\n             return\n \n         self.collect()\ndiff --git a/dvc/repo/init.py b/dvc/repo/init.py\n--- a/dvc/repo/init.py\n+++ b/dvc/repo/init.py\n@@ -7,21 +7,23 @@\n from dvc.config import Config\n from dvc.exceptions import InitError\n from dvc.utils import boxify, relpath, remove\n+from dvc.analytics import Analytics\n \n logger = logging.getLogger(__name__)\n \n \n def _welcome_message():\n-    logger.info(\n-        boxify(\n-            \"DVC has enabled anonymous aggregate usage analytics.\\n\"\n-            \"Read the analytics documentation (and how to opt-out) here:\\n\"\n-            \"{blue}https://dvc.org/doc/user-guide/analytics{nc}\".format(\n-                blue=colorama.Fore.BLUE, nc=colorama.Fore.RESET\n-            ),\n-            border_color=\"red\",\n+    if Analytics.is_enabled():\n+        logger.info(\n+            boxify(\n+                \"DVC has enabled anonymous aggregate usage analytics.\\n\"\n+                \"Read the analytics documentation (and how to opt-out) here:\\n\"\n+                \"{blue}https://dvc.org/doc/user-guide/analytics{nc}\".format(\n+                    blue=colorama.Fore.BLUE, nc=colorama.Fore.RESET\n+                ),\n+                border_color=\"red\",\n+            )\n         )\n-    )\n \n     msg = (\n         \"{yellow}What's next?{nc}\\n\"\n", "issue": "`dvc init` prints analytics warning even if has been disabled\n**When** a new repository is initialized and the `core.analytics` has been set to `False` either globally or system-wide\r\n**Then** a the analytics warning message is still printed\r\n**Causing** a bit of irritation and actually checking the code what's really going on \r\n\r\nSeems like the `_welcome_message` function in `dvc/repo/init.py` has no check if analytics is still enabled.\r\n\r\n---\r\n**DVC version**: 0.51.2\r\n**Method of installation**: `pip`\r\n\r\n\n", "before_files": [{"content": "import os\nimport colorama\nimport logging\n\nfrom dvc.repo import Repo\nfrom dvc.scm import SCM, NoSCM\nfrom dvc.config import Config\nfrom dvc.exceptions import InitError\nfrom dvc.utils import boxify, relpath, remove\n\nlogger = logging.getLogger(__name__)\n\n\ndef _welcome_message():\n    logger.info(\n        boxify(\n            \"DVC has enabled anonymous aggregate usage analytics.\\n\"\n            \"Read the analytics documentation (and how to opt-out) here:\\n\"\n            \"{blue}https://dvc.org/doc/user-guide/analytics{nc}\".format(\n                blue=colorama.Fore.BLUE, nc=colorama.Fore.RESET\n            ),\n            border_color=\"red\",\n        )\n    )\n\n    msg = (\n        \"{yellow}What's next?{nc}\\n\"\n        \"{yellow}------------{nc}\\n\"\n        \"- Check out the documentation: {blue}https://dvc.org/doc{nc}\\n\"\n        \"- Get help and share ideas: {blue}https://dvc.org/chat{nc}\\n\"\n        \"- Star us on GitHub: {blue}https://github.com/iterative/dvc{nc}\"\n    ).format(\n        yellow=colorama.Fore.YELLOW,\n        blue=colorama.Fore.BLUE,\n        nc=colorama.Fore.RESET,\n    )\n\n    logger.info(msg)\n\n\ndef init(root_dir=os.curdir, no_scm=False, force=False):\n    \"\"\"\n    Creates an empty repo on the given directory -- basically a\n    `.dvc` directory with subdirectories for configuration and cache.\n\n    It should be tracked by a SCM or use the `--no-scm` flag.\n\n    If the given directory is not empty, you must use the `--force`\n    flag to override it.\n\n    Args:\n        root_dir: Path to repo's root directory.\n\n    Returns:\n        Repo instance.\n\n    Raises:\n        KeyError: Raises an exception.\n    \"\"\"\n    root_dir = os.path.realpath(root_dir)\n    dvc_dir = os.path.join(root_dir, Repo.DVC_DIR)\n    scm = SCM(root_dir)\n    if isinstance(scm, NoSCM) and not no_scm:\n        raise InitError(\n            \"{repo} is not tracked by any supported scm tool (e.g. git). \"\n            \"Use '--no-scm' if you don't want to use any scm.\".format(\n                repo=root_dir\n            )\n        )\n\n    if os.path.isdir(dvc_dir):\n        if not force:\n            raise InitError(\n                \"'{repo}' exists. Use '-f' to force.\".format(\n                    repo=relpath(dvc_dir)\n                )\n            )\n\n        remove(dvc_dir)\n\n    os.mkdir(dvc_dir)\n\n    config = Config.init(dvc_dir)\n    proj = Repo(root_dir)\n\n    scm.add([config.config_file])\n\n    if scm.ignore_file:\n        scm.add([os.path.join(dvc_dir, scm.ignore_file)])\n        logger.info(\"\\nYou can now commit the changes to git.\\n\")\n\n    _welcome_message()\n\n    return proj\n", "path": "dvc/repo/init.py"}, {"content": "\"\"\"Collect and send usage analytics\"\"\"\n\nfrom __future__ import unicode_literals\n\nfrom dvc.utils.compat import str\n\nimport os\nimport json\nimport errno\nimport logging\n\nfrom dvc import __version__\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass Analytics(object):\n    \"\"\"Class for collecting and sending usage analytics.\n\n    Args:\n        info (dict): optional existing analytics report.\n    \"\"\"\n\n    URL = \"https://analytics.dvc.org\"\n    TIMEOUT_POST = 5\n\n    USER_ID_FILE = \"user_id\"\n\n    PARAM_DVC_VERSION = \"dvc_version\"\n    PARAM_USER_ID = \"user_id\"\n    PARAM_SYSTEM_INFO = \"system_info\"\n\n    PARAM_OS = \"os\"\n\n    PARAM_WINDOWS_VERSION_MAJOR = \"windows_version_major\"\n    PARAM_WINDOWS_VERSION_MINOR = \"windows_version_minor\"\n    PARAM_WINDOWS_VERSION_BUILD = \"windows_version_build\"\n    PARAM_WINDOWS_VERSION_SERVICE_PACK = \"windows_version_service_pack\"\n\n    PARAM_MAC_VERSION = \"mac_version\"\n\n    PARAM_LINUX_DISTRO = \"linux_distro\"\n    PARAM_LINUX_DISTRO_VERSION = \"linux_distro_version\"\n    PARAM_LINUX_DISTRO_LIKE = \"linux_distro_like\"\n\n    PARAM_SCM_CLASS = \"scm_class\"\n    PARAM_IS_BINARY = \"is_binary\"\n    PARAM_CMD_CLASS = \"cmd_class\"\n    PARAM_CMD_RETURN_CODE = \"cmd_return_code\"\n\n    def __init__(self, info=None):\n        from dvc.config import Config\n        from dvc.lock import Lock\n\n        if info is None:\n            info = {}\n\n        self.info = info\n\n        cdir = Config.get_global_config_dir()\n        try:\n            os.makedirs(cdir)\n        except OSError as exc:\n            if exc.errno != errno.EEXIST:\n                raise\n\n        self.user_id_file = os.path.join(cdir, self.USER_ID_FILE)\n        self.user_id_file_lock = Lock(cdir, self.USER_ID_FILE + \".lock\")\n\n    @staticmethod\n    def load(path):\n        \"\"\"Loads analytics report from json file specified by path.\n\n        Args:\n            path (str): path to json file with analytics report.\n        \"\"\"\n        with open(path, \"r\") as fobj:\n            analytics = Analytics(info=json.load(fobj))\n        os.unlink(path)\n        return analytics\n\n    def _write_user_id(self):\n        import uuid\n\n        with open(self.user_id_file, \"w+\") as fobj:\n            user_id = str(uuid.uuid4())\n            info = {self.PARAM_USER_ID: user_id}\n            json.dump(info, fobj)\n            return user_id\n\n    def _read_user_id(self):\n        if not os.path.exists(self.user_id_file):\n            return None\n\n        with open(self.user_id_file, \"r\") as fobj:\n            try:\n                info = json.load(fobj)\n            except ValueError as exc:\n                logger.debug(\"Failed to load user_id: {}\".format(exc))\n                return None\n\n            return info[self.PARAM_USER_ID]\n\n    def _get_user_id(self):\n        from dvc.lock import LockError\n\n        try:\n            with self.user_id_file_lock:\n                user_id = self._read_user_id()\n                if user_id is None:\n                    user_id = self._write_user_id()\n                return user_id\n        except LockError:\n            msg = \"Failed to acquire '{}'\"\n            logger.debug(msg.format(self.user_id_file_lock.lock_file))\n\n    def _collect_windows(self):\n        import sys\n\n        version = sys.getwindowsversion()  # pylint: disable=no-member\n        info = {}\n        info[self.PARAM_OS] = \"windows\"\n        info[self.PARAM_WINDOWS_VERSION_MAJOR] = version.major\n        info[self.PARAM_WINDOWS_VERSION_MINOR] = version.minor\n        info[self.PARAM_WINDOWS_VERSION_BUILD] = version.build\n        info[self.PARAM_WINDOWS_VERSION_SERVICE_PACK] = version.service_pack\n        return info\n\n    def _collect_darwin(self):\n        import platform\n\n        info = {}\n        info[self.PARAM_OS] = \"mac\"\n        info[self.PARAM_MAC_VERSION] = platform.mac_ver()[0]\n        return info\n\n    def _collect_linux(self):\n        import distro\n\n        info = {}\n        info[self.PARAM_OS] = \"linux\"\n        info[self.PARAM_LINUX_DISTRO] = distro.id()\n        info[self.PARAM_LINUX_DISTRO_VERSION] = distro.version()\n        info[self.PARAM_LINUX_DISTRO_LIKE] = distro.like()\n        return info\n\n    def _collect_system_info(self):\n        import platform\n\n        system = platform.system()\n\n        if system == \"Windows\":\n            return self._collect_windows()\n\n        if system == \"Darwin\":\n            return self._collect_darwin()\n\n        if system == \"Linux\":\n            return self._collect_linux()\n\n        raise NotImplementedError\n\n    def collect(self):\n        \"\"\"Collect analytics report.\"\"\"\n        from dvc.scm import SCM\n        from dvc.utils import is_binary\n        from dvc.repo import Repo\n        from dvc.exceptions import NotDvcRepoError\n\n        self.info[self.PARAM_DVC_VERSION] = __version__\n        self.info[self.PARAM_IS_BINARY] = is_binary()\n        self.info[self.PARAM_USER_ID] = self._get_user_id()\n\n        self.info[self.PARAM_SYSTEM_INFO] = self._collect_system_info()\n\n        try:\n            scm = SCM(root_dir=Repo.find_root())\n            self.info[self.PARAM_SCM_CLASS] = type(scm).__name__\n        except NotDvcRepoError:\n            pass\n\n    def collect_cmd(self, args, ret):\n        \"\"\"Collect analytics info from a CLI command.\"\"\"\n        from dvc.command.daemon import CmdDaemonAnalytics\n\n        assert isinstance(ret, int) or ret is None\n\n        if ret is not None:\n            self.info[self.PARAM_CMD_RETURN_CODE] = ret\n\n        if args is not None and hasattr(args, \"func\"):\n            assert args.func != CmdDaemonAnalytics\n            self.info[self.PARAM_CMD_CLASS] = args.func.__name__\n\n    def dump(self):\n        \"\"\"Save analytics report to a temporary file.\n\n        Returns:\n            str: path to the temporary file that contains the analytics report.\n        \"\"\"\n        import tempfile\n\n        with tempfile.NamedTemporaryFile(delete=False, mode=\"w\") as fobj:\n            json.dump(self.info, fobj)\n            return fobj.name\n\n    @staticmethod\n    def _is_enabled_config(config):\n        from dvc.config import Config\n\n        core = config.config.get(Config.SECTION_CORE, {})\n        return core.get(Config.SECTION_CORE_ANALYTICS, True)\n\n    @staticmethod\n    def _is_enabled(cmd=None):\n        from dvc.config import Config\n        from dvc.repo import Repo\n        from dvc.exceptions import NotDvcRepoError\n        from dvc.command.daemon import CmdDaemonBase\n\n        if os.getenv(\"DVC_TEST\"):\n            return False\n\n        if isinstance(cmd, CmdDaemonBase):\n            return False\n\n        if cmd is None or not hasattr(cmd, \"config\"):\n            try:\n                dvc_dir = Repo.find_dvc_dir()\n                config = Config(dvc_dir)\n                assert config is not None\n            except NotDvcRepoError:\n                config = Config(validate=False)\n                assert config is not None\n        else:\n            config = cmd.config\n            assert config is not None\n\n        enabled = Analytics._is_enabled_config(config)\n        logger.debug(\n            \"Analytics is {}.\".format(\"enabled\" if enabled else \"disabled\")\n        )\n        return enabled\n\n    @staticmethod\n    def send_cmd(cmd, args, ret):\n        \"\"\"Collect and send analytics for CLI command.\n\n        Args:\n            args (list): parsed args for the CLI command.\n            ret (int): return value of the CLI command.\n        \"\"\"\n        from dvc.daemon import daemon\n\n        if not Analytics._is_enabled(cmd):\n            return\n\n        analytics = Analytics()\n        analytics.collect_cmd(args, ret)\n        daemon([\"analytics\", analytics.dump()])\n\n    def send(self):\n        \"\"\"Collect and send analytics.\"\"\"\n        import requests\n\n        if not self._is_enabled():\n            return\n\n        self.collect()\n\n        logger.debug(\"Sending analytics: {}\".format(self.info))\n\n        try:\n            requests.post(self.URL, json=self.info, timeout=self.TIMEOUT_POST)\n        except requests.exceptions.RequestException as exc:\n            logger.debug(\"Failed to send analytics: {}\".format(str(exc)))\n", "path": "dvc/analytics.py"}], "after_files": [{"content": "import os\nimport colorama\nimport logging\n\nfrom dvc.repo import Repo\nfrom dvc.scm import SCM, NoSCM\nfrom dvc.config import Config\nfrom dvc.exceptions import InitError\nfrom dvc.utils import boxify, relpath, remove\nfrom dvc.analytics import Analytics\n\nlogger = logging.getLogger(__name__)\n\n\ndef _welcome_message():\n    if Analytics.is_enabled():\n        logger.info(\n            boxify(\n                \"DVC has enabled anonymous aggregate usage analytics.\\n\"\n                \"Read the analytics documentation (and how to opt-out) here:\\n\"\n                \"{blue}https://dvc.org/doc/user-guide/analytics{nc}\".format(\n                    blue=colorama.Fore.BLUE, nc=colorama.Fore.RESET\n                ),\n                border_color=\"red\",\n            )\n        )\n\n    msg = (\n        \"{yellow}What's next?{nc}\\n\"\n        \"{yellow}------------{nc}\\n\"\n        \"- Check out the documentation: {blue}https://dvc.org/doc{nc}\\n\"\n        \"- Get help and share ideas: {blue}https://dvc.org/chat{nc}\\n\"\n        \"- Star us on GitHub: {blue}https://github.com/iterative/dvc{nc}\"\n    ).format(\n        yellow=colorama.Fore.YELLOW,\n        blue=colorama.Fore.BLUE,\n        nc=colorama.Fore.RESET,\n    )\n\n    logger.info(msg)\n\n\ndef init(root_dir=os.curdir, no_scm=False, force=False):\n    \"\"\"\n    Creates an empty repo on the given directory -- basically a\n    `.dvc` directory with subdirectories for configuration and cache.\n\n    It should be tracked by a SCM or use the `--no-scm` flag.\n\n    If the given directory is not empty, you must use the `--force`\n    flag to override it.\n\n    Args:\n        root_dir: Path to repo's root directory.\n\n    Returns:\n        Repo instance.\n\n    Raises:\n        KeyError: Raises an exception.\n    \"\"\"\n    root_dir = os.path.realpath(root_dir)\n    dvc_dir = os.path.join(root_dir, Repo.DVC_DIR)\n    scm = SCM(root_dir)\n    if isinstance(scm, NoSCM) and not no_scm:\n        raise InitError(\n            \"{repo} is not tracked by any supported scm tool (e.g. git). \"\n            \"Use '--no-scm' if you don't want to use any scm.\".format(\n                repo=root_dir\n            )\n        )\n\n    if os.path.isdir(dvc_dir):\n        if not force:\n            raise InitError(\n                \"'{repo}' exists. Use '-f' to force.\".format(\n                    repo=relpath(dvc_dir)\n                )\n            )\n\n        remove(dvc_dir)\n\n    os.mkdir(dvc_dir)\n\n    config = Config.init(dvc_dir)\n    proj = Repo(root_dir)\n\n    scm.add([config.config_file])\n\n    if scm.ignore_file:\n        scm.add([os.path.join(dvc_dir, scm.ignore_file)])\n        logger.info(\"\\nYou can now commit the changes to git.\\n\")\n\n    _welcome_message()\n\n    return proj\n", "path": "dvc/repo/init.py"}, {"content": "\"\"\"Collect and send usage analytics\"\"\"\n\nfrom __future__ import unicode_literals\n\nfrom dvc.utils.compat import str\n\nimport os\nimport json\nimport errno\nimport logging\n\nfrom dvc import __version__\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass Analytics(object):\n    \"\"\"Class for collecting and sending usage analytics.\n\n    Args:\n        info (dict): optional existing analytics report.\n    \"\"\"\n\n    URL = \"https://analytics.dvc.org\"\n    TIMEOUT_POST = 5\n\n    USER_ID_FILE = \"user_id\"\n\n    PARAM_DVC_VERSION = \"dvc_version\"\n    PARAM_USER_ID = \"user_id\"\n    PARAM_SYSTEM_INFO = \"system_info\"\n\n    PARAM_OS = \"os\"\n\n    PARAM_WINDOWS_VERSION_MAJOR = \"windows_version_major\"\n    PARAM_WINDOWS_VERSION_MINOR = \"windows_version_minor\"\n    PARAM_WINDOWS_VERSION_BUILD = \"windows_version_build\"\n    PARAM_WINDOWS_VERSION_SERVICE_PACK = \"windows_version_service_pack\"\n\n    PARAM_MAC_VERSION = \"mac_version\"\n\n    PARAM_LINUX_DISTRO = \"linux_distro\"\n    PARAM_LINUX_DISTRO_VERSION = \"linux_distro_version\"\n    PARAM_LINUX_DISTRO_LIKE = \"linux_distro_like\"\n\n    PARAM_SCM_CLASS = \"scm_class\"\n    PARAM_IS_BINARY = \"is_binary\"\n    PARAM_CMD_CLASS = \"cmd_class\"\n    PARAM_CMD_RETURN_CODE = \"cmd_return_code\"\n\n    def __init__(self, info=None):\n        from dvc.config import Config\n        from dvc.lock import Lock\n\n        if info is None:\n            info = {}\n\n        self.info = info\n\n        cdir = Config.get_global_config_dir()\n        try:\n            os.makedirs(cdir)\n        except OSError as exc:\n            if exc.errno != errno.EEXIST:\n                raise\n\n        self.user_id_file = os.path.join(cdir, self.USER_ID_FILE)\n        self.user_id_file_lock = Lock(cdir, self.USER_ID_FILE + \".lock\")\n\n    @staticmethod\n    def load(path):\n        \"\"\"Loads analytics report from json file specified by path.\n\n        Args:\n            path (str): path to json file with analytics report.\n        \"\"\"\n        with open(path, \"r\") as fobj:\n            analytics = Analytics(info=json.load(fobj))\n        os.unlink(path)\n        return analytics\n\n    def _write_user_id(self):\n        import uuid\n\n        with open(self.user_id_file, \"w+\") as fobj:\n            user_id = str(uuid.uuid4())\n            info = {self.PARAM_USER_ID: user_id}\n            json.dump(info, fobj)\n            return user_id\n\n    def _read_user_id(self):\n        if not os.path.exists(self.user_id_file):\n            return None\n\n        with open(self.user_id_file, \"r\") as fobj:\n            try:\n                info = json.load(fobj)\n            except ValueError as exc:\n                logger.debug(\"Failed to load user_id: {}\".format(exc))\n                return None\n\n            return info[self.PARAM_USER_ID]\n\n    def _get_user_id(self):\n        from dvc.lock import LockError\n\n        try:\n            with self.user_id_file_lock:\n                user_id = self._read_user_id()\n                if user_id is None:\n                    user_id = self._write_user_id()\n                return user_id\n        except LockError:\n            msg = \"Failed to acquire '{}'\"\n            logger.debug(msg.format(self.user_id_file_lock.lock_file))\n\n    def _collect_windows(self):\n        import sys\n\n        version = sys.getwindowsversion()  # pylint: disable=no-member\n        info = {}\n        info[self.PARAM_OS] = \"windows\"\n        info[self.PARAM_WINDOWS_VERSION_MAJOR] = version.major\n        info[self.PARAM_WINDOWS_VERSION_MINOR] = version.minor\n        info[self.PARAM_WINDOWS_VERSION_BUILD] = version.build\n        info[self.PARAM_WINDOWS_VERSION_SERVICE_PACK] = version.service_pack\n        return info\n\n    def _collect_darwin(self):\n        import platform\n\n        info = {}\n        info[self.PARAM_OS] = \"mac\"\n        info[self.PARAM_MAC_VERSION] = platform.mac_ver()[0]\n        return info\n\n    def _collect_linux(self):\n        import distro\n\n        info = {}\n        info[self.PARAM_OS] = \"linux\"\n        info[self.PARAM_LINUX_DISTRO] = distro.id()\n        info[self.PARAM_LINUX_DISTRO_VERSION] = distro.version()\n        info[self.PARAM_LINUX_DISTRO_LIKE] = distro.like()\n        return info\n\n    def _collect_system_info(self):\n        import platform\n\n        system = platform.system()\n\n        if system == \"Windows\":\n            return self._collect_windows()\n\n        if system == \"Darwin\":\n            return self._collect_darwin()\n\n        if system == \"Linux\":\n            return self._collect_linux()\n\n        raise NotImplementedError\n\n    def collect(self):\n        \"\"\"Collect analytics report.\"\"\"\n        from dvc.scm import SCM\n        from dvc.utils import is_binary\n        from dvc.repo import Repo\n        from dvc.exceptions import NotDvcRepoError\n\n        self.info[self.PARAM_DVC_VERSION] = __version__\n        self.info[self.PARAM_IS_BINARY] = is_binary()\n        self.info[self.PARAM_USER_ID] = self._get_user_id()\n\n        self.info[self.PARAM_SYSTEM_INFO] = self._collect_system_info()\n\n        try:\n            scm = SCM(root_dir=Repo.find_root())\n            self.info[self.PARAM_SCM_CLASS] = type(scm).__name__\n        except NotDvcRepoError:\n            pass\n\n    def collect_cmd(self, args, ret):\n        \"\"\"Collect analytics info from a CLI command.\"\"\"\n        from dvc.command.daemon import CmdDaemonAnalytics\n\n        assert isinstance(ret, int) or ret is None\n\n        if ret is not None:\n            self.info[self.PARAM_CMD_RETURN_CODE] = ret\n\n        if args is not None and hasattr(args, \"func\"):\n            assert args.func != CmdDaemonAnalytics\n            self.info[self.PARAM_CMD_CLASS] = args.func.__name__\n\n    def dump(self):\n        \"\"\"Save analytics report to a temporary file.\n\n        Returns:\n            str: path to the temporary file that contains the analytics report.\n        \"\"\"\n        import tempfile\n\n        with tempfile.NamedTemporaryFile(delete=False, mode=\"w\") as fobj:\n            json.dump(self.info, fobj)\n            return fobj.name\n\n    @staticmethod\n    def _is_enabled_config(config):\n        from dvc.config import Config\n\n        core = config.config.get(Config.SECTION_CORE, {})\n        return core.get(Config.SECTION_CORE_ANALYTICS, True)\n\n    @staticmethod\n    def _get_current_config():\n        from dvc.config import Config\n        from dvc.repo import Repo\n        from dvc.exceptions import NotDvcRepoError\n\n        try:\n            dvc_dir = Repo.find_dvc_dir()\n            config = Config(dvc_dir)\n        except NotDvcRepoError:\n            config = Config(validate=False)\n        return config\n\n    @staticmethod\n    def is_enabled(cmd=None):\n        from dvc.command.daemon import CmdDaemonBase\n\n        if os.getenv(\"DVC_TEST\"):\n            return False\n\n        if isinstance(cmd, CmdDaemonBase):\n            return False\n\n        config = (\n            Analytics._get_current_config()\n            if cmd is None or not hasattr(cmd, \"config\")\n            else cmd.config\n        )\n\n        assert config is not None\n\n        enabled = Analytics._is_enabled_config(config)\n        logger.debug(\n            \"Analytics is {}.\".format(\"enabled\" if enabled else \"disabled\")\n        )\n        return enabled\n\n    @staticmethod\n    def send_cmd(cmd, args, ret):\n        \"\"\"Collect and send analytics for CLI command.\n\n        Args:\n            args (list): parsed args for the CLI command.\n            ret (int): return value of the CLI command.\n        \"\"\"\n        from dvc.daemon import daemon\n\n        if not Analytics.is_enabled(cmd):\n            return\n\n        analytics = Analytics()\n        analytics.collect_cmd(args, ret)\n        daemon([\"analytics\", analytics.dump()])\n\n    def send(self):\n        \"\"\"Collect and send analytics.\"\"\"\n        import requests\n\n        if not self.is_enabled():\n            return\n\n        self.collect()\n\n        logger.debug(\"Sending analytics: {}\".format(self.info))\n\n        try:\n            requests.post(self.URL, json=self.info, timeout=self.TIMEOUT_POST)\n        except requests.exceptions.RequestException as exc:\n            logger.debug(\"Failed to send analytics: {}\".format(str(exc)))\n", "path": "dvc/analytics.py"}]}