Robot Framework Integrated Development Environment (RIDE)
validators.py
Go to the documentation of this file.
1 # Copyright 2008-2015 Nokia Networks
2 # Copyright 2016- Robot Framework Foundation
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15 
16 import os
17 
18 from ..publish.messages import RideInputValidationError
19 
20 ERROR_ILLEGAL_CHARACTERS = "Filename contains illegal characters"
21 ERROR_EMPTY_FILENAME = "Empty filename"
22 ERROR_NEWLINES_IN_THE_FILENAME = "Newlines in the filename"
23 ERROR_FILE_ALREADY_EXISTS = "File %s already exists"
24 
25 
27 
28  def __init__(self, new_basename):
29  self._new_basename_new_basename = new_basename
30 
31  def validate(self, context):
32  # Try-except is needed to check if file can be created if named like this, using open()
33  # http://code.google.com/p/robotframework-ride/issues/detail?id=1111
34  try:
35  fileName = '%s.%s' % (self._new_basename_new_basename, context.get_format())
36  filePath = os.path.join(context.directory, fileName)
37  if self._file_exists_file_exists(filePath):
38  RideInputValidationError(message=ERROR_FILE_ALREADY_EXISTS % filePath).publish()
39  return False
40  if '\\n' in self._new_basename_new_basename or '\n' in self._new_basename_new_basename:
41  RideInputValidationError(message=ERROR_NEWLINES_IN_THE_FILENAME).publish()
42  return False
43  if len(self._new_basename_new_basename.strip()) == 0:
44  RideInputValidationError(message=ERROR_EMPTY_FILENAME).publish()
45  return False
46  createdDir = False
47  try:
48  import pathlib
49  if pathlib.PurePath(filePath).parent != pathlib.PurePath('.'):
50  # print("DEBUG: Creating dirs %s", pathlib.PurePath(filePath).parent)
51  pathlib.Path(pathlib.PurePath(filePath).parent).mkdir(parents=False,
52  exist_ok=True)
53  createdDir = True
54  # print("DEBUG: Creating file %s", filePath)
55  open(filePath, "w").close()
56  finally:
57  try:
58  os.remove(filePath) # If file creation failed, then this will trigger validation error
59  if createdDir:
60  os.rmdir(pathlib.PurePath(filePath).parent)
61  except Exception:
62  pass
63  return True
64  except (IOError, OSError):
65  RideInputValidationError(message=ERROR_ILLEGAL_CHARACTERS).publish()
66  return False
67 
68  def _file_exists(self, filename):
69  return os.path.exists(filename)
Sent whenever user input is invalid.
Definition: messages.py:157