GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — master ( cd85c1...fd728a )
by Mandeep
38s
created

commands.py (2 issues)

1
import os
2
import subprocess
3
import sys
4
5
import json
6
7
import sublime
8
import sublime_plugin
9
10
11
class CondaCommand(sublime_plugin.WindowCommand):
12
    """Contains all of the attributes that will be inherited by other commands."""
13
14
    @property
15
    def settings(self):
16
        """Load the plugin settings for commands to use."""
17
        return sublime.load_settings('conda.sublime-settings')
18
19
    @property
20
    def executable(self):
21
        """Retrieve the python executable path from settings."""
22
        return os.path.expanduser(self.settings.get('executable'))
23
24
    @property
25
    def configuration(self):
26
        """Retrieve the conda configuration file from settings."""
27
        return os.path.expanduser(self.settings.get('configuration'))
28
29
    @property
30
    def root_directory(self):
31
        """Retrieve the directory of conda's root environment."""
32
        if sys.platform == 'win32':
33
            root_directory = os.path.dirname(self.executable)
34
        else:
35
            root_directory = os.path.dirname(self.executable).replace('bin', '')
36
37
        return root_directory
38
39
    @property
40
    def conda_environments(self):
41
        """Find all conda environments in the specified directory."""
42
        try:
43
            directory = os.path.expanduser(self.settings.get('environment_directory'))
44
45
            environments = [['root', self.root_directory]]
46
            environments.extend([[environment, os.path.join(directory, environment)]
47
                                for environment in os.listdir(directory)])
48
49
            return environments
50
51
        except FileNotFoundError:
52
            return [['root', self.root_directory]]
53
54
    @property
55
    def project_data(self):
56
        """Retrieve the project data to be used in the current window."""
57
        if self.window.project_data() is None:
58
            return {}
59
        else:
60
            return self.window.project_data()
61
62
    @property
63
    def startupinfo(self):
64
        """Property used to hide command prompts when on Windows platforms."""
65
        startupinfo = None
66
67
        if sys.platform == 'win32':
68
            startupinfo = subprocess.STARTUPINFO()
69
70
            if sys.version_info.major == 3:
71
                startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
72
            else:
73
                startupinfo.dwFlags |= subprocess._subprocess.STARTF_USESHOWWINDOW
74
75
        return startupinfo
76
77
    def retrieve_environment_name(self, path):
78
        """Retrieve the environment name from the active environment path.
79
80
        If the active environment is the root environment, 'root' must be
81
        returned instead of the basename from the environment path.
82
        """
83
        if path == self.root_directory:
84
            return 'root'
85
        else:
86
            return os.path.basename(path)
87
88
89
class CreateCondaEnvironmentCommand(CondaCommand):
90
    """Contains the methods needed to create a conda environment."""
91
92
    def run(self):
93
        """Display 'Conda: Create' in Sublime Text's command palette.
94
95
        When 'Conda: Create' is clicked by the user, Sublime's text input
96
        box will show allowing the user to input the name of environment.
97
        This environment name is then passed to the create_environment
98
        method.
99
        """
100
        self.window.show_input_panel('Conda Environment Name:', '',
101
                                     self.retrieve_python_version, None, None)
102
103
    def retrieve_python_version(self, environment):
104
        """Display a list of available Python versions for the environment.
105
106
        Forcing the user to select the Python version allows conda to create
107
        a new Python executable inside the environment directory.
108
        """
109
        self.environment = environment
110
111
        python_versions = ['Python 2.7', 'Python 3.5', 'Python 3.6']
112
113
        self.window.show_quick_panel(python_versions, self.create_environment)
114
115
    def create_environment(self, index):
116
        """Create a conda environment in the envs directory."""
117
        if index != -1:
118
            if index == 0:
119
                python_version = 'python=2.7'
120
            elif index == 1:
121
                python_version = 'python=3.5'
122
            else:
123
                python_version = 'python=3.6'
124
125
            cmd = [self.executable, '-m', 'conda', 'create',
126
                   '--name', self.environment, python_version, '-y', '-q']
127
128
            self.window.run_command('exec', {'cmd': cmd})
129
130
131
class RemoveCondaEnvironmentCommand(CondaCommand):
132
    """Contains the methods needed to remove a conda environment."""
133
134
    def run(self):
135
        """Display 'Conda: Remove' in Sublime Text's command palette.
136
137
        When 'Conda: Removed' is clicked by the user, the command
138
        palette whill show all conda environments available for removal.
139
        The index of the selected environment is then passed to the
140
        remove_environment method"
141
        """
142
        self.window.show_quick_panel(self.conda_environments,
143
                                     self.remove_environment)
144
145
    def remove_environment(self, index):
146
        """Remove a conda environment from the envs directory."""
147
        if index != -1:
148
            environment = self.conda_environments[index][0]
149
150
            cmd = [self.executable, '-m', 'conda', 'remove',
151
                   '--name', environment, '--all', '-y', '-q']
152
153
            self.window.run_command('exec', {'cmd': cmd})
154
155
156
class ListCondaEnvironmentCommand(CondaCommand):
157
    """Contains the methods needed to list available conda environments."""
158
159
    def run(self):
160
        """Display 'Conda: List' in Sublime Text's command palette.
161
162
        When 'Conda: List' is clicked by the user, the command
163
        palette will show all available conda environments.
164
        """
165
        self.window.show_quick_panel(self.conda_environments,
166
                                     None)
167
168
169
class ActivateCondaEnvironmentCommand(CondaCommand):
170
    """Contains the methods needed to activate a conda environment."""
171
172
    def run(self):
173
        """Display 'Conda: Activate' in Sublime Text's command palette.
174
175
        When 'Conda: Activate' is clicked by the user, the command
176
        palette will show all available conda environments. The
177
        clicked environment will be activated as the current environment.
178
        """
179
        self.window.show_quick_panel(self.conda_environments,
180
                                     self.activate_environment)
181
182
    def activate_environment(self, index):
183
        """Activate the environment selected from the command palette."""
184
        if index != -1:
185
            project_data = self.project_data
186
187
            project_data['conda_environment'] = self.conda_environments[index][1]
188
189
            self.window.set_project_data(project_data)
190
191
            sublime.status_message('Activated conda environment: {}'
192
                                   .format(self.conda_environments[index][0]))
193
194
195
class DeactivateCondaEnvironmentCommand(CondaCommand):
196
    """Contains the methods needed to deactivate a conda environment."""
197
198
    def run(self):
199
        """Display 'Conda: Deactivate' in Sublime Text's command palette.
200
201
        When 'Conda: Deactivate' is clicked by the user, the command
202
        palette will show all available conda environments. The
203
        clicked environment will be deactivated.
204
        """
205
        self.window.show_quick_panel(self.active_environment,
206
                                     self.deactivate_environment)
207
208
    @property
209
    def active_environment(self):
210
        """Retrieve the active conda environment."""
211
        try:
212
            environment_path = self.project_data['conda_environment']
213
            environment_name = self.retrieve_environment_name(environment_path)
214
215
            return [[environment_name, os.path.dirname(environment_path)]]
216
217
        except KeyError:
218
            return ['No Active Conda Environment']
219
220
    def deactivate_environment(self, index):
221
        """Deactivate the environment selected in the command palette."""
222
        if index != -1:
223
            try:
224
                project_data = self.project_data
225
226
                del project_data['conda_environment']
227
228
                self.window.set_project_data(project_data)
229
230
                sublime.status_message('Deactivated conda environment: {}'
231
                                       .format(self.conda_environments[index][0]))
232
            except KeyError:
233
                sublime.status_message('No active conda environment')
234
235
236
class ListCondaPackageCommand(CondaCommand):
237
    """Contains all of the methods needed to list all installed packages."""
238
239
    def run(self):
240
        """Display 'Conda: List' in Sublime Text's command palette.
241
242
        When 'Conda: List' is clicked by the user, the build output
243
        displays all packages installed in the current environment.
244
        """
245
        self.window.show_quick_panel(self.environment_packages, None)
246
247 View Code Duplication
    @property
0 ignored issues
show
This code seems to be duplicated in your project.
Loading history...
248
    def environment_packages(self):
249
        """List each package name and version installed in the environment."""
250
        try:
251
            environment_path = self.project_data['conda_environment']
252
            environment = self.retrieve_environment_name(environment_path)
253
254
            package_data = subprocess.check_output([self.executable, '-m', 'conda', 'list',
255
                                                    '--name', environment],
256
                                                   startupinfo=self.startupinfo, universal_newlines=True)
257
258
            packages = package_data.splitlines()[2:]
259
            package_names = [packages[i].split()[0] for i, _ in enumerate(packages)]
260
261
            return package_names
262
        
263
        except KeyError:
264
            return ['No Active Conda Environment']
265
266
267
class InstallCondaPackageCommand(CondaCommand):
268
    """Contains all of the methods needed to install a conda package."""
269
270
    def run(self):
271
        """Display an input box allowing the user to input a package name."""
272
        self.window.show_input_panel('Package Name:', '', self.install_package,
273
                                     None, None)
274
275
    def install_package(self, package):
276
        """Install the given package name via conda."""
277
        try:
278
            environment_path = self.project_data['conda_environment']
279
            environment = self.retrieve_environment_name(environment_path)
280
            cmd = [self.executable, '-m', 'conda', 'install', package,
281
                   '--name', environment, '-y', '-q']
282
            self.window.run_command('exec', {'cmd': cmd})
283
        
284
        except KeyError:
285
            sublime.status_message('No active conda environment.')
286
287
288
class RemoveCondaPackageCommand(CondaCommand):
289
    """Contains all of the methods needed to remove a conda package."""
290
291
    def run(self):
292
        """Display an input box allowing the user to pick a package to remove."""
293
        self.window.show_quick_panel(self.environment_packages, self.remove_package)
294
295 View Code Duplication
    @property
0 ignored issues
show
This code seems to be duplicated in your project.
Loading history...
296
    def environment_packages(self):
297
        """List each package name and version installed in the environment.
298
299
        This property had to be duplicated as the attribute from
300
        ListCondaPackageCommand could not be inherited properly.
301
        """
302
        try:
303
            environment_path = self.project_data['conda_environment']
304
            environment = self.retrieve_environment_name(environment_path)
305
306
            package_data = subprocess.check_output([self.executable, '-m', 'conda', 'list',
307
                                                    '--name', environment],
308
                                                   startupinfo=self.startupinfo, universal_newlines=True)
309
310
            packages = package_data.splitlines()[2:]
311
            package_names = [packages[i].split()[0] for i, _ in enumerate(packages)]
312
313
            return package_names
314
        
315
        except KeyError:
316
            return ['No Active Conda Environment']
317
318
    def remove_package(self, index):
319
        """Remove the given package name via conda."""
320
        if index != -1:
321
            package_to_remove = self.environment_packages[index]
322
323
            environment_path = self.project_data['conda_environment']
324
325
            environment = self.retrieve_environment_name(environment_path)
326
327
            cmd = [self.executable, '-m', 'conda', 'remove', package_to_remove,
328
                   '--name', environment, '-y', '-q']
329
330
            self.window.run_command('exec', {'cmd': cmd})
331
332
333
class ListCondaChannelsCommand(CondaCommand):
334
    """Contains all of the methods needed to display conda's channel sources."""
335
336
    def run(self):
337
        """Display 'Conda: List Channel Sources' in Sublime Text's command palette.
338
339
        When 'Conda: List Channel Sources' is clicked by the user,
340
        the command palette displays all of the channel sources found
341
        in the condarc configuration file.
342
        """
343
        self.window.show_quick_panel(self.channel_sources, None)
344
345
    @property
346
    def channel_sources(self):
347
        """List each channel source found in the condarc configuration file."""
348
        sources = subprocess.check_output([self.executable, '-m', 'conda', 'config',
349
                                          '--show-sources', '--json'],
350
                                          startupinfo=self.startupinfo)
351
        sources = json.loads(sources.decode())
352
353
        try:
354
            return sources[self.configuration]['channels']
355
        
356
        except KeyError:
357
            return ['No Channel Sources Available']
358
359
360
class SearchCondaPackageCommand(CondaCommand):
361
    """Contains all of the methods needed to search for a conda package."""
362
363
    def run(self):
364
        """Display an input box allowing the user to input a package name."""
365
        self.window.show_input_panel('Package Name:', '', self.search_package,
366
                                     None, None)
367
368
    def search_package(self, package):
369
        """Search for a package included in the defaults channel."""
370
        cmd = [self.executable, '-m', 'conda', 'search', package]
371
        self.window.run_command('exec', {'cmd': cmd})
372
373
374
class AddCondaChannelCommand(CondaCommand):
375
    """Contains all of the methods needed to add a conda channel source."""
376
377
    def run(self):
378
        """Display 'Conda: Add Channel Source' in Sublime Text's command palette.
379
380
        When 'Conda: Add Channel Source' is clicked by the user,
381
        an input box will show allowing the user to type the name
382
        of the channel to add.
383
        """
384
        self.window.show_input_panel('Conda Channel Name:', '',
385
                                     self.add_channel, None, None)
386
387
    def add_channel(self, channel):
388
        """Add the given channel to the condarc configuration file."""
389
        cmd = [self.executable, '-m', 'conda', 'config', '--add',
390
               'channels', channel]
391
392
        self.window.run_command('exec', {'cmd': cmd})
393
394
395
class RemoveCondaChannelCommand(CondaCommand):
396
    """Contains all of the methods needed to remove a conda channel source."""
397
398
    def run(self):
399
        """Display 'Conda: Remove Channel Source' in Sublime Text's command palette.
400
401
        When 'Conda: Remove Channel Source' is clicked by the user,
402
        the command palette will show a list of channel sources
403
        available to be removed by the user.
404
        """
405
        self.window.show_quick_panel(self.channel_sources, self.remove_channel)
406
407
    @property
408
    def channel_sources(self):
409
        """List each channel source found in the condarc configuration file.
410
411
        This property had to be duplicated as the attribute from
412
        ListCondaChannelCommand could not be inherited properly.
413
        """
414
        sources = subprocess.check_output([self.executable, '-m', 'conda', 'config',
415
                                          '--show-sources', '--json'],
416
                                          startupinfo=self.startupinfo)
417
        sources = json.loads(sources.decode())
418
419
        try:
420
            return sources[self.configuration]['channels']
421
        
422
        except KeyError:
423
            return ['No Channel Sources Available']
424
425
    def remove_channel(self, index):
426
        """Remove a channel from the condarc configuration file."""
427
        if index != -1:
428
            channel = self.channel_sources[index]
429
430
            cmd = [self.executable, '-m', 'conda', 'config', '--remove',
431
                   'channels', channel]
432
433
            self.window.run_command('exec', {'cmd': cmd})
434
435
436
class ExecuteCondaEnvironmentCommand(CondaCommand):
437
    """Override Sublime Text's default ExecCommand with a targeted build."""
438
439
    def run(self, **kwargs):
440
        """Run the current Python file with the conda environment's Python executable.
441
442
        The activated conda environment is retrieved from the Sublime Text
443
        window project data. The Python executable found in the conda
444
        environment's bin directory is used to build the file.
445
        """
446
        try:
447
            environment = self.project_data['conda_environment']
448
            
449
            if sys.platform == 'win32':
450
                executable_path = '{}\\python' .format(environment)
451
            else:
452
                executable_path = '{}/bin/python' .format(environment)
453
454
            kwargs['cmd'][0] = os.path.normpath(executable_path)
455
        
456
        except KeyError:
457
            pass
458
459
        self.window.run_command('exec', kwargs)
460