nwo
stringlengths
10
28
sha
stringlengths
40
40
path
stringlengths
11
97
identifier
stringlengths
1
64
parameters
stringlengths
2
2.24k
return_statement
stringlengths
0
2.17k
docstring
stringlengths
0
5.45k
docstring_summary
stringlengths
0
3.83k
func_begin
int64
1
13.4k
func_end
int64
2
13.4k
function
stringlengths
28
56.4k
url
stringlengths
106
209
project
int64
1
48
executed_lines
list
executed_lines_pc
float64
0
153
missing_lines
list
missing_lines_pc
float64
0
100
covered
bool
2 classes
filecoverage
float64
2.53
100
function_lines
int64
2
1.46k
mccabe
int64
1
253
coverage
float64
0
100
docstring_lines
int64
0
112
function_nodoc
stringlengths
9
56.4k
id
int64
0
29.8k
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/build_programs.py
BuildProgram.__init__
(self, source, build_state)
54
58
def __init__(self, source, build_state): self.source = source self.build_state = build_state self.artifacts = [] self._built = False
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/build_programs.py#L54-L58
40
[ 0, 1, 2, 3, 4 ]
100
[]
0
true
97.122302
5
1
100
0
def __init__(self, source, build_state): self.source = source self.build_state = build_state self.artifacts = [] self._built = False
25,914
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/build_programs.py
BuildProgram.primary_artifact
(self)
Returns the primary artifact for this build program. By default this is the first artifact produced. This needs to be the one that corresponds to the URL of the source if it has one.
Returns the primary artifact for this build program. By default this is the first artifact produced. This needs to be the one that corresponds to the URL of the source if it has one.
61
69
def primary_artifact(self): """Returns the primary artifact for this build program. By default this is the first artifact produced. This needs to be the one that corresponds to the URL of the source if it has one. """ try: return self.artifacts[0] except IndexError: return None
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/build_programs.py#L61-L69
40
[ 0, 1, 2, 3, 4, 5, 6, 7, 8 ]
100
[]
0
true
97.122302
9
2
100
3
def primary_artifact(self): try: return self.artifacts[0] except IndexError: return None
25,915
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/build_programs.py
BuildProgram.describe_source_record
(self)
Can be used to describe the source info by returning a :class:`SourceInfo` object. This is indexed by the builder into the build state so that the UI can quickly find files without having to scan the file system.
Can be used to describe the source info by returning a :class:`SourceInfo` object. This is indexed by the builder into the build state so that the UI can quickly find files without having to scan the file system.
71
76
def describe_source_record(self): """Can be used to describe the source info by returning a :class:`SourceInfo` object. This is indexed by the builder into the build state so that the UI can quickly find files without having to scan the file system. """
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/build_programs.py#L71-L76
40
[ 0, 1, 2, 3, 4, 5 ]
100
[]
0
true
97.122302
6
1
100
4
def describe_source_record(self):
25,916
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/build_programs.py
BuildProgram.build
(self)
Invokes the build program.
Invokes the build program.
78
115
def build(self): """Invokes the build program.""" if self._built: raise RuntimeError("This build program was already used.") self._built = True self.produce_artifacts() sub_artifacts = [] failures = [] gen = self.build_state.builder def _build(artifact, build_func): ctx = gen.build_artifact(artifact, build_func) if ctx is not None: if ctx.exc_info is not None: failures.append(ctx.exc_info) else: sub_artifacts.extend(ctx.sub_artifacts) # Step one is building the artifacts that this build program # knows about. for artifact in self.artifacts: _build(artifact, self.build_artifact) # For as long as our ctx keeps producing sub artifacts, we # want to process them as well. while sub_artifacts and not failures: artifact, build_func = sub_artifacts.pop() _build(artifact, build_func) # If we failed anywhere we want to mark *all* artifacts as dirty. # This means that if a sub-artifact fails we also rebuild the # parent next time around. if failures: for artifact in self.artifacts: artifact.set_dirty_flag()
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/build_programs.py#L78-L115
40
[ 0, 1, 2, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37 ]
97.368421
[ 3 ]
2.631579
false
97.122302
38
10
97.368421
1
def build(self): if self._built: raise RuntimeError("This build program was already used.") self._built = True self.produce_artifacts() sub_artifacts = [] failures = [] gen = self.build_state.builder def _build(artifact, build_func): ctx = gen.build_artifact(artifact, build_func) if ctx is not None: if ctx.exc_info is not None: failures.append(ctx.exc_info) else: sub_artifacts.extend(ctx.sub_artifacts) # Step one is building the artifacts that this build program # knows about. for artifact in self.artifacts: _build(artifact, self.build_artifact) # For as long as our ctx keeps producing sub artifacts, we # want to process them as well. while sub_artifacts and not failures: artifact, build_func = sub_artifacts.pop() _build(artifact, build_func) # If we failed anywhere we want to mark *all* artifacts as dirty. # This means that if a sub-artifact fails we also rebuild the # parent next time around. if failures: for artifact in self.artifacts: artifact.set_dirty_flag()
25,917
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/build_programs.py
BuildProgram.produce_artifacts
(self)
This produces the artifacts for building. Usually this only produces a single artifact.
This produces the artifacts for building. Usually this only produces a single artifact.
117
120
def produce_artifacts(self): """This produces the artifacts for building. Usually this only produces a single artifact. """
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/build_programs.py#L117-L120
40
[ 0, 1, 2, 3 ]
100
[]
0
true
97.122302
4
1
100
2
def produce_artifacts(self):
25,918
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/build_programs.py
BuildProgram.declare_artifact
(self, artifact_name, sources=None, extra=None)
This declares an artifact to be built in this program.
This declares an artifact to be built in this program.
122
131
def declare_artifact(self, artifact_name, sources=None, extra=None): """This declares an artifact to be built in this program.""" self.artifacts.append( self.build_state.new_artifact( artifact_name=artifact_name, sources=sources, source_obj=self.source, extra=extra, ) )
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/build_programs.py#L122-L131
40
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
100
[]
0
true
97.122302
10
1
100
1
def declare_artifact(self, artifact_name, sources=None, extra=None): self.artifacts.append( self.build_state.new_artifact( artifact_name=artifact_name, sources=sources, source_obj=self.source, extra=extra, ) )
25,919
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/build_programs.py
BuildProgram.build_artifact
(self, artifact)
This is invoked for each artifact declared.
This is invoked for each artifact declared.
133
134
def build_artifact(self, artifact): """This is invoked for each artifact declared."""
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/build_programs.py#L133-L134
40
[ 0, 1 ]
100
[]
0
true
97.122302
2
1
100
1
def build_artifact(self, artifact):
25,920
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/build_programs.py
BuildProgram.iter_child_sources
(self)
return iter(())
This allows a build program to produce children that also need building. An individual build never recurses down to this, but a `build_all` will use this.
This allows a build program to produce children that also need building. An individual build never recurses down to this, but a `build_all` will use this.
136
142
def iter_child_sources(self): """This allows a build program to produce children that also need building. An individual build never recurses down to this, but a `build_all` will use this. """ # pylint: disable=no-self-use return iter(())
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/build_programs.py#L136-L142
40
[ 0, 1, 2, 3, 4, 5, 6 ]
100
[]
0
true
97.122302
7
1
100
3
def iter_child_sources(self): # pylint: disable=no-self-use return iter(())
25,921
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/videotools.py
_imround
(x)
return decimal.Decimal(x).to_integral(decimal.ROUND_HALF_UP)
Round float pixel values like imagemagick does it.
Round float pixel values like imagemagick does it.
20
22
def _imround(x): """Round float pixel values like imagemagick does it.""" return decimal.Decimal(x).to_integral(decimal.ROUND_HALF_UP)
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/videotools.py#L20-L22
40
[ 0, 1, 2 ]
100
[]
0
true
89.102564
3
1
100
1
def _imround(x): return decimal.Decimal(x).to_integral(decimal.ROUND_HALF_UP)
25,922
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/videotools.py
get_timecode
(td)
return timecode
Convert a timedelta to an ffmpeg compatible string timecode. A timecode has the format HH:MM:SS, with decimals if needed.
Convert a timedelta to an ffmpeg compatible string timecode.
171
190
def get_timecode(td): """Convert a timedelta to an ffmpeg compatible string timecode. A timecode has the format HH:MM:SS, with decimals if needed. """ seconds = td.total_seconds() hours = int(seconds // 3600) seconds %= 3600 minutes = int(seconds // 60) seconds %= 60 str_seconds, str_decimals = str(float(seconds)).split(".") timecode = "{:02d}:{:02d}:{}".format(hours, minutes, str_seconds.zfill(2)) if str_decimals != "0": timecode += ".{}".format(str_decimals) return timecode
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/videotools.py#L171-L190
40
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 ]
100
[]
0
true
89.102564
20
2
100
3
def get_timecode(td): seconds = td.total_seconds() hours = int(seconds // 3600) seconds %= 3600 minutes = int(seconds // 60) seconds %= 60 str_seconds, str_decimals = str(float(seconds)).split(".") timecode = "{:02d}:{:02d}:{}".format(hours, minutes, str_seconds.zfill(2)) if str_decimals != "0": timecode += ".{}".format(str_decimals) return timecode
25,923
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/videotools.py
get_ffmpeg_quality
(quality_percent)
return int(low + round(span * (1 - factor)))
Convert a value between 0-100 to an ffmpeg quality value (2-31). Note that this is only applicable to the mjpeg encoder (which is used for jpeg images). mjpeg values works in reverse, i.e. lower is better.
Convert a value between 0-100 to an ffmpeg quality value (2-31).
193
205
def get_ffmpeg_quality(quality_percent): """Convert a value between 0-100 to an ffmpeg quality value (2-31). Note that this is only applicable to the mjpeg encoder (which is used for jpeg images). mjpeg values works in reverse, i.e. lower is better. """ if not 0 <= quality_percent <= 100: raise ValueError("Video quality must be between 0 and 100") low, high = 2, 31 span = high - low factor = float(quality_percent) / 100.0 return int(low + round(span * (1 - factor)))
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/videotools.py#L193-L205
40
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]
100
[]
0
true
89.102564
13
2
100
4
def get_ffmpeg_quality(quality_percent): if not 0 <= quality_percent <= 100: raise ValueError("Video quality must be between 0 and 100") low, high = 2, 31 span = high - low factor = float(quality_percent) / 100.0 return int(low + round(span * (1 - factor)))
25,924
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/videotools.py
get_suffix
(seek, width, height, mode, quality)
return suffix
Make suffix for a thumbnail that is unique to the given parameters.
Make suffix for a thumbnail that is unique to the given parameters.
208
222
def get_suffix(seek, width, height, mode, quality): """Make suffix for a thumbnail that is unique to the given parameters.""" timecode = get_timecode(seek).replace(":", "-").replace(".", "-") suffix = "t%s" % timecode if width is not None or height is not None: suffix += "_%s" % "x".join(str(x) for x in [width, height] if x is not None) if mode != ThumbnailMode.DEFAULT: suffix += "_%s" % mode.value if quality is not None: suffix += "_q%s" % quality return suffix
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/videotools.py#L208-L222
40
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14 ]
93.333333
[ 12 ]
6.666667
false
89.102564
15
5
93.333333
1
def get_suffix(seek, width, height, mode, quality): timecode = get_timecode(seek).replace(":", "-").replace(".", "-") suffix = "t%s" % timecode if width is not None or height is not None: suffix += "_%s" % "x".join(str(x) for x in [width, height] if x is not None) if mode != ThumbnailMode.DEFAULT: suffix += "_%s" % mode.value if quality is not None: suffix += "_q%s" % quality return suffix
25,925
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/videotools.py
get_video_info
(filename)
return info
Read video information using ffprobe if available. Returns a dict with: width, height and duration.
Read video information using ffprobe if available.
225
276
def get_video_info(filename): """Read video information using ffprobe if available. Returns a dict with: width, height and duration. """ ffprobe = locate_executable("ffprobe") if ffprobe is None: raise RuntimeError("Failed to locate ffprobe") proc = portable_popen( [ ffprobe, "-v", "quiet", "-print_format", "json", "-show_format", "-show_streams", filename, ], stdout=subprocess.PIPE, ) stdout, _ = proc.communicate() if proc.returncode != 0: raise RuntimeError("ffprobe exited with code %d" % proc.returncode) ffprobe_data = json.loads(stdout.decode("utf8")) info = { "width": None, "height": None, "duration": None, } # Try to extract total video duration try: info["duration"] = timedelta(seconds=float(ffprobe_data["format"]["duration"])) except (KeyError, TypeError, ValueError): pass # Try to extract width and height from the first found video stream for stream in ffprobe_data["streams"]: if stream["codec_type"] != "video": continue info["width"] = int(stream["width"]) info["height"] = int(stream["height"]) # We currently don't bother with multiple video streams break return info
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/videotools.py#L225-L276
40
[ 0, 1, 2, 3, 4, 5, 6, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 40, 41, 42, 44, 45, 46, 47, 48, 49, 50, 51 ]
88.461538
[ 7, 25, 37, 38, 43 ]
9.615385
false
89.102564
52
6
90.384615
3
def get_video_info(filename): ffprobe = locate_executable("ffprobe") if ffprobe is None: raise RuntimeError("Failed to locate ffprobe") proc = portable_popen( [ ffprobe, "-v", "quiet", "-print_format", "json", "-show_format", "-show_streams", filename, ], stdout=subprocess.PIPE, ) stdout, _ = proc.communicate() if proc.returncode != 0: raise RuntimeError("ffprobe exited with code %d" % proc.returncode) ffprobe_data = json.loads(stdout.decode("utf8")) info = { "width": None, "height": None, "duration": None, } # Try to extract total video duration try: info["duration"] = timedelta(seconds=float(ffprobe_data["format"]["duration"])) except (KeyError, TypeError, ValueError): pass # Try to extract width and height from the first found video stream for stream in ffprobe_data["streams"]: if stream["codec_type"] != "video": continue info["width"] = int(stream["width"]) info["height"] = int(stream["height"]) # We currently don't bother with multiple video streams break return info
25,926
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/videotools.py
make_video_thumbnail
( ctx, source_video, source_url_path, seek, width=None, height=None, mode=ThumbnailMode.DEFAULT, upscale=None, quality=None, format=None, )
return Thumbnail(dst_url_path, crop_dim.width, crop_dim.height)
279
371
def make_video_thumbnail( ctx, source_video, source_url_path, seek, width=None, height=None, mode=ThumbnailMode.DEFAULT, upscale=None, quality=None, format=None, ): if mode != ThumbnailMode.FIT and (width is None or height is None): msg = '"%s" mode requires both `width` and `height` to be defined.' raise ValueError(msg % mode.value) if upscale is None: upscale = { ThumbnailMode.FIT: False, ThumbnailMode.CROP: True, ThumbnailMode.STRETCH: True, }[mode] if format is None: format = "jpg" if format not in THUMBNAIL_FORMATS: raise ValueError('Invalid thumbnail format "%s"' % format) if quality is not None and format != "jpg": raise ValueError("The quality parameter is only supported for jpeg images") if seek < timedelta(0): raise ValueError("Seek must not be negative") ffmpeg = locate_executable("ffmpeg") if ffmpeg is None: raise RuntimeError("Failed to locate ffmpeg") info = get_video_info(source_video) source_dim = Dimensions(info["width"], info["height"]) resize_dim, crop_dim = source_dim.resize(width, height, mode, upscale) # Construct a filename suffix unique to the given parameters suffix = get_suffix(seek, width, height, mode=mode, quality=quality) dst_url_path = get_dependent_url(source_url_path, suffix, ext=".{}".format(format)) if quality is None and format == "jpg": quality = 95 def build_thumbnail_artifact(artifact): artifact.ensure_dir() vfilter = "thumbnail,scale={rw}:{rh},crop={tw}:{th}".format( rw=resize_dim.width, rh=resize_dim.height, tw=crop_dim.width, th=crop_dim.height, ) cmdline = [ ffmpeg, "-loglevel", "-8", "-ss", get_timecode(seek), # Input seeking since it's faster "-i", source_video, "-vf", vfilter, "-frames:v", "1", "-qscale:v", str(get_ffmpeg_quality(quality)), artifact.dst_filename, ] reporter.report_debug_info("ffmpeg cmd line", cmdline) proc = portable_popen(cmdline) if proc.wait() != 0: raise RuntimeError("ffmpeg exited with code {}".format(proc.returncode)) if not os.path.exists(artifact.dst_filename): msg = ( "Unable to create video thumbnail for {!r}. Maybe the seek " "is outside of the video duration?" ) raise RuntimeError(msg.format(source_video)) ctx.sub_artifact(artifact_name=dst_url_path, sources=[source_video])( build_thumbnail_artifact ) return Thumbnail(dst_url_path, crop_dim.width, crop_dim.height)
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/videotools.py#L279-L371
40
[ 0, 12, 15, 16, 17, 22, 23, 24, 25, 27, 28, 30, 31, 33, 34, 35, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 58, 59, 75, 76, 77, 78, 80, 81, 87, 88, 91, 92 ]
47.311828
[ 13, 14, 26, 29, 32, 36, 79, 82, 86 ]
9.677419
false
89.102564
93
16
90.322581
0
def make_video_thumbnail( ctx, source_video, source_url_path, seek, width=None, height=None, mode=ThumbnailMode.DEFAULT, upscale=None, quality=None, format=None, ): if mode != ThumbnailMode.FIT and (width is None or height is None): msg = '"%s" mode requires both `width` and `height` to be defined.' raise ValueError(msg % mode.value) if upscale is None: upscale = { ThumbnailMode.FIT: False, ThumbnailMode.CROP: True, ThumbnailMode.STRETCH: True, }[mode] if format is None: format = "jpg" if format not in THUMBNAIL_FORMATS: raise ValueError('Invalid thumbnail format "%s"' % format) if quality is not None and format != "jpg": raise ValueError("The quality parameter is only supported for jpeg images") if seek < timedelta(0): raise ValueError("Seek must not be negative") ffmpeg = locate_executable("ffmpeg") if ffmpeg is None: raise RuntimeError("Failed to locate ffmpeg") info = get_video_info(source_video) source_dim = Dimensions(info["width"], info["height"]) resize_dim, crop_dim = source_dim.resize(width, height, mode, upscale) # Construct a filename suffix unique to the given parameters suffix = get_suffix(seek, width, height, mode=mode, quality=quality) dst_url_path = get_dependent_url(source_url_path, suffix, ext=".{}".format(format)) if quality is None and format == "jpg": quality = 95 def build_thumbnail_artifact(artifact): artifact.ensure_dir() vfilter = "thumbnail,scale={rw}:{rh},crop={tw}:{th}".format( rw=resize_dim.width, rh=resize_dim.height, tw=crop_dim.width, th=crop_dim.height, ) cmdline = [ ffmpeg, "-loglevel", "-8", "-ss", get_timecode(seek), # Input seeking since it's faster "-i", source_video, "-vf", vfilter, "-frames:v", "1", "-qscale:v", str(get_ffmpeg_quality(quality)), artifact.dst_filename, ] reporter.report_debug_info("ffmpeg cmd line", cmdline) proc = portable_popen(cmdline) if proc.wait() != 0: raise RuntimeError("ffmpeg exited with code {}".format(proc.returncode)) if not os.path.exists(artifact.dst_filename): msg = ( "Unable to create video thumbnail for {!r}. Maybe the seek " "is outside of the video duration?" ) raise RuntimeError(msg.format(source_video)) ctx.sub_artifact(artifact_name=dst_url_path, sources=[source_video])( build_thumbnail_artifact ) return Thumbnail(dst_url_path, crop_dim.width, crop_dim.height)
25,927
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/videotools.py
Dimensions.__new__
(cls, width, height)
return super(Dimensions, cls).__new__(cls, width, height)
31
38
def __new__(cls, width, height): width = int(width) height = int(height) if width < 1 or height < 1: raise ValueError("Invalid dimensions") return super(Dimensions, cls).__new__(cls, width, height)
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/videotools.py#L31-L38
40
[ 0, 1, 2, 3, 4, 6, 7 ]
87.5
[ 5 ]
12.5
false
89.102564
8
3
87.5
0
def __new__(cls, width, height): width = int(width) height = int(height) if width < 1 or height < 1: raise ValueError("Invalid dimensions") return super(Dimensions, cls).__new__(cls, width, height)
25,928
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/videotools.py
Dimensions.aspect_ratio
(self)
return float(self.width) / float(self.height)
41
42
def aspect_ratio(self): return float(self.width) / float(self.height)
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/videotools.py#L41-L42
40
[ 0, 1 ]
100
[]
0
true
89.102564
2
1
100
0
def aspect_ratio(self): return float(self.width) / float(self.height)
25,929
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/videotools.py
Dimensions._infer_dimensions
(self, width, height)
return Dimensions(width, height)
Calculate dimensions based on aspect ratio if height, width or both are missing.
Calculate dimensions based on aspect ratio if height, width or both are missing.
44
56
def _infer_dimensions(self, width, height): """Calculate dimensions based on aspect ratio if height, width or both are missing. """ if width is None and height is None: return self if width is None: width = _imround(height * self.aspect_ratio) elif height is None: height = _imround(width / self.aspect_ratio) return Dimensions(width, height)
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/videotools.py#L44-L56
40
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]
100
[]
0
true
89.102564
13
5
100
2
def _infer_dimensions(self, width, height): if width is None and height is None: return self if width is None: width = _imround(height * self.aspect_ratio) elif height is None: height = _imround(width / self.aspect_ratio) return Dimensions(width, height)
25,930
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/videotools.py
Dimensions.contains
(self, other)
return self.width >= other.width and self.height >= other.height
Return True if the given Dimensions can be completely enclosed by this Dimensions.
Return True if the given Dimensions can be completely enclosed by this Dimensions.
58
62
def contains(self, other): """Return True if the given Dimensions can be completely enclosed by this Dimensions. """ return self.width >= other.width and self.height >= other.height
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/videotools.py#L58-L62
40
[ 0, 1, 2, 3, 4 ]
100
[]
0
true
89.102564
5
2
100
2
def contains(self, other): return self.width >= other.width and self.height >= other.height
25,931
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/videotools.py
Dimensions.fit_within
(self, max_width=None, max_height=None, upscale=None)
return Rescaling(rescale=rescale_dim, crop=rescale_dim)
Calculate resizing required to make these dimensions fit within the given dimensions. Note that resizing only occurs if upscale is enabled. >>> source = Dimensions(640, 480) >>> source.fit_within(max_width=320).rescale == Dimensions(320, 240) True :param max_width: Maximum width for the new rescaled dimensions. :param max_height: Maximum height for the new rescaled dimensions. :param upscale: Allow making the dimensions larger (default False). :return: Rescaling operations :rtype: Rescaling
Calculate resizing required to make these dimensions fit within the given dimensions.
64
95
def fit_within(self, max_width=None, max_height=None, upscale=None): """Calculate resizing required to make these dimensions fit within the given dimensions. Note that resizing only occurs if upscale is enabled. >>> source = Dimensions(640, 480) >>> source.fit_within(max_width=320).rescale == Dimensions(320, 240) True :param max_width: Maximum width for the new rescaled dimensions. :param max_height: Maximum height for the new rescaled dimensions. :param upscale: Allow making the dimensions larger (default False). :return: Rescaling operations :rtype: Rescaling """ if upscale is None: upscale = False max_dim = self._infer_dimensions(max_width, max_height) # Check if we should rescale at all if max_dim == self or (not upscale and max_dim.contains(self)): return Rescaling(self, self) ar = self.aspect_ratio rescale_dim = Dimensions( width=_imround(min(max_dim.width, max_dim.height * ar)), height=_imround(min(max_dim.height, max_dim.width / ar)), ) return Rescaling(rescale=rescale_dim, crop=rescale_dim)
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/videotools.py#L64-L95
40
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31 ]
100
[]
0
true
89.102564
32
5
100
14
def fit_within(self, max_width=None, max_height=None, upscale=None): if upscale is None: upscale = False max_dim = self._infer_dimensions(max_width, max_height) # Check if we should rescale at all if max_dim == self or (not upscale and max_dim.contains(self)): return Rescaling(self, self) ar = self.aspect_ratio rescale_dim = Dimensions( width=_imround(min(max_dim.width, max_dim.height * ar)), height=_imround(min(max_dim.height, max_dim.width / ar)), ) return Rescaling(rescale=rescale_dim, crop=rescale_dim)
25,932
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/videotools.py
Dimensions.cover
(self, min_width=None, min_height=None, upscale=None)
return Rescaling(rescale=rescale_dim, crop=min_dim)
Calculate resizing required to make these dimensions cover the given dimensions. Note that resizing only occurs if upscale is enabled. >>> source = Dimensions(640, 480) >>> target = source.cover(240, 240) >>> target.rescale == Dimensions(320, 240) True >>> target.crop == Dimensions(240, 240) True :param min_width: Minimum width for the new rescaled dimensions. :param min_height: Minimum height for the new rescaled dimensions. :param upscale: Allow making the dimensions larger (default True). :return: Rescaling operations :rtype: Rescaling
Calculate resizing required to make these dimensions cover the given dimensions.
97
131
def cover(self, min_width=None, min_height=None, upscale=None): """Calculate resizing required to make these dimensions cover the given dimensions. Note that resizing only occurs if upscale is enabled. >>> source = Dimensions(640, 480) >>> target = source.cover(240, 240) >>> target.rescale == Dimensions(320, 240) True >>> target.crop == Dimensions(240, 240) True :param min_width: Minimum width for the new rescaled dimensions. :param min_height: Minimum height for the new rescaled dimensions. :param upscale: Allow making the dimensions larger (default True). :return: Rescaling operations :rtype: Rescaling """ if upscale is None: upscale = True min_dim = self._infer_dimensions(min_width, min_height) # Check if we should rescale at all if min_dim == self or (not upscale and min_dim.contains(self)): return Rescaling(self, self) ar = self.aspect_ratio rescale_dim = Dimensions( width=_imround(max(min_dim.width, min_dim.height * ar)), height=_imround(max(min_dim.height, min_dim.width / ar)), ) return Rescaling(rescale=rescale_dim, crop=min_dim)
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/videotools.py#L97-L131
40
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34 ]
100
[]
0
true
89.102564
35
5
100
17
def cover(self, min_width=None, min_height=None, upscale=None): if upscale is None: upscale = True min_dim = self._infer_dimensions(min_width, min_height) # Check if we should rescale at all if min_dim == self or (not upscale and min_dim.contains(self)): return Rescaling(self, self) ar = self.aspect_ratio rescale_dim = Dimensions( width=_imround(max(min_dim.width, min_dim.height * ar)), height=_imround(max(min_dim.height, min_dim.width / ar)), ) return Rescaling(rescale=rescale_dim, crop=min_dim)
25,933
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/videotools.py
Dimensions.stretch
(self, width=None, height=None, upscale=None)
return Rescaling(rescale=dim, crop=dim)
Calculate resizing required to the given dimensions without considering aspect ratio. Note that resizing only occurs if upscale is enabled. >>> source = Dimensions(640, 480) >>> source.cover(240, 240).rescale == Dimensions(240, 240) True :param min_width: Minimum width for the new rescaled dimensions. :param min_height: Minimum height for the new rescaled dimensions. :param upscale: Allow making the dimensions larger (default True). :return: Rescaling operations :rtype: Rescaling
Calculate resizing required to the given dimensions without considering aspect ratio.
133
158
def stretch(self, width=None, height=None, upscale=None): """Calculate resizing required to the given dimensions without considering aspect ratio. Note that resizing only occurs if upscale is enabled. >>> source = Dimensions(640, 480) >>> source.cover(240, 240).rescale == Dimensions(240, 240) True :param min_width: Minimum width for the new rescaled dimensions. :param min_height: Minimum height for the new rescaled dimensions. :param upscale: Allow making the dimensions larger (default True). :return: Rescaling operations :rtype: Rescaling """ if upscale is None: upscale = True dim = self._infer_dimensions(width, height) # Check if we should rescale at all if dim == self or (not upscale and dim.contains(self)): return Rescaling(self, self) return Rescaling(rescale=dim, crop=dim)
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/videotools.py#L133-L158
40
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25 ]
100
[]
0
true
89.102564
26
5
100
14
def stretch(self, width=None, height=None, upscale=None): if upscale is None: upscale = True dim = self._infer_dimensions(width, height) # Check if we should rescale at all if dim == self or (not upscale and dim.contains(self)): return Rescaling(self, self) return Rescaling(rescale=dim, crop=dim)
25,934
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/videotools.py
Dimensions.resize
(self, width=None, height=None, mode=ThumbnailMode.DEFAULT, upscale=None)
160
168
def resize(self, width=None, height=None, mode=ThumbnailMode.DEFAULT, upscale=None): if mode == ThumbnailMode.FIT: return self.fit_within(width, height, upscale) if mode == ThumbnailMode.CROP: return self.cover(width, height, upscale) if mode == ThumbnailMode.STRETCH: return self.stretch(width, height, upscale) raise ValueError('Unexpected mode "{!r}"'.format(mode))
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/videotools.py#L160-L168
40
[ 0, 1, 2, 3, 4, 5, 7, 8 ]
88.888889
[ 6 ]
11.111111
false
89.102564
9
4
88.888889
0
def resize(self, width=None, height=None, mode=ThumbnailMode.DEFAULT, upscale=None): if mode == ThumbnailMode.FIT: return self.fit_within(width, height, upscale) if mode == ThumbnailMode.CROP: return self.cover(width, height, upscale) if mode == ThumbnailMode.STRETCH: return self.stretch(width, height, upscale) raise ValueError('Unexpected mode "{!r}"'.format(mode))
25,935
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/publisher.py
_ssh_key_file
( credentials: Optional[Mapping[str, str]] )
47
65
def _ssh_key_file( credentials: Optional[Mapping[str, str]] ) -> Iterator[Optional["StrPath"]]: with ExitStack() as stack: key_file: Optional["StrPath"] key_file = credentials.get("key_file") if credentials else None key = credentials.get("key") if credentials else None if not key_file and key: if ":" in key: key_type, _, key = key.partition(":") key_type = key_type.upper() else: key_type = "RSA" key_file = Path(stack.enter_context(TemporaryDirectory()), "keyfile") with key_file.open("w", encoding="utf-8") as f: f.write(f"-----BEGIN {key_type} PRIVATE KEY-----\n") f.writelines(key[x : x + 64] + "\n" for x in range(0, len(key), 64)) f.write(f"-----END {key_type} PRIVATE KEY-----\n") yield key_file
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/publisher.py#L47-L65
40
[ 0, 3, 5, 6, 7, 8, 9, 10, 12, 13, 14, 15, 16, 17, 18 ]
78.947368
[]
0
false
52.767528
19
6
100
0
def _ssh_key_file( credentials: Optional[Mapping[str, str]] ) -> Iterator[Optional["StrPath"]]: with ExitStack() as stack: key_file: Optional["StrPath"] key_file = credentials.get("key_file") if credentials else None key = credentials.get("key") if credentials else None if not key_file and key: if ":" in key: key_type, _, key = key.partition(":") key_type = key_type.upper() else: key_type = "RSA" key_file = Path(stack.enter_context(TemporaryDirectory()), "keyfile") with key_file.open("w", encoding="utf-8") as f: f.write(f"-----BEGIN {key_type} PRIVATE KEY-----\n") f.writelines(key[x : x + 64] + "\n" for x in range(0, len(key), 64)) f.write(f"-----END {key_type} PRIVATE KEY-----\n") yield key_file
25,936
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/publisher.py
_ssh_command
( credentials: Optional[Mapping[str, str]], port: Optional[int] = None )
69
81
def _ssh_command( credentials: Optional[Mapping[str, str]], port: Optional[int] = None ) -> Iterator[Optional[str]]: with _ssh_key_file(credentials) as key_file: args = [] if port: args.append(f" -p {port}") if key_file: args.append(f' -i "{key_file}" -o IdentitiesOnly=yes') if args: yield "ssh" + " ".join(args) else: yield None
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/publisher.py#L69-L81
40
[ 0, 3, 4, 5, 6, 7, 8, 9, 10, 12 ]
76.923077
[]
0
false
52.767528
13
5
100
0
def _ssh_command( credentials: Optional[Mapping[str, str]], port: Optional[int] = None ) -> Iterator[Optional[str]]: with _ssh_key_file(credentials) as key_file: args = [] if port: args.append(f" -p {port}") if key_file: args.append(f' -i "{key_file}" -o IdentitiesOnly=yes') if args: yield "ssh" + " ".join(args) else: yield None
25,937
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/publisher.py
_prefix_output
(lines: Iterable[str], prefix: str = "> ")
return (f"{prefix}{line}" for line in lines)
Add prefix to lines.
Add prefix to lines.
782
784
def _prefix_output(lines: Iterable[str], prefix: str = "> ") -> Iterator[str]: """Add prefix to lines.""" return (f"{prefix}{line}" for line in lines)
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/publisher.py#L782-L784
40
[ 0, 1, 2 ]
100
[]
0
true
52.767528
3
1
100
1
def _prefix_output(lines: Iterable[str], prefix: str = "> ") -> Iterator[str]: return (f"{prefix}{line}" for line in lines)
25,938
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/publisher.py
publish
(env, target, output_path, credentials=None, **extra)
return publisher(env, output_path).publish(url, credentials, **extra)
903
908
def publish(env, target, output_path, credentials=None, **extra): url = urls.url_parse(str(target)) publisher = env.publishers.get(url.scheme) if publisher is None: raise PublishError('"%s" is an unknown scheme.' % url.scheme) return publisher(env, output_path).publish(url, credentials, **extra)
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/publisher.py#L903-L908
40
[ 0, 1, 2, 3, 4 ]
83.333333
[ 5 ]
16.666667
false
52.767528
6
2
83.333333
0
def publish(env, target, output_path, credentials=None, **extra): url = urls.url_parse(str(target)) publisher = env.publishers.get(url.scheme) if publisher is None: raise PublishError('"%s" is an unknown scheme.' % url.scheme) return publisher(env, output_path).publish(url, credentials, **extra)
25,939
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/publisher.py
Command.__init__
( self, argline: Iterable[str], cwd: Optional["StrOrBytesPath"] = None, env: Optional[Mapping[str, str]] = None, capture: bool = True, silent: bool = False, check: bool = False, input: Optional[str] = None, capture_stdout: bool = False, )
138
182
def __init__( self, argline: Iterable[str], cwd: Optional["StrOrBytesPath"] = None, env: Optional[Mapping[str, str]] = None, capture: bool = True, silent: bool = False, check: bool = False, input: Optional[str] = None, capture_stdout: bool = False, ) -> None: kwargs: Dict[str, Any] = {"cwd": cwd} if env: kwargs["env"] = {**os.environ, **env} if silent: kwargs["stdout"] = DEVNULL kwargs["stderr"] = DEVNULL capture = False if input is not None: kwargs["stdin"] = PIPE if capture or capture_stdout: kwargs["stdout"] = PIPE if capture: kwargs["stderr"] = STDOUT if not capture_stdout else PIPE # Python >= 3.7 has sane encoding defaults in the case that the system is # (likely mis-)configured to use ASCII as the default encoding (PEP538). # It also provides a way for the user to force the use of UTF-8 (PEP540). kwargs["text"] = True kwargs["errors"] = "replace" self.capture = capture # b/c - unused self.check = check self._stdout = None with ExitStack() as stack: self._cmd = stack.enter_context(portable_popen(list(argline), **kwargs)) self._closer: Optional[Callable[[], None]] = stack.pop_all().close if input is not None or capture_stdout: self._output = self._communicate(input, capture_stdout, capture) elif capture: self._output = self._cmd.stdout else: self._output = None
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/publisher.py#L138-L182
40
[ 0, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 44 ]
75.555556
[]
0
false
52.767528
45
11
100
0
def __init__( self, argline: Iterable[str], cwd: Optional["StrOrBytesPath"] = None, env: Optional[Mapping[str, str]] = None, capture: bool = True, silent: bool = False, check: bool = False, input: Optional[str] = None, capture_stdout: bool = False, ) -> None: kwargs: Dict[str, Any] = {"cwd": cwd} if env: kwargs["env"] = {**os.environ, **env} if silent: kwargs["stdout"] = DEVNULL kwargs["stderr"] = DEVNULL capture = False if input is not None: kwargs["stdin"] = PIPE if capture or capture_stdout: kwargs["stdout"] = PIPE if capture: kwargs["stderr"] = STDOUT if not capture_stdout else PIPE # Python >= 3.7 has sane encoding defaults in the case that the system is # (likely mis-)configured to use ASCII as the default encoding (PEP538). # It also provides a way for the user to force the use of UTF-8 (PEP540). kwargs["text"] = True kwargs["errors"] = "replace" self.capture = capture # b/c - unused self.check = check self._stdout = None with ExitStack() as stack: self._cmd = stack.enter_context(portable_popen(list(argline), **kwargs)) self._closer: Optional[Callable[[], None]] = stack.pop_all().close if input is not None or capture_stdout: self._output = self._communicate(input, capture_stdout, capture) elif capture: self._output = self._cmd.stdout else: self._output = None
25,940
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/publisher.py
Command._communicate
( self, input: Optional[str], capture_stdout: bool, capture: bool )
return None
184
200
def _communicate( self, input: Optional[str], capture_stdout: bool, capture: bool ) -> Optional[Iterator[str]]: proc = self._cmd try: if capture_stdout: self._stdout, errout = proc.communicate(input) else: errout, _ = proc.communicate(input) except BaseException: proc.kill() with suppress(CalledProcessError): self.close() raise if capture: return iter(errout.splitlines()) return None
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/publisher.py#L184-L200
40
[ 0, 3, 4, 5, 6, 8, 9, 10, 11, 12, 13, 14, 15, 16 ]
82.352941
[]
0
false
52.767528
17
5
100
0
def _communicate( self, input: Optional[str], capture_stdout: bool, capture: bool ) -> Optional[Iterator[str]]: proc = self._cmd try: if capture_stdout: self._stdout, errout = proc.communicate(input) else: errout, _ = proc.communicate(input) except BaseException: proc.kill() with suppress(CalledProcessError): self.close() raise if capture: return iter(errout.splitlines()) return None
25,941
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/publisher.py
Command.close
(self)
Wait for subprocess to complete. If check=True was passed to the constructor, raises ``CalledProcessError`` if the subprocess returns a non-zero status code.
Wait for subprocess to complete.
202
215
def close(self) -> None: """Wait for subprocess to complete. If check=True was passed to the constructor, raises ``CalledProcessError`` if the subprocess returns a non-zero status code. """ closer, self._closer = self._closer, None if closer: # This waits for process and closes standard file descriptors closer() if self.check: rc = self._cmd.poll() if rc != 0: raise CalledProcessError(rc, self._cmd.args, self._stdout)
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/publisher.py#L202-L215
40
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 ]
100
[]
0
true
52.767528
14
4
100
4
def close(self) -> None: closer, self._closer = self._closer, None if closer: # This waits for process and closes standard file descriptors closer() if self.check: rc = self._cmd.poll() if rc != 0: raise CalledProcessError(rc, self._cmd.args, self._stdout)
25,942
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/publisher.py
Command.wait
(self)
return self._cmd.returncode
Wait for subprocess to complete. Return status code.
Wait for subprocess to complete. Return status code.
217
221
def wait(self) -> int: """Wait for subprocess to complete. Return status code.""" self._cmd.wait() self.close() return self._cmd.returncode
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/publisher.py#L217-L221
40
[ 0, 1, 2, 3, 4 ]
100
[]
0
true
52.767528
5
1
100
1
def wait(self) -> int: self._cmd.wait() self.close() return self._cmd.returncode
25,943
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/publisher.py
Command.result
(self)
return CompletedProcess(self._cmd.args, self.wait(), self._stdout)
Wait for subprocess to complete. Return ``CompletedProcess`` instance. If ``capture_stdout=True`` was passed to the constructor, the output captured from stdout will be available on the ``.stdout`` attribute of the return value.
Wait for subprocess to complete. Return ``CompletedProcess`` instance.
223
230
def result(self) -> "CompletedProcess[str]": """Wait for subprocess to complete. Return ``CompletedProcess`` instance. If ``capture_stdout=True`` was passed to the constructor, the output captured from stdout will be available on the ``.stdout`` attribute of the return value. """ return CompletedProcess(self._cmd.args, self.wait(), self._stdout)
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/publisher.py#L223-L230
40
[ 0, 1, 2, 3, 4, 5, 6, 7 ]
100
[]
0
true
52.767528
8
1
100
5
def result(self) -> "CompletedProcess[str]": return CompletedProcess(self._cmd.args, self.wait(), self._stdout)
25,944
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/publisher.py
Command.returncode
(self)
return self._cmd.returncode
Return exit status of the subprocess. Or ``None`` if the subprocess is still alive.
Return exit status of the subprocess.
233
238
def returncode(self) -> Optional[int]: """Return exit status of the subprocess. Or ``None`` if the subprocess is still alive. """ return self._cmd.returncode
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/publisher.py#L233-L238
40
[ 0, 1, 2, 3, 4, 5 ]
100
[]
0
true
52.767528
6
1
100
3
def returncode(self) -> Optional[int]: return self._cmd.returncode
25,945
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/publisher.py
Command.__exit__
(self, *__: Any)
240
241
def __exit__(self, *__: Any) -> None: self.close()
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/publisher.py#L240-L241
40
[ 0, 1 ]
100
[]
0
true
52.767528
2
1
100
0
def __exit__(self, *__: Any) -> None: self.close()
25,946
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/publisher.py
Command.__iter__
(self)
return self.result()
A generator with yields any captured output and returns a ``CompletedProcess``. If ``capture`` is ``True`` (the default). Both stdout and stderr are available in the iterator output. If ``capture_stdout`` is set, stdout is captured to a string which is made available via ``CompletedProcess.stdout`` attribute of the return value. Stderr output is available via the iterator output, as normal.
A generator with yields any captured output and returns a ``CompletedProcess``.
243
257
def __iter__(self) -> Generator[str, None, "CompletedProcess[str]"]: """A generator with yields any captured output and returns a ``CompletedProcess``. If ``capture`` is ``True`` (the default). Both stdout and stderr are available in the iterator output. If ``capture_stdout`` is set, stdout is captured to a string which is made available via ``CompletedProcess.stdout`` attribute of the return value. Stderr output is available via the iterator output, as normal. """ if self._output is None: raise RuntimeError("Not capturing") for line in self._output: yield line.rstrip() return self.result()
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/publisher.py#L243-L257
40
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 ]
100
[]
0
true
52.767528
15
3
100
8
def __iter__(self) -> Generator[str, None, "CompletedProcess[str]"]: if self._output is None: raise RuntimeError("Not capturing") for line in self._output: yield line.rstrip() return self.result()
25,947
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/publisher.py
Command.output
(self)
return self.safe_iter()
262
263
def output(self) -> Iterator[str]: # b/c - deprecated return self.safe_iter()
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/publisher.py#L262-L263
40
[ 0, 1 ]
100
[]
0
true
52.767528
2
1
100
0
def output(self) -> Iterator[str]: # b/c - deprecated return self.safe_iter()
25,948
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/publisher.py
Publisher.__init__
(self, env: "Environment", output_path: str)
267
269
def __init__(self, env: "Environment", output_path: str) -> None: self.env = env self.output_path = os.path.abspath(output_path)
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/publisher.py#L267-L269
40
[ 0, 1, 2 ]
100
[]
0
true
52.767528
3
1
100
0
def __init__(self, env: "Environment", output_path: str) -> None: self.env = env self.output_path = os.path.abspath(output_path)
25,949
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/publisher.py
Publisher.fail
(self, message: str)
271
273
def fail(self, message: str) -> NoReturn: # pylint: disable=no-self-use raise PublishError(message)
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/publisher.py#L271-L273
40
[ 0, 1, 2 ]
100
[]
0
true
52.767528
3
1
100
0
def fail(self, message: str) -> NoReturn: # pylint: disable=no-self-use raise PublishError(message)
25,950
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/publisher.py
RsyncPublisher.get_command
(self, target_url, credentials)
286
316
def get_command(self, target_url, credentials): credentials = credentials or {} argline = ["rsync", "-rclzv", "--exclude=.lektor"] target = [] env = {} options = target_url.decode_query() exclude = options.getlist("exclude") for file in exclude: argline.extend(("--exclude", file)) delete = options.get("delete", False) in ("", "on", "yes", "true", "1", None) if delete: argline.append("--delete-after") with _ssh_command(credentials, target_url.port) as ssh_command: if ssh_command: argline.extend(("-e", ssh_command)) username = credentials.get("username") or target_url.username if username: target.append(username + "@") if target_url.ascii_host is not None: target.append(target_url.ascii_host) target.append(":") target.append(target_url.path.rstrip("/") + "/") argline.append(self.output_path.rstrip("/\\") + "/") argline.append("".join(target)) yield Command(argline, env=env)
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/publisher.py#L286-L316
40
[ 0 ]
3.225806
[ 1, 2, 3, 4, 6, 7, 8, 9, 11, 12, 13, 15, 16, 17, 19, 20, 21, 23, 24, 25, 26, 28, 29, 30 ]
77.419355
false
52.767528
31
9
22.580645
0
def get_command(self, target_url, credentials): credentials = credentials or {} argline = ["rsync", "-rclzv", "--exclude=.lektor"] target = [] env = {} options = target_url.decode_query() exclude = options.getlist("exclude") for file in exclude: argline.extend(("--exclude", file)) delete = options.get("delete", False) in ("", "on", "yes", "true", "1", None) if delete: argline.append("--delete-after") with _ssh_command(credentials, target_url.port) as ssh_command: if ssh_command: argline.extend(("-e", ssh_command)) username = credentials.get("username") or target_url.username if username: target.append(username + "@") if target_url.ascii_host is not None: target.append(target_url.ascii_host) target.append(":") target.append(target_url.path.rstrip("/") + "/") argline.append(self.output_path.rstrip("/\\") + "/") argline.append("".join(target)) yield Command(argline, env=env)
25,951
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/publisher.py
RsyncPublisher.publish
(self, target_url, credentials=None, **extra)
318
320
def publish(self, target_url, credentials=None, **extra): with self.get_command(target_url, credentials) as client: yield from client
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/publisher.py#L318-L320
40
[ 0 ]
33.333333
[ 1, 2 ]
66.666667
false
52.767528
3
2
33.333333
0
def publish(self, target_url, credentials=None, **extra): with self.get_command(target_url, credentials) as client: yield from client
25,952
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/publisher.py
FtpConnection.__init__
(self, url, credentials=None)
324
331
def __init__(self, url, credentials=None): credentials = credentials or {} self.con = self.make_connection() self.url = url self.username = credentials.get("username") or url.username self.password = credentials.get("password") or url.password self.log_buffer = [] self._known_folders = set()
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/publisher.py#L324-L331
40
[ 0 ]
12.5
[ 1, 2, 3, 4, 5, 6, 7 ]
87.5
false
52.767528
8
4
12.5
0
def __init__(self, url, credentials=None): credentials = credentials or {} self.con = self.make_connection() self.url = url self.username = credentials.get("username") or url.username self.password = credentials.get("password") or url.password self.log_buffer = [] self._known_folders = set()
25,953
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/publisher.py
FtpConnection.make_connection
()
return FTP()
334
338
def make_connection(): # pylint: disable=import-outside-toplevel from ftplib import FTP return FTP()
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/publisher.py#L334-L338
40
[ 0, 1 ]
40
[ 2, 4 ]
40
false
52.767528
5
1
60
0
def make_connection(): # pylint: disable=import-outside-toplevel from ftplib import FTP return FTP()
25,954
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/publisher.py
FtpConnection.drain_log
(self)
340
347
def drain_log(self): log = self.log_buffer[:] del self.log_buffer[:] for chunk in log: for line in chunk.splitlines(): if not isinstance(line, str): line = line.decode("utf-8", "replace") yield line.rstrip()
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/publisher.py#L340-L347
40
[ 0 ]
12.5
[ 1, 2, 3, 4, 5, 6, 7 ]
87.5
false
52.767528
8
4
12.5
0
def drain_log(self): log = self.log_buffer[:] del self.log_buffer[:] for chunk in log: for line in chunk.splitlines(): if not isinstance(line, str): line = line.decode("utf-8", "replace") yield line.rstrip()
25,955
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/publisher.py
FtpConnection.connect
(self)
return True
349
385
def connect(self): options = self.url.decode_query() log = self.log_buffer log.append("000 Connecting to server ...") try: log.append(self.con.connect(self.url.ascii_host, self.url.port or 21)) except Exception as e: log.append("000 Could not connect.") log.append(str(e)) return False try: credentials = {} if self.username: credentials["user"] = self.username if self.password: credentials["passwd"] = self.password log.append(self.con.login(**credentials)) except Exception as e: log.append("000 Could not authenticate.") log.append(str(e)) return False passive = options.get("passive") in ("on", "yes", "true", "1", None) log.append("000 Using passive mode: %s" % (passive and "yes" or "no")) self.con.set_pasv(passive) try: log.append(self.con.cwd(self.url.path)) except Exception as e: log.append(str(e)) return False log.append("000 Connected!") return True
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/publisher.py#L349-L385
40
[ 0 ]
2.702703
[ 1, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 14, 15, 16, 17, 18, 20, 21, 22, 23, 25, 26, 27, 29, 30, 31, 32, 33, 35, 36 ]
81.081081
false
52.767528
37
9
18.918919
0
def connect(self): options = self.url.decode_query() log = self.log_buffer log.append("000 Connecting to server ...") try: log.append(self.con.connect(self.url.ascii_host, self.url.port or 21)) except Exception as e: log.append("000 Could not connect.") log.append(str(e)) return False try: credentials = {} if self.username: credentials["user"] = self.username if self.password: credentials["passwd"] = self.password log.append(self.con.login(**credentials)) except Exception as e: log.append("000 Could not authenticate.") log.append(str(e)) return False passive = options.get("passive") in ("on", "yes", "true", "1", None) log.append("000 Using passive mode: %s" % (passive and "yes" or "no")) self.con.set_pasv(passive) try: log.append(self.con.cwd(self.url.path)) except Exception as e: log.append(str(e)) return False log.append("000 Connected!") return True
25,956
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/publisher.py
FtpConnection.mkdir
(self, path, recursive=True)
387
402
def mkdir(self, path, recursive=True): if not isinstance(path, str): path = path.decode("utf-8") if path in self._known_folders: return dirname, _ = posixpath.split(path) if dirname and recursive: self.mkdir(dirname) try: self.con.mkd(path) except FTPError as e: msg = str(e) if msg[:4] != "550 ": self.log_buffer.append(str(e)) return self._known_folders.add(path)
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/publisher.py#L387-L402
40
[ 0 ]
6.25
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ]
93.75
false
52.767528
16
7
6.25
0
def mkdir(self, path, recursive=True): if not isinstance(path, str): path = path.decode("utf-8") if path in self._known_folders: return dirname, _ = posixpath.split(path) if dirname and recursive: self.mkdir(dirname) try: self.con.mkd(path) except FTPError as e: msg = str(e) if msg[:4] != "550 ": self.log_buffer.append(str(e)) return self._known_folders.add(path)
25,957
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/publisher.py
FtpConnection.append
(self, filename, data)
return True
404
415
def append(self, filename, data): if not isinstance(filename, str): filename = filename.decode("utf-8") input = io.BytesIO(data.encode("utf-8")) try: self.con.storbinary("APPE " + filename, input) except FTPError as e: self.log_buffer.append(str(e)) return False return True
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/publisher.py#L404-L415
40
[ 0 ]
8.333333
[ 1, 2, 4, 6, 7, 8, 9, 10, 11 ]
75
false
52.767528
12
3
25
0
def append(self, filename, data): if not isinstance(filename, str): filename = filename.decode("utf-8") input = io.BytesIO(data.encode("utf-8")) try: self.con.storbinary("APPE " + filename, input) except FTPError as e: self.log_buffer.append(str(e)) return False return True
25,958
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/publisher.py
FtpConnection.get_file
(self, filename, out=None)
return out
417
433
def get_file(self, filename, out=None): if not isinstance(filename, str): filename = filename.decode("utf-8") getvalue = False if out is None: out = io.BytesIO() getvalue = True try: self.con.retrbinary("RETR " + filename, out.write) except FTPError as e: msg = str(e) if msg[:4] != "550 ": self.log_buffer.append(e) return None if getvalue: return out.getvalue().decode("utf-8") return out
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/publisher.py#L417-L433
40
[ 0 ]
5.882353
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ]
94.117647
false
52.767528
17
6
5.882353
0
def get_file(self, filename, out=None): if not isinstance(filename, str): filename = filename.decode("utf-8") getvalue = False if out is None: out = io.BytesIO() getvalue = True try: self.con.retrbinary("RETR " + filename, out.write) except FTPError as e: msg = str(e) if msg[:4] != "550 ": self.log_buffer.append(e) return None if getvalue: return out.getvalue().decode("utf-8") return out
25,959
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/publisher.py
FtpConnection.upload_file
(self, filename, src, mkdir=False)
return True
435
449
def upload_file(self, filename, src, mkdir=False): if isinstance(src, str): src = io.BytesIO(src.encode("utf-8")) if mkdir: directory = posixpath.dirname(filename) if directory: self.mkdir(directory, recursive=True) if not isinstance(filename, str): filename = filename.decode("utf-8") try: self.con.storbinary("STOR " + filename, src, blocksize=32768) except FTPError as e: self.log_buffer.append(str(e)) return False return True
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/publisher.py#L435-L449
40
[ 0 ]
6.666667
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 ]
93.333333
false
52.767528
15
6
6.666667
0
def upload_file(self, filename, src, mkdir=False): if isinstance(src, str): src = io.BytesIO(src.encode("utf-8")) if mkdir: directory = posixpath.dirname(filename) if directory: self.mkdir(directory, recursive=True) if not isinstance(filename, str): filename = filename.decode("utf-8") try: self.con.storbinary("STOR " + filename, src, blocksize=32768) except FTPError as e: self.log_buffer.append(str(e)) return False return True
25,960
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/publisher.py
FtpConnection.rename_file
(self, src, dst)
451
463
def rename_file(self, src, dst): try: self.con.rename(src, dst) except FTPError as e: self.log_buffer.append(str(e)) try: self.con.delete(dst) except Exception as e: self.log_buffer.append(str(e)) try: self.con.rename(src, dst) except Exception as e: self.log_buffer.append(str(e))
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/publisher.py#L451-L463
40
[ 0 ]
7.692308
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]
92.307692
false
52.767528
13
4
7.692308
0
def rename_file(self, src, dst): try: self.con.rename(src, dst) except FTPError as e: self.log_buffer.append(str(e)) try: self.con.delete(dst) except Exception as e: self.log_buffer.append(str(e)) try: self.con.rename(src, dst) except Exception as e: self.log_buffer.append(str(e))
25,961
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/publisher.py
FtpConnection.delete_file
(self, filename)
465
471
def delete_file(self, filename): if isinstance(filename, str): filename = filename.encode("utf-8") try: self.con.delete(filename) except Exception as e: self.log_buffer.append(str(e))
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/publisher.py#L465-L471
40
[ 0 ]
14.285714
[ 1, 2, 3, 4, 5, 6 ]
85.714286
false
52.767528
7
3
14.285714
0
def delete_file(self, filename): if isinstance(filename, str): filename = filename.encode("utf-8") try: self.con.delete(filename) except Exception as e: self.log_buffer.append(str(e))
25,962
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/publisher.py
FtpConnection.delete_folder
(self, filename)
473
480
def delete_folder(self, filename): if isinstance(filename, str): filename = filename.encode("utf-8") try: self.con.rmd(filename) except Exception as e: self.log_buffer.append(str(e)) self._known_folders.discard(filename)
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/publisher.py#L473-L480
40
[ 0 ]
12.5
[ 1, 2, 3, 4, 5, 6, 7 ]
87.5
false
52.767528
8
3
12.5
0
def delete_folder(self, filename): if isinstance(filename, str): filename = filename.encode("utf-8") try: self.con.rmd(filename) except Exception as e: self.log_buffer.append(str(e)) self._known_folders.discard(filename)
25,963
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/publisher.py
FtpTlsConnection.make_connection
()
return FTP_TLS()
485
489
def make_connection(): # pylint: disable=import-outside-toplevel from ftplib import FTP_TLS return FTP_TLS()
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/publisher.py#L485-L489
40
[ 0, 1 ]
40
[ 2, 4 ]
40
false
52.767528
5
1
60
0
def make_connection(): # pylint: disable=import-outside-toplevel from ftplib import FTP_TLS return FTP_TLS()
25,964
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/publisher.py
FtpTlsConnection.connect
(self)
return connected
491
496
def connect(self): connected = super().connect() if connected: # Upgrade data connection to TLS. self.con.prot_p() # pylint: disable=no-member return connected
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/publisher.py#L491-L496
40
[ 0 ]
16.666667
[ 1, 2, 4, 5 ]
66.666667
false
52.767528
6
2
33.333333
0
def connect(self): connected = super().connect() if connected: # Upgrade data connection to TLS. self.con.prot_p() # pylint: disable=no-member return connected
25,965
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/publisher.py
FtpPublisher.read_existing_artifacts
(con)
return rv, duplicates
503
521
def read_existing_artifacts(con): contents = con.get_file(".lektor/listing") if not contents: return {}, set() duplicates = set() rv = {} # Later records override earlier ones. There can be duplicate # entries if the file was not compressed. for line in contents.splitlines(): items = line.split("|") if len(items) == 2: if not isinstance(items[0], str): artifact_name = items[0].decode("utf-8") else: artifact_name = items[0] if artifact_name in rv: duplicates.add(artifact_name) rv[artifact_name] = items[1] return rv, duplicates
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/publisher.py#L503-L521
40
[ 0 ]
5.263158
[ 1, 2, 3, 4, 5, 8, 9, 10, 11, 12, 14, 15, 16, 17, 18 ]
78.947368
false
52.767528
19
6
21.052632
0
def read_existing_artifacts(con): contents = con.get_file(".lektor/listing") if not contents: return {}, set() duplicates = set() rv = {} # Later records override earlier ones. There can be duplicate # entries if the file was not compressed. for line in contents.splitlines(): items = line.split("|") if len(items) == 2: if not isinstance(items[0], str): artifact_name = items[0].decode("utf-8") else: artifact_name = items[0] if artifact_name in rv: duplicates.add(artifact_name) rv[artifact_name] = items[1] return rv, duplicates
25,966
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/publisher.py
FtpPublisher.iter_artifacts
(self)
Iterates over all artifacts in the build folder and yields the artifacts.
Iterates over all artifacts in the build folder and yields the artifacts.
523
551
def iter_artifacts(self): """Iterates over all artifacts in the build folder and yields the artifacts. """ for dirpath, dirnames, filenames in os.walk(self.output_path): dirnames[:] = [x for x in dirnames if not self.env.is_ignored_artifact(x)] for filename in filenames: if self.env.is_ignored_artifact(filename): continue full_path = os.path.join(self.output_path, dirpath, filename) local_path = full_path[len(self.output_path) :].lstrip(os.path.sep) if os.path.altsep: local_path = local_path.lstrip(os.path.altsep) h = hashlib.sha1() try: with open(full_path, "rb") as f: while 1: item = f.read(4096) if not item: break h.update(item) except IOError as e: if e.errno != errno.ENOENT: raise yield ( local_path.replace(os.path.sep, "/"), full_path, h.hexdigest(), )
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/publisher.py#L523-L551
40
[ 0, 1, 2, 3 ]
13.793103
[ 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24 ]
72.413793
false
52.767528
29
11
27.586207
2
def iter_artifacts(self): for dirpath, dirnames, filenames in os.walk(self.output_path): dirnames[:] = [x for x in dirnames if not self.env.is_ignored_artifact(x)] for filename in filenames: if self.env.is_ignored_artifact(filename): continue full_path = os.path.join(self.output_path, dirpath, filename) local_path = full_path[len(self.output_path) :].lstrip(os.path.sep) if os.path.altsep: local_path = local_path.lstrip(os.path.altsep) h = hashlib.sha1() try: with open(full_path, "rb") as f: while 1: item = f.read(4096) if not item: break h.update(item) except IOError as e: if e.errno != errno.ENOENT: raise yield ( local_path.replace(os.path.sep, "/"), full_path, h.hexdigest(), )
25,967
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/publisher.py
FtpPublisher.get_temp_filename
(filename)
return posixpath.join(dirname, "." + basename + ".tmp")
554
556
def get_temp_filename(filename): dirname, basename = posixpath.split(filename) return posixpath.join(dirname, "." + basename + ".tmp")
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/publisher.py#L554-L556
40
[ 0 ]
33.333333
[ 1, 2 ]
66.666667
false
52.767528
3
1
33.333333
0
def get_temp_filename(filename): dirname, basename = posixpath.split(filename) return posixpath.join(dirname, "." + basename + ".tmp")
25,968
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/publisher.py
FtpPublisher.upload_artifact
(self, con, artifact_name, source_file, checksum)
558
564
def upload_artifact(self, con, artifact_name, source_file, checksum): with open(source_file, "rb") as source: tmp_dst = self.get_temp_filename(artifact_name) con.log_buffer.append("000 Updating %s" % artifact_name) con.upload_file(tmp_dst, source, mkdir=True) con.rename_file(tmp_dst, artifact_name) con.append(".lektor/listing", "%s|%s\n" % (artifact_name, checksum))
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/publisher.py#L558-L564
40
[ 0 ]
14.285714
[ 1, 2, 3, 4, 5, 6 ]
85.714286
false
52.767528
7
2
14.285714
0
def upload_artifact(self, con, artifact_name, source_file, checksum): with open(source_file, "rb") as source: tmp_dst = self.get_temp_filename(artifact_name) con.log_buffer.append("000 Updating %s" % artifact_name) con.upload_file(tmp_dst, source, mkdir=True) con.rename_file(tmp_dst, artifact_name) con.append(".lektor/listing", "%s|%s\n" % (artifact_name, checksum))
25,969
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/publisher.py
FtpPublisher.consolidate_listing
(self, con, current_artifacts)
566
587
def consolidate_listing(self, con, current_artifacts): server_artifacts, duplicates = self.read_existing_artifacts(con) known_folders = set() for artifact_name in current_artifacts.keys(): known_folders.add(posixpath.dirname(artifact_name)) for artifact_name, checksum in server_artifacts.items(): if artifact_name not in current_artifacts: con.log_buffer.append("000 Deleting %s" % artifact_name) con.delete_file(artifact_name) folder = posixpath.dirname(artifact_name) if folder not in known_folders: con.log_buffer.append("000 Deleting %s" % folder) con.delete_folder(folder) if duplicates or server_artifacts != current_artifacts: listing = [] for artifact_name, checksum in current_artifacts.items(): listing.append("%s|%s\n" % (artifact_name, checksum)) listing.sort() con.upload_file(".lektor/.listing.tmp", "".join(listing)) con.rename_file(".lektor/.listing.tmp", ".lektor/listing")
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/publisher.py#L566-L587
40
[ 0 ]
4.545455
[ 1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18, 19, 20, 21 ]
86.363636
false
52.767528
22
8
13.636364
0
def consolidate_listing(self, con, current_artifacts): server_artifacts, duplicates = self.read_existing_artifacts(con) known_folders = set() for artifact_name in current_artifacts.keys(): known_folders.add(posixpath.dirname(artifact_name)) for artifact_name, checksum in server_artifacts.items(): if artifact_name not in current_artifacts: con.log_buffer.append("000 Deleting %s" % artifact_name) con.delete_file(artifact_name) folder = posixpath.dirname(artifact_name) if folder not in known_folders: con.log_buffer.append("000 Deleting %s" % folder) con.delete_folder(folder) if duplicates or server_artifacts != current_artifacts: listing = [] for artifact_name, checksum in current_artifacts.items(): listing.append("%s|%s\n" % (artifact_name, checksum)) listing.sort() con.upload_file(".lektor/.listing.tmp", "".join(listing)) con.rename_file(".lektor/.listing.tmp", ".lektor/listing")
25,970
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/publisher.py
FtpPublisher.publish
(self, target_url, credentials=None, **extra)
589
618
def publish(self, target_url, credentials=None, **extra): con = self.connection_class(target_url, credentials) connected = con.connect() for event in con.drain_log(): yield event if not connected: return yield "000 Reading server state ..." con.mkdir(".lektor") committed_artifacts, _ = self.read_existing_artifacts(con) for event in con.drain_log(): yield event yield "000 Begin sync ..." current_artifacts = {} for artifact_name, filename, checksum in self.iter_artifacts(): current_artifacts[artifact_name] = checksum if checksum != committed_artifacts.get(artifact_name): self.upload_artifact(con, artifact_name, filename, checksum) for event in con.drain_log(): yield event yield "000 Sync done!" yield "000 Consolidating server state ..." self.consolidate_listing(con, current_artifacts) for event in con.drain_log(): yield event yield "000 All done!"
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/publisher.py#L589-L618
40
[ 0 ]
3.333333
[ 1, 2, 3, 4, 5, 6, 8, 9, 10, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 24, 25, 26, 27, 29 ]
83.333333
false
52.767528
30
8
16.666667
0
def publish(self, target_url, credentials=None, **extra): con = self.connection_class(target_url, credentials) connected = con.connect() for event in con.drain_log(): yield event if not connected: return yield "000 Reading server state ..." con.mkdir(".lektor") committed_artifacts, _ = self.read_existing_artifacts(con) for event in con.drain_log(): yield event yield "000 Begin sync ..." current_artifacts = {} for artifact_name, filename, checksum in self.iter_artifacts(): current_artifacts[artifact_name] = checksum if checksum != committed_artifacts.get(artifact_name): self.upload_artifact(con, artifact_name, filename, checksum) for event in con.drain_log(): yield event yield "000 Sync done!" yield "000 Consolidating server state ..." self.consolidate_listing(con, current_artifacts) for event in con.drain_log(): yield event yield "000 All done!"
25,971
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/publisher.py
GitRepo.__init__
(self, work_tree: "StrPath")
641
658
def __init__(self, work_tree: "StrPath") -> None: environ = {**os.environ, "GIT_WORK_TREE": str(work_tree)} for what, default in [("NAME", "Lektor Bot"), ("EMAIL", "bot@getlektor.com")]: value = ( environ.get(f"GIT_AUTHOR_{what}") or environ.get(f"GIT_COMMITTER_{what}") or default ) for key in f"GIT_AUTHOR_{what}", f"GIT_COMMITTER_{what}": environ[key] = environ.get(key) or value with ExitStack() as stack: environ["GIT_DIR"] = stack.enter_context(TemporaryDirectory(suffix=".git")) self.environ = environ self.run("init", "--quiet") self._exit_stack = stack.pop_all()
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/publisher.py#L641-L658
40
[ 0, 1, 2, 3, 4, 9, 10, 11, 12, 13, 14, 15, 16, 17 ]
77.777778
[]
0
false
52.767528
18
7
100
0
def __init__(self, work_tree: "StrPath") -> None: environ = {**os.environ, "GIT_WORK_TREE": str(work_tree)} for what, default in [("NAME", "Lektor Bot"), ("EMAIL", "bot@getlektor.com")]: value = ( environ.get(f"GIT_AUTHOR_{what}") or environ.get(f"GIT_COMMITTER_{what}") or default ) for key in f"GIT_AUTHOR_{what}", f"GIT_COMMITTER_{what}": environ[key] = environ.get(key) or value with ExitStack() as stack: environ["GIT_DIR"] = stack.enter_context(TemporaryDirectory(suffix=".git")) self.environ = environ self.run("init", "--quiet") self._exit_stack = stack.pop_all()
25,972
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/publisher.py
GitRepo.__exit__
(self, *__: Any)
660
661
def __exit__(self, *__: Any) -> None: self._exit_stack.close()
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/publisher.py#L660-L661
40
[ 0, 1 ]
100
[]
0
true
52.767528
2
1
100
0
def __exit__(self, *__: Any) -> None: self._exit_stack.close()
25,973
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/publisher.py
GitRepo._popen
(self, args: Sequence[str], **kwargs: Any)
return Command(cmd, env=self.environ, **kwargs)
663
666
def _popen(self, args: Sequence[str], **kwargs: Any) -> Command: cmd = ["git"] cmd.extend(args) return Command(cmd, env=self.environ, **kwargs)
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/publisher.py#L663-L666
40
[ 0, 1, 2, 3 ]
100
[]
0
true
52.767528
4
1
100
0
def _popen(self, args: Sequence[str], **kwargs: Any) -> Command: cmd = ["git"] cmd.extend(args) return Command(cmd, env=self.environ, **kwargs)
25,974
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/publisher.py
GitRepo.popen
( self, *args: str, check: bool = True, input: Optional[str] = None, capture_stdout: bool = False, )
return self._popen( args, check=check, input=input, capture_stdout=capture_stdout )
Run a git subcommand.
Run a git subcommand.
668
678
def popen( self, *args: str, check: bool = True, input: Optional[str] = None, capture_stdout: bool = False, ) -> Command: """Run a git subcommand.""" return self._popen( args, check=check, input=input, capture_stdout=capture_stdout )
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/publisher.py#L668-L678
40
[ 0, 7, 8, 9, 10 ]
45.454545
[]
0
false
52.767528
11
1
100
1
def popen( self, *args: str, check: bool = True, input: Optional[str] = None, capture_stdout: bool = False, ) -> Command: return self._popen( args, check=check, input=input, capture_stdout=capture_stdout )
25,975
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/publisher.py
GitRepo.run
( self, *args: str, check: bool = True, input: Optional[str] = None, capture_stdout: bool = False, )
return self._popen( args, check=check, input=input, capture_stdout=capture_stdout, capture=False ).result()
Run a git subcommand and wait for completion.
Run a git subcommand and wait for completion.
680
690
def run( self, *args: str, check: bool = True, input: Optional[str] = None, capture_stdout: bool = False, ) -> "CompletedProcess[str]": """Run a git subcommand and wait for completion.""" return self._popen( args, check=check, input=input, capture_stdout=capture_stdout, capture=False ).result()
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/publisher.py#L680-L690
40
[ 0, 7, 8, 9, 10 ]
45.454545
[]
0
false
52.767528
11
1
100
1
def run( self, *args: str, check: bool = True, input: Optional[str] = None, capture_stdout: bool = False, ) -> "CompletedProcess[str]": return self._popen( args, check=check, input=input, capture_stdout=capture_stdout, capture=False ).result()
25,976
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/publisher.py
GitRepo.set_ssh_credentials
(self, credentials: Mapping[str, str])
Set up git ssh credentials. This repository will be configured to used whatever SSH credentials can found in ``credentials`` (if any).
Set up git ssh credentials.
692
701
def set_ssh_credentials(self, credentials: Mapping[str, str]) -> None: """Set up git ssh credentials. This repository will be configured to used whatever SSH credentials can found in ``credentials`` (if any). """ stack = self._exit_stack ssh_command = stack.enter_context(_ssh_command(credentials)) if ssh_command: self.environ.setdefault("GIT_SSH_COMMAND", ssh_command)
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/publisher.py#L692-L701
40
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
100
[]
0
true
52.767528
10
2
100
4
def set_ssh_credentials(self, credentials: Mapping[str, str]) -> None: stack = self._exit_stack ssh_command = stack.enter_context(_ssh_command(credentials)) if ssh_command: self.environ.setdefault("GIT_SSH_COMMAND", ssh_command)
25,977
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/publisher.py
GitRepo.set_https_credentials
(self, credentials: Mapping[str, str])
Set up git http(s) credentials. This repository will be configured to used whatever HTTP credentials can found in ``credentials`` (if any).
Set up git http(s) credentials.
703
717
def set_https_credentials(self, credentials: Mapping[str, str]) -> None: """Set up git http(s) credentials. This repository will be configured to used whatever HTTP credentials can found in ``credentials`` (if any). """ username = credentials.get("username", "") password = credentials.get("password") if username or password: userpass = f"{username}:{password}" if password else username git_dir = self.environ["GIT_DIR"] cred_file = Path(git_dir, "lektor_cred_file") # pylint: disable=unspecified-encoding cred_file.write_text(f"https://{userpass}@github.com\n") self.run("config", "credential.helper", f'store --file "{cred_file}"')
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/publisher.py#L703-L717
40
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 ]
100
[]
0
true
52.767528
15
3
100
4
def set_https_credentials(self, credentials: Mapping[str, str]) -> None: username = credentials.get("username", "") password = credentials.get("password") if username or password: userpass = f"{username}:{password}" if password else username git_dir = self.environ["GIT_DIR"] cred_file = Path(git_dir, "lektor_cred_file") # pylint: disable=unspecified-encoding cred_file.write_text(f"https://{userpass}@github.com\n") self.run("config", "credential.helper", f'store --file "{cred_file}"')
25,978
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/publisher.py
GitRepo.add_to_index
(self, filename: str, content: str)
Create a file in the index. This creates file named ``filename`` with content ``content`` in the git index.
Create a file in the index.
719
728
def add_to_index(self, filename: str, content: str) -> None: """Create a file in the index. This creates file named ``filename`` with content ``content`` in the git index. """ oid = self.run( "hash-object", "-w", "--stdin", input=content, capture_stdout=True ).stdout.strip() self.run("update-index", "--add", "--cacheinfo", "100644", oid, filename)
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/publisher.py#L719-L728
40
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
100
[]
0
true
52.767528
10
1
100
4
def add_to_index(self, filename: str, content: str) -> None: oid = self.run( "hash-object", "-w", "--stdin", input=content, capture_stdout=True ).stdout.strip() self.run("update-index", "--add", "--cacheinfo", "100644", oid, filename)
25,979
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/publisher.py
GitRepo.publish_ghpages
( self, push_url: str, branch: str, cname: Optional[str] = None, preserve_history: bool = True, )
Publish the contents of the work tree to GitHub pages. :param push_url: The URL to push to. :param branch: The branch to push to :param cname: Optional. Create a top-level ``CNAME`` with given contents.
Publish the contents of the work tree to GitHub pages.
730
779
def publish_ghpages( self, push_url: str, branch: str, cname: Optional[str] = None, preserve_history: bool = True, ) -> Iterator[str]: """Publish the contents of the work tree to GitHub pages. :param push_url: The URL to push to. :param branch: The branch to push to :param cname: Optional. Create a top-level ``CNAME`` with given contents. """ refspec = f"refs/heads/{branch}" if preserve_history: yield "Fetching existing head" fetch_cmd = self.popen("fetch", "--depth=1", push_url, refspec, check=False) yield from _prefix_output(fetch_cmd) if fetch_cmd.returncode == 0: # If fetch was succesful, reset HEAD to remote head yield from _prefix_output(self.popen("reset", "--soft", "FETCH_HEAD")) else: # otherwise assume remote branch does not exist yield f"Creating new branch {branch}" # At this point, the index is still empty. Add all but .lektor dir to index yield from _prefix_output( self.popen("add", "--force", "--all", "--", ".", ":(exclude).lektor") ) if cname is not None: self.add_to_index("CNAME", f"{cname}\n") # Check for changes diff_cmd = self.popen("diff", "--cached", "--exit-code", "--quiet", check=False) yield from _prefix_output(diff_cmd) if diff_cmd.returncode == 0: yield "No changes to publish☺" elif diff_cmd.returncode == 1: yield "Creating commit" yield from _prefix_output( self.popen("commit", "--quiet", "--message", "Synchronized build") ) push_cmd = ["push", push_url, f"HEAD:{refspec}"] if not preserve_history: push_cmd.insert(1, "--force") yield "Pushing to github" yield from _prefix_output(self.popen(*push_cmd)) yield "Success!" else: diff_cmd.result().check_returncode()
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/publisher.py#L730-L779
40
[ 0, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48 ]
76
[ 49 ]
2
false
52.767528
50
7
98
5
def publish_ghpages( self, push_url: str, branch: str, cname: Optional[str] = None, preserve_history: bool = True, ) -> Iterator[str]: refspec = f"refs/heads/{branch}" if preserve_history: yield "Fetching existing head" fetch_cmd = self.popen("fetch", "--depth=1", push_url, refspec, check=False) yield from _prefix_output(fetch_cmd) if fetch_cmd.returncode == 0: # If fetch was succesful, reset HEAD to remote head yield from _prefix_output(self.popen("reset", "--soft", "FETCH_HEAD")) else: # otherwise assume remote branch does not exist yield f"Creating new branch {branch}" # At this point, the index is still empty. Add all but .lektor dir to index yield from _prefix_output( self.popen("add", "--force", "--all", "--", ".", ":(exclude).lektor") ) if cname is not None: self.add_to_index("CNAME", f"{cname}\n") # Check for changes diff_cmd = self.popen("diff", "--cached", "--exit-code", "--quiet", check=False) yield from _prefix_output(diff_cmd) if diff_cmd.returncode == 0: yield "No changes to publish☺" elif diff_cmd.returncode == 1: yield "Creating commit" yield from _prefix_output( self.popen("commit", "--quiet", "--message", "Synchronized build") ) push_cmd = ["push", push_url, f"HEAD:{refspec}"] if not preserve_history: push_cmd.insert(1, "--force") yield "Pushing to github" yield from _prefix_output(self.popen(*push_cmd)) yield "Success!" else: diff_cmd.result().check_returncode()
25,980
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/publisher.py
GithubPagesPublisher.publish
( self, target_url: urls.URL, credentials: Optional[Mapping[str, str]] = None, **extra: Any, )
790
811
def publish( self, target_url: urls.URL, credentials: Optional[Mapping[str, str]] = None, **extra: Any, ) -> Iterator[str]: if not locate_executable("git"): self.fail("git executable not found; cannot deploy.") push_url, branch, cname, preserve_history, warnings = self._parse_url( target_url ) creds = self._parse_credentials(credentials, target_url) yield from iter(warnings) with GitRepo(self.output_path) as repo: if push_url.startswith("https:"): repo.set_https_credentials(creds) else: repo.set_ssh_credentials(creds) yield from repo.publish_ghpages(push_url, branch, cname, preserve_history)
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/publisher.py#L790-L811
40
[ 0, 6, 7, 8 ]
18.181818
[ 9, 12, 14, 16, 17, 18, 20, 21 ]
36.363636
false
52.767528
22
4
63.636364
0
def publish( self, target_url: urls.URL, credentials: Optional[Mapping[str, str]] = None, **extra: Any, ) -> Iterator[str]: if not locate_executable("git"): self.fail("git executable not found; cannot deploy.") push_url, branch, cname, preserve_history, warnings = self._parse_url( target_url ) creds = self._parse_credentials(credentials, target_url) yield from iter(warnings) with GitRepo(self.output_path) as repo: if push_url.startswith("https:"): repo.set_https_credentials(creds) else: repo.set_ssh_credentials(creds) yield from repo.publish_ghpages(push_url, branch, cname, preserve_history)
25,981
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/publisher.py
GithubPagesPublisher._parse_url
( self, target_url: urls.URL )
return push_url, branch, cname, preserve_history, warnings
813
854
def _parse_url( self, target_url: urls.URL ) -> Tuple[str, str, Optional[str], bool, Sequence[str]]: if not target_url.host: self.fail("github owner missing from target URL") gh_owner = target_url.host.lower() gh_project = target_url.path.strip("/").lower() if not gh_project: self.fail("github project missing from target URL") params = target_url.decode_query() cname = params.get("cname") branch = params.get("branch") preserve_history = bool_from_string(params.get("preserve_history"), True) warnings = [] if not branch: if gh_project == f"{gh_owner}.github.io": warnings.extend( cleandoc(self._EXPLICIT_BRANCH_SUGGESTED_MSG).splitlines() ) warn( " ".join( cleandoc(self._DEFAULT_BRANCH_DEPRECATION_MSG).splitlines() ), category=DeprecationWarning, ) branch = "master" else: branch = "gh-pages" if target_url.scheme in ("ghpages", "ghpages+ssh"): push_url = f"ssh://git@github.com/{gh_owner}/{gh_project}.git" default_port = 22 else: push_url = f"https://github.com/{gh_owner}/{gh_project}.git" default_port = 443 if target_url.port and target_url.port != default_port: self.fail("github does not support pushing to non-standard ports") return push_url, branch, cname, preserve_history, warnings
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/publisher.py#L813-L854
40
[ 0, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 22, 28, 30, 31, 32, 33, 34, 36, 37, 38, 39, 40, 41 ]
73.809524
[]
0
false
52.767528
42
8
100
0
def _parse_url( self, target_url: urls.URL ) -> Tuple[str, str, Optional[str], bool, Sequence[str]]: if not target_url.host: self.fail("github owner missing from target URL") gh_owner = target_url.host.lower() gh_project = target_url.path.strip("/").lower() if not gh_project: self.fail("github project missing from target URL") params = target_url.decode_query() cname = params.get("cname") branch = params.get("branch") preserve_history = bool_from_string(params.get("preserve_history"), True) warnings = [] if not branch: if gh_project == f"{gh_owner}.github.io": warnings.extend( cleandoc(self._EXPLICIT_BRANCH_SUGGESTED_MSG).splitlines() ) warn( " ".join( cleandoc(self._DEFAULT_BRANCH_DEPRECATION_MSG).splitlines() ), category=DeprecationWarning, ) branch = "master" else: branch = "gh-pages" if target_url.scheme in ("ghpages", "ghpages+ssh"): push_url = f"ssh://git@github.com/{gh_owner}/{gh_project}.git" default_port = 22 else: push_url = f"https://github.com/{gh_owner}/{gh_project}.git" default_port = 443 if target_url.port and target_url.port != default_port: self.fail("github does not support pushing to non-standard ports") return push_url, branch, cname, preserve_history, warnings
25,982
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/publisher.py
GithubPagesPublisher._parse_credentials
( credentials: Optional[Mapping[str, str]], target_url: urls.URL )
return creds
879
890
def _parse_credentials( credentials: Optional[Mapping[str, str]], target_url: urls.URL ) -> Mapping[str, str]: creds = dict(credentials or {}) # Fill in default username/password from target url for key, default in [ ("username", target_url.username), ("password", target_url.password), ]: if not creds.get(key) and default: creds[key] = default return creds
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/publisher.py#L879-L890
40
[ 0, 3, 4, 5, 9, 10, 11 ]
58.333333
[]
0
false
52.767528
12
5
100
0
def _parse_credentials( credentials: Optional[Mapping[str, str]], target_url: urls.URL ) -> Mapping[str, str]: creds = dict(credentials or {}) # Fill in default username/password from target url for key, default in [ ("username", target_url.username), ("password", target_url.password), ]: if not creds.get(key) and default: creds[key] = default return creds
25,983
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/packages.py
_get_package_version_from_project
(cfg, name)
return None
19
24
def _get_package_version_from_project(cfg, name): choices = (name.lower(), "lektor-" + name.lower()) for pkg, version in cfg.section_as_dict("packages").items(): if pkg.lower() in choices: return {"name": pkg, "version": version} return None
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/packages.py#L19-L24
40
[ 0, 1, 2, 5 ]
66.666667
[ 3, 4 ]
33.333333
false
57.309942
6
3
66.666667
0
def _get_package_version_from_project(cfg, name): choices = (name.lower(), "lektor-" + name.lower()) for pkg, version in cfg.section_as_dict("packages").items(): if pkg.lower() in choices: return {"name": pkg, "version": version} return None
25,984
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/packages.py
add_package_to_project
(project, req)
Given a pacakge requirement this returns the information about this plugin.
Given a pacakge requirement this returns the information about this plugin.
27
63
def add_package_to_project(project, req): """Given a pacakge requirement this returns the information about this plugin. """ if "@" in req: name, version = req.split("@", 1) version_hint = version else: name = req version = None version_hint = "latest release" cfg = project.open_config() info = _get_package_version_from_project(cfg, name) if info is not None: raise RuntimeError("The package was already added to the project.") for choice in name, "lektor-" + name: rv = requests.get(f"https://pypi.python.org/pypi/{choice}/json", timeout=10) if rv.status_code != 200: continue data = rv.json() canonical_name = data["info"]["name"] if version is None: version = data["info"]["version"] version_info = data["releases"].get(version) if version_info is None: raise RuntimeError( f"Latest requested version ({version_hint}) could not be found" ) cfg["packages.%s" % canonical_name] = version cfg.save() return {"name": canonical_name, "version": version} raise RuntimeError("The package could not be found on PyPI")
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/packages.py#L27-L63
40
[ 0, 1, 2, 3, 4, 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 31, 32, 33, 34, 35 ]
81.081081
[ 5, 6, 15, 28, 36 ]
13.513514
false
57.309942
37
7
86.486486
2
def add_package_to_project(project, req): if "@" in req: name, version = req.split("@", 1) version_hint = version else: name = req version = None version_hint = "latest release" cfg = project.open_config() info = _get_package_version_from_project(cfg, name) if info is not None: raise RuntimeError("The package was already added to the project.") for choice in name, "lektor-" + name: rv = requests.get(f"https://pypi.python.org/pypi/{choice}/json", timeout=10) if rv.status_code != 200: continue data = rv.json() canonical_name = data["info"]["name"] if version is None: version = data["info"]["version"] version_info = data["releases"].get(version) if version_info is None: raise RuntimeError( f"Latest requested version ({version_hint}) could not be found" ) cfg["packages.%s" % canonical_name] = version cfg.save() return {"name": canonical_name, "version": version} raise RuntimeError("The package could not be found on PyPI")
25,985
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/packages.py
remove_package_from_project
(project, name)
return None
66
74
def remove_package_from_project(project, name): cfg = project.open_config() choices = (name.lower(), "lektor-" + name.lower()) for pkg, version in cfg.section_as_dict("packages").items(): if pkg.lower() in choices: del cfg["packages.%s" % pkg] cfg.save() return {"name": pkg, "version": version} return None
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/packages.py#L66-L74
40
[ 0 ]
11.111111
[ 1, 2, 3, 4, 5, 6, 7, 8 ]
88.888889
false
57.309942
9
3
11.111111
0
def remove_package_from_project(project, name): cfg = project.open_config() choices = (name.lower(), "lektor-" + name.lower()) for pkg, version in cfg.section_as_dict("packages").items(): if pkg.lower() in choices: del cfg["packages.%s" % pkg] cfg.save() return {"name": pkg, "version": version} return None
25,986
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/packages.py
download_and_install_package
( package_root, package=None, version=None, requirements_file=None )
This downloads and installs a specific version of a package.
This downloads and installs a specific version of a package.
77
100
def download_and_install_package( package_root, package=None, version=None, requirements_file=None ): """This downloads and installs a specific version of a package.""" # XXX: windows env = dict(os.environ) args = [ sys.executable, "-m", "pip", "install", "--target", package_root, ] if package is not None: args.append("%s%s%s" % (package, version and "==" or "", version or "")) if requirements_file is not None: args.extend(("-r", requirements_file)) rv = portable_popen(args, env=env).wait() if rv != 0: raise RuntimeError("Failed to install dependency package.")
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/packages.py#L77-L100
40
[ 0, 4, 5, 6, 7, 15, 16, 17, 18, 20, 21, 22 ]
50
[ 19, 23 ]
8.333333
false
57.309942
24
7
91.666667
1
def download_and_install_package( package_root, package=None, version=None, requirements_file=None ): # XXX: windows env = dict(os.environ) args = [ sys.executable, "-m", "pip", "install", "--target", package_root, ] if package is not None: args.append("%s%s%s" % (package, version and "==" or "", version or "")) if requirements_file is not None: args.extend(("-r", requirements_file)) rv = portable_popen(args, env=env).wait() if rv != 0: raise RuntimeError("Failed to install dependency package.")
25,987
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/packages.py
install_local_package
(package_root, path)
This installs a local dependency of a package.
This installs a local dependency of a package.
103
151
def install_local_package(package_root, path): """This installs a local dependency of a package.""" # XXX: windows env = dict(os.environ) env["PYTHONPATH"] = package_root # Step 1: generate egg info and link us into the target folder. rv = portable_popen( [ sys.executable, "-m", "pip", "install", "--editable", path, "--install-option=--install-dir=%s" % package_root, "--no-deps", ], env=env, ).wait() if rv != 0: raise RuntimeError("Failed to install local package") # Step 2: generate the egg info into a temp folder to find the # requirements. tmp = tempfile.mkdtemp() try: rv = portable_popen( [ sys.executable, "setup.py", "--quiet", "egg_info", "--quiet", "--egg-base", tmp, ], cwd=path, ).wait() dirs = os.listdir(tmp) if rv != 0 or len(dirs) != 1: raise RuntimeError("Failed to create egg info for local package.") requires = os.path.join(tmp, dirs[0], "requires.txt") # We have dependencies, install them! if os.path.isfile(requires): download_and_install_package(package_root, requirements_file=requires) finally: shutil.rmtree(tmp)
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/packages.py#L103-L151
40
[ 0, 1, 2 ]
6.122449
[ 3, 4, 7, 20, 21, 25, 26, 27, 39, 40, 41, 42, 45, 46, 48 ]
30.612245
false
57.309942
49
5
69.387755
1
def install_local_package(package_root, path): # XXX: windows env = dict(os.environ) env["PYTHONPATH"] = package_root # Step 1: generate egg info and link us into the target folder. rv = portable_popen( [ sys.executable, "-m", "pip", "install", "--editable", path, "--install-option=--install-dir=%s" % package_root, "--no-deps", ], env=env, ).wait() if rv != 0: raise RuntimeError("Failed to install local package") # Step 2: generate the egg info into a temp folder to find the # requirements. tmp = tempfile.mkdtemp() try: rv = portable_popen( [ sys.executable, "setup.py", "--quiet", "egg_info", "--quiet", "--egg-base", tmp, ], cwd=path, ).wait() dirs = os.listdir(tmp) if rv != 0 or len(dirs) != 1: raise RuntimeError("Failed to create egg info for local package.") requires = os.path.join(tmp, dirs[0], "requires.txt") # We have dependencies, install them! if os.path.isfile(requires): download_and_install_package(package_root, requirements_file=requires) finally: shutil.rmtree(tmp)
25,988
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/packages.py
get_package_info
(path)
return { "name": _process(rv[0]), "author": _process(rv[1]), "author_email": _process(rv[2]), "license": _process(rv[3]), "url": _process(rv[4]), "path": path, }
Returns the name of a package at a path.
Returns the name of a package at a path.
154
188
def get_package_info(path): """Returns the name of a package at a path.""" rv = ( portable_popen( [ sys.executable, "setup.py", "--quiet", "--name", "--author", "--author-email", "--license", "--url", ], cwd=path, stdout=PIPE, ) .communicate()[0] .splitlines() ) def _process(value): value = value.strip() if value == "UNKNOWN": return None return value.decode("utf-8", "replace") return { "name": _process(rv[0]), "author": _process(rv[1]), "author_email": _process(rv[2]), "license": _process(rv[3]), "url": _process(rv[4]), "path": path, }
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/packages.py#L154-L188
40
[ 0, 1 ]
5.714286
[ 2, 21, 22, 23, 24, 25, 27 ]
20
false
57.309942
35
3
80
1
def get_package_info(path): rv = ( portable_popen( [ sys.executable, "setup.py", "--quiet", "--name", "--author", "--author-email", "--license", "--url", ], cwd=path, stdout=PIPE, ) .communicate()[0] .splitlines() ) def _process(value): value = value.strip() if value == "UNKNOWN": return None return value.decode("utf-8", "replace") return { "name": _process(rv[0]), "author": _process(rv[1]), "author_email": _process(rv[2]), "license": _process(rv[3]), "url": _process(rv[4]), "path": path, }
25,989
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/packages.py
register_package
(path)
Registers the plugin at the given path.
Registers the plugin at the given path.
191
193
def register_package(path): """Registers the plugin at the given path.""" portable_popen([sys.executable, "setup.py", "register"], cwd=path).wait()
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/packages.py#L191-L193
40
[ 0, 1 ]
66.666667
[ 2 ]
33.333333
false
57.309942
3
1
66.666667
1
def register_package(path): portable_popen([sys.executable, "setup.py", "register"], cwd=path).wait()
25,990
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/packages.py
publish_package
(path)
Registers the plugin at the given path.
Registers the plugin at the given path.
196
200
def publish_package(path): """Registers the plugin at the given path.""" portable_popen( [sys.executable, "setup.py", "sdist", "bdist_wheel", "upload"], cwd=path ).wait()
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/packages.py#L196-L200
40
[ 0, 1 ]
40
[ 2 ]
20
false
57.309942
5
1
80
1
def publish_package(path): portable_popen( [sys.executable, "setup.py", "sdist", "bdist_wheel", "upload"], cwd=path ).wait()
25,991
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/packages.py
load_manifest
(filename)
return rv
203
219
def load_manifest(filename): rv = {} try: with open(filename, encoding="utf-8") as f: for line in f: if line[:1] == "@": rv[line.strip()] = None continue line = line.strip().split("=", 1) if len(line) == 2: key = line[0].strip() value = line[1].strip() rv[key] = value except IOError as e: if e.errno != errno.ENOENT: raise return rv
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/packages.py#L203-L219
40
[ 0, 1, 2, 3, 13, 14, 16 ]
41.176471
[ 4, 5, 6, 7, 8, 9, 10, 11, 12, 15 ]
58.823529
false
57.309942
17
7
41.176471
0
def load_manifest(filename): rv = {} try: with open(filename, encoding="utf-8") as f: for line in f: if line[:1] == "@": rv[line.strip()] = None continue line = line.strip().split("=", 1) if len(line) == 2: key = line[0].strip() value = line[1].strip() rv[key] = value except IOError as e: if e.errno != errno.ENOENT: raise return rv
25,992
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/packages.py
write_manifest
(filename, packages)
222
228
def write_manifest(filename, packages): with open(filename, "w", encoding="utf-8") as f: for package, version in sorted(packages.items()): if package[:1] == "@": f.write("%s\n" % package) else: f.write("%s=%s\n" % (package, version))
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/packages.py#L222-L228
40
[ 0, 1, 2, 3, 6 ]
71.428571
[ 4 ]
14.285714
false
57.309942
7
4
85.714286
0
def write_manifest(filename, packages): with open(filename, "w", encoding="utf-8") as f: for package, version in sorted(packages.items()): if package[:1] == "@": f.write("%s\n" % package) else: f.write("%s=%s\n" % (package, version))
25,993
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/packages.py
list_local_packages
(path)
return rv
Lists all local packages below a path that could be installed.
Lists all local packages below a path that could be installed.
231
240
def list_local_packages(path): """Lists all local packages below a path that could be installed.""" rv = [] try: for filename in os.listdir(path): if os.path.isfile(os.path.join(path, filename, "setup.py")): rv.append("@" + filename) except OSError: pass return rv
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/packages.py#L231-L240
40
[ 0, 1, 2, 3, 4, 7, 8, 9 ]
80
[ 5, 6 ]
20
false
57.309942
10
4
80
1
def list_local_packages(path): rv = [] try: for filename in os.listdir(path): if os.path.isfile(os.path.join(path, filename, "setup.py")): rv.append("@" + filename) except OSError: pass return rv
25,994
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/packages.py
update_cache
(package_root, remote_packages, local_package_path, refresh=False)
Updates the package cache at package_root for the given dictionary of packages as well as packages in the given local package path.
Updates the package cache at package_root for the given dictionary of packages as well as packages in the given local package path.
243
295
def update_cache(package_root, remote_packages, local_package_path, refresh=False): """Updates the package cache at package_root for the given dictionary of packages as well as packages in the given local package path. """ requires_wipe = False if refresh: click.echo("Force package cache refresh.") requires_wipe = True manifest_file = os.path.join(package_root, "lektor-packages.manifest") local_packages = list_local_packages(local_package_path) old_manifest = load_manifest(manifest_file) to_install = [] all_packages = dict(remote_packages) all_packages.update((x, None) for x in local_packages) # step 1: figure out which remote packages to install. for package, version in remote_packages.items(): old_version = old_manifest.pop(package, None) if old_version is None: to_install.append((package, version)) elif old_version != version: requires_wipe = True # step 2: figure out which local packages to install for package in local_packages: if old_manifest.pop(package, False) is False: to_install.append((package, None)) # Bad news, we need to wipe everything if requires_wipe or old_manifest: try: shutil.rmtree(package_root) except OSError: pass to_install = all_packages.items() if to_install: click.echo("Updating packages in %s for project" % package_root) try: os.makedirs(package_root) except OSError: pass for package, version in to_install: if package[:1] == "@": install_local_package( package_root, os.path.join(local_package_path, package[1:]) ) else: download_and_install_package(package_root, package, version) write_manifest(manifest_file, all_packages)
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/packages.py#L243-L295
40
[ 0, 1, 2, 3, 4, 5, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 26, 27, 31, 32, 38, 39, 40, 41, 42, 45, 46, 50, 51, 52 ]
66.037736
[ 6, 7, 23, 24, 28, 29, 33, 34, 35, 36, 37, 43, 44, 47 ]
26.415094
false
57.309942
53
14
73.584906
2
def update_cache(package_root, remote_packages, local_package_path, refresh=False): requires_wipe = False if refresh: click.echo("Force package cache refresh.") requires_wipe = True manifest_file = os.path.join(package_root, "lektor-packages.manifest") local_packages = list_local_packages(local_package_path) old_manifest = load_manifest(manifest_file) to_install = [] all_packages = dict(remote_packages) all_packages.update((x, None) for x in local_packages) # step 1: figure out which remote packages to install. for package, version in remote_packages.items(): old_version = old_manifest.pop(package, None) if old_version is None: to_install.append((package, version)) elif old_version != version: requires_wipe = True # step 2: figure out which local packages to install for package in local_packages: if old_manifest.pop(package, False) is False: to_install.append((package, None)) # Bad news, we need to wipe everything if requires_wipe or old_manifest: try: shutil.rmtree(package_root) except OSError: pass to_install = all_packages.items() if to_install: click.echo("Updating packages in %s for project" % package_root) try: os.makedirs(package_root) except OSError: pass for package, version in to_install: if package[:1] == "@": install_local_package( package_root, os.path.join(local_package_path, package[1:]) ) else: download_and_install_package(package_root, package, version) write_manifest(manifest_file, all_packages)
25,995
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/packages.py
load_packages
(env, reinstall=False)
This loads all the packages of a project. What this does is updating the current cache in ``root/package-cache`` and then add the Python modules there to the load path as a site directory and register it appropriately with pkg_resource's workingset. Afterwards all entry points should function as expected and imports should be possible.
This loads all the packages of a project. What this does is updating the current cache in ``root/package-cache`` and then add the Python modules there to the load path as a site directory and register it appropriately with pkg_resource's workingset.
298
315
def load_packages(env, reinstall=False): """This loads all the packages of a project. What this does is updating the current cache in ``root/package-cache`` and then add the Python modules there to the load path as a site directory and register it appropriately with pkg_resource's workingset. Afterwards all entry points should function as expected and imports should be possible. """ config = env.load_config() package_root = env.project.get_package_cache_path() update_cache( package_root, config["PACKAGES"], os.path.join(env.root_path, "packages"), refresh=reinstall, ) site.addsitedir(package_root)
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/packages.py#L298-L315
40
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 ]
100
[]
0
true
57.309942
18
1
100
7
def load_packages(env, reinstall=False): config = env.load_config() package_root = env.project.get_package_cache_path() update_cache( package_root, config["PACKAGES"], os.path.join(env.root_path, "packages"), refresh=reinstall, ) site.addsitedir(package_root)
25,996
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/packages.py
wipe_package_cache
(env)
Wipes the entire package cache.
Wipes the entire package cache.
318
324
def wipe_package_cache(env): """Wipes the entire package cache.""" package_root = env.project.get_package_cache_path() try: shutil.rmtree(package_root) except (OSError, IOError): pass
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/packages.py#L318-L324
40
[ 0, 1 ]
28.571429
[ 2, 3, 4, 5, 6 ]
71.428571
false
57.309942
7
2
28.571429
1
def wipe_package_cache(env): package_root = env.project.get_package_cache_path() try: shutil.rmtree(package_root) except (OSError, IOError): pass
25,997
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/datamodel.py
_iter_all_fields
(obj)
226
230
def _iter_all_fields(obj): for name in sorted(x for x in obj.field_map if x[:1] == "_"): yield obj.field_map[name] for field in obj.fields: yield field
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/datamodel.py#L226-L230
40
[ 0, 1, 2, 3, 4 ]
100
[]
0
true
93.783784
5
3
100
0
def _iter_all_fields(obj): for name in sorted(x for x in obj.field_map if x[:1] == "_"): yield obj.field_map[name] for field in obj.fields: yield field
25,998
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/datamodel.py
fielddata_from_ini
(inifile)
return [ ( sect.split(".", 1)[1], inifile.section_as_dict(sect), ) for sect in inifile.sections() if sect.startswith("fields.") ]
461
469
def fielddata_from_ini(inifile): return [ ( sect.split(".", 1)[1], inifile.section_as_dict(sect), ) for sect in inifile.sections() if sect.startswith("fields.") ]
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/datamodel.py#L461-L469
40
[ 0, 1 ]
22.222222
[]
0
false
93.783784
9
2
100
0
def fielddata_from_ini(inifile): return [ ( sect.split(".", 1)[1], inifile.section_as_dict(sect), ) for sect in inifile.sections() if sect.startswith("fields.") ]
25,999
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/datamodel.py
datamodel_data_from_ini
(id, inifile)
return dict( filename=inifile.filename, id=id, parent=inifile.get("model.inherits"), name_i18n=get_i18n_block(inifile, "model.name"), label_i18n=get_i18n_block(inifile, "model.label"), primary_field=inifile.get("model.primary_field"), hidden=inifile.get_bool("model.hidden", default=None), protected=inifile.get_bool("model.protected", default=None), child_config=dict( enabled=inifile.get_bool("children.enabled", default=None), slug_format=inifile.get("children.slug_format"), model=inifile.get("children.model"), order_by=_parse_order(inifile.get("children.order_by")), replaced_with=inifile.get("children.replaced_with"), hidden=inifile.get_bool("children.hidden", default=None), ), attachment_config=dict( enabled=inifile.get_bool("attachments.enabled", default=None), model=inifile.get("attachments.model"), order_by=_parse_order(inifile.get("attachments.order_by")), hidden=inifile.get_bool("attachments.hidden", default=None), ), pagination_config=dict( enabled=inifile.get_bool("pagination.enabled", default=None), per_page=inifile.get_int("pagination.per_page"), url_suffix=inifile.get("pagination.url_suffix"), items=inifile.get("pagination.items"), ), fields=fielddata_from_ini(inifile), )
472
509
def datamodel_data_from_ini(id, inifile): def _parse_order(value): value = (value or "").strip() if not value: return None return [x for x in [x.strip() for x in value.strip().split(",")] if x] return dict( filename=inifile.filename, id=id, parent=inifile.get("model.inherits"), name_i18n=get_i18n_block(inifile, "model.name"), label_i18n=get_i18n_block(inifile, "model.label"), primary_field=inifile.get("model.primary_field"), hidden=inifile.get_bool("model.hidden", default=None), protected=inifile.get_bool("model.protected", default=None), child_config=dict( enabled=inifile.get_bool("children.enabled", default=None), slug_format=inifile.get("children.slug_format"), model=inifile.get("children.model"), order_by=_parse_order(inifile.get("children.order_by")), replaced_with=inifile.get("children.replaced_with"), hidden=inifile.get_bool("children.hidden", default=None), ), attachment_config=dict( enabled=inifile.get_bool("attachments.enabled", default=None), model=inifile.get("attachments.model"), order_by=_parse_order(inifile.get("attachments.order_by")), hidden=inifile.get_bool("attachments.hidden", default=None), ), pagination_config=dict( enabled=inifile.get_bool("pagination.enabled", default=None), per_page=inifile.get_int("pagination.per_page"), url_suffix=inifile.get("pagination.url_suffix"), items=inifile.get("pagination.items"), ), fields=fielddata_from_ini(inifile), )
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/datamodel.py#L472-L509
40
[ 0, 1, 2, 3, 4, 5, 6, 7 ]
21.052632
[]
0
false
93.783784
38
6
100
0
def datamodel_data_from_ini(id, inifile): def _parse_order(value): value = (value or "").strip() if not value: return None return [x for x in [x.strip() for x in value.strip().split(",")] if x] return dict( filename=inifile.filename, id=id, parent=inifile.get("model.inherits"), name_i18n=get_i18n_block(inifile, "model.name"), label_i18n=get_i18n_block(inifile, "model.label"), primary_field=inifile.get("model.primary_field"), hidden=inifile.get_bool("model.hidden", default=None), protected=inifile.get_bool("model.protected", default=None), child_config=dict( enabled=inifile.get_bool("children.enabled", default=None), slug_format=inifile.get("children.slug_format"), model=inifile.get("children.model"), order_by=_parse_order(inifile.get("children.order_by")), replaced_with=inifile.get("children.replaced_with"), hidden=inifile.get_bool("children.hidden", default=None), ), attachment_config=dict( enabled=inifile.get_bool("attachments.enabled", default=None), model=inifile.get("attachments.model"), order_by=_parse_order(inifile.get("attachments.order_by")), hidden=inifile.get_bool("attachments.hidden", default=None), ), pagination_config=dict( enabled=inifile.get_bool("pagination.enabled", default=None), per_page=inifile.get_int("pagination.per_page"), url_suffix=inifile.get("pagination.url_suffix"), items=inifile.get("pagination.items"), ), fields=fielddata_from_ini(inifile), )
26,000
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/datamodel.py
flowblock_data_from_ini
(id, inifile)
return dict( filename=inifile.filename, id=id, name_i18n=get_i18n_block(inifile, "block.name"), fields=fielddata_from_ini(inifile), order=inifile.get_int("block.order"), button_label=inifile.get("block.button_label"), )
512
520
def flowblock_data_from_ini(id, inifile): return dict( filename=inifile.filename, id=id, name_i18n=get_i18n_block(inifile, "block.name"), fields=fielddata_from_ini(inifile), order=inifile.get_int("block.order"), button_label=inifile.get("block.button_label"), )
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/datamodel.py#L512-L520
40
[ 0, 1 ]
22.222222
[]
0
false
93.783784
9
1
100
0
def flowblock_data_from_ini(id, inifile): return dict( filename=inifile.filename, id=id, name_i18n=get_i18n_block(inifile, "block.name"), fields=fielddata_from_ini(inifile), order=inifile.get_int("block.order"), button_label=inifile.get("block.button_label"), )
26,001
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/datamodel.py
fields_from_data
(env, data, parent_fields=None)
return fields
523
539
def fields_from_data(env, data, parent_fields=None): fields = [] known_fields = set() for name, options in data: ty = env.types[options.get("type", "string")] fields.append(Field(env=env, name=name, type=ty, options=options)) known_fields.add(name) if parent_fields is not None: prepended_fields = [] for field in parent_fields: if field.name not in known_fields: prepended_fields.append(field) fields = prepended_fields + fields return fields
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/datamodel.py#L523-L539
40
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ]
100
[]
0
true
93.783784
17
5
100
0
def fields_from_data(env, data, parent_fields=None): fields = [] known_fields = set() for name, options in data: ty = env.types[options.get("type", "string")] fields.append(Field(env=env, name=name, type=ty, options=options)) known_fields.add(name) if parent_fields is not None: prepended_fields = [] for field in parent_fields: if field.name not in known_fields: prepended_fields.append(field) fields = prepended_fields + fields return fields
26,002
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/datamodel.py
datamodel_from_data
(env, model_data, parent=None)
return DataModel( env, # data that never inherits filename=model_data["filename"], id=model_data["id"], parent=parent, name_i18n=model_data["name_i18n"], primary_field=model_data["primary_field"], # direct data that can inherit label_i18n=get_value("label_i18n"), hidden=get_value("hidden"), protected=get_value("protected"), child_config=ChildConfig( enabled=get_value("child_config.enabled"), slug_format=get_value("child_config.slug_format"), model=get_value("child_config.model"), order_by=get_value("child_config.order_by"), replaced_with=get_value("child_config.replaced_with"), hidden=get_value("child_config.hidden"), ), attachment_config=AttachmentConfig( enabled=get_value("attachment_config.enabled"), model=get_value("attachment_config.model"), order_by=get_value("attachment_config.order_by"), hidden=get_value("attachment_config.hidden"), ), pagination_config=PaginationConfig( env, enabled=get_value("pagination_config.enabled"), per_page=get_value("pagination_config.per_page"), url_suffix=get_value("pagination_config.url_suffix"), items=get_value("pagination_config.items"), ), fields=fields, )
542
595
def datamodel_from_data(env, model_data, parent=None): def get_value(key): path = key.split(".") node = model_data for item in path: node = node.get(item) if node is not None: return node if parent is not None: node = parent for item in path: node = getattr(node, item) return node return None fields = fields_from_data( env, model_data["fields"], parent and parent.fields or None ) return DataModel( env, # data that never inherits filename=model_data["filename"], id=model_data["id"], parent=parent, name_i18n=model_data["name_i18n"], primary_field=model_data["primary_field"], # direct data that can inherit label_i18n=get_value("label_i18n"), hidden=get_value("hidden"), protected=get_value("protected"), child_config=ChildConfig( enabled=get_value("child_config.enabled"), slug_format=get_value("child_config.slug_format"), model=get_value("child_config.model"), order_by=get_value("child_config.order_by"), replaced_with=get_value("child_config.replaced_with"), hidden=get_value("child_config.hidden"), ), attachment_config=AttachmentConfig( enabled=get_value("attachment_config.enabled"), model=get_value("attachment_config.model"), order_by=get_value("attachment_config.order_by"), hidden=get_value("attachment_config.hidden"), ), pagination_config=PaginationConfig( env, enabled=get_value("pagination_config.enabled"), per_page=get_value("pagination_config.per_page"), url_suffix=get_value("pagination_config.url_suffix"), items=get_value("pagination_config.items"), ), fields=fields, )
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/datamodel.py#L542-L595
40
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 18, 19 ]
33.333333
[]
0
false
93.783784
54
8
100
0
def datamodel_from_data(env, model_data, parent=None): def get_value(key): path = key.split(".") node = model_data for item in path: node = node.get(item) if node is not None: return node if parent is not None: node = parent for item in path: node = getattr(node, item) return node return None fields = fields_from_data( env, model_data["fields"], parent and parent.fields or None ) return DataModel( env, # data that never inherits filename=model_data["filename"], id=model_data["id"], parent=parent, name_i18n=model_data["name_i18n"], primary_field=model_data["primary_field"], # direct data that can inherit label_i18n=get_value("label_i18n"), hidden=get_value("hidden"), protected=get_value("protected"), child_config=ChildConfig( enabled=get_value("child_config.enabled"), slug_format=get_value("child_config.slug_format"), model=get_value("child_config.model"), order_by=get_value("child_config.order_by"), replaced_with=get_value("child_config.replaced_with"), hidden=get_value("child_config.hidden"), ), attachment_config=AttachmentConfig( enabled=get_value("attachment_config.enabled"), model=get_value("attachment_config.model"), order_by=get_value("attachment_config.order_by"), hidden=get_value("attachment_config.hidden"), ), pagination_config=PaginationConfig( env, enabled=get_value("pagination_config.enabled"), per_page=get_value("pagination_config.per_page"), url_suffix=get_value("pagination_config.url_suffix"), items=get_value("pagination_config.items"), ), fields=fields, )
26,003
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/datamodel.py
flowblock_from_data
(env, block_data)
return FlowBlockModel( env, filename=block_data["filename"], id=block_data["id"], name_i18n=block_data["name_i18n"], fields=fields_from_data(env, block_data["fields"]), order=block_data["order"], button_label=block_data["button_label"], )
598
607
def flowblock_from_data(env, block_data): return FlowBlockModel( env, filename=block_data["filename"], id=block_data["id"], name_i18n=block_data["name_i18n"], fields=fields_from_data(env, block_data["fields"]), order=block_data["order"], button_label=block_data["button_label"], )
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/datamodel.py#L598-L607
40
[ 0, 1 ]
20
[]
0
false
93.783784
10
1
100
0
def flowblock_from_data(env, block_data): return FlowBlockModel( env, filename=block_data["filename"], id=block_data["id"], name_i18n=block_data["name_i18n"], fields=fields_from_data(env, block_data["fields"]), order=block_data["order"], button_label=block_data["button_label"], )
26,004
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/datamodel.py
iter_inis
(path)
610
623
def iter_inis(path): try: for filename in os.listdir(path): if not filename.endswith(".ini") or filename[:1] in "_.": continue fn = os.path.join(path, filename) if os.path.isfile(fn): base = filename[:-4] base = base.encode("utf-8").decode("ascii", "replace") inifile = IniFile(fn) yield base, inifile except OSError as e: if e.errno != errno.ENOENT: raise
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/datamodel.py#L610-L623
40
[ 0, 1, 2, 3, 5, 6, 7, 8, 9, 10, 11, 12 ]
85.714286
[ 4, 13 ]
14.285714
false
93.783784
14
7
85.714286
0
def iter_inis(path): try: for filename in os.listdir(path): if not filename.endswith(".ini") or filename[:1] in "_.": continue fn = os.path.join(path, filename) if os.path.isfile(fn): base = filename[:-4] base = base.encode("utf-8").decode("ascii", "replace") inifile = IniFile(fn) yield base, inifile except OSError as e: if e.errno != errno.ENOENT: raise
26,005
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/datamodel.py
load_datamodels
(env)
return rv
Loads the datamodels for a specific environment.
Loads the datamodels for a specific environment.
626
666
def load_datamodels(env): """Loads the datamodels for a specific environment.""" # Models will override previous loaded models with the same name # So models paths are loaded in reverse order paths = list(reversed(env.theme_paths)) + [env.root_path] paths = [os.path.join(p, "models") for p in paths] data = {} for path in paths: for model_id, inifile in iter_inis(path): data[model_id] = datamodel_data_from_ini(model_id, inifile) rv = {} def get_model(model_id): model = rv.get(model_id) if model is not None: return model if model_id in data: return create_model(model_id) return None def create_model(model_id): model_data = data.get(model_id) if model_data is None: raise RuntimeError("Model %r not found" % model_id) if model_data["parent"] is not None: parent = get_model(model_data["parent"]) else: parent = None rv[model_id] = mod = datamodel_from_data(env, model_data, parent) return mod for model_id in data: get_model(model_id) rv["none"] = DataModel(env, "none", {"en": "None"}, hidden=True) return rv
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/datamodel.py#L626-L666
40
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 21, 22, 23, 24, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 ]
95.121951
[ 20, 25 ]
4.878049
false
93.783784
41
11
95.121951
1
def load_datamodels(env): # Models will override previous loaded models with the same name # So models paths are loaded in reverse order paths = list(reversed(env.theme_paths)) + [env.root_path] paths = [os.path.join(p, "models") for p in paths] data = {} for path in paths: for model_id, inifile in iter_inis(path): data[model_id] = datamodel_data_from_ini(model_id, inifile) rv = {} def get_model(model_id): model = rv.get(model_id) if model is not None: return model if model_id in data: return create_model(model_id) return None def create_model(model_id): model_data = data.get(model_id) if model_data is None: raise RuntimeError("Model %r not found" % model_id) if model_data["parent"] is not None: parent = get_model(model_data["parent"]) else: parent = None rv[model_id] = mod = datamodel_from_data(env, model_data, parent) return mod for model_id in data: get_model(model_id) rv["none"] = DataModel(env, "none", {"en": "None"}, hidden=True) return rv
26,006
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/datamodel.py
load_flowblocks
(env)
return rv
Loads all the flow blocks for a specific environment.
Loads all the flow blocks for a specific environment.
669
683
def load_flowblocks(env): """Loads all the flow blocks for a specific environment.""" # Flowblocks will override previous loaded flowblocks with the same name # So paths are loaded in reverse order paths = list(reversed(env.theme_paths)) + [env.root_path] paths = [os.path.join(p, "flowblocks") for p in paths] rv = {} for path in paths: for flowblock_id, inifile in iter_inis(path): rv[flowblock_id] = flowblock_from_data( env, flowblock_data_from_ini(flowblock_id, inifile) ) return rv
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/datamodel.py#L669-L683
40
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 ]
100
[]
0
true
93.783784
15
4
100
1
def load_flowblocks(env): # Flowblocks will override previous loaded flowblocks with the same name # So paths are loaded in reverse order paths = list(reversed(env.theme_paths)) + [env.root_path] paths = [os.path.join(p, "flowblocks") for p in paths] rv = {} for path in paths: for flowblock_id, inifile in iter_inis(path): rv[flowblock_id] = flowblock_from_data( env, flowblock_data_from_ini(flowblock_id, inifile) ) return rv
26,007
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/datamodel.py
add_system_field
(name, **opts)
689
692
def add_system_field(name, **opts): opts = dict(generate_i18n_kvs(**opts)) ty = builtin_types[opts.pop("type")] system_fields[name] = (ty, opts)
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/datamodel.py#L689-L692
40
[ 0, 1, 2, 3 ]
100
[]
0
true
93.783784
4
1
100
0
def add_system_field(name, **opts): opts = dict(generate_i18n_kvs(**opts)) ty = builtin_types[opts.pop("type")] system_fields[name] = (ty, opts)
26,008
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/datamodel.py
ChildConfig.__init__
( self, enabled=None, slug_format=None, model=None, order_by=None, replaced_with=None, hidden=None, )
20
36
def __init__( self, enabled=None, slug_format=None, model=None, order_by=None, replaced_with=None, hidden=None, ): if enabled is None: enabled = True self.enabled = enabled self.slug_format = slug_format self.model = model self.order_by = order_by self.replaced_with = replaced_with self.hidden = hidden
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/datamodel.py#L20-L36
40
[ 0, 9, 10, 11, 12, 13, 14, 15, 16 ]
52.941176
[]
0
false
93.783784
17
2
100
0
def __init__( self, enabled=None, slug_format=None, model=None, order_by=None, replaced_with=None, hidden=None, ): if enabled is None: enabled = True self.enabled = enabled self.slug_format = slug_format self.model = model self.order_by = order_by self.replaced_with = replaced_with self.hidden = hidden
26,009
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/datamodel.py
ChildConfig.to_json
(self)
return { "enabled": self.enabled, "slug_format": self.slug_format, "model": self.model, "order_by": self.order_by, "replaced_with": self.replaced_with, "hidden": self.hidden, }
38
46
def to_json(self): return { "enabled": self.enabled, "slug_format": self.slug_format, "model": self.model, "order_by": self.order_by, "replaced_with": self.replaced_with, "hidden": self.hidden, }
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/datamodel.py#L38-L46
40
[ 0, 1 ]
22.222222
[]
0
false
93.783784
9
1
100
0
def to_json(self): return { "enabled": self.enabled, "slug_format": self.slug_format, "model": self.model, "order_by": self.order_by, "replaced_with": self.replaced_with, "hidden": self.hidden, }
26,010
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/datamodel.py
PaginationConfig.__init__
(self, env, enabled=None, per_page=None, url_suffix=None, items=None)
50
67
def __init__(self, env, enabled=None, per_page=None, url_suffix=None, items=None): self.env = env if enabled is None: enabled = False self.enabled = enabled if per_page is None: per_page = 20 elif not isinstance(per_page, int): raise TypeError(f"per_page must be an int or None, not {per_page!r}") if per_page <= 0: raise ValueError("per_page must be positive, not {per_page}") self.per_page = per_page if url_suffix is None: url_suffix = "page" self.url_suffix = url_suffix self.items = items self._items_tmpl = None
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/datamodel.py#L50-L67
40
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 ]
100
[]
0
true
93.783784
18
6
100
0
def __init__(self, env, enabled=None, per_page=None, url_suffix=None, items=None): self.env = env if enabled is None: enabled = False self.enabled = enabled if per_page is None: per_page = 20 elif not isinstance(per_page, int): raise TypeError(f"per_page must be an int or None, not {per_page!r}") if per_page <= 0: raise ValueError("per_page must be positive, not {per_page}") self.per_page = per_page if url_suffix is None: url_suffix = "page" self.url_suffix = url_suffix self.items = items self._items_tmpl = None
26,011
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/datamodel.py
PaginationConfig.count_total_items
(self, record)
return self.get_pagination_query(record).count()
Counts the number of items over all pages.
Counts the number of items over all pages.
69
71
def count_total_items(self, record): """Counts the number of items over all pages.""" return self.get_pagination_query(record).count()
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/datamodel.py#L69-L71
40
[ 0, 1, 2 ]
100
[]
0
true
93.783784
3
1
100
1
def count_total_items(self, record): return self.get_pagination_query(record).count()
26,012
lektor/lektor
74bce9096116caffe27ab69327ed4ba274e66e1e
lektor/datamodel.py
PaginationConfig.count_pages
(self, record)
return max(npages, 1)
Returns the total number of pages for the children of a record.
Returns the total number of pages for the children of a record.
73
78
def count_pages(self, record): """Returns the total number of pages for the children of a record.""" total = self.count_total_items(record) npages = (total + self.per_page - 1) // self.per_page # Even when there are no children, we want at least one page return max(npages, 1)
https://github.com/lektor/lektor/blob/74bce9096116caffe27ab69327ed4ba274e66e1e/project40/lektor/datamodel.py#L73-L78
40
[ 0, 1, 2, 3, 4, 5 ]
100
[]
0
true
93.783784
6
1
100
1
def count_pages(self, record): total = self.count_total_items(record) npages = (total + self.per_page - 1) // self.per_page # Even when there are no children, we want at least one page return max(npages, 1)
26,013