Merge pull request #1882 from abarth/rm_scripts
Remove a number of unused Python scripts
This commit is contained in:
@@ -9,7 +9,6 @@ group("sky") {
|
||||
"//sky/engine/platform:platform_unittests($host_toolchain)",
|
||||
"//sky/engine/wtf:unittests($host_toolchain)",
|
||||
"//examples",
|
||||
"//sky/tools/imagediff($host_toolchain)",
|
||||
":sky_dev",
|
||||
]
|
||||
|
||||
|
||||
@@ -1,68 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
# Copyright 2015 The Chromium Authors. All rights reserved.
|
||||
# Use of this source code is governed by a BSD-style license that can be
|
||||
# found in the LICENSE file.
|
||||
|
||||
import argparse
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import skypy.paths
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
SRC_ROOT = skypy.paths.Paths('ignored').src_root
|
||||
ADB_PATH = os.path.join(SRC_ROOT,
|
||||
'third_party/android_tools/sdk/platform-tools/adb')
|
||||
|
||||
|
||||
# TODO(eseidel): This should be shared with adb_gdb
|
||||
def main():
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
parser = argparse.ArgumentParser(
|
||||
description='Pull all libraries used by a pid on android into a cache.')
|
||||
parser.add_argument('cache_root', type=str)
|
||||
parser.add_argument('pid', type=int)
|
||||
args = parser.parse_args()
|
||||
|
||||
if not os.path.exists(args.cache_root):
|
||||
os.makedirs(args.cache_root)
|
||||
|
||||
subprocess.check_call([ADB_PATH, 'root'])
|
||||
|
||||
# TODO(eseidel): Check the build.props, or find some way to avoid
|
||||
# re-pulling every library every time. adb_gdb has code to do this
|
||||
# but doesn't seem to notice when the set of needed libraries changed.
|
||||
|
||||
library_regexp = re.compile(r'(?P<library_path>/system/.*\.so)')
|
||||
cat_maps_cmd = [ADB_PATH, 'shell', 'cat', '/proc/%s/maps' % args.pid]
|
||||
maps_lines = subprocess.check_output(cat_maps_cmd).strip().split('\n')
|
||||
# adb shell doesn't return the return code from the shell?
|
||||
if not maps_lines or 'No such file or directory' in maps_lines[0]:
|
||||
print 'Failed to get maps for pid %s on device.' % args.pid
|
||||
sys.exit(1)
|
||||
|
||||
def library_from_line(line):
|
||||
result = library_regexp.search(line)
|
||||
if not result:
|
||||
return None
|
||||
return result.group('library_path')
|
||||
|
||||
dev_null = open(os.devnull, 'w') # Leaking.
|
||||
to_pull = set(filter(None, map(library_from_line, maps_lines)))
|
||||
to_pull.add('/system/bin/linker') # Unclear why but adb_gdb pulls this too.
|
||||
for library_path in sorted(to_pull):
|
||||
# Not using os.path.join since library_path is absolute.
|
||||
dest_file = os.path.normpath("%s/%s" % (args.cache_root, library_path))
|
||||
dest_dir = os.path.dirname(dest_file)
|
||||
if not os.path.exists(dest_dir):
|
||||
os.makedirs(dest_dir)
|
||||
if os.path.exists(dest_file):
|
||||
continue
|
||||
print '%s -> %s' % (library_path, dest_file)
|
||||
pull_cmd = [ADB_PATH, 'pull', library_path, dest_file]
|
||||
subprocess.check_call(pull_cmd, stderr=dev_null)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -1,21 +0,0 @@
|
||||
# Copyright 2014 The Chromium Authors. All rights reserved.
|
||||
# Use of this source code is governed by a BSD-style license that can be
|
||||
# found in the LICENSE file.
|
||||
|
||||
executable("imagediff") {
|
||||
output_name = "image_diff" # Different than dir nam for historical reasons.
|
||||
sources = [
|
||||
"image_diff.cc",
|
||||
"image_diff_png.h",
|
||||
"image_diff_png.cc",
|
||||
]
|
||||
|
||||
configs += [ "//build/config/compiler:wexit_time_destructors" ]
|
||||
|
||||
deps = [
|
||||
"//base",
|
||||
"//build/config/sanitizers:deps",
|
||||
"//third_party/libpng",
|
||||
"//third_party/zlib",
|
||||
]
|
||||
}
|
||||
@@ -1,450 +0,0 @@
|
||||
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
// This file input format is based loosely on
|
||||
// Tools/DumpRenderTree/ImageDiff.m
|
||||
|
||||
// The exact format of this tool's output to stdout is important, to match
|
||||
// what the run-webkit-tests script expects.
|
||||
|
||||
#include <algorithm>
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "base/basictypes.h"
|
||||
#include "base/command_line.h"
|
||||
#include "base/containers/hash_tables.h"
|
||||
#include "base/files/file_path.h"
|
||||
#include "base/files/file_util.h"
|
||||
#include "base/logging.h"
|
||||
#include "base/memory/scoped_ptr.h"
|
||||
#include "base/numerics/safe_conversions.h"
|
||||
#include "base/process/memory.h"
|
||||
#include "base/strings/string_util.h"
|
||||
#include "base/strings/utf_string_conversions.h"
|
||||
#include "sky/tools/imagediff/image_diff_png.h"
|
||||
|
||||
#if defined(OS_WIN)
|
||||
#include "windows.h"
|
||||
#endif
|
||||
|
||||
// Causes the app to remain open, waiting for pairs of filenames on stdin.
|
||||
// The caller is then responsible for terminating this app.
|
||||
static const char kOptionPollStdin[] = "use-stdin";
|
||||
// Causes the app to additionally calculate a diff of the color histograms
|
||||
// (which is resistant to shifts in layout).
|
||||
static const char kOptionCompareHistograms[] = "histogram";
|
||||
// Causes the app to output an image that visualizes the difference.
|
||||
static const char kOptionGenerateDiff[] = "diff";
|
||||
|
||||
// Return codes used by this utility.
|
||||
static const int kStatusSame = 0;
|
||||
static const int kStatusDifferent = 1;
|
||||
static const int kStatusError = 2;
|
||||
|
||||
// Color codes.
|
||||
static const uint32 RGBA_RED = 0x000000ff;
|
||||
static const uint32 RGBA_ALPHA = 0xff000000;
|
||||
|
||||
class Image {
|
||||
public:
|
||||
Image() : w_(0), h_(0) {
|
||||
}
|
||||
|
||||
Image(const Image& image)
|
||||
: w_(image.w_),
|
||||
h_(image.h_),
|
||||
data_(image.data_) {
|
||||
}
|
||||
|
||||
bool has_image() const {
|
||||
return w_ > 0 && h_ > 0;
|
||||
}
|
||||
|
||||
int w() const {
|
||||
return w_;
|
||||
}
|
||||
|
||||
int h() const {
|
||||
return h_;
|
||||
}
|
||||
|
||||
const unsigned char* data() const {
|
||||
return &data_.front();
|
||||
}
|
||||
|
||||
// Creates the image from stdin with the given data length. On success, it
|
||||
// will return true. On failure, no other methods should be accessed.
|
||||
bool CreateFromStdin(size_t byte_length) {
|
||||
if (byte_length == 0)
|
||||
return false;
|
||||
|
||||
scoped_ptr<unsigned char[]> source(new unsigned char[byte_length]);
|
||||
if (fread(source.get(), 1, byte_length, stdin) != byte_length)
|
||||
return false;
|
||||
|
||||
if (!image_diff_png::DecodePNG(source.get(), byte_length,
|
||||
&data_, &w_, &h_)) {
|
||||
Clear();
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// Creates the image from the given filename on disk, and returns true on
|
||||
// success.
|
||||
bool CreateFromFilename(const base::FilePath& path) {
|
||||
FILE* f = base::OpenFile(path, "rb");
|
||||
if (!f)
|
||||
return false;
|
||||
|
||||
std::vector<unsigned char> compressed;
|
||||
const int buf_size = 1024;
|
||||
unsigned char buf[buf_size];
|
||||
size_t num_read = 0;
|
||||
while ((num_read = fread(buf, 1, buf_size, f)) > 0) {
|
||||
compressed.insert(compressed.end(), buf, buf + num_read);
|
||||
}
|
||||
|
||||
base::CloseFile(f);
|
||||
|
||||
if (!image_diff_png::DecodePNG(&compressed[0], compressed.size(),
|
||||
&data_, &w_, &h_)) {
|
||||
Clear();
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void Clear() {
|
||||
w_ = h_ = 0;
|
||||
data_.clear();
|
||||
}
|
||||
|
||||
// Returns the RGBA value of the pixel at the given location
|
||||
uint32 pixel_at(int x, int y) const {
|
||||
DCHECK(x >= 0 && x < w_);
|
||||
DCHECK(y >= 0 && y < h_);
|
||||
return *reinterpret_cast<const uint32*>(&(data_[(y * w_ + x) * 4]));
|
||||
}
|
||||
|
||||
void set_pixel_at(int x, int y, uint32 color) const {
|
||||
DCHECK(x >= 0 && x < w_);
|
||||
DCHECK(y >= 0 && y < h_);
|
||||
void* addr = &const_cast<unsigned char*>(&data_.front())[(y * w_ + x) * 4];
|
||||
*reinterpret_cast<uint32*>(addr) = color;
|
||||
}
|
||||
|
||||
private:
|
||||
// pixel dimensions of the image
|
||||
int w_, h_;
|
||||
|
||||
std::vector<unsigned char> data_;
|
||||
};
|
||||
|
||||
float PercentageDifferent(const Image& baseline, const Image& actual) {
|
||||
int w = std::min(baseline.w(), actual.w());
|
||||
int h = std::min(baseline.h(), actual.h());
|
||||
|
||||
// Compute pixels different in the overlap.
|
||||
int pixels_different = 0;
|
||||
for (int y = 0; y < h; y++) {
|
||||
for (int x = 0; x < w; x++) {
|
||||
if (baseline.pixel_at(x, y) != actual.pixel_at(x, y))
|
||||
pixels_different++;
|
||||
}
|
||||
}
|
||||
|
||||
// Count pixels that are a difference in size as also being different.
|
||||
int max_w = std::max(baseline.w(), actual.w());
|
||||
int max_h = std::max(baseline.h(), actual.h());
|
||||
// These pixels are off the right side, not including the lower right corner.
|
||||
pixels_different += (max_w - w) * h;
|
||||
// These pixels are along the bottom, including the lower right corner.
|
||||
pixels_different += (max_h - h) * max_w;
|
||||
|
||||
// Like the WebKit ImageDiff tool, we define percentage different in terms
|
||||
// of the size of the 'actual' bitmap.
|
||||
float total_pixels = static_cast<float>(actual.w()) *
|
||||
static_cast<float>(actual.h());
|
||||
if (total_pixels == 0) {
|
||||
// When the bitmap is empty, they are 100% different.
|
||||
return 100.0f;
|
||||
}
|
||||
return 100.0f * pixels_different / total_pixels;
|
||||
}
|
||||
|
||||
typedef base::hash_map<uint32, int32> RgbaToCountMap;
|
||||
|
||||
float HistogramPercentageDifferent(const Image& baseline, const Image& actual) {
|
||||
// TODO(johnme): Consider using a joint histogram instead, as described in
|
||||
// "Comparing Images Using Joint Histograms" by Pass & Zabih
|
||||
// http://www.cs.cornell.edu/~rdz/papers/pz-jms99.pdf
|
||||
|
||||
int w = std::min(baseline.w(), actual.w());
|
||||
int h = std::min(baseline.h(), actual.h());
|
||||
|
||||
// Count occurences of each RGBA pixel value of baseline in the overlap.
|
||||
RgbaToCountMap baseline_histogram;
|
||||
for (int y = 0; y < h; y++) {
|
||||
for (int x = 0; x < w; x++) {
|
||||
// hash_map operator[] inserts a 0 (default constructor) if key not found.
|
||||
baseline_histogram[baseline.pixel_at(x, y)]++;
|
||||
}
|
||||
}
|
||||
|
||||
// Compute pixels different in the histogram of the overlap.
|
||||
int pixels_different = 0;
|
||||
for (int y = 0; y < h; y++) {
|
||||
for (int x = 0; x < w; x++) {
|
||||
uint32 actual_rgba = actual.pixel_at(x, y);
|
||||
RgbaToCountMap::iterator it = baseline_histogram.find(actual_rgba);
|
||||
if (it != baseline_histogram.end() && it->second > 0)
|
||||
it->second--;
|
||||
else
|
||||
pixels_different++;
|
||||
}
|
||||
}
|
||||
|
||||
// Count pixels that are a difference in size as also being different.
|
||||
int max_w = std::max(baseline.w(), actual.w());
|
||||
int max_h = std::max(baseline.h(), actual.h());
|
||||
// These pixels are off the right side, not including the lower right corner.
|
||||
pixels_different += (max_w - w) * h;
|
||||
// These pixels are along the bottom, including the lower right corner.
|
||||
pixels_different += (max_h - h) * max_w;
|
||||
|
||||
// Like the WebKit ImageDiff tool, we define percentage different in terms
|
||||
// of the size of the 'actual' bitmap.
|
||||
float total_pixels = static_cast<float>(actual.w()) *
|
||||
static_cast<float>(actual.h());
|
||||
if (total_pixels == 0) {
|
||||
// When the bitmap is empty, they are 100% different.
|
||||
return 100.0f;
|
||||
}
|
||||
return 100.0f * pixels_different / total_pixels;
|
||||
}
|
||||
|
||||
void PrintHelp() {
|
||||
fprintf(stderr,
|
||||
"Usage:\n"
|
||||
" image_diff [--histogram] <compare file> <reference file>\n"
|
||||
" Compares two files on disk, returning 0 when they are the same;\n"
|
||||
" passing \"--histogram\" additionally calculates a diff of the\n"
|
||||
" RGBA value histograms (which is resistant to shifts in layout)\n"
|
||||
" image_diff --use-stdin\n"
|
||||
" Stays open reading pairs of filenames from stdin, comparing them,\n"
|
||||
" and sending 0 to stdout when they are the same\n"
|
||||
" image_diff --diff <compare file> <reference file> <output file>\n"
|
||||
" Compares two files on disk, outputs an image that visualizes the\n"
|
||||
" difference to <output file>\n");
|
||||
/* For unfinished webkit-like-mode (see below)
|
||||
"\n"
|
||||
" image_diff -s\n"
|
||||
" Reads stream input from stdin, should be EXACTLY of the format\n"
|
||||
" \"Content-length: <byte length> <data>Content-length: ...\n"
|
||||
" it will take as many file pairs as given, and will compare them as\n"
|
||||
" (cmp_file, reference_file) pairs\n");
|
||||
*/
|
||||
}
|
||||
|
||||
int CompareImages(const base::FilePath& file1,
|
||||
const base::FilePath& file2,
|
||||
bool compare_histograms) {
|
||||
Image actual_image;
|
||||
Image baseline_image;
|
||||
|
||||
if (!actual_image.CreateFromFilename(file1)) {
|
||||
fprintf(stderr, "image_diff: Unable to open file \"%" PRFilePath "\"\n",
|
||||
file1.value().c_str());
|
||||
return kStatusError;
|
||||
}
|
||||
if (!baseline_image.CreateFromFilename(file2)) {
|
||||
fprintf(stderr, "image_diff: Unable to open file \"%" PRFilePath "\"\n",
|
||||
file2.value().c_str());
|
||||
return kStatusError;
|
||||
}
|
||||
|
||||
if (compare_histograms) {
|
||||
float percent = HistogramPercentageDifferent(actual_image, baseline_image);
|
||||
const char* passed = percent > 0.0 ? "failed" : "passed";
|
||||
printf("histogram diff: %01.2f%% %s\n", percent, passed);
|
||||
}
|
||||
|
||||
const char* diff_name = compare_histograms ? "exact diff" : "diff";
|
||||
float percent = PercentageDifferent(actual_image, baseline_image);
|
||||
const char* passed = percent > 0.0 ? "failed" : "passed";
|
||||
printf("%s: %01.2f%% %s\n", diff_name, percent, passed);
|
||||
if (percent > 0.0) {
|
||||
// failure: The WebKit version also writes the difference image to
|
||||
// stdout, which seems excessive for our needs.
|
||||
return kStatusDifferent;
|
||||
}
|
||||
// success
|
||||
return kStatusSame;
|
||||
|
||||
/* Untested mode that acts like WebKit's image comparator. I wrote this but
|
||||
decided it's too complicated. We may use it in the future if it looks useful
|
||||
|
||||
char buffer[2048];
|
||||
while (fgets(buffer, sizeof(buffer), stdin)) {
|
||||
|
||||
if (strncmp("Content-length: ", buffer, 16) == 0) {
|
||||
char* context;
|
||||
strtok_s(buffer, " ", &context);
|
||||
int image_size = strtol(strtok_s(NULL, " ", &context), NULL, 10);
|
||||
|
||||
bool success = false;
|
||||
if (image_size > 0 && actual_image.has_image() == 0) {
|
||||
if (!actual_image.CreateFromStdin(image_size)) {
|
||||
fputs("Error, input image can't be decoded.\n", stderr);
|
||||
return 1;
|
||||
}
|
||||
} else if (image_size > 0 && baseline_image.has_image() == 0) {
|
||||
if (!baseline_image.CreateFromStdin(image_size)) {
|
||||
fputs("Error, baseline image can't be decoded.\n", stderr);
|
||||
return 1;
|
||||
}
|
||||
} else {
|
||||
fputs("Error, image size must be specified.\n", stderr);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
if (actual_image.has_image() && baseline_image.has_image()) {
|
||||
float percent = PercentageDifferent(actual_image, baseline_image);
|
||||
if (percent > 0.0) {
|
||||
// failure: The WebKit version also writes the difference image to
|
||||
// stdout, which seems excessive for our needs.
|
||||
printf("diff: %01.2f%% failed\n", percent);
|
||||
} else {
|
||||
// success
|
||||
printf("diff: %01.2f%% passed\n", percent);
|
||||
}
|
||||
actual_image.Clear();
|
||||
baseline_image.Clear();
|
||||
}
|
||||
|
||||
fflush(stdout);
|
||||
}
|
||||
*/
|
||||
}
|
||||
|
||||
bool CreateImageDiff(const Image& image1, const Image& image2, Image* out) {
|
||||
int w = std::min(image1.w(), image2.w());
|
||||
int h = std::min(image1.h(), image2.h());
|
||||
*out = Image(image1);
|
||||
bool same = (image1.w() == image2.w()) && (image1.h() == image2.h());
|
||||
|
||||
// TODO(estade): do something with the extra pixels if the image sizes
|
||||
// are different.
|
||||
for (int y = 0; y < h; y++) {
|
||||
for (int x = 0; x < w; x++) {
|
||||
uint32 base_pixel = image1.pixel_at(x, y);
|
||||
if (base_pixel != image2.pixel_at(x, y)) {
|
||||
// Set differing pixels red.
|
||||
out->set_pixel_at(x, y, RGBA_RED | RGBA_ALPHA);
|
||||
same = false;
|
||||
} else {
|
||||
// Set same pixels as faded.
|
||||
uint32 alpha = base_pixel & RGBA_ALPHA;
|
||||
uint32 new_pixel = base_pixel - ((alpha / 2) & RGBA_ALPHA);
|
||||
out->set_pixel_at(x, y, new_pixel);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return same;
|
||||
}
|
||||
|
||||
int DiffImages(const base::FilePath& file1, const base::FilePath& file2,
|
||||
const base::FilePath& out_file) {
|
||||
Image actual_image;
|
||||
Image baseline_image;
|
||||
|
||||
if (!actual_image.CreateFromFilename(file1)) {
|
||||
fprintf(stderr, "image_diff: Unable to open file \"%" PRFilePath "\"\n",
|
||||
file1.value().c_str());
|
||||
return kStatusError;
|
||||
}
|
||||
if (!baseline_image.CreateFromFilename(file2)) {
|
||||
fprintf(stderr, "image_diff: Unable to open file \"%" PRFilePath "\"\n",
|
||||
file2.value().c_str());
|
||||
return kStatusError;
|
||||
}
|
||||
|
||||
Image diff_image;
|
||||
bool same = CreateImageDiff(baseline_image, actual_image, &diff_image);
|
||||
if (same)
|
||||
return kStatusSame;
|
||||
|
||||
std::vector<unsigned char> png_encoding;
|
||||
image_diff_png::EncodeRGBAPNG(
|
||||
diff_image.data(), diff_image.w(), diff_image.h(),
|
||||
diff_image.w() * 4, &png_encoding);
|
||||
if (base::WriteFile(out_file,
|
||||
reinterpret_cast<char*>(&png_encoding.front()),
|
||||
base::checked_cast<int>(png_encoding.size())) < 0)
|
||||
return kStatusError;
|
||||
|
||||
return kStatusDifferent;
|
||||
}
|
||||
|
||||
// It isn't strictly correct to only support ASCII paths, but this
|
||||
// program reads paths on stdin and the program that spawns it outputs
|
||||
// paths as non-wide strings anyway.
|
||||
base::FilePath FilePathFromASCII(const std::string& str) {
|
||||
#if defined(OS_WIN)
|
||||
return base::FilePath(base::ASCIIToUTF16(str));
|
||||
#else
|
||||
return base::FilePath(str);
|
||||
#endif
|
||||
}
|
||||
|
||||
int main(int argc, const char* argv[]) {
|
||||
base::EnableTerminationOnHeapCorruption();
|
||||
base::CommandLine::Init(argc, argv);
|
||||
const base::CommandLine& parsed_command_line =
|
||||
*base::CommandLine::ForCurrentProcess();
|
||||
bool histograms = parsed_command_line.HasSwitch(kOptionCompareHistograms);
|
||||
if (parsed_command_line.HasSwitch(kOptionPollStdin)) {
|
||||
// Watch stdin for filenames.
|
||||
std::string stdin_buffer;
|
||||
base::FilePath filename1;
|
||||
while (std::getline(std::cin, stdin_buffer)) {
|
||||
if (stdin_buffer.empty())
|
||||
continue;
|
||||
|
||||
if (!filename1.empty()) {
|
||||
// CompareImages writes results to stdout unless an error occurred.
|
||||
base::FilePath filename2 = FilePathFromASCII(stdin_buffer);
|
||||
if (CompareImages(filename1, filename2, histograms) == kStatusError)
|
||||
printf("error\n");
|
||||
fflush(stdout);
|
||||
filename1 = base::FilePath();
|
||||
} else {
|
||||
// Save the first filename in another buffer and wait for the second
|
||||
// filename to arrive via stdin.
|
||||
filename1 = FilePathFromASCII(stdin_buffer);
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
const base::CommandLine::StringVector& args = parsed_command_line.GetArgs();
|
||||
if (parsed_command_line.HasSwitch(kOptionGenerateDiff)) {
|
||||
if (args.size() == 3) {
|
||||
return DiffImages(base::FilePath(args[0]),
|
||||
base::FilePath(args[1]),
|
||||
base::FilePath(args[2]));
|
||||
}
|
||||
} else if (args.size() == 2) {
|
||||
return CompareImages(
|
||||
base::FilePath(args[0]), base::FilePath(args[1]), histograms);
|
||||
}
|
||||
|
||||
PrintHelp();
|
||||
return kStatusError;
|
||||
}
|
||||
@@ -1,643 +0,0 @@
|
||||
// Copyright 2013 The Chromium Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#include "sky/tools/imagediff/image_diff_png.h"
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "base/logging.h"
|
||||
#include "build/build_config.h"
|
||||
#include "third_party/libpng/png.h"
|
||||
#include "third_party/zlib/zlib.h"
|
||||
|
||||
namespace image_diff_png {
|
||||
|
||||
// This is a duplicate of ui/gfx/codec/png_codec.cc, after removing code related
|
||||
// to Skia, that we can use when running layout tests with minimal dependencies.
|
||||
namespace {
|
||||
|
||||
enum ColorFormat {
|
||||
// 3 bytes per pixel (packed), in RGB order regardless of endianness.
|
||||
// This is the native JPEG format.
|
||||
FORMAT_RGB,
|
||||
|
||||
// 4 bytes per pixel, in RGBA order in memory regardless of endianness.
|
||||
FORMAT_RGBA,
|
||||
|
||||
// 4 bytes per pixel, in BGRA order in memory regardless of endianness.
|
||||
// This is the default Windows DIB order.
|
||||
FORMAT_BGRA,
|
||||
|
||||
// 4 bytes per pixel, in pre-multiplied kARGB_8888_Config format. For use
|
||||
// with directly writing to a skia bitmap.
|
||||
FORMAT_SkBitmap
|
||||
};
|
||||
|
||||
// Represents a comment in the tEXt ancillary chunk of the png.
|
||||
struct Comment {
|
||||
std::string key;
|
||||
std::string text;
|
||||
};
|
||||
|
||||
// Converts BGRA->RGBA and RGBA->BGRA.
|
||||
void ConvertBetweenBGRAandRGBA(const unsigned char* input, int pixel_width,
|
||||
unsigned char* output, bool* is_opaque) {
|
||||
for (int x = 0; x < pixel_width; x++) {
|
||||
const unsigned char* pixel_in = &input[x * 4];
|
||||
unsigned char* pixel_out = &output[x * 4];
|
||||
pixel_out[0] = pixel_in[2];
|
||||
pixel_out[1] = pixel_in[1];
|
||||
pixel_out[2] = pixel_in[0];
|
||||
pixel_out[3] = pixel_in[3];
|
||||
}
|
||||
}
|
||||
|
||||
void ConvertRGBAtoRGB(const unsigned char* rgba, int pixel_width,
|
||||
unsigned char* rgb, bool* is_opaque) {
|
||||
for (int x = 0; x < pixel_width; x++) {
|
||||
const unsigned char* pixel_in = &rgba[x * 4];
|
||||
unsigned char* pixel_out = &rgb[x * 3];
|
||||
pixel_out[0] = pixel_in[0];
|
||||
pixel_out[1] = pixel_in[1];
|
||||
pixel_out[2] = pixel_in[2];
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
// Decoder --------------------------------------------------------------------
|
||||
//
|
||||
// This code is based on WebKit libpng interface (PNGImageDecoder), which is
|
||||
// in turn based on the Mozilla png decoder.
|
||||
|
||||
namespace {
|
||||
|
||||
// Gamma constants: We assume we're on Windows which uses a gamma of 2.2.
|
||||
const double kMaxGamma = 21474.83; // Maximum gamma accepted by png library.
|
||||
const double kDefaultGamma = 2.2;
|
||||
const double kInverseGamma = 1.0 / kDefaultGamma;
|
||||
|
||||
class PngDecoderState {
|
||||
public:
|
||||
// Output is a vector<unsigned char>.
|
||||
PngDecoderState(ColorFormat ofmt, std::vector<unsigned char>* o)
|
||||
: output_format(ofmt),
|
||||
output_channels(0),
|
||||
is_opaque(true),
|
||||
output(o),
|
||||
row_converter(NULL),
|
||||
width(0),
|
||||
height(0),
|
||||
done(false) {
|
||||
}
|
||||
|
||||
ColorFormat output_format;
|
||||
int output_channels;
|
||||
|
||||
// Used during the reading of an SkBitmap. Defaults to true until we see a
|
||||
// pixel with anything other than an alpha of 255.
|
||||
bool is_opaque;
|
||||
|
||||
// An intermediary buffer for decode output.
|
||||
std::vector<unsigned char>* output;
|
||||
|
||||
// Called to convert a row from the library to the correct output format.
|
||||
// When NULL, no conversion is necessary.
|
||||
void (*row_converter)(const unsigned char* in, int w, unsigned char* out,
|
||||
bool* is_opaque);
|
||||
|
||||
// Size of the image, set in the info callback.
|
||||
int width;
|
||||
int height;
|
||||
|
||||
// Set to true when we've found the end of the data.
|
||||
bool done;
|
||||
};
|
||||
|
||||
void ConvertRGBtoRGBA(const unsigned char* rgb, int pixel_width,
|
||||
unsigned char* rgba, bool* is_opaque) {
|
||||
for (int x = 0; x < pixel_width; x++) {
|
||||
const unsigned char* pixel_in = &rgb[x * 3];
|
||||
unsigned char* pixel_out = &rgba[x * 4];
|
||||
pixel_out[0] = pixel_in[0];
|
||||
pixel_out[1] = pixel_in[1];
|
||||
pixel_out[2] = pixel_in[2];
|
||||
pixel_out[3] = 0xff;
|
||||
}
|
||||
}
|
||||
|
||||
void ConvertRGBtoBGRA(const unsigned char* rgb, int pixel_width,
|
||||
unsigned char* bgra, bool* is_opaque) {
|
||||
for (int x = 0; x < pixel_width; x++) {
|
||||
const unsigned char* pixel_in = &rgb[x * 3];
|
||||
unsigned char* pixel_out = &bgra[x * 4];
|
||||
pixel_out[0] = pixel_in[2];
|
||||
pixel_out[1] = pixel_in[1];
|
||||
pixel_out[2] = pixel_in[0];
|
||||
pixel_out[3] = 0xff;
|
||||
}
|
||||
}
|
||||
|
||||
// Called when the png header has been read. This code is based on the WebKit
|
||||
// PNGImageDecoder
|
||||
void DecodeInfoCallback(png_struct* png_ptr, png_info* info_ptr) {
|
||||
PngDecoderState* state = static_cast<PngDecoderState*>(
|
||||
png_get_progressive_ptr(png_ptr));
|
||||
|
||||
int bit_depth, color_type, interlace_type, compression_type;
|
||||
int filter_type, channels;
|
||||
png_uint_32 w, h;
|
||||
png_get_IHDR(png_ptr, info_ptr, &w, &h, &bit_depth, &color_type,
|
||||
&interlace_type, &compression_type, &filter_type);
|
||||
|
||||
// Bounds check. When the image is unreasonably big, we'll error out and
|
||||
// end up back at the setjmp call when we set up decoding. "Unreasonably big"
|
||||
// means "big enough that w * h * 32bpp might overflow an int"; we choose this
|
||||
// threshold to match WebKit and because a number of places in code assume
|
||||
// that an image's size (in bytes) fits in a (signed) int.
|
||||
unsigned long long total_size =
|
||||
static_cast<unsigned long long>(w) * static_cast<unsigned long long>(h);
|
||||
if (total_size > ((1 << 29) - 1))
|
||||
longjmp(png_jmpbuf(png_ptr), 1);
|
||||
state->width = static_cast<int>(w);
|
||||
state->height = static_cast<int>(h);
|
||||
|
||||
// Expand to ensure we use 24-bit for RGB and 32-bit for RGBA.
|
||||
if (color_type == PNG_COLOR_TYPE_PALETTE ||
|
||||
(color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8))
|
||||
png_set_expand(png_ptr);
|
||||
|
||||
// Transparency for paletted images.
|
||||
if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS))
|
||||
png_set_expand(png_ptr);
|
||||
|
||||
// Convert 16-bit to 8-bit.
|
||||
if (bit_depth == 16)
|
||||
png_set_strip_16(png_ptr);
|
||||
|
||||
// Expand grayscale to RGB.
|
||||
if (color_type == PNG_COLOR_TYPE_GRAY ||
|
||||
color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
|
||||
png_set_gray_to_rgb(png_ptr);
|
||||
|
||||
// Deal with gamma and keep it under our control.
|
||||
double gamma;
|
||||
if (png_get_gAMA(png_ptr, info_ptr, &gamma)) {
|
||||
if (gamma <= 0.0 || gamma > kMaxGamma) {
|
||||
gamma = kInverseGamma;
|
||||
png_set_gAMA(png_ptr, info_ptr, gamma);
|
||||
}
|
||||
png_set_gamma(png_ptr, kDefaultGamma, gamma);
|
||||
} else {
|
||||
png_set_gamma(png_ptr, kDefaultGamma, kInverseGamma);
|
||||
}
|
||||
|
||||
// Tell libpng to send us rows for interlaced pngs.
|
||||
if (interlace_type == PNG_INTERLACE_ADAM7)
|
||||
png_set_interlace_handling(png_ptr);
|
||||
|
||||
// Update our info now
|
||||
png_read_update_info(png_ptr, info_ptr);
|
||||
channels = png_get_channels(png_ptr, info_ptr);
|
||||
|
||||
// Pick our row format converter necessary for this data.
|
||||
if (channels == 3) {
|
||||
switch (state->output_format) {
|
||||
case FORMAT_RGB:
|
||||
state->row_converter = NULL; // no conversion necessary
|
||||
state->output_channels = 3;
|
||||
break;
|
||||
case FORMAT_RGBA:
|
||||
state->row_converter = &ConvertRGBtoRGBA;
|
||||
state->output_channels = 4;
|
||||
break;
|
||||
case FORMAT_BGRA:
|
||||
state->row_converter = &ConvertRGBtoBGRA;
|
||||
state->output_channels = 4;
|
||||
break;
|
||||
default:
|
||||
NOTREACHED() << "Unknown output format";
|
||||
break;
|
||||
}
|
||||
} else if (channels == 4) {
|
||||
switch (state->output_format) {
|
||||
case FORMAT_RGB:
|
||||
state->row_converter = &ConvertRGBAtoRGB;
|
||||
state->output_channels = 3;
|
||||
break;
|
||||
case FORMAT_RGBA:
|
||||
state->row_converter = NULL; // no conversion necessary
|
||||
state->output_channels = 4;
|
||||
break;
|
||||
case FORMAT_BGRA:
|
||||
state->row_converter = &ConvertBetweenBGRAandRGBA;
|
||||
state->output_channels = 4;
|
||||
break;
|
||||
default:
|
||||
NOTREACHED() << "Unknown output format";
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
NOTREACHED() << "Unknown input channels";
|
||||
longjmp(png_jmpbuf(png_ptr), 1);
|
||||
}
|
||||
|
||||
state->output->resize(
|
||||
state->width * state->output_channels * state->height);
|
||||
}
|
||||
|
||||
void DecodeRowCallback(png_struct* png_ptr, png_byte* new_row,
|
||||
png_uint_32 row_num, int pass) {
|
||||
PngDecoderState* state = static_cast<PngDecoderState*>(
|
||||
png_get_progressive_ptr(png_ptr));
|
||||
|
||||
DCHECK(pass == 0);
|
||||
if (static_cast<int>(row_num) > state->height) {
|
||||
NOTREACHED() << "Invalid row";
|
||||
return;
|
||||
}
|
||||
|
||||
unsigned char* base = NULL;
|
||||
base = &state->output->front();
|
||||
|
||||
unsigned char* dest = &base[state->width * state->output_channels * row_num];
|
||||
if (state->row_converter)
|
||||
state->row_converter(new_row, state->width, dest, &state->is_opaque);
|
||||
else
|
||||
memcpy(dest, new_row, state->width * state->output_channels);
|
||||
}
|
||||
|
||||
void DecodeEndCallback(png_struct* png_ptr, png_info* info) {
|
||||
PngDecoderState* state = static_cast<PngDecoderState*>(
|
||||
png_get_progressive_ptr(png_ptr));
|
||||
|
||||
// Mark the image as complete, this will tell the Decode function that we
|
||||
// have successfully found the end of the data.
|
||||
state->done = true;
|
||||
}
|
||||
|
||||
// Automatically destroys the given read structs on destruction to make
|
||||
// cleanup and error handling code cleaner.
|
||||
class PngReadStructDestroyer {
|
||||
public:
|
||||
PngReadStructDestroyer(png_struct** ps, png_info** pi) : ps_(ps), pi_(pi) {
|
||||
}
|
||||
~PngReadStructDestroyer() {
|
||||
png_destroy_read_struct(ps_, pi_, NULL);
|
||||
}
|
||||
private:
|
||||
png_struct** ps_;
|
||||
png_info** pi_;
|
||||
};
|
||||
|
||||
bool BuildPNGStruct(const unsigned char* input, size_t input_size,
|
||||
png_struct** png_ptr, png_info** info_ptr) {
|
||||
if (input_size < 8)
|
||||
return false; // Input data too small to be a png
|
||||
|
||||
// Have libpng check the signature, it likes the first 8 bytes.
|
||||
if (png_sig_cmp(const_cast<unsigned char*>(input), 0, 8) != 0)
|
||||
return false;
|
||||
|
||||
*png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
|
||||
if (!*png_ptr)
|
||||
return false;
|
||||
|
||||
*info_ptr = png_create_info_struct(*png_ptr);
|
||||
if (!*info_ptr) {
|
||||
png_destroy_read_struct(png_ptr, NULL, NULL);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
// static
|
||||
bool Decode(const unsigned char* input, size_t input_size,
|
||||
ColorFormat format, std::vector<unsigned char>* output,
|
||||
int* w, int* h) {
|
||||
png_struct* png_ptr = NULL;
|
||||
png_info* info_ptr = NULL;
|
||||
if (!BuildPNGStruct(input, input_size, &png_ptr, &info_ptr))
|
||||
return false;
|
||||
|
||||
PngReadStructDestroyer destroyer(&png_ptr, &info_ptr);
|
||||
if (setjmp(png_jmpbuf(png_ptr))) {
|
||||
// The destroyer will ensure that the structures are cleaned up in this
|
||||
// case, even though we may get here as a jump from random parts of the
|
||||
// PNG library called below.
|
||||
return false;
|
||||
}
|
||||
|
||||
PngDecoderState state(format, output);
|
||||
|
||||
png_set_progressive_read_fn(png_ptr, &state, &DecodeInfoCallback,
|
||||
&DecodeRowCallback, &DecodeEndCallback);
|
||||
png_process_data(png_ptr,
|
||||
info_ptr,
|
||||
const_cast<unsigned char*>(input),
|
||||
input_size);
|
||||
|
||||
if (!state.done) {
|
||||
// Fed it all the data but the library didn't think we got all the data, so
|
||||
// this file must be truncated.
|
||||
output->clear();
|
||||
return false;
|
||||
}
|
||||
|
||||
*w = state.width;
|
||||
*h = state.height;
|
||||
return true;
|
||||
}
|
||||
|
||||
// Encoder --------------------------------------------------------------------
|
||||
//
|
||||
// This section of the code is based on nsPNGEncoder.cpp in Mozilla
|
||||
// (Copyright 2005 Google Inc.)
|
||||
|
||||
namespace {
|
||||
|
||||
// Passed around as the io_ptr in the png structs so our callbacks know where
|
||||
// to write data.
|
||||
struct PngEncoderState {
|
||||
explicit PngEncoderState(std::vector<unsigned char>* o) : out(o) {}
|
||||
std::vector<unsigned char>* out;
|
||||
};
|
||||
|
||||
// Called by libpng to flush its internal buffer to ours.
|
||||
void EncoderWriteCallback(png_structp png, png_bytep data, png_size_t size) {
|
||||
PngEncoderState* state = static_cast<PngEncoderState*>(png_get_io_ptr(png));
|
||||
DCHECK(state->out);
|
||||
|
||||
size_t old_size = state->out->size();
|
||||
state->out->resize(old_size + size);
|
||||
memcpy(&(*state->out)[old_size], data, size);
|
||||
}
|
||||
|
||||
void FakeFlushCallback(png_structp png) {
|
||||
// We don't need to perform any flushing since we aren't doing real IO, but
|
||||
// we're required to provide this function by libpng.
|
||||
}
|
||||
|
||||
void ConvertBGRAtoRGB(const unsigned char* bgra, int pixel_width,
|
||||
unsigned char* rgb, bool* is_opaque) {
|
||||
for (int x = 0; x < pixel_width; x++) {
|
||||
const unsigned char* pixel_in = &bgra[x * 4];
|
||||
unsigned char* pixel_out = &rgb[x * 3];
|
||||
pixel_out[0] = pixel_in[2];
|
||||
pixel_out[1] = pixel_in[1];
|
||||
pixel_out[2] = pixel_in[0];
|
||||
}
|
||||
}
|
||||
|
||||
#ifdef PNG_TEXT_SUPPORTED
|
||||
|
||||
inline char* strdup(const char* str) {
|
||||
#if defined(OS_WIN)
|
||||
return _strdup(str);
|
||||
#else
|
||||
return ::strdup(str);
|
||||
#endif
|
||||
}
|
||||
|
||||
class CommentWriter {
|
||||
public:
|
||||
explicit CommentWriter(const std::vector<Comment>& comments)
|
||||
: comments_(comments),
|
||||
png_text_(new png_text[comments.size()]) {
|
||||
for (size_t i = 0; i < comments.size(); ++i)
|
||||
AddComment(i, comments[i]);
|
||||
}
|
||||
|
||||
~CommentWriter() {
|
||||
for (size_t i = 0; i < comments_.size(); ++i) {
|
||||
free(png_text_[i].key);
|
||||
free(png_text_[i].text);
|
||||
}
|
||||
delete [] png_text_;
|
||||
}
|
||||
|
||||
bool HasComments() {
|
||||
return !comments_.empty();
|
||||
}
|
||||
|
||||
png_text* get_png_text() {
|
||||
return png_text_;
|
||||
}
|
||||
|
||||
int size() {
|
||||
return static_cast<int>(comments_.size());
|
||||
}
|
||||
|
||||
private:
|
||||
void AddComment(size_t pos, const Comment& comment) {
|
||||
png_text_[pos].compression = PNG_TEXT_COMPRESSION_NONE;
|
||||
// A PNG comment's key can only be 79 characters long.
|
||||
DCHECK(comment.key.length() < 79);
|
||||
png_text_[pos].key = strdup(comment.key.substr(0, 78).c_str());
|
||||
png_text_[pos].text = strdup(comment.text.c_str());
|
||||
png_text_[pos].text_length = comment.text.length();
|
||||
#ifdef PNG_iTXt_SUPPORTED
|
||||
png_text_[pos].itxt_length = 0;
|
||||
png_text_[pos].lang = 0;
|
||||
png_text_[pos].lang_key = 0;
|
||||
#endif
|
||||
}
|
||||
|
||||
const std::vector<Comment> comments_;
|
||||
png_text* png_text_;
|
||||
};
|
||||
#endif // PNG_TEXT_SUPPORTED
|
||||
|
||||
// The type of functions usable for converting between pixel formats.
|
||||
typedef void (*FormatConverter)(const unsigned char* in, int w,
|
||||
unsigned char* out, bool* is_opaque);
|
||||
|
||||
// libpng uses a wacky setjmp-based API, which makes the compiler nervous.
|
||||
// We constrain all of the calls we make to libpng where the setjmp() is in
|
||||
// place to this function.
|
||||
// Returns true on success.
|
||||
bool DoLibpngWrite(png_struct* png_ptr, png_info* info_ptr,
|
||||
PngEncoderState* state,
|
||||
int width, int height, int row_byte_width,
|
||||
const unsigned char* input, int compression_level,
|
||||
int png_output_color_type, int output_color_components,
|
||||
FormatConverter converter,
|
||||
const std::vector<Comment>& comments) {
|
||||
#ifdef PNG_TEXT_SUPPORTED
|
||||
CommentWriter comment_writer(comments);
|
||||
#endif
|
||||
unsigned char* row_buffer = NULL;
|
||||
|
||||
// Make sure to not declare any locals here -- locals in the presence
|
||||
// of setjmp() in C++ code makes gcc complain.
|
||||
|
||||
if (setjmp(png_jmpbuf(png_ptr))) {
|
||||
delete[] row_buffer;
|
||||
return false;
|
||||
}
|
||||
|
||||
png_set_compression_level(png_ptr, compression_level);
|
||||
|
||||
// Set our callback for libpng to give us the data.
|
||||
png_set_write_fn(png_ptr, state, EncoderWriteCallback, FakeFlushCallback);
|
||||
|
||||
png_set_IHDR(png_ptr, info_ptr, width, height, 8, png_output_color_type,
|
||||
PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT,
|
||||
PNG_FILTER_TYPE_DEFAULT);
|
||||
|
||||
#ifdef PNG_TEXT_SUPPORTED
|
||||
if (comment_writer.HasComments()) {
|
||||
png_set_text(png_ptr, info_ptr, comment_writer.get_png_text(),
|
||||
comment_writer.size());
|
||||
}
|
||||
#endif
|
||||
|
||||
png_write_info(png_ptr, info_ptr);
|
||||
|
||||
if (!converter) {
|
||||
// No conversion needed, give the data directly to libpng.
|
||||
for (int y = 0; y < height; y ++) {
|
||||
png_write_row(png_ptr,
|
||||
const_cast<unsigned char*>(&input[y * row_byte_width]));
|
||||
}
|
||||
} else {
|
||||
// Needs conversion using a separate buffer.
|
||||
row_buffer = new unsigned char[width * output_color_components];
|
||||
for (int y = 0; y < height; y ++) {
|
||||
converter(&input[y * row_byte_width], width, row_buffer, NULL);
|
||||
png_write_row(png_ptr, row_buffer);
|
||||
}
|
||||
delete[] row_buffer;
|
||||
}
|
||||
|
||||
png_write_end(png_ptr, info_ptr);
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
// static
|
||||
bool EncodeWithCompressionLevel(const unsigned char* input, ColorFormat format,
|
||||
const int width, const int height,
|
||||
int row_byte_width,
|
||||
bool discard_transparency,
|
||||
const std::vector<Comment>& comments,
|
||||
int compression_level,
|
||||
std::vector<unsigned char>* output) {
|
||||
// Run to convert an input row into the output row format, NULL means no
|
||||
// conversion is necessary.
|
||||
FormatConverter converter = NULL;
|
||||
|
||||
int input_color_components, output_color_components;
|
||||
int png_output_color_type;
|
||||
switch (format) {
|
||||
case FORMAT_RGB:
|
||||
input_color_components = 3;
|
||||
output_color_components = 3;
|
||||
png_output_color_type = PNG_COLOR_TYPE_RGB;
|
||||
discard_transparency = false;
|
||||
break;
|
||||
|
||||
case FORMAT_RGBA:
|
||||
input_color_components = 4;
|
||||
if (discard_transparency) {
|
||||
output_color_components = 3;
|
||||
png_output_color_type = PNG_COLOR_TYPE_RGB;
|
||||
converter = ConvertRGBAtoRGB;
|
||||
} else {
|
||||
output_color_components = 4;
|
||||
png_output_color_type = PNG_COLOR_TYPE_RGB_ALPHA;
|
||||
converter = NULL;
|
||||
}
|
||||
break;
|
||||
|
||||
case FORMAT_BGRA:
|
||||
input_color_components = 4;
|
||||
if (discard_transparency) {
|
||||
output_color_components = 3;
|
||||
png_output_color_type = PNG_COLOR_TYPE_RGB;
|
||||
converter = ConvertBGRAtoRGB;
|
||||
} else {
|
||||
output_color_components = 4;
|
||||
png_output_color_type = PNG_COLOR_TYPE_RGB_ALPHA;
|
||||
converter = ConvertBetweenBGRAandRGBA;
|
||||
}
|
||||
break;
|
||||
|
||||
default:
|
||||
NOTREACHED() << "Unknown pixel format";
|
||||
return false;
|
||||
}
|
||||
|
||||
// Row stride should be at least as long as the length of the data.
|
||||
DCHECK(input_color_components * width <= row_byte_width);
|
||||
|
||||
png_struct* png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,
|
||||
NULL, NULL, NULL);
|
||||
if (!png_ptr)
|
||||
return false;
|
||||
png_info* info_ptr = png_create_info_struct(png_ptr);
|
||||
if (!info_ptr) {
|
||||
png_destroy_write_struct(&png_ptr, NULL);
|
||||
return false;
|
||||
}
|
||||
|
||||
PngEncoderState state(output);
|
||||
bool success = DoLibpngWrite(png_ptr, info_ptr, &state,
|
||||
width, height, row_byte_width,
|
||||
input, compression_level, png_output_color_type,
|
||||
output_color_components, converter, comments);
|
||||
png_destroy_write_struct(&png_ptr, &info_ptr);
|
||||
|
||||
return success;
|
||||
}
|
||||
|
||||
// static
|
||||
bool Encode(const unsigned char* input, ColorFormat format,
|
||||
const int width, const int height, int row_byte_width,
|
||||
bool discard_transparency,
|
||||
const std::vector<Comment>& comments,
|
||||
std::vector<unsigned char>* output) {
|
||||
return EncodeWithCompressionLevel(input, format, width, height,
|
||||
row_byte_width,
|
||||
discard_transparency,
|
||||
comments, Z_DEFAULT_COMPRESSION,
|
||||
output);
|
||||
}
|
||||
|
||||
// Decode a PNG into an RGBA pixel array.
|
||||
bool DecodePNG(const unsigned char* input, size_t input_size,
|
||||
std::vector<unsigned char>* output,
|
||||
int* width, int* height) {
|
||||
return Decode(input, input_size, FORMAT_RGBA, output, width, height);
|
||||
}
|
||||
|
||||
// Encode an RGBA pixel array into a PNG.
|
||||
bool EncodeRGBAPNG(const unsigned char* input,
|
||||
int width,
|
||||
int height,
|
||||
int row_byte_width,
|
||||
std::vector<unsigned char>* output) {
|
||||
return Encode(input, FORMAT_RGBA,
|
||||
width, height, row_byte_width, false,
|
||||
std::vector<Comment>(), output);
|
||||
}
|
||||
|
||||
// Encode an BGRA pixel array into a PNG.
|
||||
bool EncodeBGRAPNG(const unsigned char* input,
|
||||
int width,
|
||||
int height,
|
||||
int row_byte_width,
|
||||
bool discard_transparency,
|
||||
std::vector<unsigned char>* output) {
|
||||
return Encode(input, FORMAT_BGRA,
|
||||
width, height, row_byte_width, discard_transparency,
|
||||
std::vector<Comment>(), output);
|
||||
}
|
||||
|
||||
} // image_diff_png
|
||||
@@ -1,35 +0,0 @@
|
||||
// Copyright 2013 The Chromium Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#ifndef TOOLS_IMAGEDIFF_IMAGE_DIFF_PNG_H_
|
||||
#define TOOLS_IMAGEDIFF_IMAGE_DIFF_PNG_H_
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace image_diff_png {
|
||||
|
||||
// Decode a PNG into an RGBA pixel array.
|
||||
bool DecodePNG(const unsigned char* input, size_t input_size,
|
||||
std::vector<unsigned char>* output,
|
||||
int* width, int* height);
|
||||
|
||||
// Encode an RGBA pixel array into a PNG.
|
||||
bool EncodeRGBAPNG(const unsigned char* input,
|
||||
int width,
|
||||
int height,
|
||||
int row_byte_width,
|
||||
std::vector<unsigned char>* output);
|
||||
|
||||
// Encode an BGRA pixel array into a PNG.
|
||||
bool EncodeBGRAPNG(const unsigned char* input,
|
||||
int width,
|
||||
int height,
|
||||
int row_byte_width,
|
||||
bool discard_transparency,
|
||||
std::vector<unsigned char>* output);
|
||||
|
||||
} // namespace image_diff_png
|
||||
|
||||
#endif // TOOLS_IMAGEDIFF_IMAGE_DIFF_PNG_H_
|
||||
@@ -1,88 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
# Copyright 2014 The Chromium Authors. All rights reserved.
|
||||
# Use of this source code is governed by a BSD-style license that can be
|
||||
# found in the LICENSE file.
|
||||
|
||||
import subprocess
|
||||
import os
|
||||
import argparse
|
||||
import logging
|
||||
|
||||
ROOT_DIR = os.path.abspath(os.path.join(__file__, os.pardir, os.pardir,
|
||||
os.pardir))
|
||||
|
||||
# Where to cache GN results (they're expensive to compute).
|
||||
GN_CACHE_PATH = os.path.abspath(os.path.join(ROOT_DIR, 'in_gn.txt'))
|
||||
|
||||
|
||||
def stripped_lines_from_command(cmd, cwd=None):
|
||||
lines = subprocess.check_output(cmd, cwd=cwd).splitlines()
|
||||
return map(str.strip, lines)
|
||||
|
||||
|
||||
def gn_desc(*args):
|
||||
# GN doesn't understand absolute paths yet, so use a relative BUILD_DIR
|
||||
# and pass ROOT_DIR as the CWD.
|
||||
# Hard-coding Debug for now:
|
||||
BUILD_DIR = '//out/Debug' # // means repository root-relative.
|
||||
cmd = ['gn', 'desc', BUILD_DIR] + list(args)
|
||||
return stripped_lines_from_command(cmd, cwd=ROOT_DIR)
|
||||
|
||||
|
||||
def targets_under(target):
|
||||
targets = gn_desc(target, 'deps', '--all')
|
||||
return filter(lambda s: s.startswith(target), targets)
|
||||
|
||||
|
||||
def used_files(target):
|
||||
logging.info(target)
|
||||
sources = map(lambda s: s[2:], gn_desc(target, 'sources'))
|
||||
inputs = map(lambda s: s[2:], gn_desc(target, 'inputs'))
|
||||
public = map(lambda s: s[2:], gn_desc(target, 'public'))
|
||||
script = map(lambda s: s[2:], gn_desc(target, 'script'))
|
||||
return sources + inputs + public + script
|
||||
|
||||
|
||||
def find_on_disk(path):
|
||||
# FIXME: Use os.walk and do fancier ignoring.
|
||||
find_cmd = ['find', path, '-type', 'f']
|
||||
return stripped_lines_from_command(find_cmd, cwd=ROOT_DIR)
|
||||
|
||||
|
||||
def main():
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
|
||||
if os.path.exists(GN_CACHE_PATH):
|
||||
logging.info('Using cached GN list: %s' % GN_CACHE_PATH)
|
||||
in_gn = set(map(str.strip, open(GN_CACHE_PATH).readlines()))
|
||||
else:
|
||||
logging.info('No gn cache found, rebuilding: %s' % GN_CACHE_PATH)
|
||||
in_gn = set(sum(map(used_files, targets_under('//sky')), []))
|
||||
open(GN_CACHE_PATH, 'w+').write('\n'.join(in_gn))
|
||||
|
||||
on_disk = set(find_on_disk('sky/engine'))
|
||||
# Ignore web/tests and bindings/tests
|
||||
on_disk = set(filter(lambda p: '/tests/' not in p, on_disk))
|
||||
|
||||
missing_from_gn = sorted(on_disk - in_gn)
|
||||
|
||||
IGNORED_EXTENSIONS = [
|
||||
'.py', # Probably some to remove, probably some to teach gn about.
|
||||
# Python files not being known to gn can cause flaky builds too!
|
||||
'.pyc',
|
||||
'.gypi',
|
||||
'.gn',
|
||||
'.gni',
|
||||
]
|
||||
for ext in IGNORED_EXTENSIONS:
|
||||
missing_from_gn = filter(lambda p: not p.endswith(ext), missing_from_gn)
|
||||
|
||||
# All upper-case files like README, DEPS, etc. are fine.
|
||||
missing_from_gn = filter(lambda p: not os.path.basename(p).isupper(),
|
||||
missing_from_gn)
|
||||
|
||||
print '\n'.join(missing_from_gn)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -1,134 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
# Copyright 2015 The Chromium Authors. All rights reserved.
|
||||
# Use of this source code is governed by a BSD-style license that can be
|
||||
# found in the LICENSE file.
|
||||
|
||||
import argparse
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
import subprocess
|
||||
import json
|
||||
import platform
|
||||
|
||||
|
||||
def library_paths(build_dir):
|
||||
for name in os.listdir(build_dir):
|
||||
path = os.path.realpath(os.path.join(build_dir, name))
|
||||
if not os.path.isfile(path):
|
||||
continue
|
||||
|
||||
# Only include suffixes we care about:
|
||||
basename, ext = os.path.splitext(name)
|
||||
if ext not in ('', '.mojo', '.so'):
|
||||
continue
|
||||
|
||||
# Ignore ninja's dot-files.
|
||||
if basename.startswith('.'):
|
||||
continue
|
||||
yield path
|
||||
|
||||
|
||||
def get_cached_app_id(path, cache, cache_mtime):
|
||||
if not cache_mtime:
|
||||
return None
|
||||
try:
|
||||
if os.path.getmtime(path) > cache_mtime:
|
||||
return None
|
||||
except:
|
||||
return None
|
||||
return cache.get(path)
|
||||
|
||||
|
||||
def compute_path_to_app_id_map(paths, cache, cache_mtime):
|
||||
path_to_app_id_map = {}
|
||||
for path in paths:
|
||||
app_id = get_cached_app_id(path, cache, cache_mtime)
|
||||
if not app_id:
|
||||
if platform.system() == 'Darwin':
|
||||
logging.info('shasum -a 256 %s' % path)
|
||||
output = subprocess.check_output(['shasum', '-a', '256', path])
|
||||
else:
|
||||
logging.info('sha256sum %s' % path)
|
||||
output = subprocess.check_output(['sha256sum', path])
|
||||
# Example output:
|
||||
# f82a3551478a9a0e010adccd675053b9 png_viewer.mojo
|
||||
app_id = output.strip().split()[0]
|
||||
path_to_app_id_map[path] = app_id
|
||||
return path_to_app_id_map
|
||||
|
||||
|
||||
def read_app_id_cache(cache_path):
|
||||
try:
|
||||
with open(cache_path, 'r') as cache_file:
|
||||
return json.load(cache_file), os.path.getmtime(cache_path)
|
||||
except:
|
||||
logging.warn('Failed to read file: %s' % cache_path)
|
||||
return {}, None
|
||||
|
||||
|
||||
def write_app_id_cache(cache_path, cache):
|
||||
try:
|
||||
with open(cache_path, 'w') as cache_file:
|
||||
json.dump(cache, cache_file, indent=2, sort_keys=True)
|
||||
except:
|
||||
logging.warn('Failed to write file: %s' % cache_path)
|
||||
|
||||
|
||||
# TODO(eseidel): Share logic with tools/android_stack_parser/stack
|
||||
def main():
|
||||
logging.basicConfig(level=logging.WARN)
|
||||
parser = argparse.ArgumentParser(
|
||||
description='Builds a directory of app_id symlinks to symbols'
|
||||
' to match expected dlopen names from mojo_shell\'s NetworkLoader.')
|
||||
parser.add_argument('links_dir', type=str)
|
||||
parser.add_argument('build_dir', type=str)
|
||||
parser.add_argument('-f', '--force', action='store_true')
|
||||
parser.add_argument('-v', '--verbose', action='store_true')
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.verbose:
|
||||
logging.getLogger().setLevel(logging.INFO)
|
||||
|
||||
if not os.path.isdir(args.links_dir):
|
||||
logging.fatal('links_dir: %s is not a directory' % args.links_dir)
|
||||
sys.exit(1)
|
||||
|
||||
# Some of the .so files are 100s of megabytes. Cache the md5s to save time.
|
||||
cache_path = os.path.join(args.build_dir, '.app_id_cache')
|
||||
cache, cache_mtime = read_app_id_cache(cache_path)
|
||||
if args.force:
|
||||
cache_mtime = None
|
||||
|
||||
paths = library_paths(args.build_dir)
|
||||
path_to_app_id_map = compute_path_to_app_id_map(list(paths),
|
||||
cache, cache_mtime)
|
||||
|
||||
# The cache contains unmodified app-ids.
|
||||
write_app_id_cache(cache_path, path_to_app_id_map)
|
||||
|
||||
for path, app_id in path_to_app_id_map.items():
|
||||
basename = os.path.basename(path)
|
||||
root_name, ext = os.path.splitext(basename)
|
||||
|
||||
# On android foo.mojo is stripped, but libfoo_library.so is not.
|
||||
if ext == '.mojo':
|
||||
symboled_name = 'lib%s_library.so' % root_name
|
||||
symboled_path = os.path.realpath(
|
||||
os.path.join(args.build_dir, symboled_name))
|
||||
if os.path.exists(symboled_path):
|
||||
path = symboled_path
|
||||
|
||||
link_path = os.path.join(args.links_dir, '%s.mojo' % app_id)
|
||||
|
||||
logging.info("%s -> %s" % (link_path, path))
|
||||
|
||||
if os.path.lexists(link_path):
|
||||
logging.debug('link already exists %s, replacing' % path)
|
||||
os.unlink(link_path)
|
||||
|
||||
os.symlink(path, link_path)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -1,108 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
# Copyright 2015 The Chromium Authors. All rights reserved.
|
||||
# Use of this source code is governed by a BSD-style license that can be
|
||||
# found in the LICENSE file.
|
||||
|
||||
# Modeled on examples from:
|
||||
# https://github.com/googlesamples/android-play-publisher-api/tree/master/v2/python
|
||||
|
||||
import argparse
|
||||
import httplib2
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
|
||||
from apiclient.discovery import build
|
||||
from oauth2client import client
|
||||
|
||||
|
||||
SERVICE_ACCOUNT_EMAIL = (
|
||||
'69268379666-mu02g6delkg25t856t773fkdt9p90lpd@developer.gserviceaccount.com')
|
||||
KEY_FILE_PATH = os.path.expanduser('~/sky_publish_key.p12')
|
||||
API_AUTH_SCOPE = 'https://www.googleapis.com/auth/androidpublisher'
|
||||
DEFAULT_TRACK = 'production'
|
||||
|
||||
|
||||
def read_binary_file(path):
|
||||
with file(path, 'rb') as f:
|
||||
return f.read()
|
||||
|
||||
|
||||
def read_text_file(path):
|
||||
with file(path, 'r') as f:
|
||||
return f.read()
|
||||
|
||||
|
||||
def publish_apk(service, package_name, apk_path, changes_text, track):
|
||||
edit_request = service.edits().insert(body={}, packageName=package_name)
|
||||
result = edit_request.execute()
|
||||
edit_id = result['id']
|
||||
|
||||
apk_response = service.edits().apks().upload(
|
||||
editId=edit_id,
|
||||
packageName=package_name,
|
||||
media_body=apk_path).execute()
|
||||
|
||||
print 'Version code %d has been uploaded' % apk_response['versionCode']
|
||||
|
||||
track_response = service.edits().tracks().update(
|
||||
editId=edit_id,
|
||||
track=track,
|
||||
packageName=package_name,
|
||||
body={u'versionCodes': [apk_response['versionCode']]}).execute()
|
||||
|
||||
print 'Track %s is set for version code(s) %s' % (
|
||||
track_response['track'], str(track_response['versionCodes']))
|
||||
|
||||
listing_response = service.edits().apklistings().update(
|
||||
editId=edit_id, packageName=package_name, language='en-US',
|
||||
apkVersionCode=apk_response['versionCode'],
|
||||
body={'recentChanges': changes_text}).execute()
|
||||
|
||||
print ('Listing for language %s was updated.'
|
||||
% listing_response['language'])
|
||||
|
||||
commit_request = service.edits().commit(
|
||||
editId=edit_id, packageName=package_name).execute()
|
||||
|
||||
print 'Edit "%s" has been committed' % (commit_request['id'])
|
||||
|
||||
|
||||
def connect_to_service(email, key_file, auth_scope):
|
||||
credentials = client.SignedJwtAssertionCredentials(
|
||||
email,
|
||||
read_binary_file(key_file),
|
||||
scope=auth_scope)
|
||||
http = httplib2.Http()
|
||||
http = credentials.authorize(http)
|
||||
|
||||
return build('androidpublisher', 'v2', http=http)
|
||||
|
||||
|
||||
def main(argv):
|
||||
logging.basicConfig()
|
||||
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('package_name', help='Package (e.g. com.android.sample)')
|
||||
parser.add_argument('apk_path', help='Path to the APK file to upload.')
|
||||
parser.add_argument('changes_file',
|
||||
help='Path to file containing "What\'s new in this version?" text.')
|
||||
parser.add_argument('--track', default=DEFAULT_TRACK,
|
||||
choices=['alpha', 'beta', 'production', 'rollout'])
|
||||
args = parser.parse_args()
|
||||
|
||||
changes_text = read_text_file(args.changes_file)
|
||||
|
||||
service = connect_to_service(SERVICE_ACCOUNT_EMAIL, KEY_FILE_PATH,
|
||||
API_AUTH_SCOPE)
|
||||
|
||||
try:
|
||||
publish_apk(service, args.package_name, args.apk_path, changes_text,
|
||||
args.track)
|
||||
except client.AccessTokenRefreshError:
|
||||
print ('The credentials have been revoked or expired, please re-run the '
|
||||
'application to re-authorize')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main(sys.argv)
|
||||
@@ -1,38 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
# Copyright 2014 The Chromium Authors. All rights reserved.
|
||||
# Use of this source code is governed by a BSD-style license that can be
|
||||
# found in the LICENSE file.
|
||||
|
||||
# Knows how to pull down files from the version of Blink we forked from.
|
||||
|
||||
import argparse
|
||||
import requests
|
||||
import os
|
||||
import sys
|
||||
|
||||
FORK_VERSION = "086acdd04cbe6fcb89b2fc6bd438fb8819a26776"
|
||||
|
||||
parser = argparse.ArgumentParser("Tool for resurrecting pre-fork Blink files.")
|
||||
parser.add_argument("path", help="Path from Blink's Source root to the file."
|
||||
"e.g. core/dom/ExecutionContextTask.h")
|
||||
args = parser.parse_args()
|
||||
|
||||
BASE_URL = "http://blink.lc/blink/plain/Source/%s?id=%s"
|
||||
url = BASE_URL % (args.path, FORK_VERSION)
|
||||
response = requests.get(url)
|
||||
if response.status_code != 200:
|
||||
print "Load failure: %s" % url
|
||||
sys.exit(0)
|
||||
contents = response.text
|
||||
|
||||
file_name = os.path.basename(args.path)
|
||||
|
||||
if os.path.exists(file_name):
|
||||
print "%s exists, do you want to overwrite [y/N]?" % file_name
|
||||
if raw_input().lower() not in ('y', 'yes'):
|
||||
print "Aborting."
|
||||
sys.exit(1)
|
||||
|
||||
with open(file_name, "w+") as output:
|
||||
output.write(contents)
|
||||
print "Wrote %s" % file_name
|
||||
@@ -1,71 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
# Copyright 2015 The Chromium Authors. All rights reserved.
|
||||
# Use of this source code is governed by a BSD-style license that can be
|
||||
# found in the LICENSE file.
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import subprocess
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
|
||||
MANIFEST_PREFACE = '''<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Copyright 2015 The Chromium Authors. All rights reserved.
|
||||
Use of this source code is governed by a BSD-style license that can be
|
||||
found in the LICENSE file.
|
||||
-->
|
||||
'''
|
||||
|
||||
|
||||
def increment_version(version):
|
||||
pieces = version.split('.')
|
||||
pieces[-1] = str(int(pieces[-1]) + 1)
|
||||
return '.'.join(pieces)
|
||||
|
||||
|
||||
def prepend_to_file(to_prepend, filepath):
|
||||
with open(filepath, 'r+') as f:
|
||||
content = f.read()
|
||||
f.seek(0, 0)
|
||||
f.write(to_prepend + content)
|
||||
|
||||
|
||||
def update_manifest(manifest):
|
||||
VERSION_CODE = '{http://schemas.android.com/apk/res/android}versionCode'
|
||||
VERSION_NAME = '{http://schemas.android.com/apk/res/android}versionName'
|
||||
tree = ET.parse(manifest)
|
||||
root = tree.getroot()
|
||||
package_name = root.get('package')
|
||||
old_code = root.get(VERSION_CODE)
|
||||
old_name = root.get(VERSION_NAME)
|
||||
root.set(VERSION_CODE, increment_version(old_code))
|
||||
root.set(VERSION_NAME, increment_version(old_name))
|
||||
print "%20s %6s (%s) => %6s (%s)" % (package_name, old_name, old_code,
|
||||
root.get(VERSION_NAME), root.get(VERSION_CODE))
|
||||
# TODO(eseidel): This isn't smart enough to wrap/intent multi-attribute
|
||||
# elements like <manifest> as is the typical AndroidManifiest.xml style
|
||||
# we could write our own custom prettyprinter to do that?
|
||||
tree.write(manifest)
|
||||
prepend_to_file(MANIFEST_PREFACE, manifest)
|
||||
return root.get(VERSION_NAME)
|
||||
|
||||
|
||||
def main():
|
||||
# Should chdir to the root directory.
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('manifest')
|
||||
args = parser.parse_args()
|
||||
|
||||
# TODO(eseidel): Without this ET uses 'ns0' for 'android' which is wrong.
|
||||
ET.register_namespace('android', 'http://schemas.android.com/apk/res/android')
|
||||
|
||||
new_version = update_manifest(args.manifest)
|
||||
notes_dir = os.path.join(os.path.dirname(args.manifest), 'release_notes')
|
||||
release_notes = os.path.join(notes_dir, '%s.txt' % new_version)
|
||||
# FIXME: We could open an editor for the release notes and prepopulate
|
||||
# it with the changes url like how we do for pubspec CHANGELOG.md files.
|
||||
print "Please update %s in this commit." % release_notes
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -1,83 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
# Copyright 2015 The Chromium Authors. All rights reserved.
|
||||
# Use of this source code is governed by a BSD-style license that can be
|
||||
# found in the LICENSE file.
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
import yaml
|
||||
|
||||
|
||||
PUBSPECS = [
|
||||
'sky/packages/sky/pubspec.yaml',
|
||||
'sky/packages/sky_engine/pubspec.yaml',
|
||||
'sky/packages/sky_services/pubspec.yaml',
|
||||
]
|
||||
|
||||
def increment_version(version):
|
||||
pieces = version.split('.')
|
||||
pieces[-1] = str(int(pieces[-1]) + 1)
|
||||
return '.'.join(pieces)
|
||||
|
||||
|
||||
def sort_dict(unsorted):
|
||||
sorted_dict = collections.OrderedDict()
|
||||
for key in sorted(unsorted.keys()):
|
||||
sorted_dict[key] = unsorted[key]
|
||||
return sorted_dict
|
||||
|
||||
|
||||
def count_commits(start, end):
|
||||
return subprocess.check_output([
|
||||
'git', 'rev-list', '%s...%s' % (start, end)]).count('\n')
|
||||
|
||||
|
||||
def last_commit_to(file_path):
|
||||
return subprocess.check_output(['git', 'log', '-1', '--format=%h', file_path]).strip()
|
||||
|
||||
|
||||
def update_pubspec(pubspec):
|
||||
# TODO(eseidel): This does not prserve any manual sort-order of the yaml.
|
||||
with open(pubspec, 'r') as stream:
|
||||
spec = yaml.load(stream)
|
||||
old_version = spec['version']
|
||||
spec['version'] = increment_version(old_version)
|
||||
print "%20s %6s => %6s" % (spec['name'], old_version, spec['version'])
|
||||
|
||||
with open(pubspec, 'w') as stream:
|
||||
yaml.dump(spec, stream=stream, default_flow_style=False)
|
||||
return spec['version']
|
||||
|
||||
|
||||
def update_changelog(changelog, pubspec, version):
|
||||
old = last_commit_to(pubspec)
|
||||
new = last_commit_to('.')
|
||||
url = "https://github.com/domokit/sky_engine/compare/%s...%s" % (old, new)
|
||||
count = count_commits(old, new)
|
||||
message = """## %s
|
||||
|
||||
- %s changes: %s
|
||||
|
||||
""" % (version, count, url)
|
||||
prepend_to_file(message, changelog)
|
||||
|
||||
|
||||
def prepend_to_file(to_prepend, filepath):
|
||||
with open(filepath, 'r+') as f:
|
||||
content = f.read()
|
||||
f.seek(0, 0)
|
||||
f.write(to_prepend + content)
|
||||
|
||||
|
||||
def main():
|
||||
# Should chdir to the root directory.
|
||||
|
||||
print 'Pub packages:'
|
||||
for pubspec in PUBSPECS:
|
||||
new_version = update_pubspec(pubspec)
|
||||
changelog = os.path.join(os.path.dirname(pubspec), 'CHANGELOG.md')
|
||||
update_changelog(changelog, pubspec, new_version)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -1,74 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
# Copyright 2015 The Chromium Authors. All rights reserved.
|
||||
# Use of this source code is governed by a BSD-style license that can be
|
||||
# found in the LICENSE file.
|
||||
|
||||
import argparse
|
||||
import subprocess
|
||||
import sys
|
||||
import os
|
||||
import yaml
|
||||
|
||||
|
||||
SKY_TOOLS_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||
SRC_ROOT = os.path.dirname(os.path.dirname(SKY_TOOLS_DIR))
|
||||
SKY_PACKAGE_DIR = os.path.join(SRC_ROOT, 'sky', 'packages', 'sky')
|
||||
SKY_PUBSPEC = os.path.join(SKY_PACKAGE_DIR, 'pubspec.yaml')
|
||||
SKY_PUBSPEC_LOCK = os.path.join(SKY_PACKAGE_DIR, 'pubspec.lock')
|
||||
|
||||
WORKBENCH = os.path.join(SRC_ROOT, 'sky', 'packages', 'workbench')
|
||||
|
||||
def version_for_pubspec(pubspec_path):
|
||||
with open(pubspec_path, 'r') as stream:
|
||||
dependency_spec = yaml.load(stream)
|
||||
return dependency_spec['version']
|
||||
|
||||
|
||||
def entry_for_dependency(dart_pkg_dir, dependency):
|
||||
dependency_path = os.path.join(dart_pkg_dir, dependency)
|
||||
pubspec_path = os.path.join(dependency_path, 'pubspec.yaml')
|
||||
if not os.path.exists(pubspec_path):
|
||||
dependency_path = os.path.dirname(os.path.realpath(os.path.join(WORKBENCH, 'packages', dependency)))
|
||||
pubspec_path = os.path.join(dependency_path, 'pubspec.yaml')
|
||||
if not os.path.exists(pubspec_path):
|
||||
return
|
||||
version = version_for_pubspec(pubspec_path)
|
||||
return {
|
||||
'description': {
|
||||
'path': os.path.relpath(dependency_path, SKY_PACKAGE_DIR),
|
||||
'relative': True,
|
||||
},
|
||||
'source': 'path',
|
||||
'version': version,
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description='Adds files to the source tree to make the dart analyzer happy')
|
||||
parser.add_argument('build_dir', type=str, help='Path the build directory to use for build artifacts')
|
||||
args = parser.parse_args()
|
||||
|
||||
dart_pkg_dir = os.path.join(args.build_dir, 'gen', 'dart-pkg')
|
||||
|
||||
if not os.path.exists(dart_pkg_dir):
|
||||
print 'Cannot find Dart pacakges at "%s".' % dart_pkg_dir
|
||||
print 'Did you run `ninja -C %s` ?' % os.path.relpath(args.build_dir, os.getcwd())
|
||||
return 1
|
||||
|
||||
packages = {}
|
||||
|
||||
with open(SKY_PUBSPEC, 'r') as stream:
|
||||
spec = yaml.load(stream)
|
||||
for dependency in spec['dependencies'].keys():
|
||||
entry = entry_for_dependency(dart_pkg_dir, dependency)
|
||||
if not entry:
|
||||
continue
|
||||
packages[dependency] = entry
|
||||
|
||||
lock = { 'packages': packages }
|
||||
with open(SKY_PUBSPEC_LOCK, 'w') as stream:
|
||||
yaml.dump(lock, stream=stream, default_flow_style=False)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -1,467 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
# Copyright 2015 The Chromium Authors. All rights reserved.
|
||||
# Use of this source code is governed by a BSD-style license that can be
|
||||
# found in the LICENSE file.
|
||||
|
||||
from skypy.skyserver import SkyServer
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import pipes
|
||||
import platform
|
||||
import re
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import urlparse
|
||||
|
||||
SKY_TOOLS_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||
SKY_ROOT = os.path.dirname(SKY_TOOLS_DIR)
|
||||
SRC_ROOT = os.path.dirname(SKY_ROOT)
|
||||
|
||||
GDB_PORT = 8888
|
||||
SKY_SERVER_PORT = 9888
|
||||
OBSERVATORY_PORT = 8181
|
||||
DEFAULT_URL = "https://domokit.github.io/home.dart"
|
||||
APK_NAME = 'SkyShell.apk'
|
||||
ADB_PATH = os.path.join(SRC_ROOT,
|
||||
'third_party/android_tools/sdk/platform-tools/adb')
|
||||
ANDROID_PACKAGE = "org.domokit.sky.shell"
|
||||
ANDROID_COMPONENT = '%s/%s.SkyActivity' % (ANDROID_PACKAGE, ANDROID_PACKAGE)
|
||||
SHA1_PATH = '/sdcard/%s/%s.sha1' % (ANDROID_PACKAGE, APK_NAME)
|
||||
|
||||
PID_FILE_PATH = "/tmp/shelldb.pids"
|
||||
PID_FILE_KEYS = frozenset([
|
||||
'remote_sky_server_port',
|
||||
'sky_server_pid',
|
||||
'sky_server_port',
|
||||
'sky_server_root',
|
||||
'build_dir',
|
||||
'sky_shell_pid',
|
||||
'remote_gdbserver_port',
|
||||
])
|
||||
|
||||
SYSTEM_LIBS_ROOT_PATH = '/tmp/device_libs'
|
||||
|
||||
# This 'strict dictionary' approach is useful for catching typos.
|
||||
class Pids(object):
|
||||
def __init__(self, known_keys, contents=None):
|
||||
self._known_keys = known_keys
|
||||
self._dict = contents if contents is not None else {}
|
||||
|
||||
def __len__(self):
|
||||
return len(self._dict)
|
||||
|
||||
def get(self, key, default=None):
|
||||
assert key in self._known_keys, '%s not in known_keys' % key
|
||||
return self._dict.get(key, default)
|
||||
|
||||
def __getitem__(self, key):
|
||||
assert key in self._known_keys, '%s not in known_keys' % key
|
||||
return self._dict[key]
|
||||
|
||||
def __setitem__(self, key, value):
|
||||
assert key in self._known_keys, '%s not in known_keys' % key
|
||||
self._dict[key] = value
|
||||
|
||||
def __delitem__(self, key):
|
||||
assert key in self._known_keys, '%s not in known_keys' % key
|
||||
del self._dict[key]
|
||||
|
||||
def __iter__(self):
|
||||
return iter(self._dict)
|
||||
|
||||
def __contains__(self, key):
|
||||
assert key in self._known_keys, '%s not in allowed_keys' % key
|
||||
return key in self._dict
|
||||
|
||||
def clear(self):
|
||||
self._dict = {}
|
||||
|
||||
def pop(self, key, default=None):
|
||||
assert key in self._known_keys, '%s not in allowed_keys' % key
|
||||
return self._dict.pop(key, default)
|
||||
|
||||
@classmethod
|
||||
def read_from(cls, path, known_keys):
|
||||
contents = {}
|
||||
try:
|
||||
with open(path, 'r') as pid_file:
|
||||
contents = json.load(pid_file)
|
||||
except:
|
||||
if os.path.exists(path):
|
||||
logging.warn('Failed to read pid file: %s' % path)
|
||||
return cls(known_keys, contents)
|
||||
|
||||
def write_to(self, path):
|
||||
try:
|
||||
with open(path, 'w') as pid_file:
|
||||
json.dump(self._dict, pid_file, indent=2, sort_keys=True)
|
||||
except:
|
||||
logging.warn('Failed to write pid file: %s' % path)
|
||||
|
||||
|
||||
# A free function for possible future sharing with a 'load' command.
|
||||
def _url_from_args(args, pids):
|
||||
if urlparse.urlparse(args.url_or_path).scheme:
|
||||
return args.url_or_path
|
||||
# The load happens on the remote device, use the remote port.
|
||||
remote_sky_server_port = pids.get('remote_sky_server_port',
|
||||
pids['sky_server_port'])
|
||||
return SkyServer.url_for_path(remote_sky_server_port,
|
||||
pids['sky_server_root'], args.url_or_path)
|
||||
|
||||
|
||||
def dev_packages_root(build_dir):
|
||||
return os.path.join(build_dir, 'gen', 'dart-pkg', 'packages')
|
||||
|
||||
|
||||
class SetBuildDir(object):
|
||||
def add_subparser(self, subparsers):
|
||||
start_parser = subparsers.add_parser('set_build_dir',
|
||||
help='force the build_dir to a particular value without starting Sky')
|
||||
start_parser.add_argument('build_dir', type=str)
|
||||
start_parser.set_defaults(func=self.run)
|
||||
|
||||
def run(self, args, pids):
|
||||
pids['build_dir'] = os.path.abspath(args.build_dir)
|
||||
|
||||
|
||||
class StartSky(object):
|
||||
def add_subparser(self, subparsers):
|
||||
start_parser = subparsers.add_parser('start',
|
||||
help='launch SkyShell.apk on the device')
|
||||
start_parser.add_argument('build_dir', type=str)
|
||||
start_parser.add_argument('--gdb', action="store_true")
|
||||
start_parser.add_argument('url_or_path', nargs='?', type=str,
|
||||
default=DEFAULT_URL)
|
||||
start_parser.add_argument('--no_install', action="store_false",
|
||||
default=True, dest="install",
|
||||
help="Don't install SkyShell.apk before starting")
|
||||
start_parser.set_defaults(func=self.run)
|
||||
|
||||
def _server_root_for_url(self, url_or_path):
|
||||
path = os.path.abspath(url_or_path)
|
||||
if os.path.commonprefix([path, SRC_ROOT]) == SRC_ROOT:
|
||||
server_root = SRC_ROOT
|
||||
else:
|
||||
server_root = os.path.dirname(path)
|
||||
logging.warn(
|
||||
'%s is outside of mojo root, using %s as server root' %
|
||||
(path, server_root))
|
||||
return server_root
|
||||
|
||||
def _sky_server_for_args(self, args, packages_root):
|
||||
server_root = self._server_root_for_url(args.url_or_path)
|
||||
sky_server = SkyServer(SKY_SERVER_PORT, server_root, packages_root)
|
||||
return sky_server
|
||||
|
||||
def _find_remote_pid_for_package(self, package):
|
||||
ps_output = subprocess.check_output([ADB_PATH, 'shell', 'ps'])
|
||||
for line in ps_output.split('\n'):
|
||||
fields = line.split()
|
||||
if fields and fields[-1] == package:
|
||||
return fields[1]
|
||||
return None
|
||||
|
||||
def _find_install_location_for_package(self, package):
|
||||
pm_command = [ADB_PATH, 'shell', 'pm', 'path', package]
|
||||
pm_output = subprocess.check_output(pm_command)
|
||||
# e.g. package:/data/app/org.chromium.mojo.shell-1/base.apk
|
||||
return pm_output.split(':')[-1]
|
||||
|
||||
def run(self, args, pids):
|
||||
apk_path = os.path.join(args.build_dir, 'apks', APK_NAME)
|
||||
if not os.path.exists(apk_path):
|
||||
print "'%s' does not exist?" % apk_path
|
||||
return 2
|
||||
|
||||
StopSky().run(args, pids)
|
||||
|
||||
packages_root = dev_packages_root(args.build_dir)
|
||||
sky_server = self._sky_server_for_args(args, packages_root)
|
||||
pids['sky_server_pid'] = sky_server.start()
|
||||
pids['sky_server_port'] = sky_server.port
|
||||
pids['sky_server_root'] = sky_server.root
|
||||
|
||||
pids['build_dir'] = os.path.abspath(args.build_dir)
|
||||
|
||||
if args.install:
|
||||
# We might need to install a new APK, so check SHA1
|
||||
source_sha1 = hashlib.sha1(open(apk_path, 'rb').read()).hexdigest()
|
||||
dest_sha1 = subprocess.check_output([ADB_PATH, 'shell', 'cat', SHA1_PATH])
|
||||
use_existing_apk = False
|
||||
if source_sha1 == dest_sha1:
|
||||
# Make sure that the APK didn't get uninstalled somehow
|
||||
use_existing_apk = subprocess.check_output([
|
||||
ADB_PATH, 'shell', 'pm', 'list', 'packages', ANDROID_PACKAGE
|
||||
])
|
||||
else:
|
||||
# User is telling us not to bother installing an APK
|
||||
use_existing_apk = True
|
||||
|
||||
if use_existing_apk:
|
||||
# APK is already on the device, we only need to stop it
|
||||
subprocess.check_call([
|
||||
ADB_PATH, 'shell', 'am', 'force-stop', ANDROID_PACKAGE
|
||||
])
|
||||
else:
|
||||
# Slow path, need to upload a new APK to the device
|
||||
# -r to replace an existing apk, -d to allow version downgrade.
|
||||
subprocess.check_call([ADB_PATH, 'install', '-r', '-d', apk_path])
|
||||
# record the SHA1 of the APK we just pushed
|
||||
with tempfile.NamedTemporaryFile() as fp:
|
||||
fp.write(source_sha1)
|
||||
fp.seek(0)
|
||||
subprocess.check_call([ADB_PATH, 'push', fp.name, SHA1_PATH])
|
||||
|
||||
# Set up port forwarding for observatory
|
||||
port_string = 'tcp:%s' % OBSERVATORY_PORT
|
||||
subprocess.check_call([
|
||||
ADB_PATH, 'forward', port_string, port_string
|
||||
])
|
||||
|
||||
port_string = 'tcp:%s' % sky_server.port
|
||||
subprocess.check_call([
|
||||
ADB_PATH, 'reverse', port_string, port_string
|
||||
])
|
||||
pids['remote_sky_server_port'] = sky_server.port
|
||||
|
||||
subprocess.check_call([ADB_PATH, 'shell',
|
||||
'am', 'start',
|
||||
'-a', 'android.intent.action.VIEW',
|
||||
'-d', _url_from_args(args, pids),
|
||||
ANDROID_COMPONENT])
|
||||
|
||||
if not args.gdb:
|
||||
return
|
||||
|
||||
# TODO(eseidel): am start -W does not seem to work?
|
||||
pid_tries = 0
|
||||
while True:
|
||||
pid = self._find_remote_pid_for_package(ANDROID_PACKAGE)
|
||||
if pid or pid_tries > 3:
|
||||
break
|
||||
logging.debug('No pid for %s yet, waiting' % ANDROID_PACKAGE)
|
||||
time.sleep(5)
|
||||
pid_tries += 1
|
||||
|
||||
if not pid:
|
||||
logging.error('Failed to find pid on device!')
|
||||
return
|
||||
|
||||
pids['sky_shell_pid'] = pid
|
||||
|
||||
# We push our own copy of gdbserver with the package since
|
||||
# the default gdbserver is a different version from our gdb.
|
||||
package_path = \
|
||||
self._find_install_location_for_package(ANDROID_PACKAGE)
|
||||
gdb_server_path = os.path.join(
|
||||
os.path.dirname(package_path), 'lib/arm/gdbserver')
|
||||
gdbserver_cmd = [
|
||||
ADB_PATH, 'shell',
|
||||
gdb_server_path, '--attach',
|
||||
':%d' % GDB_PORT,
|
||||
str(pid)
|
||||
]
|
||||
print ' '.join(map(pipes.quote, gdbserver_cmd))
|
||||
subprocess.Popen(gdbserver_cmd)
|
||||
|
||||
port_string = 'tcp:%d' % GDB_PORT
|
||||
subprocess.check_call([
|
||||
ADB_PATH, 'forward', port_string, port_string
|
||||
])
|
||||
pids['remote_gdbserver_port'] = GDB_PORT
|
||||
|
||||
|
||||
class GDBAttach(object):
|
||||
def add_subparser(self, subparsers):
|
||||
start_parser = subparsers.add_parser('gdb_attach',
|
||||
help='attach to gdbserver running on device')
|
||||
start_parser.set_defaults(func=self.run)
|
||||
|
||||
def _pull_system_libraries(self, pids, system_libs_root):
|
||||
# Pull down the system libraries this pid has already mapped in.
|
||||
# TODO(eseidel): This does not handle dynamic loads.
|
||||
library_cacher_path = os.path.join(
|
||||
SKY_TOOLS_DIR, 'android_library_cacher.py')
|
||||
subprocess.call([
|
||||
library_cacher_path, system_libs_root, pids['sky_shell_pid']
|
||||
])
|
||||
|
||||
# TODO(eseidel): adb_gdb does, this, unclear why solib-absolute-prefix
|
||||
# doesn't make this explicit listing not necessary?
|
||||
return subprocess.check_output([
|
||||
'find', system_libs_root,
|
||||
'-mindepth', '1',
|
||||
'-maxdepth', '4',
|
||||
'-type', 'd',
|
||||
]).strip().split('\n')
|
||||
|
||||
def run(self, args, pids):
|
||||
symbol_search_paths = [
|
||||
pids['build_dir'],
|
||||
]
|
||||
gdb_path = '/usr/bin/gdb'
|
||||
|
||||
eval_commands = [
|
||||
'directory %s' % SRC_ROOT,
|
||||
# TODO(eseidel): What file do I point it at? The apk?
|
||||
#'file %s' % self.paths.mojo_shell_path,
|
||||
'target remote localhost:%s' % GDB_PORT,
|
||||
]
|
||||
|
||||
# TODO(iansf): Fix undefined behavior when you have more than one device attached.
|
||||
device_id = subprocess.check_output([ADB_PATH, 'get-serialno']).strip()
|
||||
device_libs_path = os.path.join(SYSTEM_LIBS_ROOT_PATH, device_id)
|
||||
|
||||
system_lib_dirs = self._pull_system_libraries(pids, device_libs_path)
|
||||
eval_commands.append('set solib-absolute-prefix %s' % device_libs_path)
|
||||
|
||||
symbol_search_paths = system_lib_dirs + symbol_search_paths
|
||||
|
||||
# TODO(eseidel): We need to look up the toolchain somehow?
|
||||
if platform.system() == 'Darwin':
|
||||
gdb_path = os.path.join(SRC_ROOT, 'third_party/android_tools/ndk/'
|
||||
'toolchains/arm-linux-androideabi-4.9/prebuilt/darwin-x86_64/'
|
||||
'bin/arm-linux-androideabi-gdb')
|
||||
else:
|
||||
gdb_path = os.path.join(SRC_ROOT, 'third_party/android_tools/ndk/'
|
||||
'toolchains/arm-linux-androideabi-4.9/prebuilt/linux-x86_64/'
|
||||
'bin/arm-linux-androideabi-gdb')
|
||||
|
||||
# Set solib-search-path after letting android modify symbol_search_paths
|
||||
eval_commands.append(
|
||||
'set solib-search-path %s' % ':'.join(symbol_search_paths))
|
||||
|
||||
exec_command = [gdb_path]
|
||||
for command in eval_commands:
|
||||
exec_command += ['--eval-command', command]
|
||||
|
||||
print " ".join(exec_command)
|
||||
|
||||
# Write out our pid file before we exec ourselves.
|
||||
pids.write_to(PID_FILE_PATH)
|
||||
|
||||
# Exec gdb directly to avoid python intercepting symbols, etc.
|
||||
os.execv(exec_command[0], exec_command)
|
||||
|
||||
|
||||
|
||||
class StopSky(object):
|
||||
def add_subparser(self, subparsers):
|
||||
stop_parser = subparsers.add_parser('stop',
|
||||
help=('kill all running SkyShell.apk processes'))
|
||||
stop_parser.set_defaults(func=self.run)
|
||||
|
||||
def _kill_if_exists(self, pids, key, name):
|
||||
pid = pids.pop(key, None)
|
||||
if not pid:
|
||||
logging.info('No pid for %s, nothing to do.' % name)
|
||||
return
|
||||
logging.info('Killing %s (%d).' % (name, pid))
|
||||
try:
|
||||
os.kill(pid, signal.SIGTERM)
|
||||
except OSError:
|
||||
logging.info('%s (%d) already gone.' % (name, pid))
|
||||
|
||||
def _adb_reverse_remove(self, port):
|
||||
port_string = 'tcp:%s' % port
|
||||
subprocess.call([ADB_PATH, 'reverse', '--remove', port_string])
|
||||
|
||||
def _adb_forward_remove(self, port):
|
||||
port_string = 'tcp:%s' % port
|
||||
subprocess.call([ADB_PATH, 'forward', '--remove', port_string])
|
||||
|
||||
def run(self, args, pids):
|
||||
self._kill_if_exists(pids, 'sky_server_pid', 'sky_server')
|
||||
|
||||
if 'remote_sky_server_port' in pids:
|
||||
self._adb_reverse_remove(pids['remote_sky_server_port'])
|
||||
|
||||
if 'remote_gdbserver_port' in pids:
|
||||
self._adb_forward_remove(pids['remote_gdbserver_port'])
|
||||
|
||||
subprocess.call([
|
||||
ADB_PATH, 'shell', 'am', 'force-stop', ANDROID_PACKAGE])
|
||||
|
||||
pids.clear()
|
||||
|
||||
|
||||
class StartTracing(object):
|
||||
def add_subparser(self, subparsers):
|
||||
start_tracing_parser = subparsers.add_parser('start_tracing',
|
||||
help=('start tracing a running sky instance'))
|
||||
start_tracing_parser.set_defaults(func=self.run)
|
||||
|
||||
def run(self, args, pids):
|
||||
subprocess.check_output([ADB_PATH, 'shell',
|
||||
'am', 'broadcast',
|
||||
'-a', 'org.domokit.sky.shell.TRACING_START'])
|
||||
|
||||
|
||||
TRACE_COMPLETE_REGEXP = re.compile('Trace complete')
|
||||
TRACE_FILE_REGEXP = re.compile(r'Saving trace to (?P<path>\S+)')
|
||||
|
||||
class StopTracing(object):
|
||||
def add_subparser(self, subparsers):
|
||||
stop_tracing_parser = subparsers.add_parser('stop_tracing',
|
||||
help=('stop tracing a running sky instance'))
|
||||
stop_tracing_parser.set_defaults(func=self.run)
|
||||
|
||||
def run(self, args, pids):
|
||||
subprocess.check_output([ADB_PATH, 'logcat', '-c'])
|
||||
subprocess.check_output([ADB_PATH, 'shell',
|
||||
'am', 'broadcast',
|
||||
'-a', 'org.domokit.sky.shell.TRACING_STOP'])
|
||||
device_path = None
|
||||
is_complete = False
|
||||
while not is_complete:
|
||||
time.sleep(0.2)
|
||||
log = subprocess.check_output([ADB_PATH, 'logcat', '-d'])
|
||||
if device_path is None:
|
||||
result = TRACE_FILE_REGEXP.search(log)
|
||||
if result:
|
||||
device_path = result.group('path')
|
||||
is_complete = TRACE_COMPLETE_REGEXP.search(log) is not None
|
||||
|
||||
print 'Downloading trace %s ...' % os.path.basename(device_path)
|
||||
|
||||
if device_path:
|
||||
subprocess.check_output([ADB_PATH, 'pull', device_path])
|
||||
subprocess.check_output([ADB_PATH, 'shell', 'rm', device_path])
|
||||
|
||||
|
||||
class SkyShellRunner(object):
|
||||
def main(self):
|
||||
logging.basicConfig(level=logging.WARNING)
|
||||
|
||||
parser = argparse.ArgumentParser(description='Sky Shell Runner')
|
||||
subparsers = parser.add_subparsers(help='sub-command help')
|
||||
|
||||
commands = [
|
||||
SetBuildDir(),
|
||||
StartSky(),
|
||||
StopSky(),
|
||||
GDBAttach(),
|
||||
StartTracing(),
|
||||
StopTracing(),
|
||||
]
|
||||
|
||||
for command in commands:
|
||||
command.add_subparser(subparsers)
|
||||
|
||||
args = parser.parse_args()
|
||||
pids = Pids.read_from(PID_FILE_PATH, PID_FILE_KEYS)
|
||||
exit_code = args.func(args, pids)
|
||||
# We could do this with an at-exit handler instead?
|
||||
pids.write_to(PID_FILE_PATH)
|
||||
sys.exit(exit_code)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
SkyShellRunner().main()
|
||||
@@ -1,3 +0,0 @@
|
||||
# Copyright 2014 The Chromium Authors. All rights reserved.
|
||||
# Use of this source code is governed by a BSD-style license that can be
|
||||
# found in the LICENSE file.
|
||||
@@ -1,15 +0,0 @@
|
||||
# Copyright 2014 The Chromium Authors. All rights reserved.
|
||||
# Use of this source code is governed by a BSD-style license that can be
|
||||
# found in the LICENSE file.
|
||||
|
||||
import optparse
|
||||
|
||||
|
||||
def add_arguments(parser):
|
||||
parser.add_argument("-t", "--target", dest="configuration",
|
||||
help="Specify the target configuration to use (Debug/Release)", default='Release')
|
||||
parser.add_argument('--debug', action='store_const', const='Debug', dest="configuration",
|
||||
help='Set the configuration to Debug')
|
||||
parser.add_argument('--release', action='store_const', const='Release', dest="configuration",
|
||||
help='Set the configuration to Release')
|
||||
|
||||
@@ -1,20 +0,0 @@
|
||||
# Copyright 2014 The Chromium Authors. All rights reserved.
|
||||
# Use of this source code is governed by a BSD-style license that can be
|
||||
# found in the LICENSE file.
|
||||
|
||||
import os
|
||||
|
||||
|
||||
IGNORED_DIRECTORIES = ['resources']
|
||||
TEST_EXTENSIONS = ['sky']
|
||||
|
||||
|
||||
def find_tests(directory):
|
||||
for root, dirs, files in os.walk(directory):
|
||||
for file_name in files:
|
||||
extension = os.path.splitext(file_name)[1]
|
||||
if extension.lstrip('.') in TEST_EXTENSIONS:
|
||||
yield os.path.join(root, file_name)
|
||||
for ignored_directory in IGNORED_DIRECTORIES:
|
||||
if ignored_directory in dirs:
|
||||
dirs.remove(ignored_directory)
|
||||
@@ -1,16 +0,0 @@
|
||||
# Copyright 2014 The Chromium Authors. All rights reserved.
|
||||
# Use of this source code is governed by a BSD-style license that can be
|
||||
# found in the LICENSE file.
|
||||
|
||||
import os
|
||||
|
||||
# FIXME: All callers should use mopy/paths.py instead!
|
||||
class Paths(object):
|
||||
def __init__(self, build_directory):
|
||||
self.src_root = os.path.abspath(os.path.join(__file__,
|
||||
os.pardir, os.pardir, os.pardir, os.pardir))
|
||||
self.sky_root = os.path.join(self.src_root, 'sky')
|
||||
self.build_dir = os.path.join(self.src_root, build_directory)
|
||||
self.gen_root = os.path.join(self.build_dir, 'gen')
|
||||
self.sky_tools_directory = os.path.join(self.src_root, 'sky', 'tools')
|
||||
self.mojo_shell_path = os.path.join(self.src_root, build_directory, 'mojo_shell')
|
||||
@@ -1,63 +0,0 @@
|
||||
# Copyright 2014 The Chromium Authors. All rights reserved.
|
||||
# Use of this source code is governed by a BSD-style license that can be
|
||||
# found in the LICENSE file.
|
||||
|
||||
import socket
|
||||
import subprocess
|
||||
import logging
|
||||
import os.path
|
||||
|
||||
SKYPY_PATH = os.path.dirname(os.path.abspath(__file__))
|
||||
SRC_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(SKYPY_PATH)))
|
||||
|
||||
WORKBENCH_ROOT = os.path.join(SRC_ROOT, 'sky', 'packages', 'workbench')
|
||||
DART_SDK = os.path.join(SRC_ROOT, 'third_party', 'dart-sdk', 'dart-sdk', 'bin')
|
||||
PUB = os.path.join(DART_SDK, 'pub')
|
||||
EXAMPLES_ROOT = os.path.join(SRC_ROOT, 'examples')
|
||||
SKY_ROOT = os.path.join(SRC_ROOT, 'sky')
|
||||
|
||||
class SkyServer(object):
|
||||
def __init__(self, port, root, package_root):
|
||||
self.port = port
|
||||
self.root = root
|
||||
self.package_root = package_root
|
||||
self.server = None
|
||||
|
||||
@staticmethod
|
||||
def _port_in_use(port):
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
return sock.connect_ex(('localhost', port)) == 0
|
||||
|
||||
def start(self):
|
||||
if self._port_in_use(self.port):
|
||||
logging.warn(
|
||||
'Port %s already in use, assuming custom sky_server started.' %
|
||||
self.port)
|
||||
return
|
||||
|
||||
args = [PUB,
|
||||
'run',
|
||||
'sky_tools:sky_server',
|
||||
'--route=/sky,%s' % SKY_ROOT,
|
||||
'--route=/examples,%s' % EXAMPLES_ROOT,
|
||||
str(self.port)]
|
||||
self.server = subprocess.Popen(args, cwd=WORKBENCH_ROOT)
|
||||
return self.server.pid
|
||||
|
||||
def stop(self):
|
||||
if self.server:
|
||||
self.server.terminate()
|
||||
|
||||
def __enter__(self):
|
||||
self.start()
|
||||
|
||||
def __exit__(self, exc_type, exc_value, traceback):
|
||||
self.stop()
|
||||
|
||||
def path_as_url(self, path):
|
||||
return self.url_for_path(self.port, self.root, path)
|
||||
|
||||
@staticmethod
|
||||
def url_for_path(port, root, path):
|
||||
relative_path = os.path.relpath(path, root)
|
||||
return 'http://localhost:%s/%s' % (port, relative_path)
|
||||
@@ -1,18 +0,0 @@
|
||||
# Copyright 2014 The Chromium Authors. All rights reserved.
|
||||
# Use of this source code is governed by a BSD-style license that can be
|
||||
# found in the LICENSE file.
|
||||
|
||||
import os
|
||||
|
||||
class URLMappings(object):
|
||||
def __init__(self, src_root, build_dir):
|
||||
self.mappings = {
|
||||
'dart:mojo.internal': os.path.join(src_root, 'mojo/public/dart/sdk_ext/internal.dart'),
|
||||
'dart:ui': os.path.join(build_dir, 'gen/sky/bindings/dart_ui.dart'),
|
||||
'dart:ui_internals': os.path.join(src_root, 'sky/engine/bindings/internals.dart'),
|
||||
}
|
||||
self.packages_root = os.path.join(build_dir, 'gen/dart-pkg/packages')
|
||||
|
||||
@property
|
||||
def as_args(self):
|
||||
return map(lambda item: '--url-mapping=%s,%s' % item, self.mappings.items())
|
||||
@@ -1,120 +0,0 @@
|
||||
# From http://tools.cherrypy.org/wiki/staticdirindex
|
||||
# CherryPy code is covered under a BSD License:
|
||||
# https://bitbucket.org/cherrypy/cherrypy/src/697c7af588b8/cherrypy/LICENSE.txt
|
||||
|
||||
import os
|
||||
import re
|
||||
import stat
|
||||
import urllib
|
||||
import cherrypy
|
||||
from cherrypy.lib import cptools, http
|
||||
|
||||
# Undercover kludge to wrap staticdir
|
||||
from cherrypy.lib.static import staticdir
|
||||
|
||||
def staticdirindex(section, dir, root="", match="", content_types=None,
|
||||
index="", indexlistermatch="", indexlister=None, **kwargs):
|
||||
"""Serve a directory index listing for a dir.
|
||||
|
||||
Compatibility alert: staticdirindex is built on and is dependent on
|
||||
staticdir and its configurations. staticdirindex only works effectively
|
||||
in locations where staticdir is also configured. staticdirindex is
|
||||
coded to allow easy integration with staticdir, if demand warrants.
|
||||
|
||||
indexlister must be configured, or no function is performed.
|
||||
indexlister should be a callable that accepts the following parameters:
|
||||
section: same as for staticdir (and implicitly calculated for it)
|
||||
dir: same as for staticdir, but already combined with root
|
||||
path: combination of section and dir
|
||||
|
||||
Other parameters that are configured for staticdirindex will be passed
|
||||
on to indexlister.
|
||||
|
||||
Should use priorty > than that of staticdir, so that only directories not
|
||||
served by staticdir, call staticdirindex.
|
||||
|
||||
"""
|
||||
# first call old staticdir, and see if it does anything
|
||||
sdret = staticdir( section, dir, root, match, content_types, index )
|
||||
if sdret:
|
||||
return True
|
||||
|
||||
# if not, then see if we are configured to do anything
|
||||
if indexlister is None:
|
||||
return False
|
||||
|
||||
req = cherrypy.request
|
||||
response = cherrypy.response
|
||||
|
||||
match = indexlistermatch
|
||||
|
||||
# N.B. filename ending in a slash or not does not imply a directory
|
||||
# the following block of code directly copied from static.py staticdir
|
||||
if match and not re.search(match, cherrypy.request.path_info):
|
||||
return False
|
||||
|
||||
# Allow the use of '~' to refer to a user's home directory.
|
||||
dir = os.path.expanduser(dir)
|
||||
|
||||
# If dir is relative, make absolute using "root".
|
||||
if not os.path.isabs(dir):
|
||||
if not root:
|
||||
msg = "Static dir requires an absolute dir (or root)."
|
||||
raise ValueError(msg)
|
||||
dir = os.path.join(root, dir)
|
||||
|
||||
# Determine where we are in the object tree relative to 'section'
|
||||
# (where the static tool was defined).
|
||||
if section == 'global':
|
||||
section = "/"
|
||||
section = section.rstrip(r"\/")
|
||||
branch = cherrypy.request.path_info[len(section) + 1:]
|
||||
branch = urllib.unquote(branch.lstrip(r"\/"))
|
||||
|
||||
# If branch is "", filename will end in a slash
|
||||
filename = os.path.join(dir, branch)
|
||||
|
||||
# There's a chance that the branch pulled from the URL might
|
||||
# have ".." or similar uplevel attacks in it. Check that the final
|
||||
# filename is a child of dir.
|
||||
if not os.path.normpath(filename).startswith(os.path.normpath(dir)):
|
||||
raise cherrypy.HTTPError(403) # Forbidden
|
||||
# the above block of code directly copied from static.py staticdir
|
||||
# N.B. filename ending in a slash or not does not imply a directory
|
||||
|
||||
# Check if path is a directory.
|
||||
|
||||
path = filename
|
||||
# The following block of code copied from static.py serve_file
|
||||
|
||||
# If path is relative, users should fix it by making path absolute.
|
||||
# That is, CherryPy should not guess where the application root is.
|
||||
# It certainly should *not* use cwd (since CP may be invoked from a
|
||||
# variety of paths). If using tools.static, you can make your relative
|
||||
# paths become absolute by supplying a value for "tools.static.root".
|
||||
if not os.path.isabs(path):
|
||||
raise ValueError("'%s' is not an absolute path." % path)
|
||||
|
||||
try:
|
||||
st = os.stat(path)
|
||||
except OSError:
|
||||
# The above block of code copied from static.py serve_file
|
||||
|
||||
return False
|
||||
|
||||
if stat.S_ISDIR(st.st_mode):
|
||||
|
||||
# Set the Last-Modified response header, so that
|
||||
# modified-since validation code can work.
|
||||
response.headers['Last-Modified'] = http.HTTPDate(st.st_mtime)
|
||||
cptools.validate_since()
|
||||
response.body = indexlister( section=section, dir=dir, path=path,
|
||||
**kwargs )
|
||||
response.headers['Content-Type'] = 'text/html'
|
||||
req.is_index = True
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
# Replace the real staticdir with our version
|
||||
cherrypy.tools.staticdir = cherrypy._cptools.HandlerTool( staticdirindex )
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,99 +0,0 @@
|
||||
#!/usr/bin/ruby
|
||||
|
||||
require 'test/unit'
|
||||
require 'open-uri'
|
||||
require 'PrettyPatch'
|
||||
|
||||
# Note: internet connection is needed to run this test suite.
|
||||
|
||||
class PrettyPatch_test < Test::Unit::TestCase
|
||||
class Info
|
||||
TITLE = 0
|
||||
FILE = 1
|
||||
ADD = 2
|
||||
REMOVE = 3
|
||||
SHARED = 4
|
||||
end
|
||||
|
||||
PATCHES = {
|
||||
20510 => ["Single change", 1, 1, 0, 2],
|
||||
20528 => ["No 'Index' or 'diff' in patch header", 1, 4, 3, 7],
|
||||
21151 => ["Leading '/' in the path of files", 4, 9, 1, 16],
|
||||
# Binary files use shared blocks, there are three in 30488.
|
||||
30488 => ["Quoted filenames in git diff", 23, 28, 25, 64 + 3],
|
||||
23920 => ["Mac line ending", 3, 3, 0, 5],
|
||||
39615 => ["Git signature", 2, 2, 0, 3],
|
||||
80852 => ["Changes one line plus ChangeLog", 2, 2, 1, 4],
|
||||
83127 => ["Only add stuff", 2, 2, 0, 3],
|
||||
85071 => ["Adds and removes from a file plus git signature", 2, 5, 3, 9],
|
||||
106368 => ["Images with git delta binary patch", 69, 8, 23, 10],
|
||||
}
|
||||
|
||||
def get_patch_uri(id)
|
||||
"https://bugs.webkit.org/attachment.cgi?id=" + id.to_s
|
||||
end
|
||||
|
||||
def get_patch(id)
|
||||
result = nil
|
||||
patch_uri = get_patch_uri(id)
|
||||
begin
|
||||
result = open(patch_uri) { |f| result = f.read }
|
||||
rescue => exception
|
||||
assert(false, "Fail to get patch " + patch_uri)
|
||||
end
|
||||
result
|
||||
end
|
||||
|
||||
def check_one_patch(id, info)
|
||||
patch = get_patch(id)
|
||||
description = get_patch_uri(id)
|
||||
description += " (" + info[Info::TITLE] + ")" unless info[Info::TITLE].nil?
|
||||
puts "Testing " + description
|
||||
pretty = nil
|
||||
assert_nothing_raised("Crash while prettifying " + description) {
|
||||
pretty = PrettyPatch.prettify(patch)
|
||||
}
|
||||
assert(pretty, "Empty result while prettifying " + description)
|
||||
assert_equal(info[Info::FILE], $last_prettify_file_count, "Wrong number of files changed in " + description)
|
||||
assert_equal(info[Info::ADD], $last_prettify_part_count["add"], "Wrong number of 'add' parts in " + description)
|
||||
assert_equal(info[Info::REMOVE], $last_prettify_part_count["remove"], "Wrong number of 'remove' parts in " + description)
|
||||
assert_equal(info[Info::SHARED], $last_prettify_part_count["shared"], "Wrong number of 'shared' parts in " + description)
|
||||
assert_equal(0, $last_prettify_part_count["binary"], "Wrong number of 'binary' parts in " + description)
|
||||
assert_equal(0, $last_prettify_part_count["extract-error"], "Wrong number of 'extract-error' parts in " + description)
|
||||
return pretty
|
||||
end
|
||||
|
||||
def test_patches
|
||||
PATCHES.each { |id, info| check_one_patch(id, info) }
|
||||
end
|
||||
|
||||
def test_images_without_checksum
|
||||
pretty = check_one_patch(144064, ["Images without checksums", 10, 5, 4, 8])
|
||||
matches = pretty.match("INVALID: Image lacks a checksum.")
|
||||
# FIXME: This should match, but there's a bug when running the tests where the image data
|
||||
# doesn't get properly written out to the temp files, so there is no image and we don't print
|
||||
# the warning that the image is missing its checksum.
|
||||
assert(!matches, "Should have invalid checksums")
|
||||
# FIXME: This should only have 4 invalid images, but due to the above tempfile issue, there are 0.
|
||||
assert_equal(0, pretty.scan(/INVALID\: Image lacks a checksum\./).size)
|
||||
end
|
||||
|
||||
def test_new_image
|
||||
pretty = check_one_patch(145881, ["New image", 19, 36, 19, 56])
|
||||
matches = pretty.match("INVALID: Image lacks a checksum.")
|
||||
assert(!matches, "Should not have invalid checksums")
|
||||
end
|
||||
|
||||
def test_images_correctly_without_checksum_git
|
||||
pretty = check_one_patch(101620, ["Images correctly without checksums git", 7, 15, 10, 26])
|
||||
matches = pretty.match("INVALID: Image lacks a checksum.")
|
||||
assert(!matches, "Png should lack a checksum without an error.")
|
||||
end
|
||||
|
||||
def test_images_correctly_without_checksum_svn
|
||||
pretty = check_one_patch(31202, ["Images correctly without checksums svn", 4, 4, 1, 4])
|
||||
matches = pretty.match("INVALID: Image lacks a checksum.")
|
||||
assert(!matches, "Png should lack a checksum without an error.")
|
||||
end
|
||||
|
||||
end
|
||||
@@ -1,164 +0,0 @@
|
||||
module HTMLDiff
|
||||
|
||||
Match = Struct.new(:start_in_old, :start_in_new, :size)
|
||||
class Match
|
||||
def end_in_old
|
||||
self.start_in_old + self.size
|
||||
end
|
||||
|
||||
def end_in_new
|
||||
self.start_in_new + self.size
|
||||
end
|
||||
end
|
||||
|
||||
Operation = Struct.new(:action, :start_in_old, :end_in_old, :start_in_new, :end_in_new)
|
||||
|
||||
class DiffBuilder
|
||||
|
||||
def initialize(old_version, new_version)
|
||||
@old_version, @new_version = old_version, new_version
|
||||
split_inputs_to_words
|
||||
index_new_words
|
||||
end
|
||||
|
||||
def split_inputs_to_words
|
||||
@old_words = explode(@old_version)
|
||||
@new_words = explode(@new_version)
|
||||
end
|
||||
|
||||
def index_new_words
|
||||
@word_indices = Hash.new { |h, word| h[word] = [] }
|
||||
@new_words.each_with_index { |word, i| @word_indices[word] << i }
|
||||
end
|
||||
|
||||
def operations
|
||||
position_in_old = position_in_new = 0
|
||||
operations = []
|
||||
|
||||
matches = matching_blocks
|
||||
# an empty match at the end forces the loop below to handle the unmatched tails
|
||||
# I'm sure it can be done more gracefully, but not at 23:52
|
||||
matches << Match.new(@old_words.length, @new_words.length, 0)
|
||||
|
||||
matches.each_with_index do |match, i|
|
||||
match_starts_at_current_position_in_old = (position_in_old == match.start_in_old)
|
||||
match_starts_at_current_position_in_new = (position_in_new == match.start_in_new)
|
||||
|
||||
action_upto_match_positions =
|
||||
case [match_starts_at_current_position_in_old, match_starts_at_current_position_in_new]
|
||||
when [false, false]
|
||||
:replace
|
||||
when [true, false]
|
||||
:insert
|
||||
when [false, true]
|
||||
:delete
|
||||
else
|
||||
# this happens if the first few words are same in both versions
|
||||
:none
|
||||
end
|
||||
|
||||
if action_upto_match_positions != :none
|
||||
operation_upto_match_positions =
|
||||
Operation.new(action_upto_match_positions,
|
||||
position_in_old, match.start_in_old,
|
||||
position_in_new, match.start_in_new)
|
||||
operations << operation_upto_match_positions
|
||||
end
|
||||
if match.size != 0
|
||||
match_operation = Operation.new(:equal,
|
||||
match.start_in_old, match.end_in_old,
|
||||
match.start_in_new, match.end_in_new)
|
||||
operations << match_operation
|
||||
end
|
||||
|
||||
position_in_old = match.end_in_old
|
||||
position_in_new = match.end_in_new
|
||||
end
|
||||
|
||||
operations
|
||||
end
|
||||
|
||||
def matching_blocks
|
||||
matching_blocks = []
|
||||
recursively_find_matching_blocks(0, @old_words.size, 0, @new_words.size, matching_blocks)
|
||||
matching_blocks
|
||||
end
|
||||
|
||||
def recursively_find_matching_blocks(start_in_old, end_in_old, start_in_new, end_in_new, matching_blocks)
|
||||
match = find_match(start_in_old, end_in_old, start_in_new, end_in_new)
|
||||
if match
|
||||
if start_in_old < match.start_in_old and start_in_new < match.start_in_new
|
||||
recursively_find_matching_blocks(
|
||||
start_in_old, match.start_in_old, start_in_new, match.start_in_new, matching_blocks)
|
||||
end
|
||||
matching_blocks << match
|
||||
if match.end_in_old < end_in_old and match.end_in_new < end_in_new
|
||||
recursively_find_matching_blocks(
|
||||
match.end_in_old, end_in_old, match.end_in_new, end_in_new, matching_blocks)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
def find_match(start_in_old, end_in_old, start_in_new, end_in_new)
|
||||
|
||||
best_match_in_old = start_in_old
|
||||
best_match_in_new = start_in_new
|
||||
best_match_size = 0
|
||||
|
||||
match_length_at = Hash.new { |h, index| h[index] = 0 }
|
||||
|
||||
start_in_old.upto(end_in_old - 1) do |index_in_old|
|
||||
|
||||
new_match_length_at = Hash.new { |h, index| h[index] = 0 }
|
||||
|
||||
@word_indices[@old_words[index_in_old]].each do |index_in_new|
|
||||
next if index_in_new < start_in_new
|
||||
break if index_in_new >= end_in_new
|
||||
|
||||
new_match_length = match_length_at[index_in_new - 1] + 1
|
||||
new_match_length_at[index_in_new] = new_match_length
|
||||
|
||||
if new_match_length > best_match_size
|
||||
best_match_in_old = index_in_old - new_match_length + 1
|
||||
best_match_in_new = index_in_new - new_match_length + 1
|
||||
best_match_size = new_match_length
|
||||
end
|
||||
end
|
||||
match_length_at = new_match_length_at
|
||||
end
|
||||
|
||||
# best_match_in_old, best_match_in_new, best_match_size = add_matching_words_left(
|
||||
# best_match_in_old, best_match_in_new, best_match_size, start_in_old, start_in_new)
|
||||
# best_match_in_old, best_match_in_new, match_size = add_matching_words_right(
|
||||
# best_match_in_old, best_match_in_new, best_match_size, end_in_old, end_in_new)
|
||||
|
||||
return (best_match_size != 0 ? Match.new(best_match_in_old, best_match_in_new, best_match_size) : nil)
|
||||
end
|
||||
|
||||
def add_matching_words_left(match_in_old, match_in_new, match_size, start_in_old, start_in_new)
|
||||
while match_in_old > start_in_old and
|
||||
match_in_new > start_in_new and
|
||||
@old_words[match_in_old - 1] == @new_words[match_in_new - 1]
|
||||
match_in_old -= 1
|
||||
match_in_new -= 1
|
||||
match_size += 1
|
||||
end
|
||||
[match_in_old, match_in_new, match_size]
|
||||
end
|
||||
|
||||
def add_matching_words_right(match_in_old, match_in_new, match_size, end_in_old, end_in_new)
|
||||
while match_in_old + match_size < end_in_old and
|
||||
match_in_new + match_size < end_in_new and
|
||||
@old_words[match_in_old + match_size] == @new_words[match_in_new + match_size]
|
||||
match_size += 1
|
||||
end
|
||||
[match_in_old, match_in_new, match_size]
|
||||
end
|
||||
|
||||
def explode(sequence)
|
||||
sequence.is_a?(String) ? sequence.split(//) : sequence
|
||||
end
|
||||
|
||||
end # of class Diff Builder
|
||||
|
||||
end
|
||||
@@ -1,37 +0,0 @@
|
||||
#!/usr/bin/env ruby
|
||||
|
||||
require 'optparse'
|
||||
require 'pathname'
|
||||
require 'webrick/htmlutils'
|
||||
|
||||
$LOAD_PATH << Pathname.new(__FILE__).dirname.realpath.to_s
|
||||
|
||||
require 'PrettyPatch'
|
||||
|
||||
BACKTRACE_SEPARATOR = "\n\tfrom "
|
||||
|
||||
options = { :html_exceptions => false }
|
||||
OptionParser.new do |opts|
|
||||
opts.banner = "Usage: #{File.basename($0)} [options] [patch-file]"
|
||||
|
||||
opts.separator ""
|
||||
|
||||
opts.on("--html-exceptions", "Print exceptions to stdout as HTML") { |h| options[:html_exceptions] = h }
|
||||
end.parse!
|
||||
|
||||
patch_data = nil
|
||||
if ARGV.length == 0 || ARGV[0] == '-' then
|
||||
patch_data = $stdin.read
|
||||
else
|
||||
File.open(ARGV[0]) { |file| patch_data = file.read }
|
||||
end
|
||||
|
||||
begin
|
||||
puts PrettyPatch.prettify(patch_data)
|
||||
rescue => exception
|
||||
raise unless options[:html_exceptions]
|
||||
|
||||
backtrace = exception.backtrace
|
||||
backtrace[0] += ": " + exception + " (" + exception.class.to_s + ")"
|
||||
print "<pre>\n", WEBrick::HTMLUtils::escape(backtrace.join(BACKTRACE_SEPARATOR)), "\n</pre>\n"
|
||||
end
|
||||
Reference in New Issue
Block a user